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.

fix(language): keep the conversation language through errors, default system phrases to English (#731)

Ruben Lütkee1a0565831aa
diff --git a/jarvis.spec b/jarvis.spec
index f32e6dab58..81c4ac39e3 100644
--- a/jarvis.spec
+++ b/jarvis.spec
@@ -101,6 +101,9 @@ datas.append((str(PROJECT_ROOT / "jarvis/society/browser/pointer.py"), "jarvis/s
# sweep below also finds them; named here so a narrower sweep cannot drop them
# and send a frozen app's setup to upstream latest.
datas.append((str(PROJECT_ROOT / "jarvis/agent_runtimes/runtime-versions.json"), "jarvis/agent_runtimes"))
+# Translated system phrases (jarvis/i18n/catalog.py); without them every
+# error and fallback phrase would raise instead of being spoken.
+datas.append((str(PROJECT_ROOT / "jarvis/i18n/locales"), "jarvis/i18n/locales"))
# The local voice engine runs in its OWN Python environment, so a frozen build
# must ship its sources as plain files: setup copies them into the engine home
diff --git a/jarvis/agent_chat/control.py b/jarvis/agent_chat/control.py
index c69c7c00c3..6bd19ccd84 100644
--- a/jarvis/agent_chat/control.py
+++ b/jarvis/agent_chat/control.py
@@ -34,6 +34,27 @@ def supports_restricted_turn(session: Any) -> bool:
return session_runner(session) not in ("kimi-cli", "dsh-cli")
+def _chat_language(current: str, text: str) -> str:
+ """The conversation language after *text*, sticky, else *current*.
+
+ Never the UI language: the interface being English says nothing about
+ the language a person chats in (forensic 2026-10-19, a Turkish chat in an
+ English UI was forced into English after a slash command).
+ """
+ from jarvis.core import runtime_refs
+ from jarvis.core.turn_language import resolve_conversation_language
+ from jarvis.i18n import is_known_language
+
+ brain = runtime_refs.get_brain_manager()
+ language = resolve_conversation_language(
+ getattr(brain, "reply_language", "auto") or "auto",
+ "unknown",
+ text or "",
+ conversation_language=current,
+ )
+ return language if is_known_language(language) else current
+
+
class ChatControls:
def __init__(self, service: Any, *, evaluator: Any = None, adapters: Any = None) -> None:
self.service = service
@@ -135,15 +156,9 @@ class ChatControls:
if contains_secret(request.arguments):
raise ValueError("Configure credentials in app settings, not in chat commands")
- from jarvis.core.config import load_config
- from jarvis.core.turn_language import resolve_output_language
-
state = self.state(sid)
- state.output_language = resolve_output_language(
- load_config().brain.reply_language,
- request.locale,
- request.arguments or state.last_request,
- default=request.locale,
+ state.output_language = _chat_language(
+ state.output_language, request.arguments or state.last_request
)
self.store.save(state)
data = await self._dispatch(
@@ -343,6 +358,9 @@ class ChatControls:
if kwargs.get("direct_user", True):
state = self.state(sid)
state.last_request, state.last_status = text, "running"
+ # Keep the stored language the conversation's, turn by turn, so a
+ # later send never inherits one an older command left behind.
+ state.output_language = _chat_language(state.output_language, text)
self.store.save(state)
origin = _command_origin.get()
if origin:
diff --git a/jarvis/agent_chat/runner_brain.py b/jarvis/agent_chat/runner_brain.py
index 4e1501da48..c553711b05 100644
--- a/jarvis/agent_chat/runner_brain.py
+++ b/jarvis/agent_chat/runner_brain.py
@@ -43,7 +43,8 @@ from jarvis.agent_chat.surface_kits import kit_for
from jarvis.agent_chat.tool_catalog import ToolChoice
from jarvis.agent_chat.tools import summarize_call
from jarvis.brain.turn_override import TurnOverride
-from jarvis.core.protocols import BrainMessage, ReasoningEffort, Tool
+from jarvis.core.protocols import BrainMessage, ReasoningEffort, Tool, current_chat_turn
+from jarvis.i18n import is_known_language, is_supported_locale
if TYPE_CHECKING:
from uuid import UUID
@@ -469,16 +470,22 @@ async def run_brain_turn(
person_request = origin.user_text if origin is not None else ""
if person_request and not handle.output_language:
# The answer follows the request it continues, not the neutral
- # English line above.
- from jarvis.core.turn_language import resolve_output_language
+ # English line above — in any language, not only the four with
+ # translated system phrases.
+ from jarvis.core.turn_language import (
+ conversation_language_from_history,
+ resolve_conversation_language,
+ )
- language = resolve_output_language(
+ language = resolve_conversation_language(
getattr(brain, "reply_language", "auto") or "auto",
"unknown",
person_request,
- conversation_language=getattr(brain, "conversation_language", "") or "",
+ conversation_language=conversation_language_from_history(
+ brain_history_from_events(handle.history)
+ ),
)
- if language in {"de", "en", "es", "pt"}:
+ if is_known_language(language):
handle.output_language = language
board = getattr(getattr(handle, "control_service", None), "parked_work", None)
background = board.context_note(session.session_id) if board is not None else ""
@@ -634,6 +641,14 @@ async def _generate(
}
if output_language:
kwargs["force_output_language"] = output_language
+ from jarvis.agent_chat.delegation_wait import CONTINUE_TURN
+
+ if text == CONTINUE_TURN:
+ # The neutral English "continue" line is not the person's words: the
+ # conversation keeps its own language (a Turkish chat flipped to
+ # English on every delegated result, forensic 2026-10-19).
+ origin = current_chat_turn.get()
+ kwargs["language_text"] = origin.user_text if origin is not None else ""
secret = _agent_secret(get_jarvis_agent_secret, session.provider)
overrides = {session.provider: secret} if secret else {}
pending_before = set(getattr(brain, "_ide_background_tasks", ()))
@@ -676,10 +691,10 @@ async def _generate(
# turn lock; do not detect language from an English result prompt.
if not handle.output_language:
pin = getattr(brain, "reply_language", "")
- language = pin if pin in {"de", "en", "es", "pt"} else getattr(
+ language = pin if is_supported_locale(pin) else getattr(
brain, "conversation_language", ""
)
- if language in {"de", "en", "es", "pt"}:
+ if is_known_language(language):
handle.output_language = language
return result
task.cancel()
diff --git a/jarvis/brain/ack_brain/generator.py b/jarvis/brain/ack_brain/generator.py
index 1f14dac672..5aeaf7b74d 100644
--- a/jarvis/brain/ack_brain/generator.py
+++ b/jarvis/brain/ack_brain/generator.py
@@ -258,7 +258,7 @@ class AckGenerator:
# (the fallback has no fallback of its own), so delegation can't loop.
self._fallback = fallback
- async def run(self, utterance: str, language: str = "de") -> str | None:
+ async def run(self, utterance: str, language: str = "en") -> str | None:
"""Generate one short acknowledgment sentence or return None.
Pipeline (spec §4):
@@ -417,7 +417,7 @@ class AckGenerator:
return scrubbed
async def run_stream(
- self, utterance: str, language: str = "de"
+ self, utterance: str, language: str = "en"
) -> AsyncIterator[str]:
"""Streaming variant of run(): yield scrubbed ack sentences ASAP.
diff --git a/jarvis/brain/ack_brain/persona_prompt.py b/jarvis/brain/ack_brain/persona_prompt.py
index 45c7639a5e..ab14d2d7fd 100644
--- a/jarvis/brain/ack_brain/persona_prompt.py
+++ b/jarvis/brain/ack_brain/persona_prompt.py
@@ -305,19 +305,13 @@ cadeia vazia. Sem markdown, sem comentários, sem texto de acompanhamento."""
def _normalise_language(value: str | None) -> str:
"""Reduce any language hint to 'de', 'en', 'es' or 'pt'.
- Unknown / empty / None falls back to German because the user's
- primary chat language is German and STT defaults to DE on ambiguity.
+ Unknown / empty / None falls back to English (``DEFAULT_LOCALE``), the
+ one fallback language of every system phrase.
"""
- if not value:
- return "de"
- lower = value.lower()
- if lower.startswith("en"):
- return "en"
- if lower.startswith("es"):
- return "es"
- if lower.startswith("pt"):
- return "pt"
- return "de"
+ from jarvis.core.turn_language import normalize_language_tag
+ from jarvis.i18n import phrase_locale
+
+ return phrase_locale(normalize_language_tag(value))
def get_persona_prompt(language: str | None) -> str:
@@ -329,4 +323,6 @@ def get_persona_prompt(language: str | None) -> str:
return PERSONA_PROMPT_ES
if lang == "pt":
return PERSONA_PROMPT_PT
- return PERSONA_PROMPT_DE
+ if lang == "de":
+ return PERSONA_PROMPT_DE
+ return PERSONA_PROMPT_EN
diff --git a/jarvis/brain/ack_generator.py b/jarvis/brain/ack_generator.py
index 274ad11c0a..5d02303472 100644
--- a/jarvis/brain/ack_generator.py
+++ b/jarvis/brain/ack_generator.py
@@ -204,21 +204,15 @@ def _normalize_language(language: str | None) -> str:
The caller resolves the authoritative turn language through the ONE
resolver (jarvis/core/turn_language.py) and passes a concrete code, so
- 'es'/'pt' must survive here — collapsing them to 'de' would flip a Spanish turn's
- ack to German (a runtime-output-language doctrine violation). Anything
- unrecognised falls back to 'de' as the module's last resort; the real
- default-locale decision already happened upstream.
+ 'es'/'pt' must survive here — collapsing them to another language would
+ flip a Spanish turn's ack (a runtime-output-language doctrine violation).
+ Anything unrecognised falls back to English (``DEFAULT_LOCALE``), the one
+ fallback language of every system phrase.
"""
- if not language:
- return "de"
- low = language.lower()
- if low.startswith("en"):
- return "en"
- if low.startswith("es"):
- return "es"
- if low.startswith("pt"):
- return "pt"
- return "de"
+ from jarvis.core.turn_language import normalize_language_tag
+ from jarvis.i18n import phrase_locale
+
+ return phrase_locale(normalize_language_tag(language))
def _trim_to_words(text: str, max_chars: int) -> str:
@@ -802,7 +796,7 @@ def generate_ack(
tool_name: str,
tool_args: Mapping[str, Any] | None = None,
*,
- language: str = "de",
+ language: str = "en",
picker: AckPhrasePicker | None = None,
) -> str | None:
"""Render a short, task-specific ack string for the given tool call.
@@ -916,7 +910,7 @@ def describe_tool_action(
return "working on the request"
-def final_summary_marker(language: str = "de") -> str:
+def final_summary_marker(language: str = "en") -> str:
"""Return the short completion phrase ('Erledigt.' / 'Done.')."""
return _FINAL_MARKERS[_normalize_language(language)]
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index dee67e81c8..9e959572c5 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -52,6 +52,14 @@ from jarvis.brain.local_context import LOCAL_CONTEXT_MARKER
# the API-Keys badge can never disagree on "out of credits / over budget" (AP-22).
from jarvis.brain.provider_test import BILLING_LIMIT_MARKERS
from jarvis.brain.spawn_gate import effort_warrants_delegation
+from jarvis.brain.tool_shortlist import (
+ FIND_TOOLS_NAME,
+ ROLE_BASE,
+ FindToolsTool,
+ plan_surface,
+ tool_tokens,
+)
+from jarvis.brain.turn_override import TurnOverride
from jarvis.core.bus import EventBus
from jarvis.core.config import (
FORCE_SPAWN_MODE_BALANCED,
@@ -78,21 +86,23 @@ from jarvis.core.protocols import (
ReasoningEffort,
Tool,
)
-from jarvis.brain.tool_shortlist import (
- FIND_TOOLS_NAME,
- ROLE_BASE,
- FindToolsTool,
- plan_surface,
- tool_tokens,
-)
-from jarvis.brain.turn_override import TurnOverride
from jarvis.core.redact import safe_preview
from jarvis.core.response_style import CONVERSATIONAL_RESPONSE_STYLE
from jarvis.core.turn_language import (
DEFAULT_LOCALE,
+ TURN_LANGUAGE,
+ conversation_language_from_history,
detect_text_language,
+ resolve_conversation_language,
resolve_output_language,
- resolve_turn_language,
+)
+from jarvis.i18n import catalog as i18n_catalog
+from jarvis.i18n.locales import (
+ SUPPORTED_LANGUAGE_NAMES,
+ SUPPORTED_LOCALES,
+ is_known_language,
+ language_name,
+ phrase_locale,
)
from jarvis.memory import CoreMemory, PersonStore, RecallStore, Soul, UserProfile
from jarvis.memory.curator import Curator
@@ -1622,44 +1632,13 @@ def _extract_cli_error_line(stderr: str) -> str:
# Spoken CLI-failure readbacks; placeholders {cause} / {code}.
-_CLI_FAILURE_PHRASES: dict[str, dict[str, str]] = {
- "de": {
- "cause": "Der Befehl ist fehlgeschlagen: {cause}", # i18n-allow: German TTS
- "code": "Der Befehl ist mit Fehlercode {code} fehlgeschlagen.", # i18n-allow
- "bare": "Der Befehl ist fehlgeschlagen.", # i18n-allow: German TTS
- },
- "en": {
- "cause": "The command failed: {cause}",
- "code": "The command failed with exit code {code}.",
- "bare": "The command failed.",
- },
- "es": {
- "cause": "El comando ha fallado: {cause}", # i18n-allow: Spanish TTS
- "code": "El comando ha fallado con el código de error {code}.", # i18n-allow
- "bare": "El comando ha fallado.", # i18n-allow: Spanish TTS
- },
- "pt": {
- "cause": "O comando falhou: {cause}", # i18n-allow: PT TTS
- "code": "O comando falhou com o código de erro {code}.", # i18n-allow: PT TTS
- "bare": "O comando falhou.", # i18n-allow: PT TTS
- },
-}
+_CLI_FAILURE_PHRASES: dict[str, dict[str, str]] = i18n_catalog.locale_maps("brain.cli_failure")
# Spoken reply when a recovered tool ran but produced nothing speakable.
-_NOTHING_FOUND_PHRASE: dict[str, str] = {
- "de": "Dazu habe ich nichts gefunden.", # i18n-allow: spoken German TTS
- "en": "I couldn't find anything on that.",
- "es": "No he encontrado nada sobre eso.", # i18n-allow: Spanish TTS
- "pt": "Não encontrei nada sobre isso.", # i18n-allow: PT TTS
-}
+_NOTHING_FOUND_PHRASE: dict[str, str] = i18n_catalog.table("brain.nothing_found")
# Navigation fast-path acknowledgement; placeholder {label}.
-_NAVIGATION_ACK: dict[str, str] = {
- "de": "Öffne {label}.", # i18n-allow: German TTS
- "en": "Opening {label}.",
- "es": "Abriendo {label}.", # i18n-allow: Spanish TTS
- "pt": "A abrir {label}.", # i18n-allow: PT TTS
-}
+_NAVIGATION_ACK: dict[str, str] = i18n_catalog.table("brain.navigation_ack")
def _cli_failure_reason(output: Any, error: str | None, *, language: str) -> str:
@@ -1818,25 +1797,7 @@ def _answer_claims_unverified_data(response_text: str) -> bool:
return not _CONVERSATION_ATTRIBUTION_RE.search(text)
-_EVIDENCE_UNFULFILLED_PHRASES: dict[str, str] = {
- "de": (
- "Ich konnte das gerade nicht abrufen — der Zugriff über das passende " # i18n-allow: German TTS
- "Werkzeug ist nicht durchgelaufen. Sag noch mal Bescheid, dann " # i18n-allow: German TTS
- "versuche ich es erneut." # i18n-allow: German TTS
- ),
- "en": (
- "I couldn't retrieve that just now — the tool call didn't go through. "
- "Say the word and I'll try again."
- ),
- "es": (
- "No pude obtener eso ahora mismo — la llamada a la herramienta no se "
- "completó. Avísame y lo intento de nuevo."
- ),
- "pt": (
- "Não consegui obter isso agora — a chamada à ferramenta não foi concluída. Avisa-me e "
- "tento outra vez."
- ),
-}
+_EVIDENCE_UNFULFILLED_PHRASES: dict[str, str] = i18n_catalog.table("brain.evidence_unfulfilled")
# Spoken domain labels for the honest "couldn't reach X" fallback. Mirrors the
@@ -1845,66 +1806,15 @@ _EVIDENCE_UNFULFILLED_PHRASES: dict[str, str] = {
# instead of the generic "the tool" — which also seeds the conversation history
# so a follow-up "welches Werkzeug?" is answerable. Localized for every
# supported language; an unknown domain falls back to the generic phrase.
-_EVIDENCE_DOMAIN_LABELS: dict[str, dict[str, str]] = {
- "de": {
- "calendar": "deinen Kalender", # i18n-allow: German TTS
- "email": "dein Postfach", # i18n-allow: German TTS
- "tasks": "deine Aufgaben", # i18n-allow: German TTS
- "repos": "deine Repositories", # i18n-allow: German TTS
- "deployments": "deine Deployments", # i18n-allow: German TTS
- "cloud": "deine Cloud-Abrechnung", # i18n-allow: German TTS
- "activity": "deinen Aktivitätsverlauf", # i18n-allow: German TTS
- },
- "en": {
- "calendar": "your calendar",
- "email": "your inbox",
- "tasks": "your tasks",
- "repos": "your repositories",
- "deployments": "your deployments",
- "cloud": "your cloud billing",
- "activity": "your activity history",
- },
- "es": {
- "calendar": "tu calendario",
- "email": "tu bandeja de entrada",
- "tasks": "tus tareas",
- "repos": "tus repositorios",
- "deployments": "tus despliegues",
- "cloud": "tu facturación en la nube",
- "activity": "tu historial de actividad",
- },
- "pt": {
- "calendar": "o teu calendário",
- "email": "a tua caixa de entrada",
- "tasks": "as tuas tarefas",
- "repos": "os teus repositórios",
- "deployments": "as tuas implementações",
- "cloud": "a tua faturação na nuvem",
- "activity": "o teu histórico de atividade",
- },
-}
+_EVIDENCE_DOMAIN_LABELS: dict[str, dict[str, str]] = i18n_catalog.locale_maps(
+ "brain.evidence_domain_labels"
+)
# Domain-aware variant of the unfulfilled phrase — same honesty contract (never
# claims a "block"/invents a reason), just names the capability via {label}.
-_EVIDENCE_UNFULFILLED_DOMAIN_PHRASES: dict[str, str] = {
- "de": (
- "Ich konnte {label} gerade nicht abrufen — der Zugriff ist " # i18n-allow: German TTS
- "nicht durchgelaufen. Sag noch mal Bescheid, dann versuche " # i18n-allow: German TTS
- "ich es erneut." # i18n-allow: German TTS
- ),
- "en": (
- "I couldn't pull {label} just now — the access didn't go through. "
- "Say the word and I'll try again."
- ),
- "es": (
- "No pude obtener {label} ahora mismo — el acceso no se completó. "
- "Avísame y lo intento de nuevo."
- ),
- "pt": (
- "Não consegui obter {label} agora — o acesso não foi concluído. Avisa-me e tento outra "
- "vez."
- ),
-}
+_EVIDENCE_UNFULFILLED_DOMAIN_PHRASES: dict[str, str] = i18n_catalog.table(
+ "brain.evidence_unfulfilled_domain"
+)
def _evidence_unfulfilled_answer(*, lang: str, domain: str = "") -> str:
@@ -1930,81 +1840,9 @@ def _evidence_unfulfilled_answer(*, lang: str, domain: str = "") -> str:
# while no contact was saved). Distinct from the READ fallback above: it speaks
# to a write ("not saved yet"), not a failed lookup. Static, no LLM (AP-11);
# localized for every supported language, unknown code → default locale.
-_ACTION_UNFULFILLED_PHRASES: dict[str, dict[str, str]] = {
- "society_propose_change": {
- "de": (
- "Die Routine wurde nicht erstellt. " # i18n-allow: runtime output
- "Der Speichervorgang wurde nicht ausgeführt." # i18n-allow: runtime output
- ),
- "en": "The routine was not created. The save action did not run.",
- "es": (
- "La rutina no se creó. " # i18n-allow: runtime output
- "No se ejecutó la acción de guardarla." # i18n-allow: runtime output
- ),
- "pt": "A rotina não foi criada. A ação de a guardar não chegou a ser executada.",
- },
- "society-create-routine": {
- "de": (
- "Die Routine wurde nicht erstellt. " # i18n-allow: runtime output
- "Der Speichervorgang wurde nicht ausgeführt." # i18n-allow: runtime output
- ),
- "en": "The routine was not created. The save action did not run.",
- "es": (
- "La rutina no se creó. " # i18n-allow: runtime output
- "No se ejecutó la acción de guardarla." # i18n-allow: runtime output
- ),
- "pt": "A rotina não foi criada. A ação de a guardar não chegou a ser executada.",
- },
- "contact-upsert": {
- "de": (
- "Ich hab den Kontakt noch nicht gespeichert — sag mir die Angaben " # i18n-allow: German TTS
- "noch mal, dann lege ich ihn an." # i18n-allow: German TTS
- ),
- "en": (
- "I haven't actually saved that contact yet — give me the details "
- "once more and I'll add it."
- ),
- "es": (
- "Todavía no he guardado ese contacto — dime los datos otra vez y lo "
- "añado."
- ),
- "pt": "Ainda não guardei esse contacto — diz-me os dados outra vez e eu adiciono-o.",
- },
- "wiki-ingest": {
- "de": (
- "Ich hab das noch nicht in deinem Wiki vermerkt — sag's noch mal, " # i18n-allow: German TTS
- "dann schreib ich's rein." # i18n-allow: German TTS
- ),
- "en": (
- "I haven't actually noted that in your wiki yet — say it once more "
- "and I'll write it down."
- ),
- "es": (
- "Todavía no lo he anotado en tu wiki — dímelo otra vez y lo escribo."
- ),
- "pt": "Ainda não o anotei na tua wiki — diz-mo outra vez e eu escrevo-o.",
- },
- # Local-outcome mandate (shell-consistency rework 2026-08-08): a mandated
- # run_shell that never ran must not degrade to the contact wording.
- "run_shell": {
- "de": (
- "Das hab ich noch nicht ausgeführt — der Befehl ist nicht " # i18n-allow: German TTS
- "gelaufen. Sag's noch mal, dann mache ich es direkt." # i18n-allow: German TTS
- ),
- "en": (
- "I haven't actually done that yet — the command never ran. "
- "Say it once more and I'll do it right away."
- ),
- "es": (
- "Todavía no lo he hecho — el comando no llegó a ejecutarse. "
- "Dímelo otra vez y lo hago directamente."
- ),
- "pt": (
- "Ainda não o fiz — o comando não chegou a ser executado. Diz-mo outra vez e faço-o "
- "diretamente."
- ),
- },
-}
+_ACTION_UNFULFILLED_PHRASES: dict[str, dict[str, str]] = i18n_catalog.nested_table(
+ "brain.action_unfulfilled"
+)
# A write tool with no bespoke table reuses the contact wording's shape.
_ACTION_UNFULFILLED_DEFAULT = _ACTION_UNFULFILLED_PHRASES["contact-upsert"]
@@ -2017,7 +1855,7 @@ def _action_unfulfilled_answer(required_tool: str, *, lang: str) -> str:
the contact wording / default locale so the spoken turn never crashes.
"""
table = _ACTION_UNFULFILLED_PHRASES.get(required_tool, _ACTION_UNFULFILLED_DEFAULT)
- return table.get(lang, table.get(DEFAULT_LOCALE, table["de"]))
+ return i18n_catalog.pick(table, lang)
def _unfulfilled_replacement(
@@ -2186,39 +2024,24 @@ def _extract_leaked_tool_call(text: str) -> tuple[str, dict[str, Any]] | None:
# Single source of truth for the reply-language vocabulary (Python ↔ REST ↔ TS).
# "auto" = mirror the user's input language; the rest hard-pin that language.
-SUPPORTED_REPLY_LANGUAGES: tuple[str, ...] = ("auto", "de", "en", "es", "pt")
+SUPPORTED_REPLY_LANGUAGES: tuple[str, ...] = ("auto", *SUPPORTED_LOCALES)
_REPLY_LANGS: frozenset[str] = frozenset(SUPPORTED_REPLY_LANGUAGES)
-_REPLY_LANG_NAMES: dict[str, str] = {
- "de": "German",
- "en": "English",
- "es": "Spanish",
- "pt": "European Portuguese",
-}
+_REPLY_LANG_NAMES: dict[str, str] = dict(SUPPORTED_LANGUAGE_NAMES)
# Spoken confirmation for a deterministic reply-language switch (the
# voice_command_gate "language_switch" path). Keyed by target code and phrased
# IN that language so — because set_reply_language() runs first — the TTS voice
# resolves to the new language and the switch is audible. "auto" has no single
-# language, so it confirms in the default locale (German).
-_LANG_SWITCH_CONFIRM: dict[str, str] = {
- "de": "Erledigt — ich antworte ab jetzt auf Deutsch.",
- "en": "Done — I'll reply in English from now on.",
- "es": "Listo — a partir de ahora respondo en español.",
- "pt": "Feito — a partir de agora respondo em português.",
- "auto": "Erledigt — ich passe meine Sprache ab jetzt automatisch deiner an.",
-}
+# language, so it confirms in the conversation's phrase language
+# (``brain.lang_switch_confirm_auto``; English for an unsupported one).
+_LANG_SWITCH_CONFIRM: dict[str, str] = i18n_catalog.table("brain.lang_switch_confirm")
# Spoken when the live reply-language switch applied but PERSIST failed (read-only
# / locked jarvis.toml). Honest: scoped to this session, not "from now on", because
# it reverts on restart (audit 2026-06-27). de/en/es/pt.
-_LANG_SWITCH_CONFIRM_SESSION: dict[str, str] = {
- "de": "Für diese Sitzung antworte ich auf Deutsch — dauerhaft speichern hat nicht geklappt.",
- "en": "For this session I'll reply in English — saving it permanently didn't work.",
- "es": "Por esta sesión responderé en español — no pude guardarlo de forma permanente.",
- "pt": (
- "Nesta sessão vou responder em português — não consegui guardar isto de forma permanente."
- ),
-}
+_LANG_SWITCH_CONFIRM_SESSION: dict[str, str] = i18n_catalog.table(
+ "brain.lang_switch_confirm_session"
+)
# Sub-agent (Heavy-Task worker) provider switch — the voice_command_gate
# "subagent_switch" path. The gate returns the spoken provider word; this maps
@@ -2248,107 +2071,46 @@ _SUBAGENT_DISPLAY: dict[str, str] = {
"antigravity": "Antigravity",
"grok-build": "Grok Build",
}
-_SUBAGENT_SWITCH_CONFIRM: dict[str, str] = {
- "de": "Erledigt — dein Sub-Agent läuft ab der nächsten Mission auf {p}.",
- "en": "Done — your sub-agent will run on {p} from your next mission.",
- "es": "Listo — tu sub-agente usará {p} desde tu próxima misión.",
- "pt": "Feito — o teu subagente vai usar {p} a partir da tua próxima missão.",
-}
+_SUBAGENT_SWITCH_CONFIRM: dict[str, str] = i18n_catalog.table("brain.subagent_switch_confirm")
# Honest spoken failure phrases for a deterministic subagent switch that the
# validated apply_provider_switch refused (missing credential / unknown). Never
# a false "done"; always names what failed. de/en/es/pt (Runtime Output Language).
-_SUBAGENT_SWITCH_FAIL: dict[str, dict[str, str]] = {
- "missing_credential": {
- "de": "{p} ist nicht verbunden — richte es zuerst ein, dann stelle ich um.",
- "en": "{p} isn't connected — set it up first, then I'll switch.",
- "es": "{p} no está conectado — configúralo primero y luego cambio.",
- "pt": "{p} não está ligado — configura-o primeiro e depois eu mudo.",
- },
- "other": {
- "de": "Das konnte ich nicht auf {p} umstellen.",
- "en": "I couldn't switch the sub-agent to {p}.",
- "es": "No pude cambiar el sub-agente a {p}.",
- "pt": "Não consegui mudar o subagente para {p}.",
- },
-}
+_SUBAGENT_SWITCH_FAIL: dict[str, dict[str, str]] = i18n_catalog.nested_table(
+ "brain.subagent_switch_fail"
+)
def _subagent_switch_failure_phrase(result: dict, display: str, lang: str) -> str:
kind = str(result.get("error_kind") or "other")
table = _SUBAGENT_SWITCH_FAIL.get(kind, _SUBAGENT_SWITCH_FAIL["other"])
- return table.get(lang, table["de"]).format(p=display)
+ return i18n_catalog.pick(table, lang).format(p=display)
# Main-brain provider switch — the voice_command_gate "provider_switch" path.
# Mirrors the subagent tables: routed through the validated apply_provider_switch
# so the spoken readback is HONEST (audit 2026-06-27: the old path returned ""
# silently, even when the switch was refused). de/en/es/pt (Runtime Output Language).
-_PROVIDER_SWITCH_CONFIRM: dict[str, str] = {
- "de": "Erledigt — dein Haupt-Brain läuft jetzt auf {p}.",
- "en": "Done — your main brain now runs on {p}.",
- "es": "Listo — tu cerebro principal ahora usa {p}.",
- "pt": "Feito — o teu cérebro principal usa agora {p}.",
-}
-_PROVIDER_SWITCH_FAIL: dict[str, dict[str, str]] = {
- "missing_credential": {
- "de": "{p} ist nicht eingerichtet — hinterlege zuerst den Schlüssel, dann stelle ich um.",
- "en": "{p} isn't set up — add its key first, then I'll switch.",
- "es": "{p} no está configurado — añade su clave primero y luego cambio.",
- "pt": "{p} não está configurado — adiciona primeiro a chave e depois eu mudo.",
- },
- "subagent_only": {
- "de": "{p} geht nur als Sub-Agent, nicht als Haupt-Brain.",
- "en": "{p} only works as a sub-agent, not as the main brain.",
- "es": "{p} solo funciona como sub-agente, no como cerebro principal.",
- "pt": "{p} só funciona como subagente, não como cérebro principal.",
- },
- "other": {
- "de": "Den Haupt-Brain konnte ich nicht auf {p} umstellen.",
- "en": "I couldn't switch the main brain to {p}.",
- "es": "No pude cambiar el cerebro principal a {p}.",
- "pt": "Não consegui mudar o cérebro principal para {p}.",
- },
-}
+_PROVIDER_SWITCH_CONFIRM: dict[str, str] = i18n_catalog.table("brain.provider_switch_confirm")
+_PROVIDER_SWITCH_FAIL: dict[str, dict[str, str]] = i18n_catalog.nested_table(
+ "brain.provider_switch_fail"
+)
def _provider_switch_failure_phrase(result: dict, display: str, lang: str) -> str:
kind = str(result.get("error_kind") or "other")
table = _PROVIDER_SWITCH_FAIL.get(kind, _PROVIDER_SWITCH_FAIL["other"])
- return table.get(lang, table["de"]).format(p=display)
+ return i18n_catalog.pick(table, lang).format(p=display)
# Background-task cancel — the voice_command_gate "cancel" path. Honest readback:
# names the count when something was stopped, says so plainly when nothing ran
# (audit 2026-06-27: the old path was silent either way). de/en/es/pt.
-_CANCEL_CONFIRM: dict[str, str] = {
- "de": "Erledigt — {n} laufende Aufgabe(n) gestoppt.",
- "en": "Done — stopped {n} running task(s).",
- "es": "Listo — detuve {n} tarea(s) en curso.",
- "pt": "Feito — parei {n} tarefa(s) em curso.",
-}
-_CANCEL_NONE: dict[str, str] = {
- "de": "Es lief gerade nichts, das ich stoppen könnte.",
- "en": "Nothing was running to stop.",
- "es": "No había nada en curso que detener.",
- "pt": "Não havia nada em curso para parar.",
-}
+_CANCEL_CONFIRM: dict[str, str] = i18n_catalog.table("brain.cancel_confirm")
+_CANCEL_NONE: dict[str, str] = i18n_catalog.table("brain.cancel_none")
# Thinking-depth override — the voice_command_gate "depth_deep"/"depth_fast"
# path. Confirms the new depth instead of staying silent (audit 2026-06-27).
-_DEPTH_CONFIRM: dict[str, dict[str, str]] = {
- "deep": {
- "de": "Alles klar — ich denke ab jetzt gründlicher.",
- "en": "Got it — I'll think more deeply from now on.",
- "es": "Entendido — pensaré más a fondo a partir de ahora.",
- "pt": "Entendido — a partir de agora vou pensar com mais profundidade.",
- },
- "fast": {
- "de": "Alles klar — ich denke ab jetzt schneller.",
- "en": "Got it — I'll think faster from now on.",
- "es": "Entendido — pensaré más rápido a partir de ahora.",
- "pt": "Entendido — a partir de agora vou pensar mais depressa.",
- },
-}
+_DEPTH_CONFIRM: dict[str, dict[str, str]] = i18n_catalog.nested_table("brain.depth_confirm")
# General self-control (2026-06-22). Not every settings change can have its own
# deterministic gate — the gates (language, sub-agent) are high-precision
@@ -2545,39 +2307,9 @@ def normalize_reply_language(value: object) -> str:
# language (de/en/es/pt; "auto" → German, the default locale). Three variants
# per language so repeated failures in one session don't sound robotic
# (mirrors the ACK-variant approach). The full diagnostic stays in the logs.
-_PROVIDER_DOWN_PHRASES: dict[str, tuple[str, ...]] = {
- "de": (
- "Entschuldige, ich komme gerade nicht an mein Sprachmodell. Einen Moment, bitte.", # i18n-allow
- (
- "Tut mir leid, mein Sprachmodell ist im Moment nicht erreichbar. " # i18n-allow
- "Ich versuche es gleich erneut."
- ),
- (
- "Ich kann gerade nicht antworten — die Verbindung zu meinem Modell hakt. " # i18n-allow
- "Gib mir kurz Zeit."
- ),
- ),
- "en": (
- "Sorry, I can't reach my language model right now. One moment, please.",
- "I'm afraid my language model is unavailable at the moment. I'll try again shortly.",
- "I can't answer just now — my connection to the model is failing. Give me a second.",
- ),
- "es": (
- "Lo siento, ahora mismo no puedo acceder a mi modelo de lenguaje. Un momento, por favor.",
- (
- "Me temo que mi modelo de lenguaje no está disponible en este momento. "
- "Lo intentaré de nuevo enseguida."
- ),
- "No puedo responder ahora mismo: la conexión con mi modelo está fallando. Dame un segundo.",
- ),
- "pt": (
- "Desculpa, neste momento não consigo aceder ao meu modelo de linguagem. Um momento, por "
- "favor.",
- "Receio que o meu modelo de linguagem não esteja disponível neste momento. Volto a "
- "tentar já a seguir.",
- "Não consigo responder agora: a ligação ao meu modelo está a falhar. Dá-me um segundo.",
- ),
-}
+_PROVIDER_DOWN_PHRASES: dict[str, tuple[str, ...]] = i18n_catalog.variant_table(
+ "brain.provider_down"
+)
# Cause-aware variants of the total-failure apology (maintainer directive
@@ -2587,208 +2319,9 @@ _PROVIDER_DOWN_PHRASES: dict[str, tuple[str, ...]] = {
# in-app recovery step. Keys mirror the ``kind`` values classified by the
# provider chain (``_format_provider_chain_error``); an unknown/unlisted kind
# falls back to the generic rotation above.
-_PROVIDER_DOWN_CAUSE_PHRASES: dict[str, dict[str, str]] = {
- "missing_key": {
- "de": (
- "Entschuldige — für mein Sprachmodell ist gerade kein " # i18n-allow
- "API-Schlüssel hinterlegt. Öffne in der Seitenleiste die " # i18n-allow
- "API-Keys und trag einen ein, dann geht es sofort weiter." # i18n-allow
- ),
- "en": (
- "Sorry — no API key is set for my language model right now. "
- "Open the API keys in the sidebar and add one, and I can "
- "continue right away."
- ),
- "es": (
- "Lo siento: ahora mismo no hay ninguna clave de API configurada "
- "para mi modelo de lenguaje. Abre las claves de API en la barra "
- "lateral y añade una, y podré continuar enseguida."
- ),
- "pt": (
- "Desculpa: neste momento não há nenhuma chave de API configurada para o meu modelo "
- "de linguagem. Abre as chaves de API na barra lateral e adiciona uma, e posso "
- "continuar já a seguir."
- ),
- },
- "bad_key": {
- "de": (
- "Entschuldige — mein hinterlegter API-Schlüssel wird abgelehnt, " # i18n-allow
- "er ist wohl ungültig oder abgelaufen. Bitte ersetze ihn in den " # i18n-allow
- "API-Keys in der Seitenleiste." # i18n-allow
- ),
- "en": (
- "Sorry — my stored API key is being rejected; it looks invalid "
- "or expired. Please replace it under API keys in the sidebar."
- ),
- "es": (
- "Lo siento: mi clave de API almacenada está siendo rechazada; "
- "parece inválida o caducada. Sustitúyela en las claves de API "
- "de la barra lateral."
- ),
- "pt": (
- "Desculpa: a minha chave de API guardada está a ser rejeitada; parece inválida ou "
- "expirada. Substitui-a nas chaves de API da barra lateral."
- ),
- },
- "account_blocked": {
- "de": (
- "Entschuldige — das Konto meines Sprachmodells blockiert gerade, " # i18n-allow
- "vermutlich ist das Guthaben aufgebraucht oder das Limit " # i18n-allow
- "erreicht. Bitte wirf einen Blick auf das Anbieter-Konto." # i18n-allow
- ),
- "en": (
- "Sorry — my language model's account is blocking right now, "
- "most likely the credit is used up or a limit was reached. "
- "Please take a look at the provider account."
- ),
- "es": (
- "Lo siento: la cuenta de mi modelo de lenguaje está bloqueada "
- "ahora mismo; probablemente se agotó el crédito o se alcanzó un "
- "límite. Revisa la cuenta del proveedor, por favor."
- ),
- "pt": (
- "Desculpa: a conta do meu modelo de linguagem está bloqueada neste momento; "
- "provavelmente o crédito esgotou-se ou foi atingido um limite. Verifica a conta do "
- "fornecedor, por favor."
- ),
- },
- "rate_limit": {
- "de": (
- "Entschuldige — mein Anbieter bremst mich gerade wegen zu " # i18n-allow
- "vieler Anfragen. Warte einen Moment und frag mich dann " # i18n-allow
- "einfach noch einmal." # i18n-allow
- ),
- "en": (
- "Sorry — my provider is throttling me for too many requests. "
- "Give it a moment and just ask me again."
- ),
- "es": (
- "Lo siento: mi proveedor me está limitando por demasiadas "
- "solicitudes. Espera un momento y vuelve a preguntarme."
- ),
- "pt": (
- "Desculpa: o meu fornecedor está a limitar-me por excesso de pedidos. Espera um "
- "momento e volta a perguntar-me."
- ),
- },
- "invalid_model": {
- "de": (
- "Entschuldige — das eingestellte Modell wird vom Anbieter nicht " # i18n-allow
- "akzeptiert. Bitte prüf die Modell-Auswahl in den Einstellungen." # i18n-allow
- ),
- "en": (
- "Sorry — the configured model is not accepted by the provider. "
- "Please check the model selection in the settings."
- ),
- "es": (
- "Lo siento: el modelo configurado no es aceptado por el "
- "proveedor. Revisa la selección de modelo en los ajustes."
- ),
- "pt": (
- "Desculpa: o modelo configurado não é aceite pelo fornecedor. Verifica a escolha do "
- "modelo nas definições."
- ),
- },
- "context_overflow": {
- "de": (
- "Entschuldige — diese Anfrage ist für das eingestellte Modell zu " # i18n-allow
- "groß, sein Kontextfenster reicht dafür nicht. Wähle ein Modell " # i18n-allow
- "mit größerem Kontext oder starte einen neuen Chat." # i18n-allow
- ),
- "en": (
- "Sorry — this request is too large for the configured model; its "
- "context window is too small for it. Pick a model with a larger "
- "context or start a new chat."
- ),
- "es": (
- "Lo siento: esta solicitud es demasiado grande para el modelo "
- "configurado; su ventana de contexto no alcanza. Elige un modelo "
- "con más contexto o empieza un chat nuevo."
- ),
- "pt": (
- "Desculpa: este pedido é demasiado grande para o modelo configurado; a janela de "
- "contexto não chega. Escolhe um modelo com mais contexto ou começa uma conversa nova."
- ),
- },
- # A LOCAL server runs the model with a window too small for the request
- # (``jarvis.brain.local_context``). Unlike ``context_overflow`` the remedy
- # is not another model or a new chat but one setting on the user's own
- # machine, so the phrase names that setting.
- "local_context": {
- "de": (
- "Entschuldige — dein lokales Modell läuft mit einem zu kleinen " # i18n-allow
- "Kontextfenster für diese Anfrage. Stell in deinem lokalen " # i18n-allow
- "Modell-Server eine größere Kontextlänge ein und lade das Modell " # i18n-allow
- "neu; bei den Modellen unter Lokale Modelle geht das über Tune. " # i18n-allow
- "Die nötige Größe steht im Protokoll." # i18n-allow
- ),
- "en": (
- "Sorry — your local model runs with a context window too small "
- "for this request. Raise the context length in your local model "
- "server and reload the model; for the models under Local Models, "
- "use Tune. The log names the size it needs."
- ),
- "es": (
- "Lo siento: tu modelo local funciona con una ventana de contexto "
- "demasiado pequeña para esta solicitud. Aumenta la longitud de "
- "contexto en tu servidor de modelos local y vuelve a cargar el "
- "modelo; para los modelos de Modelos locales, usa Tune. El "
- "registro indica el tamaño necesario."
- ),
- "pt": (
- "Desculpa: o teu modelo local corre com uma janela de contexto demasiado pequena "
- "para este pedido. Aumenta o comprimento de contexto no teu servidor de modelos "
- "local e recarrega o modelo; para os modelos em Modelos locais, usa Tune. O "
- "registo indica o tamanho necessário."
- ),
- },
- "unreachable": {
- "de": (
- "Entschuldige — ich erreiche meinen Anbieter gerade nicht, " # i18n-allow
- "vermutlich ein Netzwerk- oder Anbieterproblem. Versuch es " # i18n-allow
- "gleich bitte noch einmal." # i18n-allow
- ),
- "en": (
- "Sorry — I can't reach my provider right now, likely a network "
- "or provider issue. Please try again in a moment."
- ),
- "es": (
- "Lo siento: no puedo comunicarme con mi proveedor ahora mismo; "
- "probablemente sea un problema de red o del proveedor. Inténtalo "
- "de nuevo en un momento."
- ),
- "pt": (
- "Desculpa: neste momento não consigo comunicar com o meu fornecedor; provavelmente é "
- "um problema de rede ou do fornecedor. Tenta outra vez daqui a um momento."
- ),
- },
- # A screen capture or attachment exists, but every reachable brain is blind.
- # This is NOT a missing/invalid API key — the key is often present and
- # the API-Keys card is green; the model simply cannot inspect images.
- # Spoken separately so a vision skip is not heard as "your key is broken".
- "vision_unsupported": {
- "de": (
- "Entschuldige — keiner " # i18n-allow
- "der verbundenen Assistenten kann gerade Bilder auswerten. Der " # i18n-allow
- "Schlüssel ist da, nur das Sehen fehlt. Nimm unter API-Keys " # i18n-allow
- "einen Anbieter mit Bildverarbeitung." # i18n-allow
- ),
- "en": (
- "Sorry — none of the connected "
- "assistants can inspect images right now. The key is there; "
- "vision is not. Pick a vision-capable provider under API keys."
- ),
- "es": (
- "Lo siento: ninguno de los asistentes "
- "conectados puede analizar imágenes ahora. La clave está; falta "
- "la visión. Elige un proveedor con visión en Claves API."
- ),
- "pt": (
- "Desculpa: nenhum dos assistentes ligados consegue analisar imagens agora. A chave "
- "existe; falta a visão. Escolhe um fornecedor com visão em Chaves de API."
- ),
- },
-}
+_PROVIDER_DOWN_CAUSE_PHRASES: dict[str, dict[str, str]] = i18n_catalog.nested_table(
+ "brain.provider_down_cause"
+)
# Priority when several providers failed for different reasons — the FIRST
# matching kind names the spoken cause. Mirrors the root-cause ordering of
@@ -2842,7 +2375,8 @@ def _provider_down_phrase(lang: str, idx: int, cause: str | None = None) -> str:
"""Localized apology for a total brain-chain failure, cause-aware.
``lang`` is a reply-language code (de/en/es/pt); anything else — notably
- "auto" — falls back to German (the default locale). When ``cause`` names
+ "auto" or a language without translations — falls back to English
+ (``DEFAULT_LOCALE``). When ``cause`` names
a known failure category, the phrase states WHY and the in-app recovery
step (maintainer directive 2026-07-21) — still without provider names,
URLs, or jargon (ADR-0010). Otherwise ``idx`` rotates deterministically
@@ -2853,8 +2387,8 @@ def _provider_down_phrase(lang: str, idx: int, cause: str | None = None) -> str:
if cause:
cause_table = _PROVIDER_DOWN_CAUSE_PHRASES.get(cause)
if cause_table:
- return cause_table.get(lang_key, cause_table["de"])
- variants = _PROVIDER_DOWN_PHRASES.get(lang_key, _PROVIDER_DOWN_PHRASES["de"])
+ return i18n_catalog.pick(cause_table, lang_key)
+ variants = i18n_catalog.pick(_PROVIDER_DOWN_PHRASES, lang_key)
return variants[idx % len(variants)]
@@ -2864,24 +2398,7 @@ def _provider_down_phrase(lang: str, idx: int, cause: str | None = None) -> str:
# executed tools; the empty-response guard is (correctly) skipped when tool
# calls exist, so the turn counted as success with empty text — the user heard
# NOTHING. Voice-safe: no provider names, no jargon (ADR-0010).
-_MID_ANSWER_ERROR_PHRASES: dict[str, str] = {
- "de": (
- "Ich habe die Zwischenschritte ausgeführt, aber beim Formulieren der " # i18n-allow
- "Antwort gab es einen Fehler. Frag mich bitte gleich noch einmal." # i18n-allow
- ),
- "en": (
- "I ran the steps, but something went wrong while composing the answer. "
- "Please ask me again in a moment."
- ),
- "es": (
- "Ejecuté los pasos, pero algo falló al redactar la respuesta. "
- "Vuelve a preguntarme en un momento."
- ),
- "pt": (
- "Executei os passos, mas algo falhou ao redigir a resposta. Volta a perguntar-me daqui a "
- "um momento."
- ),
-}
+_MID_ANSWER_ERROR_PHRASES: dict[str, str] = i18n_catalog.table("brain.mid_answer_error")
#: Source layers that run without a person waiting on the reply. An appshot
@@ -2903,6 +2420,37 @@ def _takes_pending_appshot(source_layer: str | None) -> bool:
return not layer.startswith(_AUTOMATED_LAYER_PREFIXES)
+def _current_turn_language(owner: object) -> str:
+ """This turn's language: the context's own, else the last one set."""
+ return TURN_LANGUAGE.get() or getattr(owner, "_turn_detected_lang", "")
+
+
+def _turn_phrase_language(owner: object, user_text: str) -> str:
+ """The de/en/es/pt language of a system phrase for *user_text*.
+
+ One resolver for every canned phrase: the pin, else the language
+ ``generate()`` resolved for this turn (which already applied stickiness,
+ the chat's own history and ``language_text`` — so an internal English
+ "continue" prompt does not make the error phrases English), else the text
+ within the running conversation, else English. ``generate()`` only
+ receives text (the pipeline resolves the STT tag separately), hence
+ ``"unknown"`` as the tag. Reads the manager's fields with ``getattr`` so
+ lightweight stand-ins work too.
+ """
+ pin = getattr(owner, "_reply_language", "")
+ if pin in _REPLY_LANG_NAMES:
+ return pin
+ turn = TURN_LANGUAGE.get()
+ if turn:
+ return phrase_locale(turn) if is_known_language(turn) else DEFAULT_LOCALE
+ return resolve_output_language(
+ pin,
+ "unknown",
+ user_text,
+ conversation_language=getattr(owner, "_conversation_language", ""),
+ )
+
+
class BrainManager:
"""Top-level orchestrator with intent router and smart fallback."""
@@ -4059,13 +3607,7 @@ class BrainManager:
if is_voice_control_utterance(user_text):
return None
bus = self._bus
- language = resolve_output_language(
- self._reply_language,
- "unknown",
- user_text,
- default=DEFAULT_LOCALE,
- conversation_language=self._conversation_language,
- )
+ language = _turn_phrase_language(self, user_text)
# Fire at most once per turn even if the provider chain retries the
# tool-use loop (a provider that emits tool_calls then errors would
# otherwise re-announce on the fallback provider's re-run).
@@ -4184,7 +3726,10 @@ class BrainManager:
@property
def conversation_language(self) -> str:
- """The sticky language of the conversation so far (de/en/es/pt, or "").
+ """The sticky language of the conversation so far (any code, or "").
+
+ de/en/es/pt or a language without translated phrases ("tr", "fr", ...);
+ consumers narrow it with ``resolve_output_language``/``phrase_locale``.
Read by the speech pipeline and threaded into deterministic tool
readbacks so a thin interjection ("Now") stays in the running
@@ -4207,17 +3752,37 @@ class BrainManager:
if self._reply_language in _REPLY_LANG_NAMES:
self._turn_detected_lang = ""
return
- detected = resolve_output_language(
+ detected = resolve_conversation_language(
self._reply_language,
None,
user_text,
- default="unknown",
- conversation_language=self._conversation_language,
+ conversation_language=self._conversation_baseline(),
)
self._turn_detected_lang = detected
- if detected in _REPLY_LANG_NAMES:
+ if TURN_LANGUAGE.get() is not None: # inside generate(): scope it to the turn
+ TURN_LANGUAGE.set(detected)
+ if is_known_language(detected):
self._conversation_language = detected
+ def _conversation_baseline(self) -> str:
+ """The conversation language this turn continues.
+
+ A chat turn carries its session's own history (``history_override``):
+ its language comes from THAT conversation, so a crash, a restart or a
+ turn in another chat or on voice never changes it (forensic
+ 2026-10-19: a Turkish chat answered in German, Spanish and English
+ after errors). A classic turn without a known language yet replays the
+ live history once.
+ """
+ history = _TURN_HISTORY_OVERRIDE.get()
+ if history is not None:
+ # Only this chat's own history: never a language another chat or
+ # a voice call left in the shared field.
+ return conversation_language_from_history(history)
+ if self._conversation_language:
+ return self._conversation_language
+ return conversation_language_from_history(getattr(self, "_history", None) or ())
+
def set_reply_language(self, lang: str) -> None:
"""Live-switch the reply-language pin (desktop "Languages" view).
@@ -4240,13 +3805,17 @@ class BrainManager:
transcript language is consistent and never the binary ``_looks_german``
gate — which silently tags any non-German reply "en" and so drops Spanish
(Runtime Output Language doctrine). An explicit pin wins; in auto mode it
- is THIS turn's detected language (set at the top of generate()); an
- undetected/ambiguous turn keeps the German default.
+ is THIS turn's language (set at the top of generate()), else the
+ conversation's. A language without translated phrases, or none at all,
+ is English (``DEFAULT_LOCALE``) — never German.
"""
lang = self._reply_language
if lang not in _REPLY_LANG_NAMES:
- lang = getattr(self, "_turn_detected_lang", "") or lang
- return lang if lang in _REPLY_LANG_NAMES else "de"
+ turn = _current_turn_language(self)
+ lang = turn if is_known_language(turn) else getattr(
+ self, "_conversation_language", ""
+ )
+ return lang if lang in _REPLY_LANG_NAMES else DEFAULT_LOCALE
def _next_provider_down_phrase(self, cause: str | None = None) -> str:
"""Localized 'I can't reach my model' apology + advance the rotation.
@@ -4336,7 +3905,9 @@ class BrainManager:
# the soft mirror. The pin only changes when the user's language
# changes, so the cached system prefix stays stable within a
# single-language conversation.
- turn_name = _REPLY_LANG_NAMES.get(getattr(self, "_turn_detected_lang", ""))
+ # Any recognised language pins, not only the four with translated
+ # phrases: a Turkish conversation is answered in Turkish.
+ turn_name = language_name(_current_turn_language(self))
if turn_name is not None:
return self._mandatory_lang_directive(turn_name)
return (
@@ -4355,32 +3926,25 @@ class BrainManager:
Spoken when a provider leaked a tool_use block as text and the
recovery produced no speakable final. Was a hardcoded German string —
an English turn ("What's weather like tomorrow?") was answered in
- German. A pinned reply language wins; ``auto`` mirrors the user's
- text; ambiguous text keeps the historical German default.
-
- ``generate()`` only ever receives ``user_text`` (the pipeline resolves
- the STT tag separately), so auto-mode detection is text-only — hence
- ``"unknown"`` as the tag. See ``tool_use_loop._localized_phrase`` for
- the same contract.
+ German. A pinned reply language wins; ``auto`` follows the
+ conversation; anything else is English.
"""
- lang = self._reply_language
- if lang not in _ACTION_FAILED_PHRASES:
- lang = resolve_turn_language("unknown", user_text, default="de")
- return _ACTION_FAILED_PHRASES.get(lang, _ACTION_FAILED_PHRASES["de"])
+ return i18n_catalog.pick(_ACTION_FAILED_PHRASES, _turn_phrase_language(self, user_text))
+
+ def _phrase_language(self, user_text: str) -> str:
+ """The de/en/es/pt language of a system phrase for *user_text*."""
+ return _turn_phrase_language(self, user_text)
def _direct_ack_language(self, user_text: str) -> str:
"""Resolve ``de``/``en``/``es`` for a DIRECT fast-path acknowledgement.
Mirrors :meth:`_action_failed_phrase`: an explicit ``reply_language``
pin (the desktop "Languages" view) wins; otherwise the turn's language
- is detected from the text; ambiguous text keeps the historical German
- default. The DIRECT path runs off the LLM, so this is the only place the
- turn language can be applied to the spoken acknowledgement.
+ within the running conversation; anything else is English. The DIRECT
+ path runs off the LLM, so this is the only place the turn language can
+ be applied to the spoken acknowledgement.
"""
- lang = self._reply_language
- if lang in _OPEN_APP_ACK_PREFIX:
- return lang
- return resolve_turn_language("unknown", user_text, default="de")
+ return _turn_phrase_language(self, user_text)
def _localize_direct_ack(
self, call: LocalToolCall, raw_output: str, lang: str
@@ -5138,8 +4702,10 @@ class BrainManager:
lang, persisted,
)
if persisted:
- return _LANG_SWITCH_CONFIRM.get(lang, _LANG_SWITCH_CONFIRM["de"])
- return _LANG_SWITCH_CONFIRM_SESSION.get(lang, _LANG_SWITCH_CONFIRM_SESSION["de"])
+ if lang == "auto":
+ return i18n_catalog.t("brain.lang_switch_confirm_auto", self._resolve_turn_lang())
+ return i18n_catalog.pick(_LANG_SWITCH_CONFIRM, lang)
+ return i18n_catalog.pick(_LANG_SWITCH_CONFIRM_SESSION, lang)
def _is_self_control_turn(self, text: str) -> bool:
"""Broad (class-level, NOT per-command) detector for a request to change
@@ -5204,7 +4770,7 @@ class BrainManager:
new = str(result.get("new_provider") or canonical)
display = _SUBAGENT_DISPLAY.get(new, new)
log.info("sub-agent provider switched to %r via deterministic voice gate", new)
- template = _SUBAGENT_SWITCH_CONFIRM.get(lang, _SUBAGENT_SWITCH_CONFIRM["de"])
+ template = i18n_catalog.pick(_SUBAGENT_SWITCH_CONFIRM, lang)
return template.format(p=display)
display = _SUBAGENT_DISPLAY.get(canonical, canonical)
return _subagent_switch_failure_phrase(result, display, lang)
@@ -5237,7 +4803,7 @@ class BrainManager:
display = getattr(spec, "label", None) or canonical
if result.get("ok"):
log.info("main-brain provider switched to %r via deterministic voice gate", canonical)
- template = _PROVIDER_SWITCH_CONFIRM.get(lang, _PROVIDER_SWITCH_CONFIRM["de"])
+ template = i18n_catalog.pick(_PROVIDER_SWITCH_CONFIRM, lang)
return template.format(p=display)
return _provider_switch_failure_phrase(result, display, lang)
@@ -5629,10 +5195,7 @@ class BrainManager:
# no calendar access (OF-15). Resolved here with the same
# arguments the honesty phrase later uses, so one turn cannot
# speak two languages.
- language=resolve_output_language(
- getattr(self, "_reply_language", ""), "unknown", user_text,
- default=DEFAULT_LOCALE,
- ),
+ language=_turn_phrase_language(self, user_text),
)
except Exception: # noqa: BLE001
log.debug("evidence gate degraded to PASS", exc_info=True)
@@ -7515,11 +7078,7 @@ class BrainManager:
if not is_inventory_question(user_text):
return None
- out_lang = resolve_output_language(
- self._reply_language, self._turn_detected_lang, user_text,
- default=DEFAULT_LOCALE,
- conversation_language=self._conversation_language,
- )
+ out_lang = _turn_phrase_language(self, user_text)
unavailable = {
"de": "Ich kann die Agentenliste gerade nicht abrufen.", # i18n-allow
"en": "I cannot retrieve the agent roster right now.",
@@ -7635,13 +7194,7 @@ class BrainManager:
if ide_intent.spawn_vehicle_outranks_workspace(user_text, names=candidates):
return None
- out_lang = resolve_output_language(
- self._reply_language,
- "unknown",
- user_text,
- default=DEFAULT_LOCALE,
- conversation_language=self._conversation_language,
- )
+ out_lang = _turn_phrase_language(self, user_text)
# A clarified pane is briefed with the ORIGINAL utterance — the sentence
# that actually carried the work — not with the "yes" that confirmed it.
@@ -8312,13 +7865,7 @@ class BrainManager:
if request is None:
return None
- out_lang = resolve_output_language(
- self._reply_language,
- "unknown",
- user_text,
- default=DEFAULT_LOCALE,
- conversation_language=self._conversation_language,
- )
+ out_lang = _turn_phrase_language(self, user_text)
registry = get_registry()
session = registry.session
if session is None:
@@ -8398,13 +7945,7 @@ class BrainManager:
if request is None:
return None
- out_lang = resolve_output_language(
- self._reply_language,
- "unknown",
- user_text,
- default=DEFAULT_LOCALE,
- conversation_language=self._conversation_language,
- )
+ out_lang = _turn_phrase_language(self, user_text)
from jarvis.voice.action_phrases import action_phrase
# The name did not clearly reach one CLI. ASK — this is the maintainer's
@@ -10235,13 +9776,7 @@ class BrainManager:
)
pending_map.pop(confirm_key, None)
- locale = resolve_output_language(
- self._reply_language,
- "unknown",
- user_text,
- default=DEFAULT_LOCALE,
- conversation_language=self._conversation_language,
- )
+ locale = _turn_phrase_language(self, user_text)
outcome = await screen_context_for_turn(
user_text,
locale=locale,
@@ -10305,10 +9840,7 @@ class BrainManager:
except (ValueError, TypeError):
log.warning("voice-confirm: bad trace_id %r — not arming", trace_raw)
return
- lang = resolve_output_language(
- self._reply_language, "unknown", user_text,
- default=DEFAULT_LOCALE, conversation_language=self._conversation_language,
- )
+ lang = _turn_phrase_language(self, user_text)
self._pending_voice_confirm = _PendingVoiceConfirm(
trace_id=tid, lang=lang, tool_name=str(descriptor.get("tool_name", "")),
)
@@ -10424,13 +9956,7 @@ class BrainManager:
"""
# getattr: lightweight managers built without __init__ (fakes, early
# boot paths) carry no turn state yet — that simply means "none known".
- return resolve_output_language(
- self._reply_language,
- getattr(self, "_turn_detected_lang", ""),
- user_text or "",
- default=DEFAULT_LOCALE,
- conversation_language=getattr(self, "_conversation_language", ""),
- )
+ return _turn_phrase_language(self, user_text or "")
def _spawn_ack_language(self, user_text: str) -> str:
"""Resolve the language for the spoken spawn acknowledgement.
@@ -10550,11 +10076,7 @@ class BrainManager:
# the force-spawn path too (the tool-use loop does this for brain
# function-calls; this caller must do it itself or ctx.config is empty
# and the language silently falls back — Runtime Output Language).
- out_lang = resolve_output_language(
- self._reply_language, "unknown", user_text,
- default=DEFAULT_LOCALE,
- conversation_language=self._conversation_language,
- )
+ out_lang = _turn_phrase_language(self, user_text)
result = await self._tool_executor.execute(
tool,
args,
@@ -10631,11 +10153,7 @@ class BrainManager:
# Same authoritative-language stamping as the force-spawn path: without
# a config snapshot ctx.config is empty and spawn_worker's language
# falls back instead of honoring the resolver (Runtime Output Language).
- out_lang = resolve_output_language(
- self._reply_language, "unknown", user_text,
- default=DEFAULT_LOCALE,
- conversation_language=self._conversation_language,
- )
+ out_lang = _turn_phrase_language(self, user_text)
result = await self._tool_executor.execute(
tool, args, user_utterance=user_text,
config_snapshot={"output_language": out_lang},
@@ -10757,14 +10275,14 @@ class BrainManager:
say plainly that nothing was running. Never silent (audit 2026-06-27)."""
lang = self._resolve_turn_lang()
if count > 0:
- return _CANCEL_CONFIRM.get(lang, _CANCEL_CONFIRM["de"]).format(n=count)
- return _CANCEL_NONE.get(lang, _CANCEL_NONE["de"])
+ return i18n_catalog.pick(_CANCEL_CONFIRM, lang).format(n=count)
+ return i18n_catalog.pick(_CANCEL_NONE, lang)
def _depth_readback(self, level: str) -> str:
"""Honest spoken confirmation of a depth override. Never silent."""
lang = self._resolve_turn_lang()
table = _DEPTH_CONFIRM.get(level, _DEPTH_CONFIRM["deep"])
- return table.get(lang, table["de"])
+ return i18n_catalog.pick(table, lang)
# ------------------------------------------------------------------
# Intent-Router → (provider, model) chain
@@ -11091,6 +10609,7 @@ class BrainManager:
force_output_language: str | None = None,
consume_pending_voice_attachments: bool = False,
turn_override: TurnOverride | None = None,
+ language_text: str | None = None,
) -> str:
"""Generate a turn, optionally leaving its public response event to the caller.
@@ -11103,12 +10622,17 @@ class BrainManager:
``turn_override`` runs the turn on a caller-picked provider / model /
effort with extra tools and tool context (the typed chat's pick) —
the live brain, its config and its dead-lists are left untouched.
+ ``language_text`` is what the conversation language is read from when
+ ``user_text`` is not the person's own words (an internal "continue"
+ prompt): ``""`` keeps the conversation's language unchanged.
"""
token = _PUBLISH_RESPONSE_EVENT.set(bool(publish_response))
history_token = _TURN_HISTORY_OVERRIDE.set(
tuple(history_override) if history_override is not None else None
)
override_token = _TURN_OVERRIDE.set(turn_override)
+ # Armed ("" = no language yet); _update_turn_language fills it in.
+ language_token = TURN_LANGUAGE.set("")
from jarvis.core.image_references import active_scope
image_scope_token = active_scope.set(
@@ -11133,6 +10657,7 @@ class BrainManager:
consume_pending_voice_attachments=(
consume_pending_voice_attachments
),
+ language_text=language_text,
)
finally:
# Keep the last completed turn inspectable for diagnostics/tests,
@@ -11144,6 +10669,7 @@ class BrainManager:
self._skill_injected_inline_fallback = skill_state.injected_inline
_SKILL_TURN_STATE.reset(skill_token)
_TURN_OVERRIDE.reset(override_token)
+ TURN_LANGUAGE.reset(language_token)
active_scope.reset(image_scope_token)
_TURN_HISTORY_OVERRIDE.reset(history_token)
_PUBLISH_RESPONSE_EVENT.reset(token)
@@ -11172,6 +10698,7 @@ class BrainManager:
emit_tool_ack: bool = True,
force_output_language: str | None = None,
consume_pending_voice_attachments: bool = False,
+ language_text: str | None = None,
) -> str:
# 1. Intercept meta-commands (cancel, switch, depth override).
# User request 2026-04-25: no standardised confirmation phrases
@@ -11213,7 +10740,7 @@ class BrainManager:
# the running conversation language instead of flipping it (forensic
# 2026-06-18); ambiguous text stays "unknown" -> soft mirror; an explicit
# reply_language pin leaves it empty -> the directive uses the pin.
- self._update_turn_language(user_text)
+ self._update_turn_language(user_text if language_text is None else language_text)
# Realtime-delegate language override (live 2026-07-23): the realtime
# session is the ONE authoritative resolver for a voice turn — its own
@@ -11225,10 +10752,12 @@ class BrainManager:
# _reply_language_directive() hard-locks it; an explicit
# brain.reply_language pin still wins (checked first in that directive).
if (
- force_output_language in _REPLY_LANG_NAMES
+ is_known_language(force_output_language)
and self._reply_language not in _REPLY_LANG_NAMES
):
self._turn_detected_lang = force_output_language
+ if TURN_LANGUAGE.get() is not None:
+ TURN_LANGUAGE.set(force_output_language)
# Two-turn voice/chat confirmation resume (turn N+1). MUST run before the
# cancel-intent intercept: a "nein"/"stop" answer to a pending
@@ -12561,8 +12090,8 @@ class BrainManager:
and tool_calls_executed
and str(agg.finish_reason or "") == "error"
):
- response_text = _MID_ANSWER_ERROR_PHRASES.get(
- self._resolve_turn_lang(), _MID_ANSWER_ERROR_PHRASES["de"]
+ response_text = i18n_catalog.pick(
+ _MID_ANSWER_ERROR_PHRASES, self._resolve_turn_lang()
)
log.warning(
"Brain %s(%s): stream ended finish_reason=error AFTER "
@@ -12783,13 +12312,7 @@ class BrainManager:
no_vision_provider_reply,
)
- language = resolve_output_language(
- self._reply_language,
- "unknown",
- user_text,
- default=DEFAULT_LOCALE,
- conversation_language=self._conversation_language,
- )
+ language = _turn_phrase_language(self, user_text)
response_text = no_vision_provider_reply(language)
await self._record_response_side_effects(
user_text=user_text,
@@ -12841,12 +12364,7 @@ class BrainManager:
# ("de" here, DEFAULT_LOCALE there), so an undetectable turn could speak
# a German evidence fallback followed by an English honesty phrase in the
# same breath. All locales are equal — the shared DEFAULT_LOCALE decides.
- honesty_lang = resolve_output_language(
- self._reply_language,
- "unknown",
- user_text,
- default=DEFAULT_LOCALE,
- )
+ honesty_lang = _turn_phrase_language(self, user_text)
# Evidence-gate enforcement (live repro 2026-06-17, session 296abc82):
# the gate MANDATED a tool this turn, but neither the normal tool loop
@@ -14108,15 +13626,7 @@ def _is_rate_limit_exc(exc: Exception) -> bool:
# Leak-recovery fallback variants — see BrainManager._action_failed_phrase.
-_ACTION_FAILED_PHRASES: dict[str, str] = {
- "de": (
- "Ich habe die Aktion erkannt, " # i18n-allow: spoken German TTS
- "konnte sie aber nicht ausführen." # i18n-allow: spoken German TTS
- ),
- "en": "I recognized the action but couldn't execute it.",
- "es": "Reconocí la acción, pero no pude ejecutarla.",
- "pt": "Reconheci a ação, mas não consegui executá-la.",
-}
+_ACTION_FAILED_PHRASES: dict[str, str] = i18n_catalog.table("brain.action_failed")
# DIRECT local-action acknowledgement — see BrainManager._localize_direct_ack.
# open_app hardcodes a German launch acknowledgement that the DIRECT fast path
diff --git a/jarvis/brain/output_filter.py b/jarvis/brain/output_filter.py
index d00789f2fc..156a4fde8e 100644
--- a/jarvis/brain/output_filter.py
+++ b/jarvis/brain/output_filter.py
@@ -6,7 +6,7 @@ filler openers. Regex-only, NO LLM calls (latency-fatal, mandate § "DO NOT").
API:
from jarvis.brain.output_filter import scrub_for_voice
- result = scrub_for_voice(text, language="de")
+ result = scrub_for_voice(text, language="en")
result.cleaned # scrubbed text, ready for TTS
result.actions # ["removed_tool_json", "rephrased_echo", ...]
result.fallback_used # True when the entire text was replaced by a standard phrase
@@ -32,6 +32,7 @@ from __future__ import annotations
import re
from dataclasses import dataclass, field
+from jarvis.i18n import catalog as i18n_catalog
from jarvis.speech.hangup import END_CALL_SIGNAL
# Mandate: user-concept words are sacred — NEVER scrubbed as jargon.
@@ -80,15 +81,7 @@ assert not (set(WHITELIST_WORDS) & set(JARGON_WORDS)), (
# Echo/filler patterns only in the first N characters. Mandate failure-mode 6.
OPENER_BUDGET = 60
-FALLBACK_PHRASES: dict[str, str] = {
- "de": "Es trat ein Fehler auf.", # i18n-allow: spoken German fallback phrase (runtime voice output)
- "en": "An error occurred.",
- # Runtime-output-language doctrine: every spoken phrase table carries all
- # supported locales (de/en/es/pt) so a Spanish-pinned user never falls back to
- # German. Used by the stacktrace, raw-dump, and post-scrub-residue guards.
- "es": "Se produjo un error.",
- "pt": "Ocorreu um erro.",
-}
+FALLBACK_PHRASES: dict[str, str] = i18n_catalog.table("output_filter.fallback")
# ---------------------------------------------------------------------------
@@ -670,7 +663,7 @@ def _is_prose_mentioning_code(text: str) -> bool:
def scrub_for_voice(
- text: str, *, language: str = "de", ack_mode: bool = False
+ text: str, *, language: str = "en", ack_mode: bool = False
) -> ScrubResult:
"""Cleans up brain output for TTS synthesis.
@@ -697,7 +690,7 @@ def scrub_for_voice(
# 1. Stacktrace: early return with the standard phrase. Mandate: "cut
# out entirely, replaced by the German fallback phrase".
if STACKTRACE_RE.search(text):
- fallback = FALLBACK_PHRASES.get(language, FALLBACK_PHRASES["de"])
+ fallback = i18n_catalog.pick(FALLBACK_PHRASES, language)
return ScrubResult(
cleaned=fallback,
actions=["replaced_stacktrace"],
@@ -711,7 +704,7 @@ def scrub_for_voice(
# future — can ever speak/show a raw {'…': …} dump again (live bug
# 2026-06-22: the whole dispatch_to_harness result reached a CU readback).
if RAW_REPR_OPENER_RE.match(text) and REPR_SIGNATURE_RE.search(text):
- fallback = FALLBACK_PHRASES.get(language, FALLBACK_PHRASES["de"])
+ fallback = i18n_catalog.pick(FALLBACK_PHRASES, language)
return ScrubResult(
cleaned=fallback,
actions=["replaced_raw_repr"],
@@ -728,7 +721,7 @@ def scrub_for_voice(
# by plain words is an ANSWER that mentions a command, not a command —
# the developer asked how to read $env:PATH and must get the answer.
if SHELL_COMMAND_RE.search(text) and not _is_prose_mentioning_code(text):
- fallback = FALLBACK_PHRASES.get(language, FALLBACK_PHRASES["de"])
+ fallback = i18n_catalog.pick(FALLBACK_PHRASES, language)
return ScrubResult(
cleaned=fallback,
actions=["replaced_shell_command"],
@@ -796,9 +789,7 @@ def scrub_for_voice(
# the scheme, the path nor the domain ever reaches TTS. Fail-closed
# defense; the real fix is the search_web answer_instruction that tells
# the brain to synthesize.
- placeholder = SOURCE_LINK_PLACEHOLDER.get(
- language, SOURCE_LINK_PLACEHOLDER["de"]
- )
+ placeholder = i18n_catalog.pick(SOURCE_LINK_PLACEHOLDER, language)
new = MORE_RESULTS_RE.sub("", out)
new = URL_RE.sub(placeholder, new)
new = BARE_WWW_RE.sub(placeholder, new)
@@ -929,7 +920,7 @@ def scrub_for_voice(
if actions:
meaningful = sum(1 for c in out if c.isalnum())
if meaningful < MIN_MEANINGFUL_CHARS:
- fallback = FALLBACK_PHRASES.get(language, FALLBACK_PHRASES["de"])
+ fallback = i18n_catalog.pick(FALLBACK_PHRASES, language)
return ScrubResult(
cleaned=fallback,
actions=actions + ["replaced_with_fallback_residue"],
diff --git a/jarvis/brain/router.py b/jarvis/brain/router.py
index 0c828152de..d173c8ba5d 100644
--- a/jarvis/brain/router.py
+++ b/jarvis/brain/router.py
@@ -588,12 +588,12 @@ def _detect_image_mime(data: bytes) -> str:
return "image/jpeg"
if data.startswith(b"\x89PNG\r\n\x1a\n"):
return "image/png"
- raise ValueError("Observation enthaelt kein unterstuetztes Bildformat")
+ raise ValueError("The observation is not in a supported image format")
async def _read_observation_png_b64(obs: Observation) -> str:
"""Backwards-compatible helper for old tests/callsites."""
mime, data_b64 = await _read_observation_image_b64(obs)
if mime != "image/png":
- raise ValueError(f"Observation ist {mime}, nicht image/png")
+ raise ValueError(f"The observation is {mime}, not image/png")
return data_b64
diff --git a/jarvis/brain/tool_use_loop.py b/jarvis/brain/tool_use_loop.py
index 5f86182359..f9ee94dafe 100644
--- a/jarvis/brain/tool_use_loop.py
+++ b/jarvis/brain/tool_use_loop.py
@@ -40,7 +40,8 @@ from jarvis.core.protocols import (
ReasoningEffort,
Tool,
)
-from jarvis.core.turn_language import resolve_output_language, resolve_turn_language
+from jarvis.core.turn_language import TURN_LANGUAGE, resolve_output_language
+from jarvis.i18n import catalog as i18n_catalog
from jarvis.safety.tool_executor import VOICE_CONFIRM_SENTINEL, ToolExecutor
from .iteration_budget import IterationBudget
@@ -399,30 +400,20 @@ def _is_meta_debug_intent(utterance: str) -> bool:
# answered in German. A pinned reply language (brain.reply_language) wins;
# in "auto" mode the phrase mirrors the language detected from the user's
# text; ambiguous text keeps the historical German default.
-_ANTI_SILENCE_PHRASES: dict[str, str] = {
- "de": (
- "Das kann ich gerade nicht ausführen — " # i18n-allow: spoken German TTS
- "mir fehlt dafür das passende Werkzeug." # i18n-allow: spoken German TTS
- ),
- "en": "I can't do that right now — I'm missing the right tool for it.",
- "es": "Ahora mismo no puedo hacerlo — me falta la herramienta adecuada.",
- "pt": "Neste momento não consigo fazer isso — falta-me a ferramenta adequada.",
-}
+_ANTI_SILENCE_PHRASES: dict[str, str] = i18n_catalog.table("tool_loop.anti_silence")
# Meta-/debug feedback acknowledgement. Must NOT narrate background bookkeeping
# (the maintainer finds "ich notiere das Feedback" / "I'm noting that" / "tomo
# nota" annoying — that work happens silently, BACKGROUND_ACTION_RE strips it
# anyway). A brief, neutral acknowledgement that invites the actual correction.
-_META_DEBUG_ACK_PHRASES: dict[str, str] = {
- "de": "Verstanden. Was genau hätte anders sein sollen?", # i18n-allow: spoken German TTS
- "en": "Understood. What exactly should have been different?",
- "es": "Entendido. ¿Qué debería haber sido diferente?",
- "pt": "Entendido. O que devia ter sido diferente?",
-}
+_META_DEBUG_ACK_PHRASES: dict[str, str] = i18n_catalog.table("tool_loop.meta_debug_ack")
def _localized_phrase(
- phrases: dict[str, str], user_utterance: str, reply_language: str
+ phrases: dict[str, str],
+ user_utterance: str,
+ reply_language: str,
+ conversation_language: str = "",
) -> str:
"""Pick the phrase variant matching the pin or the user's turn language.
@@ -433,20 +424,35 @@ def _localized_phrase(
pass ``"unknown"`` as the tag and let the text decide. Ambiguous text keeps
the historical German default. (Under the common ``[stt].language="de"`` pin
the tag would resolve to ``de`` anyway, so the text-only path is equivalent
- there and strictly better when the text is clearly English/Spanish.)
+ there and strictly better when the text is clearly English/Spanish.) The
+ running ``conversation_language`` keeps a short or ambiguous turn in the
+ conversation's language; anything without translations reads English.
"""
- lang = reply_language if reply_language in phrases else resolve_turn_language(
- "unknown", user_utterance, default="de"
+ turn = TURN_LANGUAGE.get()
+ if turn and str(reply_language or "").strip().lower() not in phrases:
+ # Inside a brain turn: the language generate() resolved for it, so an
+ # internal English prompt as the utterance never makes this English.
+ return i18n_catalog.pick(phrases, turn)
+ lang = resolve_output_language(
+ reply_language, "unknown", user_utterance, conversation_language=conversation_language
)
- return phrases.get(lang, phrases["de"])
+ return i18n_catalog.pick(phrases, lang)
-def _anti_silence_phrase(user_utterance: str, reply_language: str = "auto") -> str:
- return _localized_phrase(_ANTI_SILENCE_PHRASES, user_utterance, reply_language)
+def _anti_silence_phrase(
+ user_utterance: str, reply_language: str = "auto", conversation_language: str = ""
+) -> str:
+ return _localized_phrase(
+ _ANTI_SILENCE_PHRASES, user_utterance, reply_language, conversation_language
+ )
-def _meta_debug_ack_phrase(user_utterance: str, reply_language: str = "auto") -> str:
- return _localized_phrase(_META_DEBUG_ACK_PHRASES, user_utterance, reply_language)
+def _meta_debug_ack_phrase(
+ user_utterance: str, reply_language: str = "auto", conversation_language: str = ""
+) -> str:
+ return _localized_phrase(
+ _META_DEBUG_ACK_PHRASES, user_utterance, reply_language, conversation_language
+ )
def _has_trailing_imperative(utterance: str) -> bool:
@@ -1374,7 +1380,7 @@ class ToolUseLoop:
# used to do so even when another call in the same round
# had already succeeded, throwing that work away.
meta_debug_ack = _meta_debug_ack_phrase(
- user_utterance, reply_language
+ user_utterance, reply_language, conversation_language
)
tool_result_payload = {
"success": False,
@@ -1719,7 +1725,7 @@ class ToolUseLoop:
and not self._unattended
):
suppress_output = _anti_silence_phrase(
- user_utterance, reply_language
+ user_utterance, reply_language, conversation_language
)
# Budget check after execution: the results of this round are
diff --git a/jarvis/browser_voice/session.py b/jarvis/browser_voice/session.py
index c66623acfd..199effbec6 100644
--- a/jarvis/browser_voice/session.py
+++ b/jarvis/browser_voice/session.py
@@ -518,4 +518,4 @@ class BrowserVoiceSession:
# scrub_for_voice only knows the runtime locales de/en/es/pt (AP-11, regex
# only); an unknown tag would silently apply the wrong blacklist.
tag = (self.language_code or "de-DE").split("-", 1)[0].lower()
- return tag if tag in {"de", "en", "es", "pt"} else "de"
+ return tag if tag in {"de", "en", "es", "pt"} else "en"
diff --git a/jarvis/channels/discord.py b/jarvis/channels/discord.py
index 8b23ddebea..5e3fb55020 100644
--- a/jarvis/channels/discord.py
+++ b/jarvis/channels/discord.py
@@ -55,7 +55,7 @@ except ImportError: # pragma: no cover
self.cleaned = text
self.fallback_used = False
- def _scrub_impl(text: str, *, language: str = "de") -> Any: # type: ignore[no-redef]
+ def _scrub_impl(text: str, *, language: str = "en") -> Any: # type: ignore[no-redef]
return _IdentityScrubResult(text or "")
if TYPE_CHECKING: # pragma: no cover
@@ -64,7 +64,7 @@ if TYPE_CHECKING: # pragma: no cover
log = logging.getLogger(__name__)
-def scrub_for_voice(text: str, *, language: str = "de") -> Any:
+def scrub_for_voice(text: str, *, language: str = "en") -> Any:
return _scrub_impl(text, language=language)
__all__ = ["DiscordChannel", "InflightMap"]
@@ -458,7 +458,7 @@ class DiscordChannel:
if channel_id is None:
return
await self._send_text(
- channel_id, event.text or "", language=event.language or "de"
+ channel_id, event.text or "", language=event.language or "en"
)
async def send_message(self, msg: ChannelMessage) -> None:
@@ -474,7 +474,7 @@ class DiscordChannel:
except (TypeError, ValueError):
log.warning("Invalid discord_channel_id: %r — drop", raw)
return
- await self._send_text(channel_id, msg.content, language="de")
+ await self._send_text(channel_id, msg.content, language="en")
async def broadcast_event(self, event: Event) -> None:
"""No-op: Discord routing goes through InflightMap, not broadcast."""
diff --git a/jarvis/channels/telegram.py b/jarvis/channels/telegram.py
index dc2b7bba15..586ce825a8 100644
--- a/jarvis/channels/telegram.py
+++ b/jarvis/channels/telegram.py
@@ -46,11 +46,11 @@ except ImportError: # pragma: no cover
self.cleaned = text
self.fallback_used = False
- def _scrub_impl(text: str, *, language: str = "de") -> Any: # type: ignore[no-redef]
+ def _scrub_impl(text: str, *, language: str = "en") -> Any: # type: ignore[no-redef]
return _IdentityScrubResult(text or "")
-def scrub_for_voice(text: str, *, language: str = "de") -> Any:
+def scrub_for_voice(text: str, *, language: str = "en") -> Any:
return _scrub_impl(text, language=language)
if TYPE_CHECKING: # pragma: no cover
@@ -319,7 +319,7 @@ class TelegramChannel:
chat_id,
"Telegram is connected. Send a message here and I will "
"forward it directly to Dodaios.",
- language="de",
+ language="en",
)
return
@@ -487,7 +487,7 @@ class TelegramChannel:
if chat_id is None:
return
text = event.text or ""
- await self._send_text(chat_id, text, language=event.language or "de")
+ await self._send_text(chat_id, text, language=event.language or "en")
async def send_message(self, msg: ChannelMessage) -> None:
chat_id_raw = msg.metadata.get("telegram_chat_id")
@@ -502,7 +502,7 @@ class TelegramChannel:
except (TypeError, ValueError):
log.warning("Invalid telegram_chat_id: %r — drop", chat_id_raw)
return
- await self._send_text(chat_id, msg.content, language="de")
+ await self._send_text(chat_id, msg.content, language="en")
async def broadcast_event(self, event: Event) -> None:
"""No-op: Telegram routing goes through InflightMap, not broadcast."""
diff --git a/jarvis/commands/registry.py b/jarvis/commands/registry.py
index a5f8a84586..13ac40e3fd 100644
--- a/jarvis/commands/registry.py
+++ b/jarvis/commands/registry.py
@@ -31,9 +31,11 @@ from dataclasses import dataclass, field
from functools import lru_cache
from typing import Any
-# Kept static for zero-import-cost; parity-tested against
-# jarvis.brain.manager.SUPPORTED_REPLY_LANGUAGES (the authoritative tuple).
-REPLY_LANGUAGES: tuple[str, ...] = ("auto", "de", "en", "es", "pt")
+from jarvis.i18n.locales import SUPPORTED_LOCALES
+
+# The central language list (jarvis.i18n.locales, constants only); parity-
+# tested against jarvis.brain.manager.SUPPORTED_REPLY_LANGUAGES.
+REPLY_LANGUAGES: tuple[str, ...] = ("auto", *SUPPORTED_LOCALES)
VOICE_MODES: tuple[str, ...] = ("pipeline", "realtime")
diff --git a/jarvis/core/turn_language.py b/jarvis/core/turn_language.py
index d8f6f1dff0..75f38311c2 100644
--- a/jarvis/core/turn_language.py
+++ b/jarvis/core/turn_language.py
@@ -32,11 +32,20 @@ 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 jarvis.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",
@@ -48,16 +57,23 @@ __all__ = [
"validate_output_language",
]
-#: The fallback spoken/written language for a turn whose language cannot be
-#: detected AND no ``brain.reply_language`` pin is set. ONE shared constant so
-#: every output layer agrees on the auto-mode default instead of each hardcoding
-#: its own (the historical "pipeline defaults en, action phrases default de"
-#: split that let two layers diverge on the same ambiguous turn).
-DEFAULT_LOCALE = "en"
+# ``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 (``"auto"`` is
#: deliberately absent — it means "no pin, mirror the input").
-_REPLY_PINS: frozenset[str] = frozenset({"de", "en", "es", "pt"})
+_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
@@ -67,6 +83,10 @@ _REPLY_PINS: frozenset[str] = frozenset({"de", "en", "es", "pt"})
#: 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
@@ -92,8 +112,11 @@ _LANGUAGE_REQUEST_RE = re.compile(
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"(?:\s+(?:antworten|sprechen))?" # 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,
@@ -105,6 +128,13 @@ _REQUEST_LANGUAGE_CODES = {
"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
@@ -252,16 +282,238 @@ def normalize_language_tag(tag: object) -> str:
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:`jarvis.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.
+ 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)
@@ -422,6 +674,10 @@ def resolve_transcript_language(reported: object, text: str) -> str:
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
@@ -468,8 +724,12 @@ def _has_language_switch_evidence(text: str, detected: str) -> bool:
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.
+ 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 _REPLY_PINS:
+ 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)
@@ -477,22 +737,23 @@ def _has_language_switch_evidence(text: str, detected: str) -> bool:
return score >= 2 and score - runner_up >= 2
-def resolve_output_language(
+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,
*,
- default: str = DEFAULT_LOCALE,
conversation_language: object = "",
) -> str:
- """The SINGLE authoritative output language for one turn (de/en/es/pt).
+ """The language the person is speaking in this turn: any code, or ``unknown``.
- 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 (AGENTS.md "Runtime Output Language";
- 2026-06-18 forensic).
+ 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:
@@ -501,18 +762,12 @@ def resolve_output_language(
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
- spoken in ``conversation_language`` — it must NOT flip an established
+ 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 input language of the turn (``resolve_turn_language``:
- text heuristic first, STT tag breaks ties), an ambiguous substantive turn
- inheriting ``conversation_language`` when one is set;
- 5. else the configured ``default`` locale (``DEFAULT_LOCALE``).
-
- ``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`` (de/en/es/pt) is the language of
- the conversation so far; pass ``""`` when none is established yet.
+ 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:
@@ -520,13 +775,88 @@ def resolve_output_language(
requested = detect_language_request(text)
if requested:
return requested
- conv = str(conversation_language or "").strip().lower()
- conv = conv if conv in _REPLY_PINS else ""
+ 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:
- detected = detect_text_language(text)
if detected == conv or not _has_language_switch_evidence(text, detected):
return conv
return detected
- return resolve_turn_language(stt_language, text, default=(conv or default))
+ 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 (AGENTS.md "Runtime Output Language";
+ 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
diff --git a/jarvis/i18n/__init__.py b/jarvis/i18n/__init__.py
new file mode 100644
index 0000000000..0db31b1c8f
--- /dev/null
+++ b/jarvis/i18n/__init__.py
@@ -0,0 +1,27 @@
+"""Backend localization: the language list and the system-phrase catalog."""
+
+from jarvis.i18n.catalog import pick, t, table, variant_table, variants
+from jarvis.i18n.locales import (
+ DEFAULT_LOCALE,
+ LANGUAGE_NAMES,
+ SUPPORTED_LOCALES,
+ is_known_language,
+ is_supported_locale,
+ language_name,
+ phrase_locale,
+)
+
+__all__ = [
+ "DEFAULT_LOCALE",
+ "LANGUAGE_NAMES",
+ "SUPPORTED_LOCALES",
+ "is_known_language",
+ "is_supported_locale",
+ "language_name",
+ "phrase_locale",
+ "pick",
+ "t",
+ "table",
+ "variant_table",
+ "variants",
+]
diff --git a/jarvis/i18n/catalog.py b/jarvis/i18n/catalog.py
new file mode 100644
index 0000000000..b1aa4e199c
--- /dev/null
+++ b/jarvis/i18n/catalog.py
@@ -0,0 +1,132 @@
+"""System phrases, one JSON file per language, English as the safety net.
+
+``jarvis/i18n/locales/<code>.json`` holds the translated system phrases
+(errors, failure notices, fallbacks) under dotted keys. ``en.json`` is the
+master: every key exists there, and any key missing from another file, or
+any language without a file, reads the English text. Nothing ever falls back
+to German or to a "nearest" language.
+
+A value is either one string or a list of variants (rotated by the caller so
+a repeated failure does not sound robotic).
+
+Adding a language to the system phrases: copy ``en.json`` to ``<code>.json``,
+translate it, and add the code to ``SUPPORTED_LOCALES`` in
+``jarvis.i18n.locales``. No module that uses the phrases changes.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from collections.abc import Mapping
+from functools import cache
+from pathlib import Path
+from typing import Any, TypeVar
+
+from jarvis.i18n.locales import DEFAULT_LOCALE, SUPPORTED_LOCALES, phrase_locale
+
+_LOCALES_DIR = Path(__file__).with_name("locales")
+log = logging.getLogger(__name__)
+
+_T = TypeVar("_T")
+
+
+@cache
+def _catalog(code: str) -> dict[str, Any]:
+ path = _LOCALES_DIR / f"{code}.json"
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except FileNotFoundError:
+ # A language without a catalog reads English through the caller.
+ log.warning("i18n: no phrase catalog for %r at %s; using English", code, path)
+ return {}
+ return _flatten(data)
+
+
+def _flatten(data: Mapping[str, Any], prefix: str = "") -> dict[str, Any]:
+ out: dict[str, Any] = {}
+ for key, value in data.items():
+ full = f"{prefix}{key}"
+ if isinstance(value, Mapping):
+ out.update(_flatten(value, full + "."))
+ else:
+ out[full] = value
+ return out
+
+
+def keys() -> frozenset[str]:
+ """Every phrase key the English master catalog defines."""
+ return frozenset(_catalog(DEFAULT_LOCALE))
+
+
+def _raw(key: str, lang: object) -> Any:
+ value = _catalog(phrase_locale(lang)).get(key)
+ if value is None:
+ value = _catalog(DEFAULT_LOCALE).get(key)
+ if value is None:
+ raise KeyError(f"unknown phrase key {key!r}")
+ return value
+
+
+def variants(key: str, lang: object) -> tuple[str, ...]:
+ """All variants of *key* in *lang* (English when it has none)."""
+ value = _raw(key, lang)
+ return tuple(value) if isinstance(value, list) else (str(value),)
+
+
+def t(key: str, lang: object, /, index: int = 0, **fields: object) -> str:
+ """The phrase *key* in *lang*, falling back to English.
+
+ ``index`` picks a variant (modulo their count); ``fields`` fill
+ ``{placeholders}`` with ``str.format``.
+ """
+ options = variants(key, lang)
+ text = options[index % len(options)]
+ return text.format(**fields) if fields else text
+
+
+def table(key: str) -> dict[str, str]:
+ """``{code: phrase}`` for every supported language: a drop-in for the old
+ per-module dicts. Missing translations hold the English text."""
+ return {code: t(key, code) for code in SUPPORTED_LOCALES}
+
+
+def variant_table(key: str) -> dict[str, tuple[str, ...]]:
+ """``{code: (variant, ...)}`` for every supported language."""
+ return {code: variants(key, code) for code in SUPPORTED_LOCALES}
+
+
+def subkeys(key: str) -> tuple[str, ...]:
+ """The names directly under *key* in the English master, in file order."""
+ prefix = key + "."
+ seen: dict[str, None] = {}
+ for full in _catalog(DEFAULT_LOCALE):
+ if full.startswith(prefix):
+ seen.setdefault(full[len(prefix):].split(".", 1)[0], None)
+ return tuple(seen)
+
+
+def nested_table(key: str) -> dict[str, dict[str, str]]:
+ """``{name: {code: phrase}}`` for a group of phrases (one per cause, ...)."""
+ return {name: table(f"{key}.{name}") for name in subkeys(key)}
+
+
+def locale_maps(key: str) -> dict[str, dict[str, str]]:
+ """``{code: {name: phrase}}`` for a group of phrases, language first."""
+ names = subkeys(key)
+ return {
+ code: {name: t(f"{key}.{name}", code) for name in names}
+ for code in SUPPORTED_LOCALES
+ }
+
+
+def pick(phrases: Mapping[str, _T], lang: object) -> _T:
+ """``phrases[lang]`` for a supported language, else the English entry.
+
+ The one lookup for a module that still keeps its own ``{code: text}``
+ table: an unsupported or unknown language reads English, never German.
+ """
+ value = phrases.get(phrase_locale(lang))
+ if value is None:
+ value = phrases[DEFAULT_LOCALE]
+ return value
diff --git a/jarvis/i18n/locales.py b/jarvis/i18n/locales.py
new file mode 100644
index 0000000000..28ec9622fb
--- /dev/null
+++ b/jarvis/i18n/locales.py
@@ -0,0 +1,82 @@
+"""The one list of languages the backend speaks, and the names of the rest.
+
+Two different questions, kept apart on purpose:
+
+* **Which languages have translated system phrases?** ``SUPPORTED_LOCALES``.
+ Every canned status, error and fallback sentence exists in these, and a
+ JSON catalog under ``jarvis/i18n/locales/`` holds them. Adding a language
+ to the canned phrases means adding one catalog file and one code here.
+* **Which language is the person speaking?** Any language at all. The model
+ answers in it; only the canned phrases are limited to the list above, and
+ for every other language they fall back to English (``DEFAULT_LOCALE``),
+ never to whichever supported language happens to look closest.
+
+Forensic 2026-10-19: a person chatting in Turkish got errors in German, then
+Portuguese, then English, because Turkish ö/ü scored as German and ç as
+Portuguese, and every failure path picked its own fallback.
+"""
+
+from __future__ import annotations
+
+#: Languages with a full set of translated system phrases (the catalog files).
+SUPPORTED_LOCALES: tuple[str, ...] = ("de", "en", "es", "pt")
+
+#: The language of every system phrase when the person's language has no
+#: translation or cannot be told. One constant for every layer.
+DEFAULT_LOCALE = "en"
+
+#: English names of the supported languages, as the model is told them.
+SUPPORTED_LANGUAGE_NAMES: dict[str, str] = {
+ "de": "German",
+ "en": "English",
+ "es": "Spanish",
+ "pt": "European Portuguese",
+}
+
+#: English names of languages the detector can recognise but that have no
+#: translated system phrases. The model is still told to answer in them.
+OTHER_LANGUAGE_NAMES: dict[str, str] = {
+ "ar": "Arabic",
+ "cs": "Czech",
+ "el": "Greek",
+ "fa": "Persian",
+ "fr": "French",
+ "he": "Hebrew",
+ "hi": "Hindi",
+ "hu": "Hungarian",
+ "it": "Italian",
+ "ja": "Japanese",
+ "ko": "Korean",
+ "nl": "Dutch",
+ "pl": "Polish",
+ "ro": "Romanian",
+ "ru": "Russian",
+ "th": "Thai",
+ "tr": "Turkish",
+ "uk": "Ukrainian",
+ "vi": "Vietnamese",
+ "zh": "Chinese",
+}
+
+LANGUAGE_NAMES: dict[str, str] = {**SUPPORTED_LANGUAGE_NAMES, **OTHER_LANGUAGE_NAMES}
+
+
+def is_supported_locale(code: object) -> bool:
+ """True when *code* has translated system phrases."""
+ return isinstance(code, str) and code in SUPPORTED_LOCALES
+
+
+def is_known_language(code: object) -> bool:
+ """True when *code* names a language the model can be told to answer in."""
+ return isinstance(code, str) and code in LANGUAGE_NAMES
+
+
+def phrase_locale(code: object) -> str:
+ """The catalog language for a person's language: itself, else English."""
+ value = str(code or "").strip().lower()
+ return value if value in SUPPORTED_LOCALES else DEFAULT_LOCALE
+
+
+def language_name(code: object) -> str | None:
+ """The English name of a known language code, or None."""
+ return LANGUAGE_NAMES.get(str(code or "").strip().lower())
diff --git a/jarvis/i18n/locales/de.json b/jarvis/i18n/locales/de.json
new file mode 100644
index 0000000000..d86d34b920
--- /dev/null
+++ b/jarvis/i18n/locales/de.json
@@ -0,0 +1,136 @@
+{
+ "brain": {
+ "cli_failure": {
+ "cause": "Der Befehl ist fehlgeschlagen: {cause}",
+ "code": "Der Befehl ist mit Fehlercode {code} fehlgeschlagen.",
+ "bare": "Der Befehl ist fehlgeschlagen."
+ },
+ "nothing_found": "Dazu habe ich nichts gefunden.",
+ "navigation_ack": "Öffne {label}.",
+ "evidence_unfulfilled": "Ich konnte das gerade nicht abrufen — der Zugriff über das passende Werkzeug ist nicht durchgelaufen. Sag noch mal Bescheid, dann versuche ich es erneut.",
+ "evidence_domain_labels": {
+ "calendar": "deinen Kalender",
+ "email": "dein Postfach",
+ "tasks": "deine Aufgaben",
+ "repos": "deine Repositories",
+ "deployments": "deine Deployments",
+ "cloud": "deine Cloud-Abrechnung",
+ "activity": "deinen Aktivitätsverlauf"
+ },
+ "evidence_unfulfilled_domain": "Ich konnte {label} gerade nicht abrufen — der Zugriff ist nicht durchgelaufen. Sag noch mal Bescheid, dann versuche ich es erneut.",
+ "action_unfulfilled": {
+ "society_propose_change": "Die Routine wurde nicht erstellt. Der Speichervorgang wurde nicht ausgeführt.",
+ "society-create-routine": "Die Routine wurde nicht erstellt. Der Speichervorgang wurde nicht ausgeführt.",
+ "contact-upsert": "Ich hab den Kontakt noch nicht gespeichert — sag mir die Angaben noch mal, dann lege ich ihn an.",
+ "wiki-ingest": "Ich hab das noch nicht in deinem Wiki vermerkt — sag's noch mal, dann schreib ich's rein.",
+ "run_shell": "Das hab ich noch nicht ausgeführt — der Befehl ist nicht gelaufen. Sag's noch mal, dann mache ich es direkt."
+ },
+ "lang_switch_confirm_session": "Für diese Sitzung antworte ich auf Deutsch — dauerhaft speichern hat nicht geklappt.",
+ "subagent_switch_confirm": "Erledigt — dein Sub-Agent läuft ab der nächsten Mission auf {p}.",
+ "subagent_switch_fail": {
+ "missing_credential": "{p} ist nicht verbunden — richte es zuerst ein, dann stelle ich um.",
+ "other": "Das konnte ich nicht auf {p} umstellen."
+ },
+ "provider_switch_confirm": "Erledigt — dein Haupt-Brain läuft jetzt auf {p}.",
+ "provider_switch_fail": {
+ "missing_credential": "{p} ist nicht eingerichtet — hinterlege zuerst den Schlüssel, dann stelle ich um.",
+ "subagent_only": "{p} geht nur als Sub-Agent, nicht als Haupt-Brain.",
+ "other": "Den Haupt-Brain konnte ich nicht auf {p} umstellen."
+ },
+ "cancel_confirm": "Erledigt — {n} laufende Aufgabe(n) gestoppt.",
+ "cancel_none": "Es lief gerade nichts, das ich stoppen könnte.",
+ "depth_confirm": {
+ "deep": "Alles klar — ich denke ab jetzt gründlicher.",
+ "fast": "Alles klar — ich denke ab jetzt schneller."
+ },
+ "provider_down": [
+ "Entschuldige, ich komme gerade nicht an mein Sprachmodell. Einen Moment, bitte.",
+ "Tut mir leid, mein Sprachmodell ist im Moment nicht erreichbar. Ich versuche es gleich erneut.",
+ "Ich kann gerade nicht antworten — die Verbindung zu meinem Modell hakt. Gib mir kurz Zeit."
+ ],
+ "provider_down_cause": {
+ "missing_key": "Entschuldige — für mein Sprachmodell ist gerade kein API-Schlüssel hinterlegt. Öffne in der Seitenleiste die API-Keys und trag einen ein, dann geht es sofort weiter.",
+ "bad_key": "Entschuldige — mein hinterlegter API-Schlüssel wird abgelehnt, er ist wohl ungültig oder abgelaufen. Bitte ersetze ihn in den API-Keys in der Seitenleiste.",
+ "account_blocked": "Entschuldige — das Konto meines Sprachmodells blockiert gerade, vermutlich ist das Guthaben aufgebraucht oder das Limit erreicht. Bitte wirf einen Blick auf das Anbieter-Konto.",
+ "rate_limit": "Entschuldige — mein Anbieter bremst mich gerade wegen zu vieler Anfragen. Warte einen Moment und frag mich dann einfach noch einmal.",
+ "invalid_model": "Entschuldige — das eingestellte Modell wird vom Anbieter nicht akzeptiert. Bitte prüf die Modell-Auswahl in den Einstellungen.",
+ "context_overflow": "Entschuldige — diese Anfrage ist für das eingestellte Modell zu groß, sein Kontextfenster reicht dafür nicht. Wähle ein Modell mit größerem Kontext oder starte einen neuen Chat.",
+ "local_context": "Entschuldige — dein lokales Modell läuft mit einem zu kleinen Kontextfenster für diese Anfrage. Stell in deinem lokalen Modell-Server eine größere Kontextlänge ein und lade das Modell neu; bei den Modellen unter Lokale Modelle geht das über Tune. Die nötige Größe steht im Protokoll.",
+ "unreachable": "Entschuldige — ich erreiche meinen Anbieter gerade nicht, vermutlich ein Netzwerk- oder Anbieterproblem. Versuch es gleich bitte noch einmal.",
+ "vision_unsupported": "Entschuldige — keiner der verbundenen Assistenten kann gerade Bilder auswerten. Der Schlüssel ist da, nur das Sehen fehlt. Nimm unter API-Keys einen Anbieter mit Bildverarbeitung."
+ },
+ "mid_answer_error": "Ich habe die Zwischenschritte ausgeführt, aber beim Formulieren der Antwort gab es einen Fehler. Frag mich bitte gleich noch einmal.",
+ "action_failed": "Ich habe die Aktion erkannt, konnte sie aber nicht ausführen.",
+ "lang_switch_confirm": "Erledigt — ich antworte ab jetzt auf Deutsch.",
+ "lang_switch_confirm_auto": "Erledigt — ich passe meine Sprache ab jetzt automatisch deiner an."
+ },
+ "tool_loop": {
+ "anti_silence": "Das kann ich gerade nicht ausführen — mir fehlt dafür das passende Werkzeug.",
+ "meta_debug_ack": "Verstanden. Was genau hätte anders sein sollen?"
+ },
+ "output_filter": {
+ "fallback": "Es trat ein Fehler auf."
+ },
+ "speech": {
+ "brain_unavailable": "Entschuldige, Ruben — ich erreiche gerade keines meiner Sprachmodelle. Bitte prüf kurz, ob bei den Anbietern noch Guthaben ist.",
+ "stt_unavailable": "Entschuldige, ich habe dich akustisch gerade nicht verstanden. Sag es bitte noch einmal.",
+ "realtime_unavailable": "Die Realtime-Verbindung ist gerade nicht verfügbar. Ich wechsle für diese Sitzung zur klassischen Sprachverarbeitung.",
+ "timeout_tool_stall": "Ich habe rechtzeitig keine Antwort bekommen. Ein Tool, auf das ich gewartet habe, hat nicht reagiert.",
+ "timeout_no_answer": "Das konnte ich gerade nicht herausfinden."
+ },
+ "missions": {
+ "announcer": {
+ "failed_prefix": "Die Mission ist fehlgeschlagen.",
+ "reason_label": "Grund",
+ "cancelled": "Mission abgebrochen.",
+ "timed_out": "Die Mission lief in das Zeitlimit."
+ },
+ "readback": {
+ "failure_reason": {
+ "critic_loop_exhausted": "Drei Versuche haben nicht gereicht.",
+ "critic_rejected": "Die Prüfung war nicht zufrieden.",
+ "task_error": "Der Worker ist abgebrochen.",
+ "attempts_timed_out": "Das Zeitlimit wurde überschritten.",
+ "review_time_budget_exhausted": "Das Prüfzeitlimit ist erreicht; das Zwischenergebnis ist verfügbar.",
+ "budget_exceeded": "Das Kostenlimit ist erreicht.",
+ "decompose_failed": "Die Aufgabe konnte ich nicht zerlegen.",
+ "crash_recovery": "Eine alte Mission wurde aufgeräumt.",
+ "interrupted": "Eine laufende Mission wurde unterbrochen.",
+ "empty_diff": "Es wurden keine Dateien geschrieben.",
+ "critic_unavailable": "Der Prüfer ist abgestürzt, die Arbeit liegt im Worktree.",
+ "worktree_setup_failed": "Ich konnte keinen Arbeitsbereich anlegen.",
+ "checkpoint_missing": "Der gesicherte Zwischenstand fehlt, ich kann nicht fortsetzen.",
+ "git_missing": "{agents} brauchen eine Git-Installation im PATH.",
+ "git_not_a_repository": "{agents} brauchen einen Git-Checkout, bitte über den Git-Installer installieren, nicht als ZIP.",
+ "source_checkout_unavailable": "Diese {agent}-Aufgabe braucht den Quellcode-Checkout, der in dieser Installation nicht verfügbar ist.",
+ "provider_auth": "Die Anmeldung beim KI-Anbieter ist ungültig oder abgelaufen.",
+ "provider_quota": "Das Kontingent des KI-Anbieters ist erschöpft.",
+ "provider_unreachable": "Der KI-Anbieter ist gerade nicht erreichbar.",
+ "worker_timeout": "Der Worker hat das Zeitlimit überschritten."
+ },
+ "empty_summary": "Aufgabe erledigt.",
+ "unknown_reason": "unbekannter Fehler",
+ "no_tool_call": "Konnte ich nicht ausführen — kein Tool-Aufruf."
+ }
+ },
+ "realtime": {
+ "local_output_failure": "Ich konnte das gerade nicht abspielen. Der Lautsprecher war weg.",
+ "output_language_failure": "Ich konnte gerade keine sichere Antwort auf Deutsch erzeugen.",
+ "handshake_failure": {
+ "timeout": "Die Sprachverbindung kam nicht rechtzeitig zustande, deshalb habe ich abgebrochen.",
+ "unavailable": "Ich konnte die Sprachverbindung gerade nicht aufbauen.",
+ "rate_limited": "Die Sprachverbindung ist gerade überlastet. Bitte versuch es gleich noch einmal.",
+ "no_credits": "Das Guthaben für die Sprachverbindung ist aufgebraucht. Lade es beim Anbieter auf, dann klappt es wieder.",
+ "not_offered": "Dein Konto bietet diese Sprachverbindung gerade nicht an. Prüfe den Tarif oder wähle ein anderes Konto.",
+ "dropped": "Die Sprachverbindung ist abgebrochen."
+ }
+ },
+ "self_mod": {
+ "short_error": {
+ "pre_validate": "die Vorabprüfung hat den Wert abgelehnt",
+ "reload": "der Reload-Test hat den neuen Wert abgelehnt",
+ "rollback": "der Rollback selbst ist fehlgeschlagen — manueller Restore nötig",
+ "unexpected": "unerwarteter Fehler beim Ändern der Einstellung"
+ }
+ }
+}
diff --git a/jarvis/i18n/locales/en.json b/jarvis/i18n/locales/en.json
new file mode 100644
index 0000000000..88a4989695
--- /dev/null
+++ b/jarvis/i18n/locales/en.json
@@ -0,0 +1,136 @@
+{
+ "brain": {
+ "cli_failure": {
+ "cause": "The command failed: {cause}",
+ "code": "The command failed with exit code {code}.",
+ "bare": "The command failed."
+ },
+ "nothing_found": "I couldn't find anything on that.",
+ "navigation_ack": "Opening {label}.",
+ "evidence_unfulfilled": "I couldn't retrieve that just now — the tool call didn't go through. Say the word and I'll try again.",
+ "evidence_domain_labels": {
+ "calendar": "your calendar",
+ "email": "your inbox",
+ "tasks": "your tasks",
+ "repos": "your repositories",
+ "deployments": "your deployments",
+ "cloud": "your cloud billing",
+ "activity": "your activity history"
+ },
+ "evidence_unfulfilled_domain": "I couldn't pull {label} just now — the access didn't go through. Say the word and I'll try again.",
+ "action_unfulfilled": {
+ "society_propose_change": "The routine was not created. The save action did not run.",
+ "society-create-routine": "The routine was not created. The save action did not run.",
+ "contact-upsert": "I haven't actually saved that contact yet — give me the details once more and I'll add it.",
+ "wiki-ingest": "I haven't actually noted that in your wiki yet — say it once more and I'll write it down.",
+ "run_shell": "I haven't actually done that yet — the command never ran. Say it once more and I'll do it right away."
+ },
+ "lang_switch_confirm_session": "For this session I'll reply in English — saving it permanently didn't work.",
+ "subagent_switch_confirm": "Done — your sub-agent will run on {p} from your next mission.",
+ "subagent_switch_fail": {
+ "missing_credential": "{p} isn't connected — set it up first, then I'll switch.",
+ "other": "I couldn't switch the sub-agent to {p}."
+ },
+ "provider_switch_confirm": "Done — your main brain now runs on {p}.",
+ "provider_switch_fail": {
+ "missing_credential": "{p} isn't set up — add its key first, then I'll switch.",
+ "subagent_only": "{p} only works as a sub-agent, not as the main brain.",
+ "other": "I couldn't switch the main brain to {p}."
+ },
+ "cancel_confirm": "Done — stopped {n} running task(s).",
+ "cancel_none": "Nothing was running to stop.",
+ "depth_confirm": {
+ "deep": "Got it — I'll think more deeply from now on.",
+ "fast": "Got it — I'll think faster from now on."
+ },
+ "provider_down": [
+ "Sorry, I can't reach my language model right now. One moment, please.",
+ "I'm afraid my language model is unavailable at the moment. I'll try again shortly.",
+ "I can't answer just now — my connection to the model is failing. Give me a second."
+ ],
+ "provider_down_cause": {
+ "missing_key": "Sorry — no API key is set for my language model right now. Open the API keys in the sidebar and add one, and I can continue right away.",
+ "bad_key": "Sorry — my stored API key is being rejected; it looks invalid or expired. Please replace it under API keys in the sidebar.",
+ "account_blocked": "Sorry — my language model's account is blocking right now, most likely the credit is used up or a limit was reached. Please take a look at the provider account.",
+ "rate_limit": "Sorry — my provider is throttling me for too many requests. Give it a moment and just ask me again.",
+ "invalid_model": "Sorry — the configured model is not accepted by the provider. Please check the model selection in the settings.",
+ "context_overflow": "Sorry — this request is too large for the configured model; its context window is too small for it. Pick a model with a larger context or start a new chat.",
+ "local_context": "Sorry — your local model runs with a context window too small for this request. Raise the context length in your local model server and reload the model; for the models under Local Models, use Tune. The log names the size it needs.",
+ "unreachable": "Sorry — I can't reach my provider right now, likely a network or provider issue. Please try again in a moment.",
+ "vision_unsupported": "Sorry — none of the connected assistants can inspect images right now. The key is there; vision is not. Pick a vision-capable provider under API keys."
+ },
+ "mid_answer_error": "I ran the steps, but something went wrong while composing the answer. Please ask me again in a moment.",
+ "action_failed": "I recognized the action but couldn't execute it.",
+ "lang_switch_confirm": "Done — I'll reply in English from now on.",
+ "lang_switch_confirm_auto": "Done — from now on I'll match the language you use."
+ },
+ "tool_loop": {
+ "anti_silence": "I can't do that right now — I'm missing the right tool for it.",
+ "meta_debug_ack": "Understood. What exactly should have been different?"
+ },
+ "output_filter": {
+ "fallback": "An error occurred."
+ },
+ "speech": {
+ "brain_unavailable": "Sorry, Ruben — I can't reach any of my language models right now. Please check whether your providers still have credit.",
+ "stt_unavailable": "Sorry, I didn't catch that just now. Could you say it again?",
+ "realtime_unavailable": "The realtime connection is unavailable right now. I am switching this session to the classic voice pipeline.",
+ "timeout_tool_stall": "I couldn't get an answer in time. A tool I was waiting on didn't respond.",
+ "timeout_no_answer": "I couldn't find that out just now."
+ },
+ "missions": {
+ "announcer": {
+ "failed_prefix": "The mission failed.",
+ "reason_label": "Reason",
+ "cancelled": "Mission cancelled.",
+ "timed_out": "The mission timed out."
+ },
+ "readback": {
+ "failure_reason": {
+ "critic_loop_exhausted": "Three attempts were not enough.",
+ "critic_rejected": "The review wasn't satisfied.",
+ "task_error": "The worker aborted.",
+ "attempts_timed_out": "The time limit was reached.",
+ "review_time_budget_exhausted": "The review time budget was reached; partial output is available.",
+ "budget_exceeded": "The cost limit was reached.",
+ "decompose_failed": "I could not break the task down.",
+ "crash_recovery": "An old mission was cleaned up.",
+ "interrupted": "A running mission was interrupted; the partial results are available.",
+ "empty_diff": "No files were written.",
+ "critic_unavailable": "The reviewer crashed; the work is preserved in the worktree.",
+ "worktree_setup_failed": "I could not create a workspace.",
+ "checkpoint_missing": "The saved progress is missing, so I cannot continue.",
+ "git_missing": "{agents} require git to be installed and on PATH.",
+ "git_not_a_repository": "{agents} require a git checkout (install via the git-based installer, not a ZIP download).",
+ "source_checkout_unavailable": "This {agent} task requires the source checkout, which is not available in this installation.",
+ "provider_auth": "The AI provider sign-in is invalid or expired.",
+ "provider_quota": "The AI provider's quota is exhausted.",
+ "provider_unreachable": "The AI provider is currently unreachable.",
+ "worker_timeout": "The worker hit its time limit."
+ },
+ "empty_summary": "Task completed.",
+ "unknown_reason": "unknown error",
+ "no_tool_call": "I could not do that — no tool call was made."
+ }
+ },
+ "realtime": {
+ "local_output_failure": "I couldn't play that just now. The speaker disappeared.",
+ "output_language_failure": "I couldn't produce a safe answer in English just now.",
+ "handshake_failure": {
+ "timeout": "The voice connection did not come up in time, so I stopped.",
+ "unavailable": "I couldn't establish the voice connection just now.",
+ "rate_limited": "The voice connection is busy right now. Please try again in a moment.",
+ "no_credits": "The credit for the voice connection is used up. Top it up with the provider and it will work again.",
+ "not_offered": "Your account does not offer this voice connection right now. Check its plan or select another account.",
+ "dropped": "The voice connection dropped."
+ }
+ },
+ "self_mod": {
+ "short_error": {
+ "pre_validate": "the pre-check rejected the value",
+ "reload": "the reload test rejected the new value",
+ "rollback": "the rollback itself failed — a manual restore is needed",
+ "unexpected": "an unexpected error while changing the setting"
+ }
+ }
+}
diff --git a/jarvis/i18n/locales/es.json b/jarvis/i18n/locales/es.json
new file mode 100644
index 0000000000..35219dcf4e
--- /dev/null
+++ b/jarvis/i18n/locales/es.json
@@ -0,0 +1,136 @@
+{
+ "brain": {
+ "cli_failure": {
+ "cause": "El comando ha fallado: {cause}",
+ "code": "El comando ha fallado con el código de error {code}.",
+ "bare": "El comando ha fallado."
+ },
+ "nothing_found": "No he encontrado nada sobre eso.",
+ "navigation_ack": "Abriendo {label}.",
+ "evidence_unfulfilled": "No pude obtener eso ahora mismo — la llamada a la herramienta no se completó. Avísame y lo intento de nuevo.",
+ "evidence_domain_labels": {
+ "calendar": "tu calendario",
+ "email": "tu bandeja de entrada",
+ "tasks": "tus tareas",
+ "repos": "tus repositorios",
+ "deployments": "tus despliegues",
+ "cloud": "tu facturación en la nube",
+ "activity": "tu historial de actividad"
+ },
+ "evidence_unfulfilled_domain": "No pude obtener {label} ahora mismo — el acceso no se completó. Avísame y lo intento de nuevo.",
+ "action_unfulfilled": {
+ "society_propose_change": "La rutina no se creó. No se ejecutó la acción de guardarla.",
+ "society-create-routine": "La rutina no se creó. No se ejecutó la acción de guardarla.",
+ "contact-upsert": "Todavía no he guardado ese contacto — dime los datos otra vez y lo añado.",
+ "wiki-ingest": "Todavía no lo he anotado en tu wiki — dímelo otra vez y lo escribo.",
+ "run_shell": "Todavía no lo he hecho — el comando no llegó a ejecutarse. Dímelo otra vez y lo hago directamente."
+ },
+ "lang_switch_confirm_session": "Por esta sesión responderé en español — no pude guardarlo de forma permanente.",
+ "subagent_switch_confirm": "Listo — tu sub-agente usará {p} desde tu próxima misión.",
+ "subagent_switch_fail": {
+ "missing_credential": "{p} no está conectado — configúralo primero y luego cambio.",
+ "other": "No pude cambiar el sub-agente a {p}."
+ },
+ "provider_switch_confirm": "Listo — tu cerebro principal ahora usa {p}.",
+ "provider_switch_fail": {
+ "missing_credential": "{p} no está configurado — añade su clave primero y luego cambio.",
+ "subagent_only": "{p} solo funciona como sub-agente, no como cerebro principal.",
+ "other": "No pude cambiar el cerebro principal a {p}."
+ },
+ "cancel_confirm": "Listo — detuve {n} tarea(s) en curso.",
+ "cancel_none": "No había nada en curso que detener.",
+ "depth_confirm": {
+ "deep": "Entendido — pensaré más a fondo a partir de ahora.",
+ "fast": "Entendido — pensaré más rápido a partir de ahora."
+ },
+ "provider_down": [
+ "Lo siento, ahora mismo no puedo acceder a mi modelo de lenguaje. Un momento, por favor.",
+ "Me temo que mi modelo de lenguaje no está disponible en este momento. Lo intentaré de nuevo enseguida.",
+ "No puedo responder ahora mismo: la conexión con mi modelo está fallando. Dame un segundo."
+ ],
+ "provider_down_cause": {
+ "missing_key": "Lo siento: ahora mismo no hay ninguna clave de API configurada para mi modelo de lenguaje. Abre las claves de API en la barra lateral y añade una, y podré continuar enseguida.",
+ "bad_key": "Lo siento: mi clave de API almacenada está siendo rechazada; parece inválida o caducada. Sustitúyela en las claves de API de la barra lateral.",
+ "account_blocked": "Lo siento: la cuenta de mi modelo de lenguaje está bloqueada ahora mismo; probablemente se agotó el crédito o se alcanzó un límite. Revisa la cuenta del proveedor, por favor.",
+ "rate_limit": "Lo siento: mi proveedor me está limitando por demasiadas solicitudes. Espera un momento y vuelve a preguntarme.",
+ "invalid_model": "Lo siento: el modelo configurado no es aceptado por el proveedor. Revisa la selección de modelo en los ajustes.",
+ "context_overflow": "Lo siento: esta solicitud es demasiado grande para el modelo configurado; su ventana de contexto no alcanza. Elige un modelo con más contexto o empieza un chat nuevo.",
+ "local_context": "Lo siento: tu modelo local funciona con una ventana de contexto demasiado pequeña para esta solicitud. Aumenta la longitud de contexto en tu servidor de modelos local y vuelve a cargar el modelo; para los modelos de Modelos locales, usa Tune. El registro indica el tamaño necesario.",
+ "unreachable": "Lo siento: no puedo comunicarme con mi proveedor ahora mismo; probablemente sea un problema de red o del proveedor. Inténtalo de nuevo en un momento.",
+ "vision_unsupported": "Lo siento: ninguno de los asistentes conectados puede analizar imágenes ahora. La clave está; falta la visión. Elige un proveedor con visión en Claves API."
+ },
+ "mid_answer_error": "Ejecuté los pasos, pero algo falló al redactar la respuesta. Vuelve a preguntarme en un momento.",
+ "action_failed": "Reconocí la acción, pero no pude ejecutarla.",
+ "lang_switch_confirm": "Listo — a partir de ahora respondo en español.",
+ "lang_switch_confirm_auto": "Listo — a partir de ahora respondo en el idioma que uses."
+ },
+ "tool_loop": {
+ "anti_silence": "Ahora mismo no puedo hacerlo — me falta la herramienta adecuada.",
+ "meta_debug_ack": "Entendido. ¿Qué debería haber sido diferente?"
+ },
+ "output_filter": {
+ "fallback": "Se produjo un error."
+ },
+ "speech": {
+ "brain_unavailable": "Lo siento, Ruben — ahora mismo no puedo acceder a ninguno de mis modelos de lenguaje. Comprueba si tus proveedores aún tienen crédito.",
+ "stt_unavailable": "Perdona, no te he entendido bien ahora mismo. ¿Puedes repetirlo, por favor?",
+ "realtime_unavailable": "La conexión en tiempo real no está disponible ahora mismo. Cambiaré esta sesión al sistema de voz clásico.",
+ "timeout_tool_stall": "No pude obtener una respuesta a tiempo. Una herramienta que esperaba no respondió.",
+ "timeout_no_answer": "No pude averiguar eso ahora mismo."
+ },
+ "missions": {
+ "announcer": {
+ "failed_prefix": "La misión ha fallado.",
+ "reason_label": "Motivo",
+ "cancelled": "Misión cancelada.",
+ "timed_out": "La misión superó el tiempo límite."
+ },
+ "readback": {
+ "failure_reason": {
+ "critic_loop_exhausted": "Tres intentos no han bastado.",
+ "critic_rejected": "La revisión no quedó satisfecha.",
+ "task_error": "El worker se ha interrumpido.",
+ "attempts_timed_out": "Se alcanzó el tiempo límite.",
+ "review_time_budget_exhausted": "Se agotó el tiempo de revisión; el resultado parcial está disponible.",
+ "budget_exceeded": "Se alcanzó el límite de coste.",
+ "decompose_failed": "No he podido dividir la tarea.",
+ "crash_recovery": "Se ha limpiado una misión antigua.",
+ "interrupted": "Se interrumpió una misión en curso; los resultados parciales están disponibles.",
+ "empty_diff": "No se escribió ningún archivo.",
+ "critic_unavailable": "El revisor ha fallado; el trabajo se conserva en el worktree.",
+ "worktree_setup_failed": "No he podido crear un espacio de trabajo.",
+ "checkpoint_missing": "Falta el progreso guardado, así que no puedo continuar.",
+ "git_missing": "{agents} necesitan que git esté instalado y en el PATH.",
+ "git_not_a_repository": "{agents} necesitan una copia de git (instala con el instalador de git, no con una descarga ZIP).",
+ "source_checkout_unavailable": "Esta tarea de {agent} necesita el repositorio del código fuente, que no está disponible en esta instalación.",
+ "provider_auth": "El inicio de sesión del proveedor de IA no es válido o ha caducado.",
+ "provider_quota": "La cuota del proveedor de IA está agotada.",
+ "provider_unreachable": "El proveedor de IA no está disponible ahora.",
+ "worker_timeout": "El worker superó su tiempo límite."
+ },
+ "empty_summary": "Tarea completada.",
+ "unknown_reason": "error desconocido",
+ "no_tool_call": "No pude hacerlo: no hubo ninguna llamada a herramienta."
+ }
+ },
+ "realtime": {
+ "local_output_failure": "No pude reproducirlo ahora. El altavoz desapareció.",
+ "output_language_failure": "No pude generar una respuesta segura en español ahora mismo.",
+ "handshake_failure": {
+ "timeout": "La conexión de voz no se estableció a tiempo, así que lo detuve.",
+ "unavailable": "No pude establecer la conexión de voz ahora mismo.",
+ "rate_limited": "La conexión de voz está saturada ahora mismo. Inténtalo de nuevo en un momento.",
+ "no_credits": "Se agotó el saldo de la conexión de voz. Recárgalo con el proveedor y volverá a funcionar.",
+ "not_offered": "Tu cuenta no ofrece esta conexión de voz ahora mismo. Revisa el plan o elige otra cuenta.",
+ "dropped": "Se cortó la conexión de voz."
+ }
+ },
+ "self_mod": {
+ "short_error": {
+ "pre_validate": "la comprobación previa rechazó el valor",
+ "reload": "la prueba de recarga rechazó el nuevo valor",
+ "rollback": "la reversión misma ha fallado; hace falta una restauración manual",
+ "unexpected": "un error inesperado al cambiar el ajuste"
+ }
+ }
+}
diff --git a/jarvis/i18n/locales/pt.json b/jarvis/i18n/locales/pt.json
new file mode 100644
index 0000000000..15d5989e5d
--- /dev/null
+++ b/jarvis/i18n/locales/pt.json
@@ -0,0 +1,136 @@
+{
+ "brain": {
+ "cli_failure": {
+ "cause": "O comando falhou: {cause}",
+ "code": "O comando falhou com o código de erro {code}.",
+ "bare": "O comando falhou."
+ },
+ "nothing_found": "Não encontrei nada sobre isso.",
+ "navigation_ack": "A abrir {label}.",
+ "evidence_unfulfilled": "Não consegui obter isso agora — a chamada à ferramenta não foi concluída. Avisa-me e tento outra vez.",
+ "evidence_domain_labels": {
+ "calendar": "o teu calendário",
+ "email": "a tua caixa de entrada",
+ "tasks": "as tuas tarefas",
+ "repos": "os teus repositórios",
+ "deployments": "as tuas implementações",
+ "cloud": "a tua faturação na nuvem",
+ "activity": "o teu histórico de atividade"
+ },
+ "evidence_unfulfilled_domain": "Não consegui obter {label} agora — o acesso não foi concluído. Avisa-me e tento outra vez.",
+ "action_unfulfilled": {
+ "society_propose_change": "A rotina não foi criada. A ação de a guardar não chegou a ser executada.",
+ "society-create-routine": "A rotina não foi criada. A ação de a guardar não chegou a ser executada.",
+ "contact-upsert": "Ainda não guardei esse contacto — diz-me os dados outra vez e eu adiciono-o.",
+ "wiki-ingest": "Ainda não o anotei na tua wiki — diz-mo outra vez e eu escrevo-o.",
+ "run_shell": "Ainda não o fiz — o comando não chegou a ser executado. Diz-mo outra vez e faço-o diretamente."
+ },
+ "lang_switch_confirm_session": "Nesta sessão vou responder em português — não consegui guardar isto de forma permanente.",
+ "subagent_switch_confirm": "Feito — o teu subagente vai usar {p} a partir da tua próxima missão.",
+ "subagent_switch_fail": {
+ "missing_credential": "{p} não está ligado — configura-o primeiro e depois eu mudo.",
+ "other": "Não consegui mudar o subagente para {p}."
+ },
+ "provider_switch_confirm": "Feito — o teu cérebro principal usa agora {p}.",
+ "provider_switch_fail": {
+ "missing_credential": "{p} não está configurado — adiciona primeiro a chave e depois eu mudo.",
+ "subagent_only": "{p} só funciona como subagente, não como cérebro principal.",
+ "other": "Não consegui mudar o cérebro principal para {p}."
+ },
+ "cancel_confirm": "Feito — parei {n} tarefa(s) em curso.",
+ "cancel_none": "Não havia nada em curso para parar.",
+ "depth_confirm": {
+ "deep": "Entendido — a partir de agora vou pensar com mais profundidade.",
+ "fast": "Entendido — a partir de agora vou pensar mais depressa."
+ },
+ "provider_down": [
+ "Desculpa, neste momento não consigo aceder ao meu modelo de linguagem. Um momento, por favor.",
+ "Receio que o meu modelo de linguagem não esteja disponível neste momento. Volto a tentar já a seguir.",
+ "Não consigo responder agora: a ligação ao meu modelo está a falhar. Dá-me um segundo."
+ ],
+ "provider_down_cause": {
+ "missing_key": "Desculpa: neste momento não há nenhuma chave de API configurada para o meu modelo de linguagem. Abre as chaves de API na barra lateral e adiciona uma, e posso continuar já a seguir.",
+ "bad_key": "Desculpa: a minha chave de API guardada está a ser rejeitada; parece inválida ou expirada. Substitui-a nas chaves de API da barra lateral.",
+ "account_blocked": "Desculpa: a conta do meu modelo de linguagem está bloqueada neste momento; provavelmente o crédito esgotou-se ou foi atingido um limite. Verifica a conta do fornecedor, por favor.",
+ "rate_limit": "Desculpa: o meu fornecedor está a limitar-me por excesso de pedidos. Espera um momento e volta a perguntar-me.",
+ "invalid_model": "Desculpa: o modelo configurado não é aceite pelo fornecedor. Verifica a escolha do modelo nas definições.",
+ "context_overflow": "Desculpa: este pedido é demasiado grande para o modelo configurado; a janela de contexto não chega. Escolhe um modelo com mais contexto ou começa uma conversa nova.",
+ "local_context": "Desculpa: o teu modelo local corre com uma janela de contexto demasiado pequena para este pedido. Aumenta o comprimento de contexto no teu servidor de modelos local e recarrega o modelo; para os modelos em Modelos locais, usa Tune. O registo indica o tamanho necessário.",
+ "unreachable": "Desculpa: neste momento não consigo comunicar com o meu fornecedor; provavelmente é um problema de rede ou do fornecedor. Tenta outra vez daqui a um momento.",
+ "vision_unsupported": "Desculpa: nenhum dos assistentes ligados consegue analisar imagens agora. A chave existe; falta a visão. Escolhe um fornecedor com visão em Chaves de API."
+ },
+ "mid_answer_error": "Executei os passos, mas algo falhou ao redigir a resposta. Volta a perguntar-me daqui a um momento.",
+ "action_failed": "Reconheci a ação, mas não consegui executá-la.",
+ "lang_switch_confirm": "Feito — a partir de agora respondo em português.",
+ "lang_switch_confirm_auto": "Feito — a partir de agora respondo na língua que usares."
+ },
+ "tool_loop": {
+ "anti_silence": "Neste momento não consigo fazer isso — falta-me a ferramenta adequada.",
+ "meta_debug_ack": "Entendido. O que devia ter sido diferente?"
+ },
+ "output_filter": {
+ "fallback": "Ocorreu um erro."
+ },
+ "speech": {
+ "brain_unavailable": "Desculpa, Ruben — neste momento não consigo aceder a nenhum dos meus modelos de linguagem. Verifica se os teus fornecedores ainda têm crédito.",
+ "stt_unavailable": "Desculpa, não percebi bem o que disseste. Podes repetir, por favor?",
+ "realtime_unavailable": "A ligação em tempo real não está disponível neste momento. Vou mudar esta sessão para o sistema de voz clássico.",
+ "timeout_tool_stall": "Não consegui obter uma resposta a tempo. Uma ferramenta de que estava à espera não respondeu.",
+ "timeout_no_answer": "Não consegui descobrir isso agora."
+ },
+ "missions": {
+ "announcer": {
+ "failed_prefix": "A missão falhou.",
+ "reason_label": "Motivo",
+ "cancelled": "Missão cancelada.",
+ "timed_out": "A missão excedeu o tempo limite."
+ },
+ "readback": {
+ "failure_reason": {
+ "critic_loop_exhausted": "Três tentativas não chegaram.",
+ "critic_rejected": "A revisão não ficou satisfeita.",
+ "task_error": "O worker foi interrompido.",
+ "attempts_timed_out": "O tempo limite foi atingido.",
+ "review_time_budget_exhausted": "O tempo de revisão esgotou-se; o resultado parcial está disponível.",
+ "budget_exceeded": "O limite de custo foi atingido.",
+ "decompose_failed": "Não consegui dividir a tarefa.",
+ "crash_recovery": "Uma missão antiga foi limpa.",
+ "interrupted": "Uma missão em curso foi interrompida; os resultados parciais estão disponíveis.",
+ "empty_diff": "Não foi escrito nenhum ficheiro.",
+ "critic_unavailable": "O revisor falhou; o trabalho está guardado no worktree.",
+ "worktree_setup_failed": "Não consegui criar um espaço de trabalho.",
+ "checkpoint_missing": "Falta o progresso guardado, por isso não posso continuar.",
+ "git_missing": "{agents} precisam que o git esteja instalado e no PATH.",
+ "git_not_a_repository": "{agents} precisam de uma cópia git (instala com o instalador do git, não com uma transferência ZIP).",
+ "source_checkout_unavailable": "Esta tarefa de {agent} precisa do repositório do código-fonte, que não está disponível nesta instalação.",
+ "provider_auth": "O início de sessão no fornecedor de IA é inválido ou expirou.",
+ "provider_quota": "A quota do fornecedor de IA está esgotada.",
+ "provider_unreachable": "O fornecedor de IA não está acessível agora.",
+ "worker_timeout": "O worker excedeu o tempo limite."
+ },
+ "empty_summary": "Tarefa concluída.",
+ "unknown_reason": "erro desconhecido",
+ "no_tool_call": "Não consegui fazer isso: não houve nenhuma chamada a ferramenta."
+ }
+ },
+ "realtime": {
+ "local_output_failure": "Não consegui reproduzir isso agora. O altifalante desapareceu.",
+ "output_language_failure": "Não consegui gerar uma resposta segura em português agora.",
+ "handshake_failure": {
+ "timeout": "A ligação de voz não ficou pronta a tempo, por isso parei.",
+ "unavailable": "Não consegui estabelecer a ligação de voz agora.",
+ "rate_limited": "A ligação de voz está sobrecarregada neste momento. Tenta outra vez daqui a pouco.",
+ "no_credits": "O saldo da ligação de voz esgotou-se. Carrega-o no fornecedor e volta a funcionar.",
+ "not_offered": "A tua conta não oferece esta ligação de voz neste momento. Verifica o plano ou escolhe outra conta.",
+ "dropped": "A ligação de voz caiu."
+ }
+ },
+ "self_mod": {
+ "short_error": {
+ "pre_validate": "a verificação prévia rejeitou o valor",
+ "reload": "o teste de recarga rejeitou o novo valor",
+ "rollback": "a própria reversão falhou; é necessário um restauro manual",
+ "unexpected": "um erro inesperado ao alterar a definição"
+ }
+ }
+}
diff --git a/jarvis/missions/events.py b/jarvis/missions/events.py
index 39ab78c0f0..965bdd83e5 100644
--- a/jarvis/missions/events.py
+++ b/jarvis/missions/events.py
@@ -14,6 +14,8 @@ from typing import Annotated, Any, Final, Literal
from pydantic import BaseModel, ConfigDict, Field
+from jarvis.i18n.locales import SUPPORTED_LOCALES
+
from .ids import uuid7_str
# Language a mission is dispatched in and read back in: every supported reply
@@ -21,10 +23,10 @@ from .ids import uuid7_str
# "auto"), mirrored in frontend/src/types/missions.ts. Parity is guarded by
# tests/missions/test_mission_language_pt.py and test_mission_approved_parity.py.
MissionLanguage = Literal["de", "en", "es", "pt"]
-MISSION_LANGUAGES: Final[tuple[str, ...]] = ("de", "en", "es", "pt")
+MISSION_LANGUAGES: Final[tuple[str, ...]] = SUPPORTED_LOCALES
-def coerce_mission_language(value: object, default: str = "de") -> str:
+def coerce_mission_language(value: object, default: str = "en") -> str:
"""Return *value* when it is a mission language, else *default*."""
code = str(value or "").strip().lower()
return code if code in MISSION_LANGUAGES else default
diff --git a/jarvis/missions/init.py b/jarvis/missions/init.py
index 4de8f37aa7..47fa060320 100644
--- a/jarvis/missions/init.py
+++ b/jarvis/missions/init.py
@@ -1131,7 +1131,7 @@ async def bootstrap_missions(
budget_enabled: bool = True,
# Voice flags (from [phase6.voice])
voice_announce_critic_loop: bool = False,
- voice_language_default: str = "de",
+ voice_language_default: str = "en",
# Cleanup flags (from [phase6.cleanup])
cleanup_days: int = 14,
cleanup_startup_sweep: bool = True,
diff --git a/jarvis/missions/kontrollierer/deliverable.py b/jarvis/missions/kontrollierer/deliverable.py
index c06ef31f85..445b6eae32 100644
--- a/jarvis/missions/kontrollierer/deliverable.py
+++ b/jarvis/missions/kontrollierer/deliverable.py
@@ -137,10 +137,10 @@ def _templates(table: dict[str, dict[str, str]], language: str) -> dict[str, str
German is the back-compat default (every pre-2026-06-24 caller and the
``Literal["de","en"]`` spawn contract's ``es``-fallback resolve here).
"""
- return table.get(language, table["de"])
+ return table.get(language, table["en"])
-def build_deliverable_summary(mission_dir: Path, *, language: str = "de") -> str:
+def build_deliverable_summary(mission_dir: Path, *, language: str = "en") -> str:
"""Return a TTS-safe sentence naming the mission's archived files.
Args:
@@ -478,7 +478,7 @@ def deliver_to_user_folder(
return delivered
-def build_delivered_summary(delivered: list[Path], *, language: str = "de") -> str:
+def build_delivered_summary(delivered: list[Path], *, language: str = "en") -> str:
"""TTS-safe sentence naming delivered files as artifacts.
Until 2026-08-23 this also spoke the mirror folder's name ("liegt im Ordner
diff --git a/jarvis/missions/kontrollierer/orchestrator.py b/jarvis/missions/kontrollierer/orchestrator.py
index 64d546ec9f..618a4bd1b4 100644
--- a/jarvis/missions/kontrollierer/orchestrator.py
+++ b/jarvis/missions/kontrollierer/orchestrator.py
@@ -4393,15 +4393,15 @@ class Kontrollierer:
await self._manager.store.append_and_publish(env)
async def _mission_language(self, mission_id: str) -> str:
- """The mission's dispatch language, ``"de"`` when it cannot be read."""
+ """The mission's dispatch language, English when it cannot be read."""
try:
view = await self._manager.store.get_mission_view(mission_id)
except Exception: # noqa: BLE001 — the readback language is never mission-fatal
logger.warning(
"could not read the dispatch language of %s", mission_id, exc_info=True
)
- return "de"
- return str(view[2]) if view else "de"
+ return "en"
+ return str(view[2]) if view else "en"
async def _fail_mission(
self,
diff --git a/jarvis/missions/voice/announcer.py b/jarvis/missions/voice/announcer.py
index 6dfb293814..91bebb866b 100644
--- a/jarvis/missions/voice/announcer.py
+++ b/jarvis/missions/voice/announcer.py
@@ -38,6 +38,7 @@ from jarvis.brain.output_filter import scrub_for_voice
from jarvis.brain.scrub_verdict import is_harmless_scrub_residue
from jarvis.core.bus import EventBus
from jarvis.core.events import AnnouncementRequested
+from jarvis.i18n import catalog as i18n_catalog
from jarvis.missions.voice.readback import (
FAILURE_REASON_PHRASES,
Lang,
@@ -66,30 +67,10 @@ _MISSION_LANGS: tuple[str, ...] = get_args(Lang)
# Fixed announcer phrases per mission language (every supported reply
# language; an unknown code speaks English).
-_FAILED_PREFIX: dict[str, str] = {
- "de": "Die Mission ist fehlgeschlagen.", # i18n-allow: German TTS
- "en": "The mission failed.",
- "es": "La misión ha fallado.", # i18n-allow: Spanish TTS
- "pt": "A missão falhou.", # i18n-allow: PT TTS
-}
-_REASON_LABEL: dict[str, str] = {
- "de": "Grund", # i18n-allow: German TTS
- "en": "Reason",
- "es": "Motivo", # i18n-allow: Spanish TTS
- "pt": "Motivo", # i18n-allow: PT TTS
-}
-_CANCELLED: dict[str, str] = {
- "de": "Mission abgebrochen.", # i18n-allow: German TTS
- "en": "Mission cancelled.",
- "es": "Misión cancelada.", # i18n-allow: Spanish TTS
- "pt": "Missão cancelada.", # i18n-allow: PT TTS
-}
-_TIMED_OUT: dict[str, str] = {
- "de": "Die Mission lief in das Zeitlimit.", # i18n-allow: German TTS
- "en": "The mission timed out.",
- "es": "La misión superó el tiempo límite.", # i18n-allow: Spanish TTS
- "pt": "A missão excedeu o tempo limite.", # i18n-allow: PT TTS
-}
+_FAILED_PREFIX: dict[str, str] = i18n_catalog.table("missions.announcer.failed_prefix")
+_REASON_LABEL: dict[str, str] = i18n_catalog.table("missions.announcer.reason_label")
+_CANCELLED: dict[str, str] = i18n_catalog.table("missions.announcer.cancelled")
+_TIMED_OUT: dict[str, str] = i18n_catalog.table("missions.announcer.timed_out")
def _phrase(table: dict[str, str], lang: str) -> str:
@@ -131,7 +112,7 @@ class MissionAnnouncer:
speech_bus: EventBus,
scrub: bool = True,
announce_critic_loop: bool = False,
- language_default: _Lang = "de",
+ language_default: _Lang = "en",
) -> None:
self._bus = bus
self._store = store
diff --git a/jarvis/missions/voice/readback.py b/jarvis/missions/voice/readback.py
index 89aaf7dd85..140d2de22d 100644
--- a/jarvis/missions/voice/readback.py
+++ b/jarvis/missions/voice/readback.py
@@ -27,6 +27,8 @@ from __future__ import annotations
from collections import deque
from typing import TYPE_CHECKING, Final, Literal
+from jarvis.i18n import catalog as i18n_catalog
+
if TYPE_CHECKING:
from jarvis.missions.critic.runner import CapabilityHonestyCheck
@@ -258,165 +260,9 @@ READBACK_TEMPLATES: Final[dict[TemplateKey, dict[Lang, list[str]]]] = { # i18n-
# so a code without an entry falls back cleanly. The de/en parity gate
# (``test_failure_reason_phrases_de_en_parity``) still guards those two; ``es``
# here carries only the keys that have been translated so far.
-FAILURE_REASON_PHRASES: Final[dict[str, dict[str, str]]] = {
- "de": {
- "critic_loop_exhausted": "Drei Versuche haben nicht gereicht.", # i18n-allow
- "critic_rejected": "Die Prüfung war nicht zufrieden.", # i18n-allow
- "task_error": "Der Worker ist abgebrochen.", # i18n-allow
- "attempts_timed_out": "Das Zeitlimit wurde überschritten.", # i18n-allow (DE TTS phrase)
- "review_time_budget_exhausted": ( # i18n-allow: German TTS phrase
- "Das Prüfzeitlimit ist erreicht; das Zwischenergebnis ist verfügbar." # i18n-allow
- ),
- "budget_exceeded": "Das Kostenlimit ist erreicht.", # i18n-allow
- "decompose_failed": "Die Aufgabe konnte ich nicht zerlegen.", # i18n-allow
- "crash_recovery": "Eine alte Mission wurde aufgeräumt.", # i18n-allow
- "interrupted": "Eine laufende Mission wurde unterbrochen.", # i18n-allow (DE TTS phrase)
- "empty_diff": "Es wurden keine Dateien geschrieben.", # i18n-allow
- "critic_unavailable": "Der Prüfer ist abgestürzt, die Arbeit liegt im Worktree.", # i18n-allow
- "worktree_setup_failed": "Ich konnte keinen Arbeitsbereich anlegen.", # i18n-allow
- "checkpoint_missing": (
- "Der gesicherte Zwischenstand fehlt, ich kann nicht fortsetzen." # i18n-allow
- ),
- "git_missing": "{agents} brauchen eine Git-Installation im PATH.", # i18n-allow
- "git_not_a_repository": (
- "{agents} brauchen einen Git-Checkout, bitte über den " # i18n-allow
- "Git-Installer installieren, nicht als ZIP." # i18n-allow
- ),
- "source_checkout_unavailable": (
- "Diese {agent}-Aufgabe braucht den " # i18n-allow: German TTS
- "Quellcode-Checkout, der in dieser " # i18n-allow: German TTS
- "Installation nicht verfügbar ist." # i18n-allow: German TTS
- ),
- # error_class keys (looked up BEFORE the reason key; see
- # failure_phrase_key). Same table so announcer + direct-TTS listener
- # cannot drift (2026-05-27 finding #7).
- "provider_auth": (
- "Die Anmeldung beim KI-Anbieter ist ungültig oder abgelaufen." # i18n-allow
- ),
- "provider_quota": "Das Kontingent des KI-Anbieters ist erschöpft.", # i18n-allow
- "provider_unreachable": "Der KI-Anbieter ist gerade nicht erreichbar.", # i18n-allow
- "worker_timeout": "Der Worker hat das Zeitlimit überschritten.", # i18n-allow
- },
- "en": {
- "critic_loop_exhausted": "Three attempts were not enough.",
- "critic_rejected": "The review wasn't satisfied.",
- "task_error": "The worker aborted.",
- "attempts_timed_out": "The time limit was reached.",
- "review_time_budget_exhausted": (
- "The review time budget was reached; partial output is available."
- ),
- "budget_exceeded": "The cost limit was reached.",
- "decompose_failed": "I could not break the task down.",
- "crash_recovery": "An old mission was cleaned up.",
- "interrupted": "A running mission was interrupted; the partial results are available.",
- "empty_diff": "No files were written.",
- "critic_unavailable": (
- "The reviewer crashed; the work is preserved in the worktree."
- ),
- "worktree_setup_failed": "I could not create a workspace.",
- "checkpoint_missing": "The saved progress is missing, so I cannot continue.",
- "git_missing": "{agents} require git to be installed and on PATH.",
- "git_not_a_repository": (
- "{agents} require a git checkout (install via the "
- "git-based installer, not a ZIP download)."
- ),
- "source_checkout_unavailable": (
- "This {agent} task requires the source checkout, which is "
- "not available in this installation."
- ),
- "provider_auth": "The AI provider sign-in is invalid or expired.",
- "provider_quota": "The AI provider's quota is exhausted.",
- "provider_unreachable": "The AI provider is currently unreachable.",
- "worker_timeout": "The worker hit its time limit.",
- },
- # Spanish and European Portuguese are equal supported product-surface
- # languages (AGENTS.md §2); both carry the full de/en key set, guarded by
- # ``test_failure_reason_phrases_all_locales_parity``.
- "es": {
- "critic_loop_exhausted": "Tres intentos no han bastado.", # i18n-allow: Spanish TTS
- "critic_rejected": "La revisión no quedó satisfecha.", # i18n-allow: Spanish TTS
- "task_error": "El worker se ha interrumpido.", # i18n-allow: Spanish TTS
- "attempts_timed_out": "Se alcanzó el tiempo límite.", # i18n-allow: Spanish TTS
- "review_time_budget_exhausted": ( # i18n-allow: Spanish TTS phrase
- "Se agotó el tiempo de revisión; el resultado parcial está " # i18n-allow
- "disponible." # i18n-allow
- ),
- "budget_exceeded": "Se alcanzó el límite de coste.", # i18n-allow: Spanish TTS
- "decompose_failed": "No he podido dividir la tarea.", # i18n-allow: Spanish TTS
- "crash_recovery": "Se ha limpiado una misión antigua.", # i18n-allow: Spanish TTS
- "interrupted": (
- "Se interrumpió una misión en curso; los resultados " # i18n-allow: Spanish TTS
- "parciales están disponibles." # i18n-allow: Spanish TTS
- ),
- "empty_diff": "No se escribió ningún archivo.", # i18n-allow: Spanish TTS
- "critic_unavailable": (
- "El revisor ha fallado; el trabajo se conserva en el worktree." # i18n-allow
- ),
- "worktree_setup_failed": "No he podido crear un espacio de trabajo.", # i18n-allow
- "checkpoint_missing": (
- "Falta el progreso guardado, así que no puedo continuar." # i18n-allow: Spanish TTS
- ),
- "git_missing": "{agents} necesitan que git esté instalado y en el PATH.", # i18n-allow
- "git_not_a_repository": (
- "{agents} necesitan una copia de git (instala con el " # i18n-allow
- "instalador de git, no con una descarga ZIP)." # i18n-allow
- ),
- "source_checkout_unavailable": (
- "Esta tarea de {agent} necesita el " # i18n-allow: Spanish TTS
- "repositorio del código fuente, que no está " # i18n-allow: Spanish TTS
- "disponible en esta instalación." # i18n-allow: Spanish TTS
- ),
- "provider_auth": (
- "El inicio de sesión del proveedor de IA no es válido o ha caducado." # i18n-allow
- ),
- "provider_quota": "La cuota del proveedor de IA está agotada.", # i18n-allow: Spanish TTS
- "provider_unreachable": "El proveedor de IA no está disponible ahora.", # i18n-allow
- "worker_timeout": "El worker superó su tiempo límite.", # i18n-allow: Spanish TTS
- },
- "pt": {
- "critic_loop_exhausted": "Três tentativas não chegaram.", # i18n-allow: PT TTS
- "critic_rejected": "A revisão não ficou satisfeita.", # i18n-allow: PT TTS
- "task_error": "O worker foi interrompido.", # i18n-allow: PT TTS
- "attempts_timed_out": "O tempo limite foi atingido.", # i18n-allow: PT TTS
- "review_time_budget_exhausted": ( # i18n-allow: Portuguese TTS phrase
- "O tempo de revisão esgotou-se; o resultado parcial está " # i18n-allow
- "disponível." # i18n-allow
- ),
- "budget_exceeded": "O limite de custo foi atingido.", # i18n-allow: PT TTS
- "decompose_failed": "Não consegui dividir a tarefa.", # i18n-allow: PT TTS
- "crash_recovery": "Uma missão antiga foi limpa.", # i18n-allow: PT TTS
- "interrupted": (
- "Uma missão em curso foi interrompida; os resultados " # i18n-allow: PT TTS
- "parciais estão disponíveis." # i18n-allow: PT TTS
- ),
- "empty_diff": "Não foi escrito nenhum ficheiro.", # i18n-allow: PT TTS
- "critic_unavailable": (
- "O revisor falhou; o trabalho está guardado no worktree." # i18n-allow: PT TTS
- ),
- "worktree_setup_failed": "Não consegui criar um espaço de trabalho.", # i18n-allow: PT TTS
- "checkpoint_missing": (
- "Falta o progresso guardado, por isso não posso continuar." # i18n-allow: PT TTS
- ),
- "git_missing": (
- "{agents} precisam que o git esteja instalado e no PATH." # i18n-allow: PT TTS
- ),
- "git_not_a_repository": (
- "{agents} precisam de uma cópia git (instala com o " # i18n-allow: PT TTS
- "instalador do git, não com uma transferência ZIP)." # i18n-allow: PT TTS
- ),
- "source_checkout_unavailable": (
- "Esta tarefa de {agent} precisa do " # i18n-allow: PT TTS
- "repositório do código-fonte, que não está " # i18n-allow: PT TTS
- "disponível nesta instalação." # i18n-allow: PT TTS
- ),
- "provider_auth": (
- "O início de sessão no fornecedor de IA é inválido ou expirou." # i18n-allow: PT TTS
- ),
- "provider_quota": "A quota do fornecedor de IA está esgotada.", # i18n-allow: PT TTS
- "provider_unreachable": "O fornecedor de IA não está acessível agora.", # i18n-allow
- "worker_timeout": "O worker excedeu o tempo limite.", # i18n-allow: PT TTS
- },
-}
+FAILURE_REASON_PHRASES: Final[dict[str, dict[str, str]]] = i18n_catalog.locale_maps(
+ "missions.readback.failure_reason"
+)
def approved_summary(payload: object, language: str) -> str:
@@ -597,24 +443,9 @@ _PROVIDER_FALLBACK_NAME: Final[dict[str, str]] = {
}
# Spoken defaults for an empty summary / reason / destructive target.
-_EMPTY_SUMMARY: Final[dict[str, str]] = {
- "de": "Aufgabe erledigt.", # i18n-allow: German TTS
- "en": "Task completed.",
- "es": "Tarea completada.", # i18n-allow: Spanish TTS
- "pt": "Tarefa concluída.", # i18n-allow: PT TTS
-}
-_UNKNOWN_REASON: Final[dict[str, str]] = {
- "de": "unbekannter Fehler", # i18n-allow: German TTS
- "en": "unknown error",
- "es": "error desconocido", # i18n-allow: Spanish TTS
- "pt": "erro desconhecido", # i18n-allow: PT TTS
-}
-_NO_TOOL_CALL: Final[dict[str, str]] = {
- "de": "Konnte ich nicht ausführen — kein Tool-Aufruf.", # i18n-allow: German TTS
- "en": "I could not do that — no tool call was made.",
- "es": "No pude hacerlo: no hubo ninguna llamada a herramienta.", # i18n-allow: Spanish TTS
- "pt": "Não consegui fazer isso: não houve nenhuma chamada a ferramenta.", # i18n-allow: PT TTS
-}
+_EMPTY_SUMMARY: Final[dict[str, str]] = i18n_catalog.table("missions.readback.empty_summary")
+_UNKNOWN_REASON: Final[dict[str, str]] = i18n_catalog.table("missions.readback.unknown_reason")
+_NO_TOOL_CALL: Final[dict[str, str]] = i18n_catalog.table("missions.readback.no_tool_call")
_DEFAULT_TARGET: Final[dict[str, str]] = {
"de": "diese Aktion", # i18n-allow: German TTS
"en": "this action",
diff --git a/jarvis/plugins/tool/spawn_worker.py b/jarvis/plugins/tool/spawn_worker.py
index 8f744d7b64..95dd145fbd 100644
--- a/jarvis/plugins/tool/spawn_worker.py
+++ b/jarvis/plugins/tool/spawn_worker.py
@@ -810,7 +810,7 @@ class SpawnWorkerTool:
manager: MissionManager,
kontrollierer: Any | None,
*,
- mission_language: str = "de",
+ mission_language: str = "en",
readback_language: str | None = None,
) -> None:
"""Laeuft im Background. Dispatched + executes eine Mission.
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index eae2644c89..9ddfaf5c4c 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -63,6 +63,7 @@ from jarvis.core.turn_language import (
resolve_output_language,
validate_output_language,
)
+from jarvis.i18n import catalog as i18n_catalog
from jarvis.realtime.audio import StreamingPcm16Resampler
from jarvis.realtime.protocol import RealtimeSessionConfig, RealtimeUnavailableError
from jarvis.realtime.report_prompt import clip_report, report_update_prompt
@@ -1038,24 +1039,14 @@ _HANDOVER_END_REASONS = frozenset({HANGUP_DESKTOP_FALLBACK, HANGUP_REALTIME_FALL
# owner prevents garbage collection from cancelling that user-visible debt.
_DETACHED_DELEGATE_TASKS: set[asyncio.Task[None]] = set()
-_LOCAL_OUTPUT_FAILURE: dict[str, str] = {
- "de": "Ich konnte das gerade nicht abspielen. Der Lautsprecher war weg.", # i18n-allow
- "en": "I couldn't play that just now. The speaker disappeared.",
- "es": "No pude reproducirlo ahora. El altavoz desapareció.", # i18n-allow
- "pt": "Não consegui reproduzir isso agora. O altifalante desapareceu.", # i18n-allow
-}
+_LOCAL_OUTPUT_FAILURE: dict[str, str] = i18n_catalog.table("realtime.local_output_failure")
_HISTORY_LOST_INSTRUCTION = (
"The previous realtime connection dropped and this is a FRESH session. "
"You have no memory of earlier turns in this call. Do not invent, recall, "
"or assert any prior topic, name, or request. Wait for the user's next "
"words and treat them as the start of the conversation."
)
-_OUTPUT_LANGUAGE_FAILURE: dict[str, str] = {
- "de": "Ich konnte gerade keine sichere Antwort auf Deutsch erzeugen.", # i18n-allow
- "en": "I couldn't produce a safe answer in English just now.",
- "es": "No pude generar una respuesta segura en español ahora mismo.", # i18n-allow
- "pt": "Não consegui gerar uma resposta segura em português agora.", # i18n-allow
-}
+_OUTPUT_LANGUAGE_FAILURE: dict[str, str] = i18n_catalog.table("realtime.output_language_failure")
_PUBLIC_FACT_UNCERTAINTY: dict[str, str] = {
"de": ( # i18n-allow
"Ich konnte das gerade nicht zuverlässig mit einer öffentlichen " # i18n-allow
@@ -1726,101 +1717,9 @@ _DELEGATE_BRIDGE_TEXTS: dict[str, tuple[str, ...]] = {
#: apology: "it did not come up in time" and "it could not be reached" send the
#: user to different places, and the whole point of speaking here is that the
#: call used to end after the full handshake budget with nothing said at all.
-_HANDSHAKE_FAILURE_MESSAGES: dict[str, dict[str, str]] = {
- "timeout": {
- "de": ( # i18n-allow: localized runtime voice output
- "Die Sprachverbindung kam nicht rechtzeitig zustande, " # i18n-allow
- "deshalb habe ich abgebrochen." # i18n-allow
- ),
- "en": (
- "The voice connection did not come up in time, so I stopped."
- ),
- "es": ( # i18n-allow: localized runtime voice output
- "La conexión de voz no se estableció a tiempo, así que lo detuve."
- ),
- "pt": ( # i18n-allow: localized runtime voice output
- "A ligação de voz não ficou pronta a tempo, por isso parei."
- ),
- },
- "unavailable": {
- "de": ( # i18n-allow: localized runtime voice output
- "Ich konnte die Sprachverbindung gerade nicht aufbauen." # i18n-allow
- ),
- "en": "I couldn't establish the voice connection just now.",
- "es": ( # i18n-allow: localized runtime voice output
- "No pude establecer la conexión de voz ahora mismo."
- ),
- "pt": ( # i18n-allow: localized runtime voice output
- "Não consegui estabelecer a ligação de voz agora."
- ),
- },
- "rate_limited": {
- "de": ( # i18n-allow: localized runtime voice output
- "Die Sprachverbindung ist gerade überlastet. " # i18n-allow
- "Bitte versuch es gleich noch einmal." # i18n-allow
- ),
- "en": (
- "The voice connection is busy right now. "
- "Please try again in a moment."
- ),
- "es": ( # i18n-allow: localized runtime voice output
- "La conexión de voz está saturada ahora mismo. "
- "Inténtalo de nuevo en un momento."
- ),
- "pt": ( # i18n-allow: localized runtime voice output
- "A ligação de voz está sobrecarregada neste momento. "
- "Tenta outra vez daqui a pouco."
- ),
- },
- "no_credits": {
- "de": ( # i18n-allow: localized runtime voice output
- "Das Guthaben für die Sprachverbindung ist aufgebraucht. " # i18n-allow
- "Lade es beim Anbieter auf, dann klappt es wieder." # i18n-allow
- ),
- "en": (
- "The credit for the voice connection is used up. "
- "Top it up with the provider and it will work again."
- ),
- "es": ( # i18n-allow: localized runtime voice output
- "Se agotó el saldo de la conexión de voz. "
- "Recárgalo con el proveedor y volverá a funcionar."
- ),
- "pt": ( # i18n-allow: localized runtime voice output
- "O saldo da ligação de voz esgotou-se. "
- "Carrega-o no fornecedor e volta a funcionar."
- ),
- },
- "not_offered": {
- "de": ( # i18n-allow: localized runtime voice output
- "Dein Konto bietet diese Sprachverbindung gerade nicht an. " # i18n-allow
- "Prüfe den Tarif oder wähle ein anderes Konto." # i18n-allow
- ),
- "en": (
- "Your account does not offer this voice connection right now. "
- "Check its plan or select another account."
- ),
- "es": ( # i18n-allow: localized runtime voice output
- "Tu cuenta no ofrece esta conexión de voz ahora mismo. "
- "Revisa el plan o elige otra cuenta."
- ),
- "pt": ( # i18n-allow: localized runtime voice output
- "A tua conta não oferece esta ligação de voz neste momento. "
- "Verifica o plano ou escolhe outra conta."
- ),
- },
- "dropped": {
- "de": ( # i18n-allow: localized runtime voice output
- "Die Sprachverbindung ist abgebrochen." # i18n-allow
- ),
- "en": "The voice connection dropped.",
- "es": ( # i18n-allow: localized runtime voice output
- "Se cortó la conexión de voz."
- ),
- "pt": ( # i18n-allow: localized runtime voice output
- "A ligação de voz caiu."
- ),
- },
-}
+_HANDSHAKE_FAILURE_MESSAGES: dict[str, dict[str, str]] = i18n_catalog.nested_table(
+ "realtime.handshake_failure"
+)
def _handshake_failure_message(cause: str, language: str) -> str:
diff --git a/jarvis/sessions/models.py b/jarvis/sessions/models.py
index b8464d8319..f41b4a0763 100644
--- a/jarvis/sessions/models.py
+++ b/jarvis/sessions/models.py
@@ -162,7 +162,7 @@ class VoiceSessionRow(BaseModel):
total_tokens_in: int = 0
total_tokens_out: int = 0
providers_used: list[str] = Field(default_factory=list)
- language: str = "de"
+ language: str = "en"
wake_keyword: str = ""
voice_mode: VoiceMode = VOICE_MODE_UNKNOWN
diff --git a/jarvis/sessions/recorder.py b/jarvis/sessions/recorder.py
index b149e8bf5c..1952aa16ab 100644
--- a/jarvis/sessions/recorder.py
+++ b/jarvis/sessions/recorder.py
@@ -484,7 +484,7 @@ class SessionRecorder:
self._state = _SessionState(
session_id=event.session_id,
started_ms=ts_ms,
- language=event.language or "de",
+ language=event.language or "en",
)
self._auto_turn_counter = 0
# A fresh session supersedes the previous one as the attach target for
@@ -496,7 +496,7 @@ class SessionRecorder:
session_id=event.session_id,
started_ms=ts_ms,
wake_keyword=event.wake_keyword,
- language=event.language or "de",
+ language=event.language or "en",
)
log.info("SessionRecorder: session started id=%s", event.session_id)
diff --git a/jarvis/sessions/store.py b/jarvis/sessions/store.py
index a7e19893d4..8cd75b0dd1 100644
--- a/jarvis/sessions/store.py
+++ b/jarvis/sessions/store.py
@@ -201,7 +201,7 @@ class SessionStore:
session_id: str,
started_ms: int,
wake_keyword: str = "",
- language: str = "de",
+ language: str = "en",
voice_mode: str = VOICE_MODE_UNKNOWN,
) -> None:
"""Create, or (on a recorder re-init) idempotently re-upsert.
diff --git a/jarvis/society/reply_preference.py b/jarvis/society/reply_preference.py
index 1fda739b7f..becd600deb 100644
--- a/jarvis/society/reply_preference.py
+++ b/jarvis/society/reply_preference.py
@@ -6,6 +6,7 @@ import logging
import re
from jarvis.core.turn_language import detect_language_request, resolve_output_language
+from jarvis.i18n import LANGUAGE_NAMES, SUPPORTED_LOCALES
from .notebook import Entry
from .working_rules import PREFIX
@@ -13,7 +14,7 @@ from .working_rules import PREFIX
_DURABLE = re.compile(
r"\b(?:always|from now on|immer|ab jetzt|siempre|a partir de ahora)\b", re.I # i18n-allow
) # i18n-allow
-_NAMES = {"en": "English", "de": "German", "es": "Spanish", "pt": "European Portuguese"}
+_NAMES = LANGUAGE_NAMES
log = logging.getLogger(__name__)
@@ -58,5 +59,9 @@ async def resolve_agent_reply_language(session_id: str, text: str, fallback: str
configured = getattr(getattr(runtime.config(), "brain", None), "reply_language", "auto")
# Explicit settings retain their precedence. A current language request
# overrides an older agent preference without mutating the shared config.
- pin = configured if configured in _NAMES else requested or preference
+ pin = configured if configured in SUPPORTED_LOCALES else requested or preference
+ if pin in _NAMES and pin not in SUPPORTED_LOCALES:
+ # A language without translated phrases (Turkish, ...): the agent
+ # still answers in it.
+ return pin
return resolve_output_language(pin, "unknown", text)
diff --git a/jarvis/speech/persona.py b/jarvis/speech/persona.py
index 6fd6838c95..c71b95e1ff 100644
--- a/jarvis/speech/persona.py
+++ b/jarvis/speech/persona.py
@@ -44,9 +44,8 @@ class PhrasePicker:
def pick(self, category: Category, lang: Lang = "de") -> str:
pool = PHRASES.get(category, {}).get(lang, [])
if not pool:
- # Fallback: andere Sprache
- other: Lang = "en" if lang == "de" else "de"
- pool = PHRASES.get(category, {}).get(other, [])
+ # Fallback: English, the one fallback language of system phrases.
+ pool = PHRASES.get(category, {}).get("en", [])
if not pool:
return ""
key = (category, lang)
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index d0c810f7df..87c7f1507a 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -97,6 +97,7 @@ from jarvis.core.turn_language import (
normalize_language_tag,
resolve_output_language,
)
+from jarvis.i18n import catalog as i18n_catalog
from jarvis.plugins.stt.fwhisper import FasterWhisperProvider
from jarvis.plugins.tts.gemini_flash_tts import GEMINI_TTS_SAMPLE_RATE, GeminiFlashTTS
from jarvis.plugins.wake.openwakeword_provider import (
@@ -448,24 +449,7 @@ async def _echo_brain(text: str) -> str:
# is UI-only, so it must not be read aloud. ``_speak`` does not scrub, so these
# phrases reach TTS verbatim. (Runtime TTS strings stay bilingual per the
# voice-output policy; only artifacts must be English.)
-_BRAIN_UNAVAILABLE_PHRASE: dict[str, str] = {
- "de": (
- "Entschuldige, Ruben — ich erreiche gerade keines meiner Sprachmodelle. "
- "Bitte prüf kurz, ob bei den Anbietern noch Guthaben ist."
- ),
- "en": (
- "Sorry, Ruben — I can't reach any of my language models right now. "
- "Please check whether your providers still have credit."
- ),
- "es": (
- "Lo siento, Ruben — ahora mismo no puedo acceder a ninguno de mis "
- "modelos de lenguaje. Comprueba si tus proveedores aún tienen crédito."
- ),
- "pt": (
- "Desculpa, Ruben — neste momento não consigo aceder a nenhum dos meus "
- "modelos de linguagem. Verifica se os teus fornecedores ainda têm crédito."
- ),
-}
+_BRAIN_UNAVAILABLE_PHRASE: dict[str, str] = i18n_catalog.table("speech.brain_unavailable")
# AD-OE6 zero-silent-drop fallback for the *final* utterance STT. A cloud STT
# (Groq/OpenAI/Deepgram) can transiently 429 when the in-utterance stability
@@ -473,38 +457,13 @@ _BRAIN_UNAVAILABLE_PHRASE: dict[str, str] = {
# ``_transcribe_final`` exhausts its retries we say this instead of dropping the
# user into silence (the "Jarvis listens forever, never answers" bug,
# 2026-05-25). Short, bilingual, TTS-clean (``_speak`` does not scrub).
-_STT_UNAVAILABLE_PHRASE: dict[str, str] = {
- "de": (
- "Entschuldige, ich habe dich akustisch gerade nicht verstanden. "
- "Sag es bitte noch einmal."
- ),
- "en": "Sorry, I didn't catch that just now. Could you say it again?",
- "es": "Perdona, no te he entendido bien ahora mismo. ¿Puedes repetirlo, por favor?",
- "pt": "Desculpa, não percebi bem o que disseste. Podes repetir, por favor?",
-}
+_STT_UNAVAILABLE_PHRASE: dict[str, str] = i18n_catalog.table("speech.stt_unavailable")
# Honest cross-family fallback when a requested duplex provider cannot open a
# session. The classic pipeline remains available for this voice call so a
# missing key, exhausted balance, unsupported model, or network outage never
# turns the Realtime switch into a silent dead end (AP-22/AP-23).
-_REALTIME_UNAVAILABLE_PHRASE: dict[str, str] = {
- "de": (
- "Die Realtime-Verbindung ist gerade nicht verfügbar. "
- "Ich wechsle für diese Sitzung zur klassischen Sprachverarbeitung."
- ),
- "en": (
- "The realtime connection is unavailable right now. "
- "I am switching this session to the classic voice pipeline."
- ),
- "es": (
- "La conexión en tiempo real no está disponible ahora mismo. "
- "Cambiaré esta sesión al sistema de voz clásico."
- ),
- "pt": (
- "A ligação em tempo real não está disponível neste momento. "
- "Vou mudar esta sessão para o sistema de voz clássico."
- ),
-}
+_REALTIME_UNAVAILABLE_PHRASE: dict[str, str] = i18n_catalog.table("speech.realtime_unavailable")
# AD-OE6 zero-silent-drop fallback for a brain TURN that times out. Live bug
# 2026-05-29: "kannst du Claude Code öffnen" stalled the Gemini stream; the
@@ -528,25 +487,9 @@ _REALTIME_UNAVAILABLE_PHRASE: dict[str, str] = {
# call in this timeout/scrub path (AP-11). Resolved through the ONE output-
# language decision via ``_resolve_timeout_phrase`` below (AGENTS.md §1 — no
# per-layer language re-derivation).
-_TIMEOUT_TOOL_STALL_PHRASE: dict[str, str] = {
- "de": (
- "Ich habe rechtzeitig keine Antwort bekommen. Ein Tool, auf das ich "
- "gewartet habe, hat nicht reagiert."
- ),
- "en": "I couldn't get an answer in time. A tool I was waiting on didn't respond.",
- "es": "No pude obtener una respuesta a tiempo. Una herramienta que esperaba no respondió.",
- "pt": (
- "Não consegui obter uma resposta a tempo. "
- "Uma ferramenta de que estava à espera não respondeu."
- ),
-}
+_TIMEOUT_TOOL_STALL_PHRASE: dict[str, str] = i18n_catalog.table("speech.timeout_tool_stall")
-_TIMEOUT_NO_ANSWER_PHRASE: dict[str, str] = {
- "de": "Das konnte ich gerade nicht herausfinden.",
- "en": "I couldn't find that out just now.",
- "es": "No pude averiguar eso ahora mismo.",
- "pt": "Não consegui descobrir isso agora.",
-}
+_TIMEOUT_NO_ANSWER_PHRASE: dict[str, str] = i18n_catalog.table("speech.timeout_no_answer")
# AD-OE6 zero-silent-drop fallback for an ABANDONED incomplete utterance. When
# the user trails off on a dangling fragment ("…erinnere mich daran, dass" +
@@ -9395,7 +9338,7 @@ class SpeechPipeline:
source_layer="speech.pipeline",
session_id=session_id,
wake_keyword=wake_keyword,
- language="de",
+ language=DEFAULT_LOCALE,
)
)
# A close accepted while a slow start subscriber runs must
@@ -17360,9 +17303,7 @@ class SpeechPipeline:
lang, len(dropped_sentences),
)
await _speak_sentence(
- FALLBACK_PHRASES.get(
- _phrase_lang(lang), FALLBACK_PHRASES["de"]
- )
+ i18n_catalog.pick(FALLBACK_PHRASES, _phrase_lang(lang))
)
except asyncio.CancelledError:
raise
@@ -18325,7 +18266,7 @@ class SpeechPipeline:
event = SpeechSpoken(
source_layer="speech.pipeline",
text=text,
- language=(language or "de"),
+ language=(language or "en"),
spoken_kind=kind,
detail=(detail or None),
voice=voice,
@@ -18415,11 +18356,13 @@ class SpeechPipeline:
# Conversation stickiness: a thin interjection ("Now") inherits the
# running conversation language instead of flipping ack/phrases/TTS
# (forensic 2026-06-18). The brain owns the sticky conversation language.
+ # An undetectable turn falls back to English (DEFAULT_LOCALE), never
+ # the UI language: the interface language says nothing about the
+ # language spoken (forensic 2026-10-19).
conv = getattr(brain, "conversation_language", "")
- ui = getattr(getattr(self, "_config", None), "ui", None)
return resolve_output_language(
pin, stt_language, text, conversation_language=conv,
- default=_phrase_lang(getattr(ui, "language", None)),
+ default=DEFAULT_LOCALE,
)
async def _speak(
diff --git a/jarvis/speech/rolling_whisper_wake.py b/jarvis/speech/rolling_whisper_wake.py
index 9163c78dea..c353971437 100644
--- a/jarvis/speech/rolling_whisper_wake.py
+++ b/jarvis/speech/rolling_whisper_wake.py
@@ -285,7 +285,7 @@ class RollingWhisperWake:
# During silence/quiet noise the gain is capped (max_gain_db).
target_peak_dbfs: float = -3.0,
max_gain_db: float = 40.0,
- language: str = "de",
+ language: str = "de", # input language, not output
# faster-whisper's exp(avg_logprob) score is harsh on 1-2 word wake
# chunks: live, cleanly-heard custom-name wakes land at ~0.28-0.52 (real
# samples 2026-06-23: "Ruben." 0.318, "Hey Ruhm" 0.365, "Hey Ruben" 0.52).
diff --git a/jarvis/telephony/session.py b/jarvis/telephony/session.py
index 1710ff3791..f3e7f4ca42 100644
--- a/jarvis/telephony/session.py
+++ b/jarvis/telephony/session.py
@@ -628,9 +628,9 @@ class TelephonyCallSession:
# -- helpers -----------------------------------------------------------
def _lang_short(self) -> str:
- """Short language code of the call (de/en/es/pt); German for others."""
+ """Short language code of the call (de/en/es/pt); English for others."""
short = self.language_code.lower().split("-")[0]
- return short if short in _DEFAULT_GREETINGS else "de"
+ return short if short in _DEFAULT_GREETINGS else "en"
def _default_greeting(self) -> str:
"""Greeting spoken when no custom ``greeting`` was configured.
diff --git a/jarvis/voice/action_phrases.py b/jarvis/voice/action_phrases.py
index 4967ae711a..22a74de16c 100644
--- a/jarvis/voice/action_phrases.py
+++ b/jarvis/voice/action_phrases.py
@@ -18,7 +18,7 @@ import re
from jarvis.core.turn_language import resolve_turn_language
-_DEFAULT = "de"
+_DEFAULT = "en"
_SUPPORTED = ("de", "en", "es", "pt")
#: ``HarnessTask.env`` key carrying the turn's resolved output language (de/en/es/pt)
diff --git a/jarvis/voice/config_readback.py b/jarvis/voice/config_readback.py
index f8836c39d5..e5ff12874d 100644
--- a/jarvis/voice/config_readback.py
+++ b/jarvis/voice/config_readback.py
@@ -21,7 +21,7 @@ from typing import Any, Literal
from .echo_confirmation import is_sensitive_path
_SUPPORTED = ("de", "en", "es", "pt")
-_DEFAULT = "de"
+_DEFAULT = "en"
# outcome key -> {lang -> template}. ``{label}`` / ``{value}`` are filled for the
# success cases; the failure cases are deliberately generic (no path/value leak).
diff --git a/jarvis/voice/contextual_readback.py b/jarvis/voice/contextual_readback.py
index 132b8f6a81..6647627de5 100644
--- a/jarvis/voice/contextual_readback.py
+++ b/jarvis/voice/contextual_readback.py
@@ -119,7 +119,7 @@ def build_readback_persona(language: str, *, instruction: str, facts_block: str)
situation supplied by the call site; ``facts_block`` is the rendered,
deterministic ground truth the model may use and nothing else.
"""
- language_name = _LANGUAGE_NAMES.get(language, "German")
+ language_name = _LANGUAGE_NAMES.get(language, "English")
return f"""You are the user's personal assistant, speaking one short \
status sentence out loud.
diff --git a/jarvis/voice/echo_confirmation.py b/jarvis/voice/echo_confirmation.py
index 2fc10f86e5..2e7432c8bf 100644
--- a/jarvis/voice/echo_confirmation.py
+++ b/jarvis/voice/echo_confirmation.py
@@ -197,7 +197,9 @@ _AMBIGUOUS_PATTERNS_PT: tuple[str, ...] = (
ResponseVerdict = Literal["confirm", "veto", "ambiguous", "unknown"]
-def classify_response(transcript: str, *, language: str = "de") -> ResponseVerdict:
+def classify_response(
+ transcript: str, *, language: str = "de" # input language, not output
+) -> ResponseVerdict:
"""Deterministically classifies the user's answer (no LLM call).
Order: Veto > Confirm > Ambiguous > Unknown.
@@ -317,7 +319,7 @@ def _lang_key(language: str, table: dict[str, Any]) -> str:
return language if language in table else "en"
-def _format_value_for_speech(value: Any, language: str = "de") -> str:
+def _format_value_for_speech(value: Any, language: str = "en") -> str:
"""Voice-friendly string from a primitive value.
Phase 7.4 keeps this simple — number verbalization ("one point three")
@@ -352,7 +354,7 @@ _ECHO_TEMPLATES_SENSITIVE: dict[str, str] = {
def format_confirmation(
- pending: PendingMutation, *, language: str = "de"
+ pending: PendingMutation, *, language: str = "en"
) -> str:
"""Renders the echo question per Plan-§7.4 + sensitive protection.
@@ -484,7 +486,7 @@ def format_outcome(
kind: OutcomeKind,
pending: PendingMutation,
*,
- language: str = "de",
+ language: str = "en",
short_error: str | None = None,
) -> str:
"""Plan-§7.4 voice-output templates.
@@ -512,7 +514,7 @@ def format_outcome(
return template.format(label=label, new=new_str, old=old_str, err=err)
-def short_error_from_exception(exc: BaseException) -> str:
+def short_error_from_exception(exc: BaseException, language: str | None = None) -> str:
"""Shortens a pipeline exception to a voice-friendly phrase.
Sub-agent-review-MAJOR (2026-04-26): the fallback branch used to pass
@@ -520,14 +522,17 @@ def short_error_from_exception(exc: BaseException) -> str:
widens the catch block (e.g. `except Exception`), the fallback
would leak plaintext values into TTS. Now: only a hard allowlist of
phrases, plus the Pydantic field path (no value) for PreValidateError.
+ The phrase is in ``language`` (the flow's language), English otherwise.
"""
+ from jarvis.i18n import t
+
if isinstance(exc, PreValidateError):
# `str(exc)` contains `repr(new_value)` in writer.py:_mutate_locked.
# We discard the message entirely and return a generic
# phrase. The detailed trace lands in the audit log, not in the TTS.
- return "Pre-Validate hat den Wert abgelehnt" # i18n-allow
+ return t("self_mod.short_error.pre_validate", language)
if isinstance(exc, ReloadError):
- return "der Reload-Test hat den neuen Wert abgelehnt" # i18n-allow
+ return t("self_mod.short_error.reload", language)
if isinstance(exc, RollbackError):
- return "der Rollback selbst ist fehlgeschlagen — manueller Restore nötig" # i18n-allow
- return "unerwarteter Fehler in der Mutation-Pipeline" # i18n-allow
+ return t("self_mod.short_error.rollback", language)
+ return t("self_mod.short_error.unexpected", language)
diff --git a/jarvis/voice/number_speller.py b/jarvis/voice/number_speller.py
index de6fcc20ac..35a63ee83d 100644
--- a/jarvis/voice/number_speller.py
+++ b/jarvis/voice/number_speller.py
@@ -135,7 +135,7 @@ _LAST_WORD_RE = re.compile(r"([^\W\d_]+)\W*$")
def _norm_lang(language: str | None) -> str:
if not language:
- return "de"
+ return "en"
low = language.lower()
if low.startswith("en"):
return "en"
@@ -343,7 +343,7 @@ def _spell_dotted_token(token: str, lang: str, cue: str, at_end: bool) -> str |
return None if spoken is None else spoken + tail
-def spell_out_numbers(text: str, language: str = "de") -> str:
+def spell_out_numbers(text: str, language: str = "en") -> str:
"""Spell every digit run in ``text`` out as words for the given locale.
Never raises. A no-op when ``num2words`` is missing, the language is
diff --git a/jarvis/voice/self_mod_flow.py b/jarvis/voice/self_mod_flow.py
index 92f647a100..588c2e468c 100644
--- a/jarvis/voice/self_mod_flow.py
+++ b/jarvis/voice/self_mod_flow.py
@@ -80,7 +80,7 @@ class FlowSession:
state: FlowState
echo_question: str
deadline_ts: float
- language: str = "de"
+ language: str = "en"
transcript: str | None = None
confidence: float | None = None
final_message: str | None = None
@@ -121,7 +121,7 @@ class SelfModFlowController:
pending_store: PendingMutationStore,
audit: SelfModAudit | None = None,
timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
- default_language: str = "de",
+ default_language: str = "en",
) -> None:
self._pending_store = pending_store
# Audit for pre-events (voice_confirmed). Reject events run through
@@ -258,7 +258,7 @@ class SelfModFlowController:
else "validate_failed",
session.pending,
language=session.language,
- short_error=short_error_from_exception(exc),
+ short_error=short_error_from_exception(exc, session.language),
),
)
except KeyError as exc:
diff --git a/jarvis/voice/subscription_profile.py b/jarvis/voice/subscription_profile.py
index dbf3d01c3b..d2ce4d7bbc 100644
--- a/jarvis/voice/subscription_profile.py
+++ b/jarvis/voice/subscription_profile.py
@@ -16,15 +16,13 @@ from typing import Any
from jarvis.brain.turn_planner import TurnReason, plan_turn
from jarvis.core.protocols import BrainMessage, BrainRequest
-from jarvis.core.turn_language import is_substantive_turn, resolve_output_language
+from jarvis.core.turn_language import is_substantive_turn, resolve_conversation_language
+from jarvis.i18n import is_known_language, language_name
from jarvis.plugins.brain.codex import CodexBrain
CODEX_SUBSCRIPTION_VOICE_PROFILE = "codex-subscription-voice"
LEGACY_CODEX_REALTIME_PROVIDER = "codex-subscription-realtime"
-_LANGUAGE_NAMES = {
- "de": "German", "en": "English", "es": "Spanish", "pt": "European Portuguese",
-}
_MAX_HISTORY_MESSAGES = 6
_SUPPORTED_DESKTOP_PLATFORMS = frozenset({"win32", "darwin", "linux"})
@@ -119,7 +117,7 @@ def subscription_voice_selected(config: object) -> bool:
def subscription_language_directive(language: str) -> str:
- name = _LANGUAGE_NAMES.get(language, "English")
+ name = language_name(language) or "English"
return (
f"REPLY LANGUAGE — MANDATORY: Always reply in {name}, no matter which "
"language the user writes or speaks in. This overrides every other "
@@ -241,13 +239,15 @@ class CodexSubscriptionVoiceBrain:
self._last_turn_executed_action_tool = False
reply_pin = getattr(getattr(self._config, "brain", None), "reply_language", "auto")
- language = resolve_output_language(
+ # The language the person speaks, any one: a Turkish speaker is
+ # answered in Turkish, not in the nearest language with system phrases.
+ language = resolve_conversation_language(
reply_pin,
"",
text,
conversation_language=self._conversation_language,
)
- if is_substantive_turn(text):
+ if is_substantive_turn(text) and is_known_language(language):
self._conversation_language = language
messages = tuple([*self._history[-_MAX_HISTORY_MESSAGES:], BrainMessage("user", text)])
diff --git a/jarvis/voice/tool_confirmation.py b/jarvis/voice/tool_confirmation.py
index 5741b70098..67f8183a17 100644
--- a/jarvis/voice/tool_confirmation.py
+++ b/jarvis/voice/tool_confirmation.py
@@ -110,7 +110,7 @@ _IMPACT_COMMANDS_MAX_CHARS = 60
def format_tool_confirmation(
tool_name: str,
*,
- language: str = "de",
+ language: str = "en",
impact_level: str | None = None,
impact_commands: str | None = None,
) -> str:
@@ -193,7 +193,7 @@ _FAILED_DETAIL_MAX_CHARS = 160
def format_confirm_outcome(
- kind: str, tool_name: str, *, language: str = "de", detail: str | None = None
+ kind: str, tool_name: str, *, language: str = "en", detail: str | None = None
) -> str:
"""Render the outcome phrase after the user answered a confirmation.
diff --git a/pyproject.toml b/pyproject.toml
index 0896528548..e40570ce57 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -920,6 +920,8 @@ jarvis = [
# The Hermes / OpenClaw releases setup installs and accepts
# (agent_runtimes/versions.py); without it setup falls back to latest.
"agent_runtimes/runtime-versions.json",
+ # Translated system phrases, one file per language (jarvis/i18n/catalog.py).
+ "i18n/locales/*.json",
# Seed catalogs (CLI tools / skills / marketplace plugins) — named
# explicitly rather than a repo-wide "**/*.json" glob, which would also
# sweep in jarvis/ui/web/frontend's SOURCE config (package.json,
diff --git a/tests/missions/kontrollierer/test_answer_document.py b/tests/missions/kontrollierer/test_answer_document.py
index 34efd0fdf1..5dae211dac 100644
--- a/tests/missions/kontrollierer/test_answer_document.py
+++ b/tests/missions/kontrollierer/test_answer_document.py
@@ -78,14 +78,14 @@ def test_report_lands_in_deliverable_subtree(tmp_path: Path) -> None:
assert rel[3] == "files"
-def test_report_is_found_by_build_deliverable_summary(tmp_path: Path) -> None:
+def test_report_is_found_by_build_deliverable_summary(tmp_path: Path, language="de") -> None:
"""End-to-end: after materialising, the readback summary names the report."""
_task_dir(tmp_path)
out = materialize_answer_document(
tmp_path, answers=[_LONG_ANSWER], prompt="relocate to SF"
)
assert out is not None
- summary = build_deliverable_summary(tmp_path)
+ summary = build_deliverable_summary(tmp_path, language="de")
assert out.name in summary
assert "Artefakt" in summary # i18n-allow: DE readback
diff --git a/tests/missions/kontrollierer/test_deliver_to_user_folder.py b/tests/missions/kontrollierer/test_deliver_to_user_folder.py
index e92669aa06..71790bfdc4 100644
--- a/tests/missions/kontrollierer/test_deliver_to_user_folder.py
+++ b/tests/missions/kontrollierer/test_deliver_to_user_folder.py
@@ -90,7 +90,7 @@ def test_build_delivered_summary_single(tmp_path: Path) -> None:
folder.mkdir()
f = folder / "report.html"
f.write_text("x", encoding="utf-8")
- out = build_delivered_summary([f])
+ out = build_delivered_summary([f], language="de")
assert "report.html" in out
# The folder is never spoken (maintainer 2026-08-23): the file is "an artifact".
assert "Jarvis-Outputs" not in out
@@ -99,7 +99,7 @@ def test_build_delivered_summary_single(tmp_path: Path) -> None:
def test_build_delivered_summary_empty() -> None:
- assert build_delivered_summary([]) == ""
+ assert build_delivered_summary([], language="de") == ""
def test_skips_browser_profile_scratch(tmp_path: Path) -> None:
diff --git a/tests/missions/kontrollierer/test_deliverable.py b/tests/missions/kontrollierer/test_deliverable.py
index b059d79f1e..f2148ee13b 100644
--- a/tests/missions/kontrollierer/test_deliverable.py
+++ b/tests/missions/kontrollierer/test_deliverable.py
@@ -23,13 +23,13 @@ from jarvis.missions.kontrollierer.deliverable import (
def test_no_tasks_dir_returns_empty(tmp_path: Path) -> None:
"""No ``tasks/`` subdir → empty string, caller falls back to generic."""
- assert build_deliverable_summary(tmp_path) == ""
+ assert build_deliverable_summary(tmp_path, language="de") == ""
def test_tasks_dir_without_artifacts_returns_empty(tmp_path: Path) -> None:
"""Tasks exist but produced no files (Edit-only on tracked files) → empty."""
(tmp_path / "tasks" / "019e63c5-5855").mkdir(parents=True)
- assert build_deliverable_summary(tmp_path) == ""
+ assert build_deliverable_summary(tmp_path, language="de") == ""
def test_single_file_is_named(tmp_path: Path) -> None:
@@ -37,7 +37,7 @@ def test_single_file_is_named(tmp_path: Path) -> None:
files = tmp_path / "tasks" / "019e63c5-5855" / "artifacts" / "files"
files.mkdir(parents=True)
(files / "landing.html").write_text("<html/>", encoding="utf-8")
- s = build_deliverable_summary(tmp_path)
+ s = build_deliverable_summary(tmp_path, language="de")
assert "landing.html" in s, f"filename must appear in summary, got {s!r}"
assert "Artefakt" in s # i18n-allow: asserts the German TTS readback text
assert "Artefakt" in s # i18n-allow: asserts the German TTS readback text
@@ -49,7 +49,7 @@ def test_two_files_are_named(tmp_path: Path) -> None:
files.mkdir(parents=True)
(files / "landing.html").write_text("<html/>", encoding="utf-8")
(files / "notes.md").write_text("notes", encoding="utf-8")
- s = build_deliverable_summary(tmp_path)
+ s = build_deliverable_summary(tmp_path, language="de")
assert "landing.html" in s and "notes.md" in s
assert "2 Dateien" in s
@@ -60,7 +60,7 @@ def test_many_files_collapses_to_count(tmp_path: Path) -> None:
files.mkdir(parents=True)
for i in range(5):
(files / f"f{i}.txt").write_text(str(i), encoding="utf-8")
- s = build_deliverable_summary(tmp_path)
+ s = build_deliverable_summary(tmp_path, language="de")
assert "5 Dateien" in s
# Individual filenames must NOT all be in the spoken text
spoken_filenames = sum(1 for i in range(5) if f"f{i}.txt" in s)
@@ -75,7 +75,7 @@ def test_multi_task_files_are_aggregated(tmp_path: Path) -> None:
files = tmp_path / "tasks" / task_id / "artifacts" / "files"
files.mkdir(parents=True)
(files / f"{task_id}.html").write_text("<html/>", encoding="utf-8")
- s = build_deliverable_summary(tmp_path)
+ s = build_deliverable_summary(tmp_path, language="de")
assert "2 Dateien" in s
assert "task1.html" in s and "task2.html" in s
@@ -85,7 +85,7 @@ def test_nested_files_are_counted(tmp_path: Path) -> None:
nested = tmp_path / "tasks" / "task1" / "artifacts" / "files" / "subdir"
nested.mkdir(parents=True)
(nested / "inner.txt").write_text("inner", encoding="utf-8")
- s = build_deliverable_summary(tmp_path)
+ s = build_deliverable_summary(tmp_path, language="de")
assert "inner.txt" in s
@@ -95,7 +95,7 @@ def test_only_basename_in_summary_no_path_separators(tmp_path: Path) -> None:
nested = tmp_path / "tasks" / "task1" / "artifacts" / "files" / "deep" / "nest"
nested.mkdir(parents=True)
(nested / "report.md").write_text("x", encoding="utf-8")
- s = build_deliverable_summary(tmp_path)
+ s = build_deliverable_summary(tmp_path, language="de")
assert "report.md" in s
assert "/" not in s and "\\" not in s, (
f"path separators must not leak into the spoken summary: {s!r}"
@@ -105,7 +105,7 @@ def test_only_basename_in_summary_no_path_separators(tmp_path: Path) -> None:
def test_missing_mission_dir_returns_empty(tmp_path: Path) -> None:
"""Defensive: a non-existent mission dir must not crash the readback path."""
bogus = tmp_path / "does-not-exist"
- assert build_deliverable_summary(bogus) == ""
+ assert build_deliverable_summary(bogus, language="de") == ""
# --- Dispatch-language localisation -----------------------------------------
@@ -143,12 +143,12 @@ def test_two_files_summary_in_english(tmp_path: Path) -> None:
assert "Dateien" not in s, f"English summary leaked German plural: {s!r}"
-def test_deliverable_summary_defaults_to_german(tmp_path: Path) -> None:
- """No language arg keeps the historical German output (back-compat)."""
+def test_deliverable_summary_defaults_to_english(tmp_path: Path) -> None:
+ """No language arg reads English, the fallback of every system phrase."""
files = tmp_path / "tasks" / "019e63c5-5855" / "artifacts" / "files"
files.mkdir(parents=True)
(files / "landing.html").write_text("<html/>", encoding="utf-8")
- assert "Artefakt" in build_deliverable_summary(tmp_path) # i18n-allow: DE readback
+ assert "artifact" in build_deliverable_summary(tmp_path)
def test_delivered_summary_in_english(tmp_path: Path) -> None:
@@ -167,16 +167,15 @@ def test_delivered_summary_in_english(tmp_path: Path) -> None:
)
-def test_delivered_summary_defaults_to_german(tmp_path: Path) -> None:
- """No language arg keeps the German output (back-compat) — as an artifact,
- never as a folder."""
+def test_delivered_summary_defaults_to_english(tmp_path: Path) -> None:
+ """No language arg reads English — as an artifact, never as a folder."""
folder = tmp_path / "Jarvis-Outputs"
folder.mkdir()
f = folder / "report.md"
f.write_text("x", encoding="utf-8")
s = build_delivered_summary([f])
- assert "Artefakt" in s # i18n-allow: asserts the German TTS readback text
- assert "Ordner" not in s and "Jarvis-Outputs" not in s # i18n-allow: asserts absence
+ assert "artifact" in s
+ assert "folder" not in s and "Jarvis-Outputs" not in s
# --- End-of-chain seam ------------------------------------------------------
diff --git a/tests/missions/test_mission_language_pt.py b/tests/missions/test_mission_language_pt.py
index e92f827f55..cb558dde5a 100644
--- a/tests/missions/test_mission_language_pt.py
+++ b/tests/missions/test_mission_language_pt.py
@@ -49,7 +49,7 @@ def test_dispatch_payload_accepts_portuguese() -> None:
@pytest.mark.parametrize(
("value", "expected"),
- [("pt", "pt"), ("ES", "es"), ("fr", "de"), (None, "de"), ("", "de")],
+ [("pt", "pt"), ("ES", "es"), ("fr", "en"), (None, "en"), ("", "en")],
)
def test_coerce_mission_language(value: object, expected: str) -> None:
assert coerce_mission_language(value) == expected
diff --git a/tests/unit/agent_chat/test_runner_brain.py b/tests/unit/agent_chat/test_runner_brain.py
index 307fbbf181..1732ca2f4c 100644
--- a/tests/unit/agent_chat/test_runner_brain.py
+++ b/tests/unit/agent_chat/test_runner_brain.py
@@ -386,6 +386,35 @@ async def test_a_continuation_is_briefing_not_the_persons_words(
assert kw["force_output_language"] == "en" # the request's language, resolved once
+async def test_a_continuation_keeps_a_turkish_conversation_turkish(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, no_cli
+):
+ """Forensic 2026-10-19: the neutral English continue line flipped a Turkish
+ chat to English on every delegated result. The turn is pinned to the
+ request's language and the brain reads its language from the request."""
+ from jarvis.agent_chat.delegation_wait import CONTINUE_TURN, continuation_prompt
+
+ fake = FakeBrainManager()
+ monkeypatch.setattr(runner_brain, "brain_manager", lambda: fake)
+ svc = _service(None)
+ session = _jarvis_session(svc, tmp_path)
+ q = svc.subscribe(session.session_id)
+ original = "Kai'ye giriş hatasını düzeltmesini söyle lütfen." # i18n-allow
+ prompt = continuation_prompt(
+ [{"status": "failed", "report": "Kai could not finish.", "agent": "Kai"}],
+ original,
+ later=True,
+ )
+
+ await svc.send(session.session_id, prompt, display_text=original, background_result=True)
+ await _drain(q, "turn_finished")
+
+ text, kw = fake.calls[0]
+ assert text == CONTINUE_TURN
+ assert kw["force_output_language"] == "tr"
+ assert kw["language_text"] == original
+
+
async def test_an_ordinary_turn_names_no_separate_request(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, no_cli
):
diff --git a/tests/unit/brain/test_ack_brain/test_persona_language.py b/tests/unit/brain/test_ack_brain/test_persona_language.py
index d4b010334c..2a23ee2a55 100644
--- a/tests/unit/brain/test_ack_brain/test_persona_language.py
+++ b/tests/unit/brain/test_ack_brain/test_persona_language.py
@@ -22,15 +22,16 @@ def test_get_persona_prompt_resolves_each_language() -> None:
assert get_persona_prompt("pt") == PERSONA_PROMPT_PT
-def test_get_persona_prompt_normalises_tags_and_falls_back_to_de() -> None:
+def test_get_persona_prompt_normalises_tags_and_falls_back_to_en() -> None:
assert get_persona_prompt("en-US") == PERSONA_PROMPT_EN
assert get_persona_prompt("es-ES") == PERSONA_PROMPT_ES
assert get_persona_prompt("pt-PT") == PERSONA_PROMPT_PT
assert get_persona_prompt("de-DE") == PERSONA_PROMPT_DE
- # Unknown / empty / None falls back to German (the STT default on ambiguity).
- assert get_persona_prompt("fr") == PERSONA_PROMPT_DE
- assert get_persona_prompt("") == PERSONA_PROMPT_DE
- assert get_persona_prompt(None) == PERSONA_PROMPT_DE
+ assert get_persona_prompt("german") == PERSONA_PROMPT_DE
+ # Unknown / empty / None falls back to English (DEFAULT_LOCALE), never German.
+ assert get_persona_prompt("fr") == PERSONA_PROMPT_EN
+ assert get_persona_prompt("") == PERSONA_PROMPT_EN
+ assert get_persona_prompt(None) == PERSONA_PROMPT_EN
def test_preamble_personas_are_name_neutral() -> None:
diff --git a/tests/unit/brain/test_ack_generator.py b/tests/unit/brain/test_ack_generator.py
index d16432809f..ba25d105f6 100644
--- a/tests/unit/brain/test_ack_generator.py
+++ b/tests/unit/brain/test_ack_generator.py
@@ -394,12 +394,17 @@ class TestLanguageCoverage:
ack = generate_ack("run_shell", {}, language=hint, picker=_fresh())
assert ack in _SHELL_ACK["en"]
- @pytest.mark.parametrize("hint", ["de", "DE", "de-DE", "german", "deutsch", "fr", ""])
- def test_non_english_hints_default_to_de(self, hint: str) -> None:
- # Project default is German; unrecognized hints fall to de.
+ @pytest.mark.parametrize("hint", ["de", "DE", "de-DE", "german", "deutsch"])
+ def test_german_hints_resolve_to_de(self, hint: str) -> None:
ack = generate_ack("run_shell", {}, language=hint, picker=_fresh())
assert ack in _SHELL_ACK["de"]
+ @pytest.mark.parametrize("hint", ["fr", "tr", ""])
+ def test_unknown_hints_default_to_en(self, hint: str) -> None:
+ # Every system phrase falls back to English (DEFAULT_LOCALE), never German.
+ ack = generate_ack("run_shell", {}, language=hint, picker=_fresh())
+ assert ack in _SHELL_ACK["en"]
+
def test_spanish_hint_resolves_to_es(self) -> None:
ack = generate_ack("run_shell", {}, language="es", picker=_fresh())
assert ack in _SHELL_ACK["es"]
@@ -409,9 +414,9 @@ class TestLanguageCoverage:
ack = generate_ack("run_shell", {}, language=hint, picker=_fresh())
assert ack in _SHELL_ACK["pt"]
- def test_none_language_defaults_to_de(self) -> None:
+ def test_none_language_defaults_to_en(self) -> None:
ack = generate_ack("run_shell", {}, language=None, picker=_fresh()) # type: ignore[arg-type]
- assert ack in _SHELL_ACK["de"]
+ assert ack in _SHELL_ACK["en"]
class TestGermanDiacritics:
@@ -472,8 +477,8 @@ class TestFinalSummaryMarker:
def test_english(self) -> None:
assert final_summary_marker("en") == "Done."
- def test_unknown_language_defaults_to_de(self) -> None:
- assert final_summary_marker("fr") == "Erledigt." # i18n-allow: German completion marker under test
+ def test_unknown_language_defaults_to_en(self) -> None:
+ assert final_summary_marker("fr") == "Done."
class TestShouldPrependMarker:
diff --git a/tests/unit/brain/test_conversation_language_retention.py b/tests/unit/brain/test_conversation_language_retention.py
new file mode 100644
index 0000000000..0db6063b7a
--- /dev/null
+++ b/tests/unit/brain/test_conversation_language_retention.py
@@ -0,0 +1,225 @@
+"""A conversation keeps its language through failures, restarts and internal turns.
+
+Forensic 2026-10-19: a person chatting in Turkish in the English UI got error
+messages in German, then Spanish, then English, and the answers themselves
+switched between Turkish, German and English after an error. Turkish umlauts
+scored as German and ç as Portuguese, the misdetected language was pinned as
+"Always reply in German", every failure path fell back to its own language
+(mostly German), and an internal English "continue" prompt flipped the shared
+conversation language to English.
+"""
+from __future__ import annotations
+
+import pytest
+
+from jarvis.brain.manager import (
+ _PROVIDER_DOWN_PHRASES,
+ _TURN_HISTORY_OVERRIDE,
+ BrainManager,
+ _provider_down_phrase,
+)
+from jarvis.core.protocols import BrainMessage
+from jarvis.core.turn_language import (
+ conversation_language_from_history,
+ detect_conversation_language,
+ detect_language_request,
+ detect_text_language,
+ resolve_conversation_language,
+ resolve_output_language,
+)
+
+_TURKISH = (
+ "Merhaba, bugün hava nasıl?", # i18n-allow
+ "Bana bir e-posta yazar mısın lütfen", # i18n-allow
+ "Neden çalışmıyor bu program",
+ "Şunu al ve bana ver",
+ "El yazısı ile yaz",
+ "Bu dosyayı düzeltebilir misin? Çok önemli.", # i18n-allow
+ "yarın için bir hatırlatıcı kur",
+)
+
+
+def _mgr(reply_language: str = "auto", conv: str = "") -> BrainManager:
+ m = BrainManager.__new__(BrainManager)
+ m._reply_language = reply_language
+ m._conversation_language = conv
+ m._turn_detected_lang = ""
+ m._provider_down_idx = 0
+ return m
+
+
[email protected]("text", _TURKISH)
+def test_turkish_is_turkish_not_the_supported_language_it_resembles(text: str) -> None:
+ assert detect_text_language(text) == "unknown"
+ assert detect_conversation_language(text) == "tr"
+
+
+ ("text", "code"),
+ [
+ ("Wie wird das Wetter morgen in Istanbul?", "de"), # i18n-allow
+ ("Öffne die Datei", "de"), # i18n-allow
+ ("Ruf bitte Łukasz an", "de"),
+ ("What is the weather like tomorrow?", "en"),
+ ("¿Qué tiempo hace hoy?", "es"),
+ ("Não consigo abrir o ficheiro", "pt"),
+ ],
+)
+def test_supported_languages_are_unchanged(text: str, code: str) -> None:
+ assert detect_text_language(text) == code
+ assert detect_conversation_language(text) == code
+
+
+ ("text", "code"),
+ [
+ ("Bonjour, je voudrais savoir pourquoi ça ne marche pas", "fr"),
+ ("سلام، حال شما چطور است؟", "fa"),
+ ("Привіт, як справи? Їжак", "uk"),
+ ("Привет, как дела?", "ru"),
+ ("こんにちは、元気ですか", "ja"),
+ ("你好,今天天气怎么样", "zh"),
+ ("Hoe gaat het met je vandaag?", "nl"),
+ ("Cześć, jak się masz?", "pl"),
+ ],
+)
+def test_other_languages_are_recognised(text: str, code: str) -> None:
+ assert detect_conversation_language(text) == code
+
+
+ "text",
+ [
+ "Sie hat nie angerufen",
+ "Hast du mit ihm gesprochen",
+ "Mi mamá ama a Pedro",
+ "Le dije que no",
+ "Eu vi este filme",
+ "Ich war most of the time da",
+ ],
+)
+def test_everyday_supported_words_never_read_as_another_language(text: str) -> None:
+ assert detect_conversation_language(text) in {"de", "en", "es", "pt", "unknown"}
+
+
+def test_other_language_word_lists_share_no_word_with_the_supported_ones() -> None:
+ from jarvis.core.turn_language import _OTHER_TOKENS, _SETS, _SUPPORTED_COMMON_WORDS
+
+ supported = set().union(*(words for _code, words in _SETS)) | _SUPPORTED_COMMON_WORDS
+ for code, words in _OTHER_TOKENS.items():
+ assert not words & supported, (code, sorted(words & supported))
+
+
+def test_a_pinned_stt_tag_never_runs_german_rules_on_turkish() -> None:
+ from jarvis.core.turn_language import resolve_transcript_language
+
+ assert resolve_transcript_language("german", "Neden çalışmıyor bu program") == "unknown"
+
+
+def test_a_continuation_turn_keeps_its_phrase_language() -> None:
+ # Inside generate() the turn's resolved language wins over the text, so an
+ # internal English prompt never makes a German chat's error phrase English.
+ from jarvis.core.turn_language import TURN_LANGUAGE
+
+ m = _mgr(conv="de")
+ token = TURN_LANGUAGE.set("de")
+ try:
+ assert m._phrase_language("Continue the earlier request with the results") == "de"
+ assert m._resolve_turn_lang() == "de"
+ finally:
+ TURN_LANGUAGE.reset(token)
+ token = TURN_LANGUAGE.set("tr")
+ try:
+ assert m._phrase_language("Continue the earlier request with the results") == "en"
+ assert "Turkish" in m._reply_language_directive()
+ finally:
+ TURN_LANGUAGE.reset(token)
+
+
+def test_system_phrases_for_a_language_without_translations_are_english() -> None:
+ for text in _TURKISH:
+ assert resolve_output_language("auto", "unknown", text) == "en"
+ assert resolve_output_language("auto", None, "tamam", conversation_language="tr") == "en"
+
+
+def test_turkish_conversation_survives_short_turns_and_stays_turkish() -> None:
+ language = ""
+ for text in (_TURKISH[0], "tamam", "ok", _TURKISH[2]):
+ language = resolve_conversation_language(
+ "auto", None, text, conversation_language=language
+ )
+ assert language == "tr", text
+
+
+def test_a_short_turn_in_its_own_script_switches_language() -> None:
+ assert resolve_conversation_language(
+ "auto", None, "Dosyayı aç", conversation_language="en"
+ ) == "tr"
+ assert resolve_conversation_language("auto", None, "Now", conversation_language="tr") == "tr"
+
+
+def test_language_requests_name_languages_without_translations() -> None:
+ assert detect_language_request("Türkçe konuş") == "tr" # i18n-allow
+ assert detect_language_request("please answer in Turkish") == "tr"
+ assert detect_language_request("reply in German") == "de"
+
+
+def test_history_restores_the_conversation_language_after_a_restart() -> None:
+ history = [
+ BrainMessage(role="user", content="Merhaba, bugün hava nasıl?"), # i18n-allow
+ BrainMessage(role="assistant", content="Bugün hava güneşli."), # i18n-allow
+ BrainMessage(role="user", content="tamam"),
+ ]
+ assert conversation_language_from_history(history) == "tr"
+ assert conversation_language_from_history([{"role": "user", "content": "ok"}]) == ""
+
+
+def test_model_is_told_to_answer_in_turkish() -> None:
+ m = _mgr()
+ m._update_turn_language("Merhaba, bugün hava nasıl?") # i18n-allow
+ assert m.conversation_language == "tr"
+ directive = m._reply_language_directive()
+ assert "Always reply in Turkish" in directive
+ assert "German" not in directive
+
+
+def test_failure_phrases_in_a_turkish_conversation_are_always_english() -> None:
+ m = _mgr()
+ for text in _TURKISH:
+ m._update_turn_language(text)
+ assert m._resolve_turn_lang() == "en", text
+ assert m._next_provider_down_phrase() in _PROVIDER_DOWN_PHRASES["en"]
+ assert m._action_failed_phrase(text) == m._action_failed_phrase("Do it now please")
+
+
+def test_an_internal_english_prompt_does_not_change_the_conversation() -> None:
+ m = _mgr(conv="tr")
+ m._update_turn_language("") # generate(language_text="") for a continue turn
+ assert m.conversation_language == "tr"
+ assert m._turn_detected_lang == "tr"
+
+
+def test_a_chat_turn_takes_its_language_from_its_own_history() -> None:
+ # Another chat or a voice turn left English in the shared manager; this
+ # chat's own history is Turkish, so a short turn stays Turkish.
+ m = _mgr(conv="en")
+ token = _TURN_HISTORY_OVERRIDE.set(
+ (BrainMessage(role="user", content="Bana bir e-posta yazar mısın lütfen"),) # i18n-allow
+ )
+ try:
+ m._update_turn_language("tamam")
+ finally:
+ _TURN_HISTORY_OVERRIDE.reset(token)
+ assert m._turn_detected_lang == "tr"
+ assert m.conversation_language == "tr"
+
+
+def test_a_forced_language_without_translations_is_pinned() -> None:
+ m = _mgr()
+ m._turn_detected_lang = "tr"
+ assert "Turkish" in m._reply_language_directive()
+
+
[email protected]("lang", ["auto", "", "tr", "fr", "xx"])
+def test_provider_down_phrase_falls_back_to_english(lang: str) -> None:
+ assert _provider_down_phrase(lang, 0) == _PROVIDER_DOWN_PHRASES["en"][0]
diff --git a/tests/unit/brain/test_fallback_language.py b/tests/unit/brain/test_fallback_language.py
index 3de8606e99..36579be079 100644
--- a/tests/unit/brain/test_fallback_language.py
+++ b/tests/unit/brain/test_fallback_language.py
@@ -77,9 +77,9 @@ def test_anti_silence_phrase_pin_beats_text_detection() -> None:
assert _DE_ANTI_SILENCE_MARKER in phrase
-def test_anti_silence_phrase_ambiguous_text_defaults_german() -> None:
+def test_anti_silence_phrase_ambiguous_text_defaults_english() -> None:
phrase = _anti_silence_phrase("", "auto")
- assert _DE_ANTI_SILENCE_MARKER in phrase
+ assert phrase == _EN_ANTI_SILENCE
def test_meta_debug_ack_phrase_localized() -> None:
diff --git a/tests/unit/brain/test_honesty_language_parity.py b/tests/unit/brain/test_honesty_language_parity.py
index b526f18f16..a986de1c23 100644
--- a/tests/unit/brain/test_honesty_language_parity.py
+++ b/tests/unit/brain/test_honesty_language_parity.py
@@ -47,6 +47,6 @@ def test_no_output_language_call_pins_its_own_default() -> None:
def test_the_two_honesty_guards_share_one_resolution() -> None:
"""The evidence fallback and the action-honesty guard read one variable."""
source = _MANAGER.read_text(encoding="utf-8")
- assert "honesty_lang = resolve_output_language(" in source
+ assert "honesty_lang = _turn_phrase_language(self, " in source
assert source.count("lang=honesty_lang") == 1
assert source.count("language=honesty_lang") == 1
diff --git a/tests/unit/brain/test_output_filter.py b/tests/unit/brain/test_output_filter.py
index 05a14207a7..d60c41dd1f 100644
--- a/tests/unit/brain/test_output_filter.py
+++ b/tests/unit/brain/test_output_filter.py
@@ -39,7 +39,7 @@ POSITIVE_CASES = [
@pytest.mark.parametrize("text", POSITIVE_CASES)
def test_clean_text_passes_through_unchanged(text: str) -> None:
"""Clean text is not modified, no fallback_used."""
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert isinstance(result, ScrubResult)
assert result.cleaned == text
assert result.actions == []
@@ -54,7 +54,7 @@ def test_clean_text_passes_through_unchanged(text: str) -> None:
def test_tool_json_is_removed() -> None:
"""Tool-call JSON in the middle of the text is cut out entirely."""
text = 'Sub-Jarvis startet: spawn_worker({"utterance": "test"}) — bitte warten.' # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert '{"utterance"' not in result.cleaned
assert "spawn_worker(" not in result.cleaned
assert "removed_tool_json" in result.actions or "removed_tool_call" in result.actions
@@ -68,7 +68,7 @@ def test_tool_call_python_keyword_args_is_removed() -> None:
"spawn_worker(utterance='Wie kann ich das beschleunigen?', " # i18n-allow
"context_hints=['x', 'y'], action='analyze', target='')"
)
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "spawn_worker" not in result.cleaned
assert "utterance=" not in result.cleaned
assert "removed_tool_json" in result.actions
@@ -80,7 +80,7 @@ def test_tool_xml_tags_are_removed() -> None:
"Ich delegiere das. <spawn_worker> <utterance>Lies die Datei</utterance>" # i18n-allow
" <action>x</action> </spawn_worker> Fertig." # i18n-allow
)
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "<spawn_worker" not in result.cleaned
assert "<utterance>" not in result.cleaned
assert "removed_tool_json" in result.actions
@@ -95,7 +95,7 @@ def test_tool_kw_pattern_does_not_break_harmless_python() -> None:
match, not every ``\\w+(...)`` call.
"""
text = "Use print(x=1) to debug."
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
# 'print' is not in TOOL_NAMES — the call is preserved (the digit is only
# spelled out for speech output: "print(x=eins)").
assert "print(x=" in result.cleaned
@@ -111,7 +111,7 @@ def test_stacktrace_is_replaced_with_fallback_phrase() -> None:
" raise ValueError('boom')\n"
"ValueError: boom"
)
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "Traceback" not in result.cleaned
assert 'File "' not in result.cleaned
assert "ValueError" not in result.cleaned
@@ -123,7 +123,7 @@ def test_stacktrace_is_replaced_with_fallback_phrase() -> None:
def test_markdown_is_stripped() -> None:
"""Leftover markdown (``**``, ``##``, code fences, list bullets) is removed."""
text = "## Bericht\n\n**Wichtig:** Die Datei ist da.\n\n- Punkt eins\n- Punkt zwei" # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "**" not in result.cleaned
assert "##" not in result.cleaned
assert "- Punkt" not in result.cleaned # i18n-allow
@@ -136,7 +136,7 @@ def test_markdown_is_stripped() -> None:
def test_self_reference_is_removed() -> None:
"""``Als KI`` / ``Ich bin nur ein Sprachmodell`` are scrubbed."""
text = "Als KI kann ich das natuerlich pruefen. Halb drei." # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
low = result.cleaned.lower()
assert "als ki" not in low # i18n-allow
assert "als sprachmodell" not in low # i18n-allow
@@ -196,7 +196,7 @@ def test_background_action_narration_no_false_positive(
def test_echo_paraphrase_in_opener_is_cut() -> None:
"""Echo paraphrase at the start of the sentence is cut off — the answer is the substance."""
text = "Du möchtest also wissen, wie spät es ist. Halb drei." # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
low = result.cleaned.lower()
assert "du möchtest also" not in low # i18n-allow
assert "halb drei" in low # i18n-allow
@@ -206,7 +206,7 @@ def test_echo_paraphrase_in_opener_is_cut() -> None:
def test_filler_opener_is_removed() -> None:
"""``Großartige Frage`` / ``Tolle Frage`` as an opener are removed."""
text = "Großartige Frage! Es ist halb drei." # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
low = result.cleaned.lower()
assert "großartige frage" not in low # i18n-allow
assert "grossartige frage" not in low
@@ -217,7 +217,7 @@ def test_filler_opener_is_removed() -> None:
def test_engineering_jargon_is_removed() -> None:
"""``MCP``/``Subprocess``/``Provider`` as standalone words are scrubbed."""
text = "Der Subprocess wurde via MCP-Provider gestartet." # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
low = result.cleaned.lower()
# The substance words either disappear or get rephrased — what matters is
# that none of the three jargon words remains as a standalone word.
@@ -239,7 +239,7 @@ def test_mixed_stacktrace_with_markdown() -> None:
' File "/x/y.py", line 1, in <module>\n'
" raise RuntimeError('x')"
)
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "Traceback" not in result.cleaned
assert "**" not in result.cleaned
assert "##" not in result.cleaned
@@ -249,7 +249,7 @@ def test_mixed_stacktrace_with_markdown() -> None:
def test_mixed_tool_json_with_clean_text() -> None:
"""Tool JSON mid-sentence + clean text -> tool JSON gone, text stays."""
text = 'Bitte: dispatch_to_admin({"op": "shutdown"}) ist nicht erlaubt.' # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "dispatch_to_admin" not in result.cleaned
assert "{\"op\"" not in result.cleaned
assert "ist nicht erlaubt" in result.cleaned.lower() # i18n-allow
@@ -264,7 +264,7 @@ def test_mixed_filler_with_clean_rest() -> None:
JARGON_RE.
"""
text = "Tolle Frage! Die Datei jarvis.toml hat vier Brain-Modelle." # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "Tolle Frage" not in result.cleaned # i18n-allow
# User-concept words (Datei) must NOT disappear
assert "Datei" in result.cleaned # i18n-allow
@@ -280,7 +280,7 @@ def test_mixed_filler_with_clean_rest() -> None:
def test_whitelist_datei_is_protected() -> None:
"""``Datei`` is NEVER scrubbed, not even as a jargon lookalike."""
text = "Die Datei wurde gespeichert." # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert result.cleaned == text
assert result.actions == []
@@ -288,7 +288,7 @@ def test_whitelist_datei_is_protected() -> None:
def test_whitelist_user_concepts_protected() -> None:
"""``Browser``/``Email``/``Terminal``/``Notiz``/``Termin``/``Kalender`` stay."""
text = "Browser geöffnet, Email versendet, Termin im Kalender eingetragen, Notiz im Terminal gespeichert." # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
for concept in ("Browser", "Email", "Termin", "Kalender", "Notiz", "Terminal"):
assert concept in result.cleaned, f"Whitelist word {concept!r} was scrubbed"
@@ -314,7 +314,7 @@ def test_echo_paraphrase_mid_sentence_is_kept() -> None:
echo_pos = text.lower().find("du möchtest also") # i18n-allow
assert echo_pos > 60, f"Test setup bug: echo pattern at position {echo_pos}"
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
# Mid-sentence echo is preserved
assert "möchtest also" in result.cleaned.lower() # i18n-allow
assert "rephrased_echo" not in result.actions
@@ -329,14 +329,14 @@ def test_echo_paraphrase_mid_sentence_is_kept() -> None:
def test_em_dash_becomes_comma() -> None:
text = "Kurz nach drei — Viertel nach, genau genommen."
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "—" not in result.cleaned
assert "Kurz nach drei, Viertel nach" in result.cleaned
def test_en_dash_becomes_comma() -> None:
text = "Alles bereit – wir können sofort loslegen." # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "–" not in result.cleaned
assert "Alles bereit, wir können" in result.cleaned # i18n-allow
@@ -344,13 +344,13 @@ def test_en_dash_becomes_comma() -> None:
def test_hyphen_compound_survives_em_dash_filter() -> None:
"""A plain ASCII hyphen compound has no surrounding spaces and must stay."""
text = "Dein T-Shirt liegt im Schrank."
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "T-Shirt" in result.cleaned
def test_trailing_em_dash_leaves_no_dangling_comma() -> None:
text = "Im Hintergrund laufen mehrere Programme —"
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "—" not in result.cleaned
assert not result.cleaned.endswith(",")
@@ -360,7 +360,9 @@ def test_ascii_double_hyphen_dash_aside_becomes_comma() -> None:
same hard TTS pause as an em dash — collapse it to a comma too. The
Unicode-only scrub missed it, and several canned phrases / LLM outputs use
' -- ' (live forensic 2026-06-30)."""
- result = scrub_for_voice("Mach ich -- ich sage Bescheid, sobald es fertig ist.") # i18n-allow
+ result = scrub_for_voice(
+ "Mach ich -- ich sage Bescheid, sobald es fertig ist.", language="de" # i18n-allow
+ )
assert "--" not in result.cleaned
assert "Mach ich, ich sage Bescheid" in result.cleaned # i18n-allow
@@ -369,7 +371,7 @@ def test_ascii_hyphen_compound_and_range_survive_double_hyphen_filter() -> None:
"""No false positive: a compound ('T-Shirt') or numeric range ('20-30') has
no surrounding spaces and must survive the double-hyphen scrub. The range
endpoints are spelled out for speech, but the joining hyphen is preserved."""
- result = scrub_for_voice("Dein T-Shirt kostet 20-30 Euro.") # i18n-allow
+ result = scrub_for_voice("Dein T-Shirt kostet 20-30 Euro.", language="de") # i18n-allow
assert "T-Shirt" in result.cleaned
assert "zwanzig-dreißig" in result.cleaned # i18n-allow
@@ -378,13 +380,13 @@ def test_fallback_used_true_only_for_stacktrace() -> None:
"""``fallback_used`` is only ``True`` when the whole text was replaced by
the standard phrase (stacktrace), not for a partial scrub."""
# A filler opener only removes part of the text — no fallback
- result = scrub_for_voice("Großartige Frage! Halb drei.") # i18n-allow
+ result = scrub_for_voice("Großartige Frage! Halb drei.", language="de") # i18n-allow
assert result.fallback_used is False
def test_empty_input_returns_empty() -> None:
"""Empty input -> empty output, no exception."""
- result = scrub_for_voice("")
+ result = scrub_for_voice("", language="de")
assert result.cleaned == ""
assert result.actions == []
assert result.fallback_used is False
@@ -406,7 +408,7 @@ def test_empty_input_returns_empty() -> None:
def test_sir_anrede_is_removed() -> None: # i18n-allow
"""A1: 'Sir' as a salutation is scrubbed — mandate A1 (Ruben instead of Sir)."""
text = "Sir, ich starte die Analyse." # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
low = result.cleaned.lower()
assert "sir" not in low.split(",")[0].split() # not as a word in the opener
assert "sir" not in low
@@ -417,7 +419,7 @@ def test_sir_anrede_is_removed() -> None: # i18n-allow
def test_sir_anrede_mid_sentence_is_removed() -> None: # i18n-allow
"""A1: 'Sir' is also removed in the middle of a sentence (after a comma)."""
text = "Erledigt, Sir. Die Datei ist gespeichert." # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "Sir" not in result.cleaned
assert "Datei" in result.cleaned # i18n-allow
assert "removed_anrede_drift" in result.actions # i18n-allow
@@ -431,14 +433,14 @@ def test_legitimate_sir_in_quote_is_kept() -> None:
quotes is not scrubbed.
"""
text = 'Im Lied steht: "Yes, Sir, I can boogie." — kennst du das?' # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "Sir" in result.cleaned, "Sir inside the quote was scrubbed by mistake"
def test_sub_agent_jargon_is_removed() -> None:
"""'Sub-Agent' as an engineering reveal is removed — probe drift 03/07."""
text = "Ich starte einen Sub-Agent, der die Datei analysiert." # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "Sub-Agent" not in result.cleaned
assert "sub-agent" not in result.cleaned.lower()
# Core content remains
@@ -465,7 +467,7 @@ def test_agent_compound_leaves_a_sentence_not_a_hole() -> None:
def test_agent_compound_keeps_the_german_declension() -> None:
""""einen Subagenten" must not become "einen Agent" — nor "einen"."""
- result = scrub_for_voice("Ich starte dafür einen Subagenten.") # i18n-allow
+ result = scrub_for_voice("Ich starte dafür einen Subagenten.", language="de") # i18n-allow
assert result.cleaned == "Ich starte dafür einen Agenten." # i18n-allow
@@ -476,7 +478,8 @@ def test_agent_compound_announcement_survives() -> None:
of a spawn with the spawned thing deleted out of it.
"""
cleaned = scrub_for_voice(
- "Ich aktiviere einen Subagent für die Aufgabe." # i18n-allow
+ "Ich aktiviere einen Subagent für die Aufgabe.", # i18n-allow
+ language="de",
).cleaned
assert "Subagent" not in cleaned
assert "Agent" in cleaned
@@ -494,7 +497,7 @@ def test_official_jarvis_agent_label_is_preserved() -> None:
def test_supervisor_agent_jargon_is_removed() -> None:
"""'Supervisor-Agent' as an engineering reveal is removed — probe drift 13."""
text = "Dein persoenlicher Supervisor-Agent erledigt das." # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "Supervisor-Agent" not in result.cleaned
assert "supervisor-agent" not in result.cleaned.lower()
assert "erledigt" in result.cleaned.lower() # i18n-allow
@@ -523,7 +526,7 @@ def test_tool_args_yaml_block_is_removed() -> None:
'action: "die Beschleunigung einer unklaren Aufgabe analysiert"\n' # i18n-allow
'target: ""'
)
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "context_hints" not in result.cleaned
assert "action:" not in result.cleaned
assert "target:" not in result.cleaned
@@ -542,7 +545,7 @@ def test_post_scrub_residue_triggers_fallback() -> None:
"""
# Only a '}' remains — nothing else
text = '<spawn_worker>{"utterance": "test"}</spawn_worker>}'
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
# Either fallback_used=True OR cleaned is empty (both acceptable)
assert (result.fallback_used and result.cleaned), (
f"Post-scrub residue {result.cleaned!r} was not replaced by the fallback"
@@ -554,7 +557,7 @@ def test_post_scrub_meaningful_text_no_fallback() -> None:
"""Defense against the fallback trigger: substantial remaining text does
NOT trigger fallback_used."""
text = "Erledigt. Die Datei ist da." # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert result.fallback_used is False
assert "Datei" in result.cleaned # i18n-allow
@@ -580,7 +583,7 @@ def test_anthropic_function_calls_block_is_removed() -> None:
'</function_calls>\n'
'Fertig.' # i18n-allow
)
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "<function_calls>" not in result.cleaned
assert "<invoke" not in result.cleaned
assert "<parameter" not in result.cleaned
@@ -602,7 +605,7 @@ def test_generic_tool_call_tags_are_removed() -> None:
'</tool_response>\n'
'09:17 Uhr.' # i18n-allow
)
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "<tool_call>" not in result.cleaned
assert "</tool_call>" not in result.cleaned
assert "<tool_response>" not in result.cleaned
@@ -620,7 +623,7 @@ def test_base64_image_block_is_removed() -> None:
+ 'A' * 800
+ '. Fertig.' # i18n-allow
)
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
# The base64 block is gone
assert ("A" * 200) not in result.cleaned, "Long base64 sequence not removed"
assert "data:image" not in result.cleaned
@@ -632,7 +635,7 @@ def test_short_clean_alphanumeric_is_kept() -> None:
"""Defense against base64 false positives: short alphanumeric strings
(e.g. file names, hashes, tokens in ordinary communication) stay."""
text = "Die Datei abc123def456 wurde gespeichert." # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "abc123def456" in result.cleaned
assert result.actions == []
@@ -661,7 +664,7 @@ def test_filler_selbstreferenz_opener_is_removed(opener: str, rest: str) -> None
the user isn't meant to hear the phrase anyway.
"""
text = f"{opener} {rest}"
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
low = result.cleaned.lower()
assert "lass mich kurz" not in low # i18n-allow
assert "let me think" not in low
@@ -688,7 +691,7 @@ def test_filler_selbstreferenz_mid_sentence_is_kept() -> None: # i18n-allow
pos = text.lower().find("lass mich kurz") # i18n-allow
assert pos > 60, f"Test setup bug: pos={pos}"
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "lass mich kurz" in result.cleaned.lower() # i18n-allow
assert "removed_filler_opener" not in result.actions
@@ -715,7 +718,7 @@ def test_tool_call_prose_with_keys_is_removed() -> None:
"erfassen action is das Projekt analysiert target is Arbeitsordner. " # i18n-allow
"Fertig." # i18n-allow
)
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "spawn_worker" not in result.cleaned
assert "utterance is" not in result.cleaned
assert "context_hints" not in result.cleaned
@@ -729,7 +732,7 @@ def test_tool_call_prose_with_keys_is_removed() -> None:
def test_tool_args_prose_without_tool_name_is_removed() -> None:
"""'utterance is X' alone (without a tool-name prefix) is also scrubbed."""
text = "Ich versuche es. utterance is lies die Datei. Fertig." # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "utterance is" not in result.cleaned
assert "removed_tool_json" in result.actions
assert "Ich versuche es" in result.cleaned # i18n-allow
@@ -744,7 +747,7 @@ def test_legitimate_is_sentence_is_kept() -> None:
'Es' are not tool-arg keys.
"""
text = "Es ist halb drei. Die Datei ist gespeichert." # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "ist halb drei" in result.cleaned # i18n-allow
assert "Datei ist gespeichert" in result.cleaned # i18n-allow
assert "removed_tool_json" not in result.actions
@@ -765,7 +768,7 @@ def test_openclaw_brand_name_is_scrubbed() -> None:
"Mach ich, ich lasse dafür einen OpenClaw-Subagent " # i18n-allow
"ein Hello-World-Programm schreiben." # i18n-allow
)
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "OpenClaw" not in result.cleaned
assert "Subagent" not in result.cleaned
assert "removed_engineering_jargon" in result.actions
@@ -774,7 +777,7 @@ def test_openclaw_brand_name_is_scrubbed() -> None:
def test_bare_subagent_still_scrubbed_without_brand_prefix() -> None:
"""A bare 'Subagent' / 'Sub-Agent' without a brand prefix stays scrubbed."""
text = "Ich aktiviere einen Subagent für die Aufgabe." # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "Subagent" not in result.cleaned
assert "removed_engineering_jargon" in result.actions
@@ -782,7 +785,7 @@ def test_bare_subagent_still_scrubbed_without_brand_prefix() -> None:
def test_openclaw_compound_prefix_stripped_but_noun_kept() -> None:
"""The retired 'OpenClaw-Mission' brand prefix is stripped, the noun 'Mission' stays."""
text = "Die OpenClaw-Mission ist fertig." # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "OpenClaw" not in result.cleaned
assert "Mission" in result.cleaned
@@ -790,7 +793,7 @@ def test_openclaw_compound_prefix_stripped_but_noun_kept() -> None:
def test_openclaw_subagenten_plural_also_scrubbed() -> None:
"""The plural 'OpenClaw-Subagenten' (retired brand) must also be scrubbed."""
text = "Mehrere OpenClaw-Subagenten arbeiten parallel." # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "OpenClaw" not in result.cleaned
assert "Subagenten" not in result.cleaned
@@ -816,7 +819,7 @@ def test_scrub_strips_end_call_sentinel() -> None:
def test_http_url_is_stripped_from_voice() -> None:
"""A spoken answer must never read out an http(s) URL."""
text = "Die Prüfung dauert 190 Minuten. Mehr unter https://www.km.bayern.de/schueler.html" # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "http" not in result.cleaned.lower()
assert "km.bayern.de" not in result.cleaned.lower()
assert "einhundertneunzig minuten" in result.cleaned.lower() # i18n-allow
@@ -826,7 +829,7 @@ def test_http_url_is_stripped_from_voice() -> None:
def test_serp_more_results_footer_is_stripped() -> None:
"""The 'Weitere Ergebnisse von <domain>' SERP footer is never spoken."""
text = "Note 2 gibt es ab 34,5 Punkten. Weitere Ergebnisse von www.gutefrage.net"
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
low = result.cleaned.lower()
assert "gutefrage" not in low
assert "weitere ergebnisse" not in low
@@ -837,7 +840,7 @@ def test_serp_more_results_footer_is_stripped() -> None:
def test_bare_www_domain_is_stripped_from_voice() -> None:
"""A bare www-domain hit reference is stripped (English/Spanish SERP too)."""
text = "Insgesamt 190 Minuten. Mehr dazu: www.realschule.bayern.de Viel Erfolg."
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert "www." not in result.cleaned.lower()
assert "realschule.bayern.de" not in result.cleaned.lower()
assert "einhundertneunzig minuten" in result.cleaned.lower()
@@ -848,7 +851,7 @@ def test_clean_answer_without_sources_is_untouched() -> None:
"""Defense against false positives: a normal spoken answer with no URL /
domain / SERP footer must pass through unchanged (no source-artifact pass)."""
text = "Morgen schreiben alle Realschüler in Bayern ihre Mathe-Abschlussprüfung." # i18n-allow
- result = scrub_for_voice(text)
+ result = scrub_for_voice(text, language="de")
assert result.cleaned == text
assert "removed_source_artifacts" not in result.actions
@@ -1250,4 +1253,4 @@ def test_serp_footer_is_still_deleted_whole_not_placeholdered() -> None:
)
def test_the_openclaw_runtime_name_survives(text: str) -> None:
"""OpenClaw as a society agent runtime is real and may be named (2026-10-06)."""
- assert "OpenClaw" in scrub_for_voice(text).cleaned
+ assert "OpenClaw" in scrub_for_voice(text, language="de").cleaned
diff --git a/tests/unit/brain/test_provider_down_phrase.py b/tests/unit/brain/test_provider_down_phrase.py
index d1d56ca861..d03d791628 100644
--- a/tests/unit/brain/test_provider_down_phrase.py
+++ b/tests/unit/brain/test_provider_down_phrase.py
@@ -47,11 +47,11 @@ class TestProviderDownPhrase:
assert got[0] == got[3] and got[1] == got[4] and got[2] == got[5]
assert len({got[0], got[1], got[2]}) == 3
- def test_auto_falls_back_to_german(self) -> None:
- assert _provider_down_phrase("auto", 0) == _PROVIDER_DOWN_PHRASES["de"][0]
+ def test_auto_falls_back_to_english(self) -> None:
+ assert _provider_down_phrase("auto", 0) == _PROVIDER_DOWN_PHRASES["en"][0]
- def test_unknown_language_falls_back_to_german(self) -> None:
- assert _provider_down_phrase("fr", 1) == _PROVIDER_DOWN_PHRASES["de"][1]
+ def test_language_without_translations_falls_back_to_english(self) -> None:
+ assert _provider_down_phrase("tr", 1) == _PROVIDER_DOWN_PHRASES["en"][1]
@pytest.mark.parametrize("lang", ["de", "en", "es", "pt", "auto", "FR"])
def test_phrase_is_voice_safe_no_provider_jargon(self, lang: str) -> None:
@@ -93,9 +93,9 @@ class TestNextProviderDownPhraseAutoDetect:
m = self._manager("auto", "es")
assert m._next_provider_down_phrase() == _PROVIDER_DOWN_PHRASES["es"][0]
- def test_auto_mode_unknown_turn_keeps_german_default(self) -> None:
+ def test_auto_mode_unknown_turn_uses_english_default(self) -> None:
m = self._manager("auto", "")
- assert m._next_provider_down_phrase() == _PROVIDER_DOWN_PHRASES["de"][0]
+ assert m._next_provider_down_phrase() == _PROVIDER_DOWN_PHRASES["en"][0]
def test_pin_wins_over_detected_turn_language(self) -> None:
m = self._manager("de", "en")
@@ -148,11 +148,11 @@ class TestCauseAwareProviderDownPhrase:
def test_unknown_cause_falls_back_to_generic_rotation(self) -> None:
assert _provider_down_phrase("en", 1, "weird_kind") == (_PROVIDER_DOWN_PHRASES["en"][1])
- def test_unknown_language_falls_back_to_german_cause_phrase(self) -> None:
+ def test_language_without_translations_falls_back_to_english_cause_phrase(self) -> None:
from jarvis.brain.manager import _PROVIDER_DOWN_CAUSE_PHRASES
- got = _provider_down_phrase("fr", 0, "rate_limit")
- assert got == _PROVIDER_DOWN_CAUSE_PHRASES["rate_limit"]["de"]
+ got = _provider_down_phrase("tr", 0, "rate_limit")
+ assert got == _PROVIDER_DOWN_CAUSE_PHRASES["rate_limit"]["en"]
class TestPrimaryProviderDownCause:
diff --git a/tests/unit/dictation/test_delivery_gates.py b/tests/unit/dictation/test_delivery_gates.py
index e9e0f88892..ff74a7448c 100644
--- a/tests/unit/dictation/test_delivery_gates.py
+++ b/tests/unit/dictation/test_delivery_gates.py
@@ -291,14 +291,15 @@ async def test_a_tag_outside_the_supported_set_is_kept_rather_than_coerced() ->
~95 of the 100 recognition languages.
The fixture is chosen to make that concrete: this French sentence shares
- enough tokens with the Spanish vocabulary that the detector calls it "es",
- so a resolver that trusted the text here would clean French with Spanish
- rules.
+ tokens with the Spanish vocabulary ("la", "de"), so a resolver that trusted
+ a four-language guess would clean French with Spanish rules. The detector
+ now recognises it as another language and answers "unknown" for the four.
"""
french = "Le rapport est sur la table, avec les notes de la réunion."
- from jarvis.core.turn_language import detect_text_language
+ from jarvis.core.turn_language import detect_conversation_language, detect_text_language
- assert detect_text_language(french) == "es", "fixture no longer bites"
+ assert detect_text_language(french) == "unknown"
+ assert detect_conversation_language(french) == "fr"
pipe, events, _inserted = _pipeline()
await pipe._finish_dictation(
diff --git a/tests/unit/i18n/__init__.py b/tests/unit/i18n/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/unit/i18n/test_catalog.py b/tests/unit/i18n/test_catalog.py
new file mode 100644
index 0000000000..47ad81561b
--- /dev/null
+++ b/tests/unit/i18n/test_catalog.py
@@ -0,0 +1,118 @@
+"""The backend system-phrase catalog: one file per language, English as the net."""
+from __future__ import annotations
+
+import json
+import re
+from pathlib import Path
+
+import pytest
+
+from jarvis.i18n import (
+ DEFAULT_LOCALE,
+ SUPPORTED_LOCALES,
+ phrase_locale,
+ pick,
+ t,
+ table,
+ variants,
+)
+from jarvis.i18n.catalog import keys
+
+_REPO = Path(__file__).resolve().parents[3]
+_LOCALES = _REPO / "jarvis" / "i18n" / "locales"
+_PLACEHOLDER = re.compile(r"\{(\w+)\}")
+
+
+def _flat(code: str) -> dict[str, object]:
+ out: dict[str, object] = {}
+
+ def walk(node: dict, prefix: str) -> None:
+ for key, value in node.items():
+ if isinstance(value, dict):
+ walk(value, f"{prefix}{key}.")
+ else:
+ out[prefix + key] = value
+
+ walk(json.loads((_LOCALES / f"{code}.json").read_text(encoding="utf-8")), "")
+ return out
+
+
+def test_every_supported_language_has_a_catalog_and_nothing_else_does() -> None:
+ files = {path.stem for path in _LOCALES.glob("*.json")}
+ assert files == set(SUPPORTED_LOCALES)
+
+
[email protected]("code", [c for c in SUPPORTED_LOCALES if c != DEFAULT_LOCALE])
+def test_catalogs_have_the_same_keys_shapes_and_placeholders(code: str) -> None:
+ master, other = _flat(DEFAULT_LOCALE), _flat(code)
+ assert set(other) == set(master)
+ for key, value in master.items():
+ theirs = other[key]
+ assert type(theirs) is type(value), key
+ if isinstance(value, list):
+ assert len(theirs) == len(value), key
+ pairs = zip(value, theirs, strict=True)
+ else:
+ pairs = [(value, theirs)]
+ for mine, translated in pairs:
+ assert set(_PLACEHOLDER.findall(mine)) == set(_PLACEHOLDER.findall(translated)), key
+
+
[email protected]("lang", ["tr", "fr", "", None, "auto", "xx-YY"])
+def test_a_language_without_translations_reads_english(lang: object) -> None:
+ assert phrase_locale(lang) == "en"
+ for key in keys():
+ assert variants(key, lang) == variants(key, "en")
+
+
+def test_lookup_helpers() -> None:
+ assert t("brain.cli_failure.code", "de", code=3).endswith("3 fehlgeschlagen.") # i18n-allow
+ assert t("brain.provider_down", "en", index=4) == variants("brain.provider_down", "en")[1]
+ assert set(table("brain.cancel_none")) == set(SUPPORTED_LOCALES)
+ assert pick({"en": "x", "de": "y"}, "tr") == "x"
+ assert pick({"en": "x", "de": "y"}, "de") == "y"
+ with pytest.raises(KeyError):
+ t("no.such.key", "en")
+
+
+def test_reply_and_mission_languages_come_from_the_central_list() -> None:
+ from jarvis.brain.manager import SUPPORTED_REPLY_LANGUAGES
+ from jarvis.commands.registry import REPLY_LANGUAGES
+ from jarvis.core.turn_language import _REPLY_PINS
+ from jarvis.missions.events import MISSION_LANGUAGES
+
+ assert SUPPORTED_REPLY_LANGUAGES == REPLY_LANGUAGES == ("auto", *SUPPORTED_LOCALES)
+ assert _REPLY_PINS == frozenset(SUPPORTED_LOCALES)
+ assert MISSION_LANGUAGES == SUPPORTED_LOCALES
+
+
+# Phrase lookups that fall back to German. Every system phrase falls back to
+# English (DEFAULT_LOCALE); German is only ever the answer when the person's
+# language is German (forensic 2026-10-19).
+_GERMAN_FALLBACK = re.compile(
+ r"""\.get\([^)]*\[\s*["']de["']\s*\]\s*\)"""
+ r"""|default\s*=\s*["']de["']"""
+ r"""|_DEFAULT(?:_LANG)?\s*=\s*["']de["']"""
+ r"""|else\s+["']de["']\s*$"""
+ r"""|or\s+["']de["']\s*\)"""
+ r"""|language:\s*str\s*=\s*["']de["']"""
+)
+# Input-side vocabulary, not output: which word lists to MATCH against.
+_INPUT_SIDE = {
+ "jarvis/agentic_ide/clarify.py",
+ "jarvis/speech/completion.py",
+}
+
+
+def test_no_backend_phrase_falls_back_to_german() -> None:
+ offenders = []
+ for path in sorted((_REPO / "jarvis").rglob("*.py")):
+ rel = path.relative_to(_REPO).as_posix()
+ if rel in _INPUT_SIDE:
+ continue
+ for number, line in enumerate(
+ path.read_text(encoding="utf-8-sig").splitlines(), start=1
+ ):
+ if _GERMAN_FALLBACK.search(line) and "input language, not output" not in line:
+ offenders.append(f"{rel}:{number}: {line.strip()}")
+ assert not offenders, "\n".join(offenders)
diff --git a/tests/unit/plugins/tool/test_open_app_reuse.py b/tests/unit/plugins/tool/test_open_app_reuse.py
index a4e2e41e7e..385c0c7b59 100644
--- a/tests/unit/plugins/tool/test_open_app_reuse.py
+++ b/tests/unit/plugins/tool/test_open_app_reuse.py
@@ -97,7 +97,7 @@ async def test_launches_when_not_running(monkeypatch):
monkeypatch.setattr(oa.window_state, "is_app_running", lambda n: None)
res = await OpenAppTool().execute({"app_name": "obs"}, _ctx())
assert res.success is True
- assert "Gestartet" in (res.output or "") # i18n-allow: matches the tool's real (currently German) readback text
+ assert "Launched" in (res.output or "") # no language stamped: the English readback
assert len(calls) == 1
@@ -129,7 +129,7 @@ async def test_focus_failure_falls_through_to_launch(monkeypatch):
monkeypatch.setattr(oa.window_state, "raise_window", lambda w: (False, "lock timeout"))
res = await OpenAppTool().execute({"app_name": "obs"}, _ctx())
assert res.success is True
- assert "Gestartet" in (res.output or "") # launched after the raise failed # i18n-allow: matches the tool's real (currently German) readback text
+ assert "Launched" in (res.output or "") # launched after the raise failed
assert len(calls) == 1
@@ -159,7 +159,7 @@ async def test_fresh_launch_raises_window_to_foreground(monkeypatch):
assert res.success is True
assert len(calls) == 1 # launched once
assert raised == ["chrome"] # and actively pulled to the front
- assert "vorn" in (res.output or "").lower() # honest readback
+ assert "front" in (res.output or "").lower() # no language stamped: English readback
async def test_fresh_launch_requests_maximize(monkeypatch):
@@ -195,14 +195,14 @@ async def test_url_launch_does_not_maximize(monkeypatch):
async def test_raise_miss_keeps_success(monkeypatch):
# The launch already succeeded; a foreground-raise miss must NOT flip the
- # result to failure — it only softens the readback back to plain "Gestartet". # i18n-allow: quotes the tool's real (currently German) readback text
+ # result to failure — it only softens the readback back to plain "Launched".
calls = _stub_launch(monkeypatch)
monkeypatch.setattr(oa.window_state, "is_app_running", lambda n: None)
monkeypatch.setattr(oa.window_state, "raise_after_launch", lambda n, **k: (False, "no window"))
res = await OpenAppTool().execute({"app_name": "chrome"}, _ctx())
assert res.success is True
- assert "Gestartet" in (res.output or "") # i18n-allow: matches the tool's real (currently German) readback text
- assert "vorn" not in (res.output or "").lower()
+ assert "Launched" in (res.output or "") # no language stamped: the English readback
+ assert "front" not in (res.output or "").lower()
assert len(calls) == 1
@@ -216,7 +216,7 @@ async def test_raise_crash_never_breaks_launch(monkeypatch):
monkeypatch.setattr(oa.window_state, "raise_after_launch", boom)
res = await OpenAppTool().execute({"app_name": "chrome"}, _ctx())
assert res.success is True # crash in the raise never fails the launch
- assert "Gestartet" in (res.output or "") # i18n-allow: matches the tool's real (currently German) readback text
+ assert "Launched" in (res.output or "") # no language stamped: the English readback
assert len(calls) == 1
diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.py
index 6efe93b69d..48543dbd65 100644
--- a/tests/unit/realtime/test_session.py
+++ b/tests/unit/realtime/test_session.py
@@ -3198,7 +3198,7 @@ async def test_generative_voice_provider_mute_still_falls_back_to_surface_tts():
elapsed = asyncio.get_event_loop().time() - start
assert elapsed >= 2.0, "surface TTS claimed the reply before the wait window"
spoken = [m for m in jsons if m.get("type") == "error_spoken"]
- assert [m["text"] for m in spoken] == [scrub_for_voice(reply).cleaned]
+ assert [m["text"] for m in spoken] == [scrub_for_voice(reply, language="de").cleaned]
assert binaries == []
provider.session.release.set()
await sess.end(reason="test")
diff --git a/tests/unit/speech/test_local_stt_isolation.py b/tests/unit/speech/test_local_stt_isolation.py
index af88a8b494..0940291654 100644
--- a/tests/unit/speech/test_local_stt_isolation.py
+++ b/tests/unit/speech/test_local_stt_isolation.py
@@ -92,7 +92,7 @@ def test_live_switch_does_not_share_local_final_with_preview(monkeypatch, settin
("de", "en", "en", None, "de"),
("es", "en", "en", None, "es"),
("auto", "es", "de", None, "es"),
- ("auto", "", "de", None, "de"),
+ ("auto", "", "de", None, "en"), # never the UI language: English
("auto", "", "en", None, "en"),
("en", "", "en", "es", "es"),
],
diff --git a/tests/unit/voice/test_action_phrases.py b/tests/unit/voice/test_action_phrases.py
index b902689c51..f6418fe773 100644
--- a/tests/unit/voice/test_action_phrases.py
+++ b/tests/unit/voice/test_action_phrases.py
@@ -29,8 +29,8 @@ class TestResolvePhraseLanguage:
assert resolve_phrase_language(None, "Could you please open Chrome for me?") == "en"
assert resolve_phrase_language("auto", "Kannst du mir bitte Chrome aufmachen?") == "de"
- def test_ambiguous_keeps_german_default(self) -> None:
- assert resolve_phrase_language("auto", "ok") == "de"
+ def test_ambiguous_uses_english_default(self) -> None:
+ assert resolve_phrase_language("auto", "ok") == "en"
class TestActionPhrase:
@@ -56,8 +56,8 @@ class TestActionPhrase:
assert "pt" in variants, key
assert fields(variants["pt"]) == fields(variants["es"]), key
- def test_unknown_language_falls_back_to_german(self) -> None:
- assert action_phrase("cu_done", "fr") == "Erledigt."
+ def test_unknown_language_falls_back_to_english(self) -> None:
+ assert action_phrase("cu_done", "fr") == "Done."
def test_failure_with_reason_fills_field(self) -> None:
out = action_phrase("cu_failed_reason", "en", error="HTTP 403")
@@ -296,9 +296,9 @@ class TestNoCapableProviderPhrase:
# points the user at the real fix: keys / credit / settings.
assert any(w in en.lower() for w in ("key", "credit", "settings"))
- def test_exit_3_unknown_language_falls_back_to_german(self) -> None:
+ def test_exit_3_unknown_language_falls_back_to_english(self) -> None:
assert action_phrase("cu_exit_no_provider", "fr") == action_phrase(
- "cu_exit_no_provider", "de"
+ "cu_exit_no_provider", "en"
)
@@ -324,9 +324,9 @@ class TestElevationPausePhrases:
# It must tell the user WHAT to do: confirm an admin/security prompt.
assert "admin" in en.lower()
- def test_awaiting_elevation_unknown_language_falls_back_to_german(self) -> None:
+ def test_awaiting_elevation_unknown_language_falls_back_to_english(self) -> None:
assert action_phrase("cu_awaiting_elevation", "fr") == action_phrase(
- "cu_awaiting_elevation", "de"
+ "cu_awaiting_elevation", "en"
)
def test_exit_9_is_the_needs_elevation_phrase(self) -> None:
diff --git a/tests/unit/voice/test_localize_failure_reason.py b/tests/unit/voice/test_localize_failure_reason.py
index 79b5352a5c..2d8c95e761 100644
--- a/tests/unit/voice/test_localize_failure_reason.py
+++ b/tests/unit/voice/test_localize_failure_reason.py
@@ -106,7 +106,7 @@ def test_empty_input_stays_empty() -> None:
def test_an_unknown_language_falls_back_to_the_module_default() -> None:
- assert localize_failure_reason(GMAIL, "fr") == localize_failure_reason(GMAIL, "de")
+ assert localize_failure_reason(GMAIL, "fr") == localize_failure_reason(GMAIL, "en")
def test_the_localized_cause_fits_the_failure_phrase() -> None:
diff --git a/tests/unit/voice/test_self_mod_flow.py b/tests/unit/voice/test_self_mod_flow.py
index 65ce84fcad..fd79e57dcf 100644
--- a/tests/unit/voice/test_self_mod_flow.py
+++ b/tests/unit/voice/test_self_mod_flow.py
@@ -448,6 +448,7 @@ class TestIntegrationToolCallToMutation:
pending_store=pending_store,
audit=audit_log,
timeout_seconds=30.0,
+ default_language="de", # the spoken answer below is German
)
# 1. Hauptjarvis ruft set_config_value-Tool