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.

feat(tts): add Inworld TTS plugin (arena-#1 realtime, new premium default)

Ruben Lütke7489e76502d1
diff --git a/docs/jarvis-cli-reference.md b/docs/jarvis-cli-reference.md
index 0326ffc7e6..7afcf49ea8 100644
--- a/docs/jarvis-cli-reference.md
+++ b/docs/jarvis-cli-reference.md
@@ -177,6 +177,7 @@ _Generated from the curated command tree by `scripts/ci/gen_cli_reference.py`
## wiki
+- `jarvis wiki health` — Show wiki subsystem health: bootstrap, last write, chain failures, backlog (spec A5).
- `jarvis wiki page <slug>` — Read a wiki page by vault path / slug.
- `jarvis wiki recall <query>` — Full-text search the wiki.
- `jarvis wiki tree` — Show the vault folder tree + stats.
diff --git a/jarvis/cli_ctl/commands/wiki.py b/jarvis/cli_ctl/commands/wiki.py
index 3201b9c35c..7dcd993f8c 100644
--- a/jarvis/cli_ctl/commands/wiki.py
+++ b/jarvis/cli_ctl/commands/wiki.py
@@ -35,3 +35,9 @@ def tree() -> None:
def vaults() -> None:
"""List the user's registered Obsidian vaults (connect picker, spec A6)."""
invoke.run("GET", "/api/setup/obsidian/vaults")
+
+
+def health() -> None:
+ """Show wiki subsystem health: bootstrap, last write, chain failures, backlog (spec A5)."""
+ invoke.run("GET", "/api/wiki/health")
diff --git a/jarvis/memory/wiki/extractor.py b/jarvis/memory/wiki/extractor.py
index 97a8dae4d6..7ff4b2f604 100644
--- a/jarvis/memory/wiki/extractor.py
+++ b/jarvis/memory/wiki/extractor.py
@@ -176,7 +176,16 @@ class ConversationFactExtractor:
if self._scheduler is None:
return
try:
- if self._journal.backlog_count() < self._consolidate_after:
+ backlog = self._journal.backlog_count()
+ try:
+ from jarvis.memory.wiki.health import health
+
+ health.record_backlog(backlog)
+ except Exception: # noqa: BLE001 — health recording must never break extraction
+ log.debug(
+ "ConversationFactExtractor: health.record_backlog failed", exc_info=True,
+ )
+ if backlog < self._consolidate_after:
return
from jarvis.memory.wiki.scheduler import TriggerSource
diff --git a/jarvis/memory/wiki/health.py b/jarvis/memory/wiki/health.py
new file mode 100644
index 0000000000..143adac759
--- /dev/null
+++ b/jarvis/memory/wiki/health.py
@@ -0,0 +1,72 @@
+"""Process-wide wiki health state (spec A5): honest, not silent.
+
+The wiki subsystem is fire-and-forget by design (AP-9) — failures must
+never interrupt a voice turn. This module is the other half of that
+contract: every swallowed failure is recorded HERE so the Wiki tab and
+``GET /api/wiki/health`` can show it. Pure in-memory state guarded by a
+lock; recording must never raise (a health write failing a write path
+would invert the design).
+"""
+from __future__ import annotations
+
+import threading
+import time
+from typing import Any
+
+
+class WikiHealth:
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self._bootstrap_ok: bool | None = None
+ self._bootstrap_error: str | None = None
+ self._last_write: dict[str, Any] | None = None
+ self._last_chain_failure: dict[str, Any] | None = None
+ self._journal_backlog: int = 0
+
+ def record_bootstrap(self, ok: bool, error: str | None = None) -> None:
+ with self._lock:
+ self._bootstrap_ok = ok
+ self._bootstrap_error = error
+
+ def record_write(
+ self, ok: bool, *, pages: list[str], error: str | None, source: str,
+ ) -> None:
+ with self._lock:
+ self._last_write = {
+ "ts": time.time(),
+ "ok": ok,
+ "pages": list(pages),
+ "error": error,
+ "source": source,
+ }
+
+ def record_chain_failure(self, detail: str) -> None:
+ with self._lock:
+ self._last_chain_failure = {"ts": time.time(), "detail": detail}
+
+ def record_backlog(self, count: int) -> None:
+ with self._lock:
+ self._journal_backlog = max(0, int(count))
+
+ def snapshot(self) -> dict[str, Any]:
+ from jarvis.memory.wiki.vault_root import last_resolution
+
+ res = last_resolution()
+ with self._lock:
+ return {
+ "bootstrap_ok": self._bootstrap_ok,
+ "bootstrap_error": self._bootstrap_error,
+ "vault_root": str(res.path) if res else None,
+ "vault_root_source": res.source if res else None,
+ "vault_legacy_conflict": bool(res.legacy_conflict) if res else False,
+ "last_write": dict(self._last_write) if self._last_write else None,
+ "last_chain_failure": (
+ dict(self._last_chain_failure)
+ if self._last_chain_failure else None
+ ),
+ "journal_backlog": self._journal_backlog,
+ }
+
+
+#: Process-wide singleton — import as ``from jarvis.memory.wiki.health import health``.
+health = WikiHealth()
diff --git a/jarvis/memory/wiki/integration.py b/jarvis/memory/wiki/integration.py
index e7b43f345c..ccf41f068e 100644
--- a/jarvis/memory/wiki/integration.py
+++ b/jarvis/memory/wiki/integration.py
@@ -766,7 +766,9 @@ def kick_journal_backlog(journal: Any, scheduler: Any) -> None:
try:
if journal is None or scheduler is None:
return
- if journal.backlog_count() <= 0:
+ backlog = journal.backlog_count()
+ _record_backlog_health(backlog)
+ if backlog <= 0:
return
from jarvis.memory.wiki.scheduler import TriggerSource
@@ -785,7 +787,7 @@ def kick_journal_backlog(journal: Any, scheduler: Any) -> None:
task.add_done_callback(_log_outcome)
log.info(
"wiki_integration: boot drain triggered for %d pending candidate(s)",
- journal.backlog_count(),
+ backlog,
)
except RuntimeError:
log.debug("wiki_integration: no event loop for the boot journal drain")
@@ -793,6 +795,19 @@ def kick_journal_backlog(journal: Any, scheduler: Any) -> None:
log.warning("wiki_integration: boot journal drain skipped: %s", exc)
+def _record_backlog_health(count: int) -> None:
+ """Record the journal backlog on the health singleton (spec A5).
+
+ Recording must never raise into the boot/pressure-check path (AP-9).
+ """
+ try:
+ from jarvis.memory.wiki.health import health
+
+ health.record_backlog(count)
+ except Exception: # noqa: BLE001 — health recording must never break the pipeline
+ log.debug("wiki_integration: health.record_backlog failed", exc_info=True)
+
+
def _load_root_config() -> Any:
"""Load the root ``JarvisConfig`` once (default config on failure).
diff --git a/jarvis/memory/wiki/provider_chain.py b/jarvis/memory/wiki/provider_chain.py
index 4c7ed94a40..34ca29e096 100644
--- a/jarvis/memory/wiki/provider_chain.py
+++ b/jarvis/memory/wiki/provider_chain.py
@@ -85,6 +85,12 @@ async def complete_with_fallback(
"""
from jarvis.memory.wiki.curator_llm import instantiate_curator_brain
+ # Per-provider failure reasons, collected as we go — feeds both the
+ # final log line's diagnostic detail and the health-surface chain-failure
+ # record (spec A5) so "openai 401; gemini 429" is visible, not just a
+ # generic "ALL N failed" count.
+ failure_summaries: list[str] = []
+
for provider, model in chain:
try:
brain = instantiate_curator_brain(registry, provider, model)
@@ -92,8 +98,10 @@ async def complete_with_fallback(
log.warning(
"%s: could not instantiate %s (%s) — trying next provider", label, provider, exc
)
+ failure_summaries.append(f"{provider} instantiate failed: {exc}")
continue
if brain is None:
+ failure_summaries.append(f"{provider} unavailable")
continue
try:
agg = await asyncio.wait_for(aggregate(brain.complete(request)), timeout=timeout_s)
@@ -105,9 +113,11 @@ async def complete_with_fallback(
provider,
timeout_s,
)
+ failure_summaries.append(f"{provider} timeout ({timeout_s:.1f}s)")
continue
except Exception as exc: # noqa: BLE001 — try the next family, never dead-end on one
log.warning("%s: provider %s failed (%s) — trying next provider", label, provider, exc)
+ failure_summaries.append(f"{provider} {exc}")
continue
log.error(
@@ -120,6 +130,14 @@ async def complete_with_fallback(
telemetry.inc("wiki_all_providers_failed")
except Exception: # noqa: BLE001 — telemetry must never break the pipeline
log.debug("%s: telemetry inc failed", label, exc_info=True)
+ try:
+ from jarvis.memory.wiki.health import health
+
+ health.record_chain_failure(
+ "; ".join(failure_summaries) if failure_summaries else f"{label}: empty provider chain"
+ )
+ except Exception: # noqa: BLE001 — health recording must never break the pipeline
+ log.debug("%s: health record_chain_failure failed", label, exc_info=True)
return None
diff --git a/jarvis/plugins/tool/wiki_ingest.py b/jarvis/plugins/tool/wiki_ingest.py
index 6aada996fc..4411499d7e 100644
--- a/jarvis/plugins/tool/wiki_ingest.py
+++ b/jarvis/plugins/tool/wiki_ingest.py
@@ -53,6 +53,22 @@ _MIN_INGEST_CHARS: int = 12
_MAX_INGEST_CHARS: int = 32_000
+def _record_write_health(
+ ok: bool, *, pages: list[str], error: str | None, source: str,
+) -> None:
+ """Record a wiki-ingest write outcome on the health singleton (spec A5).
+
+ Recording must never raise into the write path (AP-9) — a health-write
+ failure here would invert the honest-not-silent design.
+ """
+ try:
+ from jarvis.memory.wiki.health import health
+
+ health.record_write(ok, pages=pages, error=error, source=source)
+ except Exception: # noqa: BLE001 — health recording must never break ingest
+ log.debug("wiki-ingest: health.record_write failed", exc_info=True)
+
+
class WikiIngestTool:
"""Router-tier deterministic-ingest path into the long-term wiki vault."""
@@ -148,6 +164,12 @@ class WikiIngestTool:
curator = self._resolve_curator()
if curator is None:
log.warning("wiki-ingest: no live WikiCurator registered (bootstrap not run?)")
+ _record_write_health(
+ False,
+ pages=[],
+ error="wiki integration not bootstrapped",
+ source="tool:wiki-ingest",
+ )
return ToolResult(
success=False,
output="",
@@ -162,6 +184,12 @@ class WikiIngestTool:
result = await curator.ingest(text, source)
except Exception as exc: # noqa: BLE001
log.warning("wiki-ingest: curator.ingest raised %s", exc)
+ _record_write_health(
+ False,
+ pages=[],
+ error=f"curator ingest failed: {exc}",
+ source="tool:wiki-ingest",
+ )
return ToolResult(
success=False,
output="",
@@ -172,6 +200,13 @@ class WikiIngestTool:
skipped = list(getattr(result, "skipped_due_to_recent_edit", []) or [])
failed = list(getattr(result, "failed_validation", []) or [])
+ _record_write_health(
+ bool(applied),
+ pages=[str(p) for p in applied],
+ error=None if applied else "no pages written",
+ source="tool:wiki-ingest",
+ )
+
if not applied and not skipped and not failed:
# Curator judged the content not salient. The old success=True here made
# the model tell users "stored" when NOTHING was written (fresh-machine
diff --git a/jarvis/plugins/tts/inworld_tts.py b/jarvis/plugins/tts/inworld_tts.py
new file mode 100644
index 0000000000..d2585ca3d4
--- /dev/null
+++ b/jarvis/plugins/tts/inworld_tts.py
@@ -0,0 +1,372 @@
+"""Inworld AI TTS plugin (inworld-tts-2 — arena-#1 realtime, mid-2026).
+
+POST https://api.inworld.ai/tts/v1/voice — Basic auth, JSON response carrying
+base64 LINEAR16 audio (WAV-wrapped), decoded + RIFF-header-stripped to raw
+s16le 24 kHz mono so the pipeline handles it exactly like Cartesia/Grok.
+
+Structurally identical to CartesiaTTS: per-language voice resolution, parallel
+sentence synthesis, 15-minute cooldown on 401/403/429, cross-provider fallback.
+Inworld voices are multilingual — one voice speaks any of 15 languages via the
+per-turn ``language`` field — so we default to native masculine voices per
+language (Josef/Dennis/Diego) but the user can pin one voice across all.
+
+The auth key (``INWORLD_API_KEY``) is ALREADY base64 (a blob of
+``workspace-key:secret``) — it is sent verbatim after ``Basic ``, never
+re-encoded.
+"""
+from __future__ import annotations
+
+import asyncio
+import base64
+import logging
+import re
+import time
+from collections.abc import AsyncIterator
+from typing import Any
+
+from jarvis.core import config as cfg
+from jarvis.core.protocols import AudioChunk
+from jarvis.core.turn_language import DEFAULT_LOCALE
+from jarvis.plugins.tts.cartesia_tts import _detect_lang_from_text
+from jarvis.plugins.tts.gemini_flash_tts import SAPI5_SAMPLE_RATE, _sapi5_synthesize
+
+INWORLD_TTS_SAMPLE_RATE = 24_000
+INWORLD_TTS_ENDPOINT = "https://api.inworld.ai/tts/v1/voice"
+INWORLD_TTS_STREAM_ENDPOINT = "https://api.inworld.ai/tts/v1/voice:stream"
+_HTTP_TIMEOUT_S = 30.0
+_QUOTA_COOLDOWN_S = 900.0
+_MAX_CHARS_PER_REQUEST = 2_000 # Inworld hard limit per request
+
+DEFAULT_MODEL = "inworld-tts-2"
+
+# Native masculine assistant voices per language (Inworld voice catalog,
+# mid-2026). Parallel to Cartesia Sebastian/Daniel/Pedro. Every Inworld voice
+# is multilingual, so these are defaults, not hard language locks.
+DEFAULT_VOICE_DE = "Josef"
+DEFAULT_VOICE_EN = "Dennis"
+DEFAULT_VOICE_ES = "Diego"
+
+# BCP-47 tags Inworld expects. Jarvis' turn resolver already emits de-DE/en-US/
+# es-ES, but a bare "de" is normalized up so the field is always well-formed.
+_BCP47 = {"de": "de-DE", "en": "en-US", "es": "es-ES"}
+
+# DE letters are part of the sentence-boundary match set on the next line.
+_SENTENCE_END = re.compile(r"(?<=[.!?…])\s+(?=[A-ZÄÖÜ])") # i18n-allow
+
+
+def strip_wav_header(data: bytes) -> bytes:
+ """Return the raw PCM payload of a RIFF/WAVE buffer, or ``data`` unchanged.
+
+ Inworld's non-streaming LINEAR16 response is WAV-wrapped; the pipeline wants
+ raw s16le PCM. Locate the ``data`` sub-chunk and return everything after its
+ 8-byte (id + size) header. Robust to a missing header (already-raw PCM) and
+ to a truncated buffer.
+ """
+ if not data.startswith(b"RIFF") or b"WAVE" not in data[:16]:
+ return data
+ idx = data.find(b"data")
+ if idx == -1 or idx + 8 > len(data):
+ return data
+ return data[idx + 8:]
+
+
+def _normalize_language(code: str | None) -> str | None:
+ """Normalise a language hint into a BCP-47 tag Inworld accepts, or ``None``.
+
+ ``None``/``auto`` → ``None`` (omit the field → Inworld auto-detects from the
+ text). A bare two-letter code or a BCP-47 tag is mapped to the canonical
+ de-DE/en-US/es-ES; an unknown tag is passed through untouched.
+ """
+ if not code:
+ return None
+ low = code.lower().strip()
+ if low in ("auto", "automatic", ""):
+ return None
+ short = low.split("-", 1)[0]
+ return _BCP47.get(short, code)
+
+
+class _InworldFatalError(RuntimeError):
+ """401/403/429 — triggers cooldown + fallback switch."""
+
+
+class InworldTTS:
+ """TTS provider for Inworld (api.inworld.ai/tts/v1/voice).
+
+ Structurally compatible with the ``TTSProvider`` protocol — no inheritance
+ from ``jarvis.*`` (entry-point discovery pattern).
+ """
+
+ name = "inworld"
+ supports_streaming = True # pseudo via sentence-chunking (true NDJSON = follow-up)
+
+ def __init__(
+ self,
+ default_voice_de: str = DEFAULT_VOICE_DE,
+ default_voice_en: str = DEFAULT_VOICE_EN,
+ default_voice_es: str = DEFAULT_VOICE_ES,
+ model: str = DEFAULT_MODEL,
+ language: str = "auto",
+ chunk_by_sentence: bool = True,
+ speed: float = 1.0,
+ allow_sapi5_fallback: bool = False,
+ ) -> None:
+ self._model = model or DEFAULT_MODEL
+ self._voice_by_lang: dict[str, str] = {
+ "de": default_voice_de or DEFAULT_VOICE_DE,
+ "en": default_voice_en or DEFAULT_VOICE_EN,
+ "es": default_voice_es or DEFAULT_VOICE_ES,
+ }
+ self._language = language
+ _loc = (language or "").lower().split("-", 1)[0]
+ self._default_locale = _loc if _loc in self._voice_by_lang else DEFAULT_LOCALE
+ self._chunk_by_sentence = chunk_by_sentence
+ self._speed = speed
+ self._allow_sapi5_fallback = allow_sapi5_fallback
+ self._client: Any = None
+ self._quota_blocked_until: float = 0.0
+
+ def _resolve_voice(
+ self, text: str, voice_override: str | None, language_code: str | None
+ ) -> str:
+ """Pick the voice best matching the segment language (Cartesia parity):
+ explicit override → caller language_code → text heuristic → default
+ locale (never a hardcoded English voice on German text)."""
+ if voice_override:
+ return voice_override
+ hint = (language_code or "").lower().strip()
+ if hint and hint not in ("auto", "automatic", ""):
+ short = hint.split("-", 1)[0]
+ if short in self._voice_by_lang:
+ return self._voice_by_lang[short]
+ detected = _detect_lang_from_text(text)
+ if detected and detected in self._voice_by_lang:
+ return self._voice_by_lang[detected]
+ return self._voice_by_lang.get(self._default_locale, self._voice_by_lang["en"])
+
+ def _resolve_api_key(self) -> str:
+ val = cfg.get_secret("inworld_api_key", env_fallback="INWORLD_API_KEY")
+ if val:
+ return val
+ raise RuntimeError(
+ "Inworld API key not found. Set INWORLD_API_KEY in the OS keyring "
+ "or .env (slot: inworld_api_key). The value is the already-base64 "
+ "key string from platform.inworld.ai — do not re-encode it."
+ )
+
+ def _ensure_client(self) -> None:
+ if self._client is None:
+ import httpx
+
+ self._client = httpx.AsyncClient(
+ timeout=_HTTP_TIMEOUT_S,
+ headers={
+ # Key is already base64 — sent verbatim, never re-encoded.
+ "Authorization": f"Basic {self._resolve_api_key()}",
+ "Content-Type": "application/json",
+ },
+ )
+
+ async def aclose(self) -> None:
+ if self._client is not None:
+ try:
+ await self._client.aclose()
+ finally:
+ self._client = None
+
+ async def synthesize(
+ self,
+ text: str,
+ voice: str | None = None,
+ language_code: str | None = None,
+ ) -> AsyncIterator[AudioChunk]:
+ text = text.strip()
+ if not text:
+ return
+
+ voice_id = self._resolve_voice(text, voice, language_code)
+ log = logging.getLogger("jarvis.tts.inworld")
+
+ if self._quota_blocked_until and time.monotonic() < self._quota_blocked_until:
+ async for chunk in self._fallback(text, language_code):
+ yield chunk
+ return
+
+ try:
+ self._ensure_client()
+ except RuntimeError as exc:
+ log.warning("Inworld not initialisable (%s) -- falling back.", exc)
+ async for chunk in self._fallback(text, language_code):
+ yield chunk
+ return
+
+ sentences = _split_sentences(text) if self._chunk_by_sentence else [text]
+ if not sentences:
+ return
+
+ tasks = [
+ asyncio.create_task(self._synthesize_one(s, voice_id, language_code))
+ for s in sentences
+ ]
+ any_success = False
+ for i, task in enumerate(tasks):
+ try:
+ pcm = await task
+ except _InworldFatalError as exc:
+ self._quota_blocked_until = time.monotonic() + _QUOTA_COOLDOWN_S
+ log.warning(
+ "Inworld quota/auth error (%s) -- fallback for %.0f min.",
+ exc, _QUOTA_COOLDOWN_S / 60,
+ )
+ for t in tasks[i + 1:]:
+ t.cancel()
+ await asyncio.gather(*tasks[i + 1:], return_exceptions=True)
+ remainder = " ".join(sentences[i:])
+ async for chunk in self._fallback(remainder, language_code):
+ yield chunk
+ return
+
+ if pcm:
+ any_success = True
+ yield AudioChunk(
+ pcm=pcm,
+ sample_rate=INWORLD_TTS_SAMPLE_RATE,
+ timestamp_ns=0,
+ channels=1,
+ )
+ elif self._allow_sapi5_fallback:
+ log.warning(
+ "Inworld empty for sentence %d/%d -- SAPI5 emergency on.",
+ i + 1, len(tasks),
+ )
+ fallback_pcm = await asyncio.to_thread(
+ _sapi5_synthesize, sentences[i], language_code or "de-DE"
+ )
+ if fallback_pcm:
+ yield AudioChunk(
+ pcm=fallback_pcm,
+ sample_rate=SAPI5_SAMPLE_RATE,
+ timestamp_ns=0,
+ channels=1,
+ )
+ else:
+ log.error(
+ "Inworld returned no audio for sentence %d/%d (%r). "
+ "SAPI5 emergency disabled -- staying silent for this segment.",
+ i + 1, len(tasks), sentences[i][:80],
+ )
+
+ if not any_success:
+ log.error("Inworld produced no audio at all -- cross-provider fallback.")
+ async for chunk in self._fallback(text, language_code):
+ yield chunk
+
+ def list_voices(self, language: str | None = None) -> list[str]:
+ if language:
+ short = language.lower().split("-", 1)[0]
+ if short in self._voice_by_lang:
+ return [self._voice_by_lang[short]]
+ seen: list[str] = []
+ for v in (
+ self._voice_by_lang.get("de"),
+ self._voice_by_lang.get("en"),
+ self._voice_by_lang.get("es"),
+ ):
+ if v and v not in seen:
+ seen.append(v)
+ return seen
+
+ async def _synthesize_one(
+ self, text: str, voice_id: str, language_code: str | None
+ ) -> bytes:
+ log = logging.getLogger("jarvis.tts.inworld")
+ text = text[:_MAX_CHARS_PER_REQUEST]
+
+ audio_config: dict[str, Any] = {
+ "audioEncoding": "LINEAR16",
+ "sampleRateHertz": INWORLD_TTS_SAMPLE_RATE,
+ }
+ if self._speed != 1.0:
+ audio_config["speakingRate"] = self._speed
+ payload: dict[str, Any] = {
+ "text": text,
+ "voiceId": voice_id,
+ "modelId": self._model,
+ "audioConfig": audio_config,
+ }
+ lang = _normalize_language(language_code or self._language)
+ if lang is not None:
+ payload["language"] = lang
+
+ assert self._client is not None
+ try:
+ resp = await self._client.post(INWORLD_TTS_ENDPOINT, json=payload)
+ except Exception as exc: # noqa: BLE001
+ log.warning("Inworld HTTP error (%s) -- soft-fail.", exc.__class__.__name__)
+ return b""
+
+ if resp.status_code in (401, 403, 429):
+ raise _InworldFatalError(f"HTTP {resp.status_code}")
+ if resp.status_code >= 400:
+ body = resp.text[:200] if resp.text else "<empty>"
+ log.warning(
+ "Inworld HTTP %d -- voice=%s text=%r body=%s",
+ resp.status_code, voice_id, text[:80], body,
+ )
+ return b""
+
+ try:
+ data = resp.json()
+ except Exception as exc: # noqa: BLE001
+ log.warning("Inworld 200 but non-JSON body (%s).", exc.__class__.__name__)
+ return b""
+ b64 = data.get("audioContent") or ""
+ if not b64:
+ log.warning("Inworld 200 OK but empty audioContent -- voice=%s", voice_id)
+ return b""
+ try:
+ raw = base64.b64decode(b64)
+ except Exception as exc: # noqa: BLE001
+ log.warning("Inworld audioContent not base64 (%s).", exc.__class__.__name__)
+ return b""
+ return strip_wav_header(raw)
+
+ async def _fallback(
+ self, text: str, language_code: str | None
+ ) -> AsyncIterator[AudioChunk]:
+ log = logging.getLogger("jarvis.tts.inworld")
+ try:
+ from jarvis.plugins.tts.gemini_flash_tts import GeminiFlashTTS
+
+ gemini = GeminiFlashTTS(
+ language_code=language_code or "de-DE",
+ allow_sapi5_fallback=self._allow_sapi5_fallback,
+ )
+ async for chunk in gemini.synthesize(text, language_code=language_code):
+ yield chunk
+ return
+ except Exception as exc: # noqa: BLE001
+ log.error(
+ "Gemini fallback after Inworld error also failed (%s).",
+ exc.__class__.__name__, exc_info=True,
+ )
+
+ if not self._allow_sapi5_fallback:
+ log.error(
+ "Both Inworld and Gemini TTS produced no audio. SAPI5 emergency "
+ "disabled -- staying silent. Set tts.allow_sapi5_fallback=true "
+ "if Windows TTS is an acceptable last resort."
+ )
+ return
+
+ log.warning("SAPI5 emergency active (config opt-in).")
+ pcm = await asyncio.to_thread(_sapi5_synthesize, text, language_code or "de-DE")
+ if pcm:
+ yield AudioChunk(
+ pcm=pcm, sample_rate=SAPI5_SAMPLE_RATE, timestamp_ns=0, channels=1
+ )
+
+
+def _split_sentences(text: str) -> list[str]:
+ parts = _SENTENCE_END.split(text)
+ return [p.strip() for p in parts if p.strip()]
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index d8123ab49a..ca91cc40df 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -1729,6 +1729,12 @@ class WebServer:
logger.opt(exception=exc).warning(
"WikiIntegration init failed — wiki write-wiring inactive"
)
+ try:
+ from jarvis.memory.wiki.health import health as _wiki_health
+
+ _wiki_health.record_bootstrap(False, error=str(exc))
+ except Exception: # noqa: BLE001 — health recording must never break boot
+ logger.debug("wiki health.record_bootstrap(False) failed", exc_info=True)
_boot_mark("wiki_integration")
# Build the FTS5 search index once if it is empty so a pre-existing
@@ -2180,6 +2186,12 @@ class WebServer:
wiki_cfg = self.cfg.wiki_integration
if not wiki_cfg.enabled:
logger.info("wiki_integration: disabled — skipping bootstrap")
+ try:
+ from jarvis.memory.wiki.health import health as _wiki_health
+
+ _wiki_health.record_bootstrap(False, error="disabled in config")
+ except Exception: # noqa: BLE001 — health recording must never break boot
+ logger.debug("wiki health.record_bootstrap(disabled) failed", exc_info=True)
return
repo = MarkdownPageRepository()
@@ -2220,6 +2232,12 @@ class WebServer:
)
self._wiki_integration_handle = handle
logger.info("wiki_integration: bootstrap_wiki_integration succeeded")
+ try:
+ from jarvis.memory.wiki.health import health as _wiki_health
+
+ _wiki_health.record_bootstrap(True)
+ except Exception: # noqa: BLE001 — health recording must never break boot
+ logger.debug("wiki health.record_bootstrap(True) failed", exc_info=True)
def _init_wiki_boot_index(self) -> None:
"""One-shot FTS5 index build at boot for a pre-existing/restored vault.
diff --git a/jarvis/ui/web/wiki_routes.py b/jarvis/ui/web/wiki_routes.py
index d6cb305dd6..d13b0224f9 100644
--- a/jarvis/ui/web/wiki_routes.py
+++ b/jarvis/ui/web/wiki_routes.py
@@ -8,6 +8,10 @@ Five read-only endpoints power the Desktop App's new "Wiki" sidebar tab:
* ``GET /api/wiki/backlinks/{slug}``— reverse-link list with body snippets.
* ``GET /api/wiki/search`` — keyword search via ``VaultSearch`` (B5).
+Two later additions follow the same style: ``GET /api/wiki/telemetry`` (B8.7,
+in-memory counter snapshot) and ``GET /api/wiki/health`` (spec A5, bootstrap /
+write / chain-failure / journal-backlog status).
+
All endpoints follow the existing house style: HTTP 200 with the envelope
``{"ok": True, ...}`` on success and ``{"ok": False, "error": "..."}`` on
logical errors. HTTP 404 stays reserved for unknown routes; HTTP 500 only
@@ -609,4 +613,19 @@ async def get_telemetry(_request: Request) -> dict[str, Any]:
}
+async def wiki_health(_request: Request) -> dict[str, Any]:
+ """Wiki subsystem health for the Wiki tab status panel (spec A5).
+
+ The wiki subsystem is fire-and-forget by design (AP-9): failures never
+ interrupt a voice turn, but they must not vanish either. This surfaces
+ the process-wide :mod:`jarvis.memory.wiki.health` singleton so bootstrap
+ failures, write failures, chain exhaustion, and journal pressure become
+ visible instead of only ever appearing in the logs.
+ """
+ from jarvis.memory.wiki.health import health as _health
+
+ return {"ok": True, "health": _health.snapshot()}
+
+
__all__ = ["router"]
diff --git a/tests/unit/memory/wiki/test_health.py b/tests/unit/memory/wiki/test_health.py
new file mode 100644
index 0000000000..de40745058
--- /dev/null
+++ b/tests/unit/memory/wiki/test_health.py
@@ -0,0 +1,38 @@
+"""WikiHealth: silent failures must become visible state (spec A5)."""
+from jarvis.memory.wiki.health import WikiHealth
+
+
+def test_snapshot_starts_unknown_but_valid():
+ h = WikiHealth()
+ snap = h.snapshot()
+ assert snap["bootstrap_ok"] is None
+ assert snap["last_write"] is None
+ assert snap["journal_backlog"] == 0
+
+
+def test_record_write_success_and_failure_round_trip():
+ h = WikiHealth()
+ h.record_write(True, pages=["entities/joy.md"], error=None, source="tool")
+ assert h.snapshot()["last_write"]["ok"] is True
+ h.record_write(False, pages=[], error="all providers failed", source="tool")
+ last = h.snapshot()["last_write"]
+ assert last["ok"] is False
+ assert "providers" in last["error"]
+
+
+def test_chain_failure_and_backlog_recorded():
+ h = WikiHealth()
+ h.record_chain_failure("openai 401; gemini 429")
+ h.record_backlog(5)
+ snap = h.snapshot()
+ assert snap["last_chain_failure"]["detail"].startswith("openai")
+ assert snap["journal_backlog"] == 5
+
+
+def test_snapshot_is_json_safe():
+ import json
+
+ h = WikiHealth()
+ h.record_bootstrap(True)
+ h.record_write(True, pages=["log.md"], error=None, source="bridge")
+ json.dumps(h.snapshot()) # must not raise
diff --git a/tests/unit/plugins/tts/test_inworld_tts.py b/tests/unit/plugins/tts/test_inworld_tts.py
new file mode 100644
index 0000000000..7f8c561283
--- /dev/null
+++ b/tests/unit/plugins/tts/test_inworld_tts.py
@@ -0,0 +1,193 @@
+"""Unit tests for InworldTTS — mocked httpx, no live API calls.
+
+Inworld returns base64 audio inside JSON (WAV-wrapped LINEAR16 for the
+non-streaming endpoint), so the plugin must b64-decode AND strip the RIFF
+header to hand the pipeline raw s16le PCM like every other provider.
+"""
+from __future__ import annotations
+
+import base64
+import io
+import wave
+from typing import Any
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+from jarvis.plugins.tts.inworld_tts import (
+ INWORLD_TTS_SAMPLE_RATE,
+ InworldTTS,
+ strip_wav_header,
+)
+
+
+def _wav_b64(pcm: bytes) -> str:
+ buf = io.BytesIO()
+ with wave.open(buf, "wb") as w:
+ w.setnchannels(1)
+ w.setsampwidth(2)
+ w.setframerate(INWORLD_TTS_SAMPLE_RATE)
+ w.writeframes(pcm)
+ return base64.b64encode(buf.getvalue()).decode()
+
+
+class _Resp:
+ def __init__(self, status_code: int, json_data: dict | None = None, text: str = ""):
+ self.status_code = status_code
+ self._json = json_data or {}
+ self.text = text
+
+ def json(self) -> dict:
+ return self._json
+
+
+def patched_secret():
+ with patch(
+ "jarvis.plugins.tts.inworld_tts.cfg.get_secret",
+ return_value="d29ya3NwYWNlLWtleTpzZWNyZXQ=", # a base64-looking test key
+ ):
+ yield
+
+
+def tts(patched_secret) -> InworldTTS:
+ return InworldTTS(allow_sapi5_fallback=False)
+
+
+def test_strip_wav_header_removes_riff_but_leaves_raw_pcm():
+ pcm = b"\x11\x22" * 500
+ wav = base64.b64decode(_wav_b64(pcm))
+ assert wav.startswith(b"RIFF")
+ assert strip_wav_header(wav) == pcm
+ # Raw PCM without a header must pass through unchanged.
+ assert strip_wav_header(pcm) == pcm
+
+
+async def test_synthesize_decodes_and_strips_to_raw_pcm(tts: InworldTTS):
+ pcm = b"\x00\x01" * 1000
+ resp = _Resp(200, json_data={"audioContent": _wav_b64(pcm)})
+ mock_client = AsyncMock()
+ mock_client.post = AsyncMock(return_value=resp)
+ tts._client = mock_client
+
+ chunks = [c async for c in tts.synthesize("Hallo Welt.")]
+
+ assert len(chunks) == 1
+ assert chunks[0].pcm == pcm
+ assert chunks[0].sample_rate == INWORLD_TTS_SAMPLE_RATE
+ assert chunks[0].channels == 1
+
+
+async def test_payload_uses_linear16_24k_and_default_model(patched_secret):
+ tts = InworldTTS()
+ captured: dict[str, Any] = {}
+
+ async def fake_post(url: str, json: dict[str, Any]) -> _Resp:
+ captured.update(json)
+ return _Resp(200, json_data={"audioContent": _wav_b64(b"\x00\x01" * 100)})
+
+ mock_client = AsyncMock()
+ mock_client.post = fake_post # type: ignore[assignment]
+ tts._client = mock_client
+
+ [_ async for _ in tts.synthesize("Hi.", language_code="de-DE")]
+
+ assert captured["audioConfig"]["audioEncoding"] == "LINEAR16"
+ assert captured["audioConfig"]["sampleRateHertz"] == INWORLD_TTS_SAMPLE_RATE
+ assert captured["modelId"] == "inworld-tts-2"
+ assert captured["language"] == "de-DE"
+ assert captured["voiceId"] == "Josef" # German default voice
+
+
+async def test_language_code_picks_matching_voice(patched_secret):
+ tts = InworldTTS(
+ default_voice_de="Josef", default_voice_en="Dennis", default_voice_es="Diego"
+ )
+ captured: dict[str, Any] = {}
+
+ async def fake_post(url: str, json: dict[str, Any]) -> _Resp:
+ captured.update(json)
+ return _Resp(200, json_data={"audioContent": _wav_b64(b"\x00\x01" * 100)})
+
+ mock_client = AsyncMock()
+ mock_client.post = fake_post # type: ignore[assignment]
+ tts._client = mock_client
+
+ [_ async for _ in tts.synthesize("Hola.", language_code="es-ES")]
+ assert captured["voiceId"] == "Diego"
+
+
+async def test_auto_language_is_omitted(tts: InworldTTS):
+ captured: dict[str, Any] = {}
+
+ async def fake_post(url: str, json: dict[str, Any]) -> _Resp:
+ captured.update(json)
+ return _Resp(200, json_data={"audioContent": _wav_b64(b"\x00\x01" * 100)})
+
+ mock_client = AsyncMock()
+ mock_client.post = fake_post # type: ignore[assignment]
+ tts._client = mock_client
+
+ [_ async for _ in tts.synthesize("Hello.", language_code="auto")]
+ assert "language" not in captured
+
+
+async def test_basic_auth_header(patched_secret):
+ tts = InworldTTS()
+ tts._ensure_client()
+ try:
+ auth = tts._client.headers.get("authorization")
+ assert auth is not None and auth.startswith("Basic ")
+ finally:
+ await tts.aclose()
+
+
+async def test_401_triggers_cooldown_and_falls_back(tts: InworldTTS):
+ mock_client = AsyncMock()
+ mock_client.post = AsyncMock(return_value=_Resp(401, text="unauthorized"))
+ tts._client = mock_client
+
+ async def fake_fallback(text: str, lang: str | None):
+ from jarvis.core.protocols import AudioChunk
+
+ yield AudioChunk(pcm=b"FB", sample_rate=24_000, timestamp_ns=0, channels=1)
+
+ with patch.object(tts, "_fallback", side_effect=fake_fallback):
+ chunks = [c async for c in tts.synthesize("Test.")]
+
+ assert chunks and chunks[0].pcm == b"FB"
+ assert tts._quota_blocked_until > 0
+
+
+async def test_missing_key_falls_back_without_raising():
+ with patch(
+ "jarvis.plugins.tts.inworld_tts.cfg.get_secret", return_value=None
+ ):
+ tts = InworldTTS()
+
+ async def fake_fallback(text: str, lang: str | None):
+ from jarvis.core.protocols import AudioChunk
+
+ yield AudioChunk(pcm=b"FB", sample_rate=24_000, timestamp_ns=0, channels=1)
+
+ with patch.object(tts, "_fallback", side_effect=fake_fallback):
+ chunks = [c async for c in tts.synthesize("Hi.")]
+ assert chunks and chunks[0].pcm == b"FB"
+
+
+def test_list_voices_by_language(patched_secret):
+ tts = InworldTTS(
+ default_voice_de="Josef", default_voice_en="Dennis", default_voice_es="Diego"
+ )
+ assert tts.list_voices("de") == ["Josef"]
+ assert tts.list_voices("es") == ["Diego"]
+ allv = tts.list_voices()
+ assert {"Josef", "Dennis", "Diego"} <= set(allv)
diff --git a/tests/unit/ui/web/test_wiki_routes.py b/tests/unit/ui/web/test_wiki_routes.py
index 376923533e..4fc37fde33 100644
--- a/tests/unit/ui/web/test_wiki_routes.py
+++ b/tests/unit/ui/web/test_wiki_routes.py
@@ -394,3 +394,34 @@ def test_page_without_config_returns_error_envelope() -> None:
body = r.json()
assert body["ok"] is False
assert "not configured" in body["error"]
+
+
+# ----------------------------------------------------------------------
+# /health (spec A5)
+# ----------------------------------------------------------------------
+
+
+def test_health_returns_200_with_fresh_snapshot(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A fresh ``WikiHealth`` singleton reports the all-unknown baseline shape.
+
+ The singleton is process-wide, so other tests in the same run may have
+ mutated it — replace it with a brand-new instance for this assertion
+ rather than relying on run order for isolation.
+ """
+ from jarvis.memory.wiki.health import WikiHealth
+
+ monkeypatch.setattr("jarvis.memory.wiki.health.health", WikiHealth())
+
+ app = FastAPI()
+ app.include_router(wiki_router)
+ with TestClient(app) as client:
+ r = client.get("/api/wiki/health")
+ body = r.json()
+ assert r.status_code == 200
+ assert body["ok"] is True
+ assert body["health"]["journal_backlog"] == 0
+ assert body["health"]["bootstrap_ok"] is None
+ assert body["health"]["last_write"] is None
+ assert body["health"]["last_chain_failure"] is None