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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
"""Atomic edits to the jarvis.toml configuration at runtime.
Used by the provider-switch endpoint so that a user's change of Brain provider
updates not only the BrainManager's in-memory state but also the persistent default
selection in jarvis.toml. tomlkit preserves comments and formatting — the user has
many explanatory comments in jarvis.toml that must not be lost.
Writes atomically via a tempfile + os.replace (atomic on NTFS).
BOM handling: On Windows it is common for editors (Notepad, VS Code with
``files.encoding=utf8bom``) to prepend a UTF-8 BOM. ``tomlkit.parse``
does not tolerate this and raises EmptyKeyError. We strip the BOM on read and
write it back on save — so the file stays byte-identical for tools that expect
the BOM, while the patch is still applied in-place.
"""
from __future__ import annotations
import json
import logging
import os
import stat
import sys
import tempfile
import threading
import time
from dataclasses import dataclass
from pathlib import Path
import tomlkit
from tomlkit import TOMLDocument
from .config import (
DEFAULT_CONFIG_FILE,
OLLAMA_MODEL_OPTION_KEYS,
PROJECT_ROOT,
VOICE_ENGINE_VOICES,
OllamaModelOptions,
clear_config_cache,
)
log = logging.getLogger(__name__)
@dataclass(frozen=True)
class WriteReceipt:
"""What a three-layer model write actually landed.
``toml_ok`` is the jarvis.toml write (it raises on failure, so it is
``True`` whenever a receipt is returned at all). ``baseline_ok`` says whether
the drift baseline (``scripts/config-soll.json``) verifiably holds the # i18n-allow
same value after the best-effort sync — ``False`` means the drift guard may
revert the pick within its next run, and the caller should say so instead
of staying silent. ``baseline_path`` names the baseline file for the log.
"""
toml_ok: bool
baseline_ok: bool
baseline_path: str
_WRITE_LOCK = threading.Lock()
_ATOMIC_REPLACE_RETRY_DELAYS_S = (0.0, 0.025, 0.05, 0.1, 0.2, 0.4)
_BOM = ""
# Canonical User-scope ENV var that overrides ``[brain] primary`` at boot
# (see dodaios/core/config.py: ``JARVIS__*`` overrides are applied LAST and win
# over the TOML). The UI provider switch must keep this in sync, otherwise a
# stale env value silently reverts the switch on the next start.
_BRAIN_PRIMARY_ENV = "JARVIS__BRAIN__PRIMARY"
# Canonical User-scope ENV var that overrides ``[brain.worker] provider``
# at boot. ``_apply_env_overrides`` splits on ``__`` and lower-cases, so
# ``JARVIS__BRAIN__WORKER__PROVIDER`` -> ``brain.worker.provider``
# (renamed from JARVIS__BRAIN__SUB_JARVIS__PROVIDER in the 2026-06-29
# Jarvis-Agents rename; the old var is accepted via AliasChoices + migration shim).
_WORKER_PROVIDER_ENV = "JARVIS__BRAIN__WORKER__PROVIDER"
_WORKER_MODEL_ENV = "JARVIS__BRAIN__WORKER__MODEL"
# Back-compat aliases for the old ENV var names — kept so any code that
# references these constants by name still resolves without an ImportError.
_SUB_JARVIS_PROVIDER_ENV = _WORKER_PROVIDER_ENV # back-compat alias (pre-rename)
_SUB_JARVIS_MODEL_ENV = _WORKER_MODEL_ENV # back-compat alias (pre-rename)
# Canonical User-scope ENV var that overrides ``[brain.computer_use] provider``
# at boot — the dedicated GLOBAL Computer-Use planner provider, decoupled
# from ``[brain] primary``. Same shape as ``_WORKER_PROVIDER_ENV``.
_CU_PROVIDER_ENV = "JARVIS__BRAIN__COMPUTER_USE__PROVIDER"
# Canonical Tool Model selection. The legacy Computer-Use variable above is
# still read for old installations, but new Tool Model saves use this key.
_TOOL_MODEL_PROVIDER_ENV = "JARVIS__BRAIN__TOOL_MODEL__PROVIDER"
# Canonical User-scope ENV vars that override ``[tts] provider`` / ``[stt]
# provider`` at boot. Both section + key are single words, so
# ``_apply_env_overrides`` maps them cleanly to ``tts.provider`` / ``stt.provider``.
_TTS_PROVIDER_ENV = "JARVIS__TTS__PROVIDER"
_STT_PROVIDER_ENV = "JARVIS__STT__PROVIDER"
# ``[stt] model`` / ``[stt] language`` have the same single-word section + key,
# so a stale User-scope ENV var (e.g. one the wizard once wrote) OVERRIDES the
# TOML at boot and silently masks any later UI/TOML edit — the "model is
# hardcoded, I can't change it" trap (forensic 2026-06-28). The model/language
# setters therefore clear/sync this layer too, not just TOML + config-soll. # i18n-allow
_STT_MODEL_ENV = "JARVIS__STT__MODEL"
_STT_LANGUAGE_ENV = "JARVIS__STT__LANGUAGE"
def set_agentic_ide_prompt_writer(value: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Set ``[agentic_ide] prompt_writer`` — who writes Agentic IDE task briefs.
One layer only, deliberately. The brain-provider setters above also mirror
into the drift-guard soll file and a User-scope ENV var because a *provider* # i18n-allow
switch that survived only in TOML kept getting rolled back by a parallel
session. This setting has no soll entry and no ENV override reading it, so a # i18n-allow
second layer would be a lie about where the value lives.
Raises ``FileNotFoundError`` if the TOML config file does not exist — a
broken setup we do not silently mask.
"""
_patch_table(path, "agentic_ide", "prompt_writer", value)
def set_agentic_ide_follow_main(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Set ``[agentic_ide] follow_main``: keep this checkout's app on the newest main."""
_patch_table(path, "agentic_ide", "follow_main", bool(enabled))
def set_brain_primary(name: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Set ``[brain] primary`` to the given provider name across all layers.
This is the AUTHORITATIVE writer for the user's Brain-provider choice.
There are three persistence layers and a UI switch that only wrote one of
them did not survive a restart:
1. ``jarvis.toml`` ``[brain] primary`` (universal, always runs)
2. ``scripts/config-soll.json`` ``brain.primary`` (drift-guard soll value) # i18n-allow
3. ``JARVIS__BRAIN__PRIMARY`` User-scope ENV var (boot override)
Raises ``FileNotFoundError`` if the TOML config file does not exist (a
broken setup we do not silently mask). Layers 2 and 3 are best-effort
cloud-first enhancements: they degrade to a graceful no-op on a headless
Linux VPS (no config-soll.json, no Windows registry) and never raise out # i18n-allow
of this function nor break the TOML write.
"""
# Layer 1 — universal, runs on every platform. May raise FileNotFoundError.
_patch_table(path, "brain", "primary", name)
# Layers 2 + 3 — best-effort, never raise.
_sync_brain_primary_drift_soll(name) # i18n-allow
def set_worker_provider(
name: str, *, path: Path = DEFAULT_CONFIG_FILE, previous_provider: str | None = None
) -> str:
"""Set ``[brain.worker] provider`` (the Heavy-Task Jarvis-Agent provider)
across all persistence layers.
This is the AUTHORITATIVE writer for the user's subagent-provider choice
and the write-side counterpart to the read-side resolution in
``dodaios.missions.worker_runtime.provider_map.canonical_worker_provider`` /
``dodaios.missions.init._worker_factory``. The worker provider is pinned
in ``config-soll.json`` (``brain.worker.provider``), so a switch that # i18n-allow
wrote only the TOML would be reverted by the drift-guard within minutes —
the same failure mode that hit ``brain.primary`` before it went 3-layer.
1. ``jarvis.toml`` ``[brain.worker] provider`` (TOML)
2. ``scripts/config-soll.json`` ``brain.worker.provider`` (drift-soll) # i18n-allow
3. ``JARVIS__BRAIN__WORKER__PROVIDER`` User-scope ENV var (boot override)
Raises ``FileNotFoundError`` if the TOML config file does not exist. Layers
2 + 3 are best-effort cloud-first enhancements: graceful no-op on a headless
Linux VPS and never raise out of this function nor break the TOML write.
A different provider clears the previous provider's model override. The fallback chain
(``fallback_provider`` etc.) is left untouched, mirroring how the brain
switch leaves ``[brain]`` siblings alone.
Renamed from ``set_sub_jarvis_provider`` in the 2026-06-29 Jarvis-Agents
rename. The old name is preserved as a back-compat alias below.
"""
# Layer 1 — universal, runs on every platform. May raise FileNotFoundError.
model = _patch_worker_provider_toml(path, name, previous_provider=previous_provider)
# Layers 2 + 3 — best-effort, never raise.
_sync_worker_provider_drift_soll(name) # i18n-allow
_sync_worker_model_drift_soll(model) # i18n-allow
return model
# Back-compat alias — callers that imported set_sub_jarvis_provider still work.
set_sub_jarvis_provider = set_worker_provider
def set_computer_use_provider(name: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Set ``[brain.computer_use] provider`` (the dedicated GLOBAL
Computer-Use planner provider) across all persistence layers.
This is the AUTHORITATIVE writer for the user's Computer-Use-provider
choice and the write-side counterpart to the read-side resolution in
``dodaios.brain.manager.BrainManager._cu_provider`` (consumed by
``dodaios.cu.brain_call.call_vision_brain``'s dispatch hoist). The CU
provider is GLOBAL — one engine for both Realtime and Pipeline voice —
and is decoupled from ``[brain] primary`` (a new tier field, same shape
as ``[brain.worker]``/``[brain.realtime]``).
Mirrors :func:`set_worker_provider` exactly (same 3-layer + drift-guard
rationale — a TOML-only write would be reverted by the drift-guard
within minutes):
1. ``jarvis.toml`` ``[brain.computer_use] provider`` (TOML)
2. ``scripts/config-soll.json`` ``brain.computer_use.provider`` (drift-soll) # i18n-allow
3. ``JARVIS__BRAIN__COMPUTER_USE__PROVIDER`` User-scope ENV var (boot override)
Raises ``FileNotFoundError`` if the TOML config file does not exist. Layers
2 + 3 are best-effort cloud-first enhancements: graceful no-op on a
headless Linux VPS and never raise out of this function nor break the
TOML write.
NB: this writes only ``provider``. The fallback chain
(``fallback_provider`` etc.) is left untouched, mirroring
:func:`set_worker_provider`.
"""
# Layer 1 — universal, runs on every platform. May raise FileNotFoundError.
_patch_computer_use_provider_toml(path, name)
# Layers 2 + 3 — best-effort, never raise.
_sync_computer_use_provider_drift_soll(name) # i18n-allow
def set_tool_model_selection(
provider: str,
*,
model: str | None = None,
path: Path = DEFAULT_CONFIG_FILE,
) -> None:
"""Persist the canonical global Tool Model selection atomically.
``provider="auto"`` enables capability-aware automatic selection. ``model``
is a per-provider override; ``None`` leaves the existing override unchanged,
while ``""`` explicitly returns to the provider's main model. Legacy
``[brain.computer_use]`` and ``cu_model`` keys are deliberately left intact
so old installations remain readable without making them authoritative.
"""
provider = provider.strip()
if not provider:
raise ValueError("Tool Model provider must not be empty.")
if provider == "auto" and model not in (None, ""):
raise ValueError("An automatic Tool Model selection cannot pin a model.")
path = _ensure_writable_config_path(path)
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
brain = doc.get("brain")
if brain is None:
brain = tomlkit.table()
doc["brain"] = brain
tier = brain.get("tool_model")
if tier is None:
tier = tomlkit.table()
brain["tool_model"] = tier
tier["provider"] = provider
if model is not None and provider != "auto":
providers = brain.get("providers")
if providers is None:
providers = tomlkit.table(True)
brain["providers"] = providers
block = providers.get(provider)
if block is None:
block = tomlkit.table()
providers[provider] = block
block["tool_model"] = model
# Keep the legacy Computer-Use pin in lockstep: the route layer
# sets both fields in memory, and resolution falls back to
# ``cu_model`` when ``tool_model`` is ever cleared — persisting
# only one lets the pair drift apart across a restart.
block["cu_model"] = model
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
# The TOML write is authoritative. The drift-guard and User environment
# mirrors are best-effort so headless hosts never lose the successful save.
try:
_update_config_soll_section("brain.tool_model", {"provider": provider}) # i18n-allow
if model is not None and provider != "auto":
_update_config_soll_section( # i18n-allow
f"brain.providers.{provider}", {"tool_model": model}
)
except Exception as exc: # noqa: BLE001
log.warning( # i18n-allow: config-soll filename false positive
"Could not sync Tool Model selection to config-soll.json: %s", # i18n-allow
exc,
)
try:
_set_user_env_var(_TOOL_MODEL_PROVIDER_ENV, provider)
except Exception as exc: # noqa: BLE001
log.warning(
"Could not sync %s to the User environment: %s",
_TOOL_MODEL_PROVIDER_ENV,
exc,
)
def set_worker_model(model: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Set ``[brain.worker] model`` (the dedicated Jarvis-Agent LLM override)
across all persistence layers.
The write-side counterpart to the read-side resolution in
``dodaios.missions.workers.provider_chain._resolve_provider_chain`` (the
worker's primary model) and the ``/api/jarvis-agent/status`` ``model_resolved``
display. Empty string is the documented sentinel: the active worker
provider's ``deep_model`` (frontier) wins.
``brain.worker.model`` is pinned in ``config-soll.json`` like the # i18n-allow
provider, so a TOML-only write would be reverted by the drift-guard within
minutes (BUG-010 class). Three layers, same shape as
:func:`set_worker_provider`:
1. ``jarvis.toml`` ``[brain.worker] model`` (TOML)
2. ``scripts/config-soll.json`` ``brain.worker.model`` (drift-soll) # i18n-allow
3. ``JARVIS__BRAIN__WORKER__MODEL`` User-scope ENV var (boot override)
Layers 2 + 3 are best-effort cloud-first enhancements: graceful no-op on a
headless Linux VPS and never raise out of this function nor break the TOML
write. Takes effect for the NEXT mission (the worker resolves its chain per
spawn).
Renamed from ``set_sub_jarvis_model`` in the 2026-06-29 Jarvis-Agents rename.
The old name is preserved as a back-compat alias below.
"""
# Layer 1 — universal, runs on every platform. May raise FileNotFoundError.
_patch_worker_key_toml(path, "model", model)
# Layers 2 + 3 — best-effort, never raise.
_sync_worker_model_drift_soll(model) # i18n-allow
def migrate_worker_tier_table(*, path: Path = DEFAULT_CONFIG_FILE) -> bool:
"""One-time boot heal for the [brain.sub_jarvis] / [brain.worker] split-brain.
Both tables feed the SAME config field (``BrainConfig.worker`` via
``AliasChoices``), so a file carrying both is a latent conflict: the
canonical ``[brain.worker]`` wins at load time while the legacy table
silently rots (live case 2026-07-25: ``provider = "antigravity"`` vs
``"openai-codex"``, with the whole ``fallback_*`` chain stranded in the
dead table). This migration makes the file match what the loader
already resolves:
* both tables present -> copy legacy-ONLY keys (e.g. the ``fallback_*``
chain) into ``[brain.worker]``, then drop ``[brain.sub_jarvis]``;
keys present in both keep the canonical worker value.
* only the legacy table -> its keys move to ``[brain.worker]`` verbatim.
* no legacy table -> no-op (a cheap string probe skips the parse).
Returns True when the file was rewritten. Best-effort by design: a
missing file, unparsable TOML, or a write failure (read-only flag /
drift-guard EPERM) degrades to a logged no-op — boot must never break
on this heal. Reading old files keeps working either way through the
``AliasChoices`` read-compat alias, which stays.
"""
try:
if path == DEFAULT_CONFIG_FILE:
from dodaios.core.config import resolve_config_path # noqa: PLC0415
path = resolve_config_path()
if not path.exists():
return False
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
# Fast path: steady-state boots pay one file read, no TOML parse.
if "sub_jarvis" not in raw:
return False
doc: TOMLDocument = tomlkit.parse(raw)
brain = doc.get("brain")
if brain is None or "sub_jarvis" not in brain:
return False
legacy = brain["sub_jarvis"]
worker = brain.get("worker")
if worker is None:
worker = tomlkit.table()
brain["worker"] = worker
if isinstance(legacy, dict):
for key in legacy:
if key not in worker:
worker[key] = legacy[key]
del brain["sub_jarvis"]
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
log.info(
"Merged legacy [brain.sub_jarvis] into canonical [brain.worker] (%s).",
path,
)
return True
except Exception as exc: # noqa: BLE001 — boot heal must never raise
log.warning("Worker-tier TOML migration skipped: %s", exc)
return False
# Back-compat alias — callers that imported set_sub_jarvis_model still work.
set_sub_jarvis_model = set_worker_model
def set_tts_provider(name: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Set ``[tts] provider`` and reconcile the provider-dependent defaults,
across all THREE persistence layers.
Beyond ``provider`` this also writes the provider-specific voice / language /
model so the file never holds an invalid mix (e.g. switching Gemini ->
Grok-Voice must not leave ``voice_de = "Charon"`` behind, a voice Grok cannot
use). An existing value that is already valid for the new provider is kept —
user overrides win.
Three-layer persist (like ``set_brain_primary``): ``tts.provider`` (and the
voice keys) are pinned in ``config-soll.json``, so a TOML-only write would be # i18n-allow
reverted by the drift-guard within 5 minutes — the same bug class that hit
``brain.primary``. We therefore sync config-soll.json + ENV too. Crucially, # i18n-allow
config-soll receives EXACTLY the keys the TOML write touched (provider + the # i18n-allow
voice/language/model it set or preserved) so the guard sees zero drift across
the whole block.
Layers 2 + 3 are best-effort (cloud-first): a graceful no-op on a headless
Linux VPS, they never raise out of this function nor break the TOML write.
"""
# Layer 1 — universal, runs on every platform. May raise FileNotFoundError.
defaults = _TTS_DEFAULTS.get(name.lower(), {})
applied = _patch_tts_block(path, name, defaults)
# Layers 2 + 3 — best-effort, never raise.
_sync_tts_provider_drift_soll(applied) # i18n-allow
def set_stt_provider(name: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Set ``[stt] provider`` across all THREE persistence layers.
Takes effect on the next SpeechPipeline bootstrap (a voice restart): the STT
provider is instantiated once at pipeline start.
``stt.provider`` is pinned in ``config-soll.json``, so — like Brain/TTS — the # i18n-allow
switch needs the 3-layer persist (TOML + config-soll + ENV), otherwise the # i18n-allow
drift-guard reverts it within 5 minutes. Layers 2 + 3 are best-effort
(cloud-first) and never break the TOML write.
"""
# Layer 1 — universal, runs on every platform. The marker lands in the
# same atomic write and makes this explicit user choice authoritative over
# a stale provider override inherited by a later desktop process.
_patch_table(
path,
"stt",
"provider",
name,
extra={"provider_user_selected": True},
)
# Layers 2 + 3 — best-effort, never raise.
_sync_stt_provider_drift_soll(name) # i18n-allow
def set_tts_voice(voice: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Set the global TTS voice (``[tts] voice_de`` + ``voice_en``).
The TTS config is a single ``[tts]`` block, so this is the voice of the
ACTIVE TTS provider. Most generative voices are multilingual (Gemini Charon,
Grok leo …), so both language slots get the same value. ``voice_de`` /
``voice_en`` are pinned in ``config-soll.json`` (like ``tts.provider``), so a # i18n-allow
TOML-only write would be reverted by the drift-guard — we sync config-soll too. # i18n-allow
"""
_patch_table(path, "tts", "voice_de", voice)
_patch_table(path, "tts", "voice_en", voice)
try:
_update_config_soll_section("tts", {"voice_de": voice, "voice_en": voice}) # i18n-allow
except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
log.warning("Could not sync tts voice to config-soll.json: %s", exc) # i18n-allow
def set_tts_model(model: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Set the global TTS model (``[tts] model``) — e.g. Cartesia ``sonic-3.5``.
Synced to config-soll (drift-guard pinned, same class as the voice keys). # i18n-allow
"""
_patch_table(path, "tts", "model", model)
try:
_update_config_soll_section("tts", {"model": model}) # i18n-allow
except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
log.warning("Could not sync tts.model to config-soll.json: %s", exc) # i18n-allow
def set_tts_volume(volume: float, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Set the master TTS output volume (``[tts] volume``), a 0.0–1.0 gain.
Clamped to the same bounds the config field enforces (``ge=0.0, le=1.0``) so
a stray value can never over-drive (>1.0 clips) or invert (<0) playback. The
``[tts]`` block is drift-guard pinned (its reference snapshot already tracks
other ``[tts]`` keys), so a TOML-only write would be reverted — we sync that
snapshot too, exactly like :func:`set_tts_voice`. The Settings route applies
the change live to the running player; this persists the boot default.
"""
v = max(0.0, min(1.0, float(volume)))
_patch_table(path, "tts", "volume", v)
try:
_update_config_soll_section("tts", {"volume": v}) # i18n-allow
except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
log.warning("Could not sync tts.volume to config-soll.json: %s", exc) # i18n-allow
def set_audio_device(kind: str, value: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Set ``[audio] input_device`` / ``[audio] output_device``.
``kind`` is ``"input"`` or ``"output"``; ``value`` is a device display
NAME (the identifier stable across reboots/hot-plugs) or the
``"auto-headset"`` sentinel to restore automatic selection. The ``[audio]``
block is NOT drift-guard pinned, so the atomic TOML patch alone persists
it. The Settings route live-applies the change to the running pipeline;
this stores the boot default.
"""
if kind not in ("input", "output"):
raise ValueError(f"kind must be 'input' or 'output', got {kind!r}")
_patch_table(path, "audio", f"{kind}_device", str(value))
def set_stt_model(model: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Set the global STT model (``[stt] model``) across all THREE layers.
Takes effect on the next SpeechPipeline bootstrap (a voice restart): the STT
provider is instantiated once at pipeline start.
``stt.model`` is pinned in ``config-soll.json`` AND the single-word # i18n-allow
``JARVIS__STT__MODEL`` ENV var overrides the TOML at boot, so — exactly like
``stt.provider`` — the switch needs the 3-layer persist (TOML + config-soll + # i18n-allow
ENV); otherwise a stale ENV var (the "model is hardcoded" trap, forensic
2026-06-28) or the drift-guard silently reverts it. Layers 2 + 3 are
best-effort (cloud-first) and never break the TOML write.
"""
_patch_table(path, "stt", "model", model)
try:
_update_config_soll_section("stt", {"model": model}) # i18n-allow
except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
log.warning("Could not sync stt.model to config-soll.json: %s", exc) # i18n-allow
try:
_set_user_env_var(_STT_MODEL_ENV, model)
except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
log.warning("Could not sync %s to the User environment: %s", _STT_MODEL_ENV, exc)
def set_stt_provider_model(
provider: str, model: str, *, path: Path = DEFAULT_CONFIG_FILE
) -> dict[str, str]:
"""Pin ONE provider's transcription model (``[stt.models].<provider>``).
Returns the full mapping after the write, so a caller can update the live
config object without re-reading the file.
Why per provider rather than the single ``[stt] model``: that key holds a
faster-whisper CHECKPOINT name, which means nothing to a hosted API. One
global value therefore could not be forwarded to a cloud recognizer without
a fresh install posting ``large-v3-turbo`` to Groq — so the picker's choice
reached no provider at all and the dropdown changed nothing (AP-31).
Two layers, not three: the mapping is a TOML sub-table, and the ENV
override this repo uses for single-word keys (``JARVIS__STT__MODEL``) has
no shape that could carry it. The ``config-soll`` sync is what keeps the # i18n-allow
drift guard from reverting the pin, which is the layer that actually
mattered for the single-word keys anyway.
An empty ``model`` REMOVES the pin, which is how a user goes back to the
provider's own default without hand-editing anything.
"""
key = str(provider or "").strip()
if not key:
raise ValueError("A provider id is required to pin an STT model.")
value = str(model or "").strip()
path = _ensure_writable_config_path(path)
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
section = doc.get("stt")
if section is None:
section = tomlkit.table()
doc["stt"] = section
models = section.get("models")
if models is None:
models = tomlkit.table()
section["models"] = models
if value:
models[key] = value
else:
models.pop(key, None)
merged = {str(k): str(v) for k, v in models.items()}
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
try:
_update_config_soll_section("stt", {"models": merged}) # i18n-allow
except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
log.warning("Could not sync stt.models to config-soll.json: %s", exc) # i18n-allow
return merged
def set_stt_language(language: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Set the STT recognition language (``[stt] language``).
``auto`` or any code in ``RECOGNITION_LANGUAGES`` (validated by the caller).
``auto`` lets the recogniser detect the spoken language per utterance (the
default); a concrete code forces that language. Takes effect on the next SpeechPipeline
bootstrap (a voice restart): the STT provider is instantiated once at pipeline
start. Persisted across all THREE layers (TOML + config-soll + ENV): the stt # i18n-allow
block is drift-guard pinned, and the single-word ``JARVIS__STT__LANGUAGE`` ENV
var would otherwise override the TOML at boot, so a 2-layer write could be
silently masked (same trap as stt.model — forensic 2026-06-28).
"""
_patch_table(path, "stt", "language", language)
try:
_update_config_soll_section("stt", {"language": language}) # i18n-allow
except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
log.warning("Could not sync stt.language to config-soll.json: %s", exc) # i18n-allow
try:
_set_user_env_var(_STT_LANGUAGE_ENV, language)
except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
log.warning("Could not sync %s to the User environment: %s", _STT_LANGUAGE_ENV, exc)
def set_tts_cartesia_model(model: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Set Cartesia's model in its OWN sub-table ``[tts.cartesia] model_id``.
Cartesia reads its model from this sub-table (default ``sonic-3.5``), NOT the
global ``[tts] model`` that Gemini/OpenAI use. ``[tts.cartesia]`` is not pinned
in config-soll, so a plain atomic TOML write suffices (no drift-guard revert). # i18n-allow
"""
path = _ensure_writable_config_path(path)
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
tts = doc.get("tts")
if tts is None:
tts = tomlkit.table()
doc["tts"] = tts
cart = tts.get("cartesia")
if cart is None:
cart = tomlkit.table()
tts["cartesia"] = cart
cart["model_id"] = model
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
def set_codex_binary_path(binary_path: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Set ``[codex] binary_path`` to work around Windows PATH issues."""
_patch_table(path, "codex", "binary_path", binary_path)
# Voice-keybind action vocabulary. Shared with the keybinds API
# (dodaios/ui/web/settings_routes.py) and the TS type KeybindAction in the
# frontend (dodaios/ui/web/frontend/src/hooks/useHotkey.ts). Keep these layers in
# sync. The mapped value is BOTH the jarvis.toml key under [trigger] AND the
# TriggerConfig field name (they are intentionally identical).
KEYBIND_ACTIONS = ("call", "hangup", "dictate", "dictate_toggle", "paste_last", "pet_toggle")
KEYBIND_TOML_KEY = {
"call": "hotkey_call",
"hangup": "hotkey_hangup",
# Push-to-talk dictation: HOLD to speak, release to insert the transcript
# into whatever text field has focus. Ships bound to a curated combo (see
# TriggerConfig.hotkey_dictate for the reasoning and the collision proof).
# An empty value means "dictation has no shortcut", which stays a valid
# state, not a broken one: the bar, the UI and `jarvis api dictation start`
# all still work (and are the documented Wayland path).
"dictate": "hotkey_dictate",
# Hands-free dictation: press once to start, press again to stop. A
# separate action rather than a mode flag, so a user can arm a hold key and
# a toggle key at the same time.
"dictate_toggle": "hotkey_dictate_toggle",
# Insert the most recent dictation again — the recovery key for a paste
# that landed nowhere. Needs no microphone and no speech-to-text; it reads
# the local history, because a successful paste restores the previous
# clipboard content and therefore takes the transcript back off the
# clipboard within a second.
"paste_last": "hotkey_paste_last",
# Hide the desktop pet, or show it and bring it forward (docs/pets.md).
# Ships bound; see TriggerConfig.hotkey_pet_toggle for the collision proof.
"pet_toggle": "hotkey_pet_toggle",
}
#: One-time marker under ``[trigger]`` recording that the dictation-shortcut
#: backfill below has already run on this install. It is deliberately NOT a
#: user setting; see :func:`migrate_dictation_hotkey_defaults`.
DICTATION_HOTKEY_MIGRATION_KEY = "dictation_hotkeys_migrated"
#: The keys the backfill may touch, in the order it reports them.
_DICTATION_HOTKEY_FIELDS = ("hotkey_dictate", "hotkey_dictate_toggle")
def _combo_key_set(combo: object) -> set[str]:
"""Key SET of a combo — the unit the keybind collision rule compares."""
return {p.strip() for p in str(combo or "").strip().lower().split("+") if p.strip()}
def migrate_dictation_hotkey_defaults(*, path: Path = DEFAULT_CONFIG_FILE) -> bool:
"""One-time backfill of the dictation shortcuts. Runs exactly once, ever.
The problem it fixes (BUG-010 config drift). ``hotkey_dictate`` shipped as
``""`` for a while, so every install from that period has ``hotkey_dictate
= ""`` written into its ``jarvis.toml``. A persisted empty string beats the
code default, so when the default became a real combo those installs kept
reading "no key assigned" — while ``hotkey_dictate_toggle``, which was
never persisted because it did not exist yet, WAS armed from the new
default. Same feature, two different answers, decided by which key happened
to be in the file.
Why ``""`` is not simply treated as "use the default": that would make the
Clear button impossible. An unbound shortcut is a state the user is
entitled to, and it has to survive restarts. So the two cases are told
apart by a MARKER rather than by the value:
* marker absent -> this install has never been through the migration, so
an empty value is stale rather than chosen: write the current default.
* marker present -> every empty value from here on was chosen by the user
and is left alone forever.
The marker is written the first time the migration has a stale value to
consider, and never otherwise: this function is reached from
``load_config``, so a config file that has nothing to heal must come back
from a load byte-identical. The OTHER writer of the marker is
:func:`set_keybind` — an explicit save of a dictation shortcut, empty or
not, is proof the user has seen the value and chosen it, so it stamps the
marker too. Between them, an install where the keys are simply ABSENT is
never rewritten by a boot, and a Clear performed there is still permanent.
A default is skipped (while the marker is still written) when its key set
is a subset or superset of another shortcut already in the file: the
polling hotkey backend fires on subsets, so backfilling there would hand
the user two shortcuts that trigger each other. Better an unbound row the
user can fill in than a config the keybind route itself would refuse to
save.
Returns True when the file was rewritten. Best-effort by design: a missing
file, unparsable TOML or a failed write degrades to a logged no-op — a boot
heal must never break a boot.
"""
try:
if path == DEFAULT_CONFIG_FILE:
from dodaios.core.config import resolve_config_path # noqa: PLC0415
path = resolve_config_path()
if not path.exists():
# Nothing persisted yet, so nothing can be stale: a fresh install
# gets the code defaults, and the marker is written the first time
# anything else touches the file.
return False
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
# Fast path: healed installs pay one file read, never a TOML parse.
if DICTATION_HOTKEY_MIGRATION_KEY in raw:
return False
from dodaios.core.config import TriggerConfig # noqa: PLC0415
shipped = TriggerConfig()
doc: TOMLDocument = tomlkit.parse(raw)
trigger = doc.get("trigger")
if trigger is None:
# Nothing under [trigger] is persisted, so nothing can be
# stale: the code defaults already apply and there is nothing
# to heal. Returning without a write is what keeps a plain
# ``load_config`` from mutating a file it only had to read.
return False
backfilled: list[str] = []
considered = False
for field in _DICTATION_HOTKEY_FIELDS:
default = str(getattr(shipped, field, "") or "")
if not default:
continue
current = trigger.get(field)
if current is None or str(current).strip():
# Absent (the code default already applies) or already set
# by the user — either way, not this migration's business.
continue
considered = True
keys = _combo_key_set(default)
taken = [
_combo_key_set(trigger.get(other))
for other in KEYBIND_TOML_KEY.values()
if other != field and trigger.get(other) is not None
]
if any(other and (keys <= other or other <= keys) for other in taken):
log.info(
"Dictation shortcut %s left unbound: the shipped default "
"%r overlaps a shortcut this install already uses.",
field,
default,
)
continue
trigger[field] = default
backfilled.append(field)
if not considered:
return False
trigger[DICTATION_HOTKEY_MIGRATION_KEY] = True
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
log.info(
"Dictation shortcut migration applied to %s (backfilled: %s).",
path,
", ".join(backfilled) or "nothing",
)
return True
except Exception as exc: # noqa: BLE001 — a boot heal must never raise
log.warning("Dictation shortcut migration skipped: %s", exc)
return False
def set_keybind(action: str, hotkey: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist a voice keybind (call / hangup) to ``[trigger]`` in jarvis.toml.
Toml-only by design (same rationale as the other [trigger] writers — these
keys are NOT tracked in the drift-guard's reference snapshot, so it never reverts
them; a plain atomic write suffices and the BUG-010 3-layer rule does not
apply). Takes effect on the next SpeechPipeline bootstrap (a Jarvis restart):
bindings are armed once at pipeline start via ``TriggerConfig.resolve_hotkeys``
plus the ``hotkey_hangup`` read at the call sites.
Saving a DICTATION shortcut also stamps the one-time migration marker (see
:func:`migrate_dictation_hotkey_defaults`). An explicit save — including
clearing the row — is proof the user has seen this shortcut and chosen its
value, so the backfill must never reach it afterwards. Without the stamp,
Clear would work until the next restart and then quietly undo itself.
"""
try:
key = KEYBIND_TOML_KEY[action]
except KeyError:
raise ValueError(f"unknown keybind action: {action!r}") from None
if key in _DICTATION_HOTKEY_FIELDS:
_patch_table(
path,
"trigger",
key,
hotkey,
extra={DICTATION_HOTKEY_MIGRATION_KEY: True},
)
return
_patch_table(path, "trigger", key, hotkey)
#: Dictation settings that may be changed through the API. The value is both
#: the ``[dictation]`` TOML key and the ``DictationConfig`` field name; keep in
#: sync with the model and with the TS type in the frontend's dictation hook.
DICTATION_SETTING_KEYS = (
"mode",
"target",
"insert_method",
"paste_chord",
"paste_delay_ms",
"paste_delay_after_ms",
"restore_clipboard",
"remove_fillers",
"filler_max_removed_fraction",
"max_seconds",
"partial_interval_s",
"segment_seconds",
"final_quality_pass",
"final_window_seconds",
"final_overlap_seconds",
"local_engine",
"local_model",
"local_min_free_gb",
"code_switching",
"history_enabled",
"history_max_entries",
"history_retention_days",
"language",
"keep_failed_audio",
"audio_retention_days",
"audio_max_files",
# The polish pass. Persisted through the same PUT as everything else — the
# feature adds no route of its own, so a key missing from this tuple is a
# setting the user can switch in the UI and lose on the next restart.
"polish",
"polish_provider",
"polish_model",
"polish_timeout_ms",
"polish_timeout_max_ms",
"polish_max_input_chars",
"polish_min_words",
"polish_max_output_tokens",
"polish_temperature",
"polish_drift_max_shrink",
"polish_drift_max_growth",
"polish_style",
"polish_precision",
"polish_conversation",
# The translate pass. Same rule as the polish keys above: a key missing here
# is a switch the UI appears to save and loses on the next restart.
"translate",
"translate_target",
"translate_drift_max_shrink",
"translate_drift_max_growth",
# Prompt Mode. Same rule again: a key missing here is a switch the UI
# appears to save and loses on the next restart.
"prompt_mode",
"prompt_mode_timeout_ms",
)
def set_dictation_setting(
key: str,
value: str | bool | int | float,
*,
path: Path = DEFAULT_CONFIG_FILE,
) -> None:
"""Persist one ``[dictation]`` key in jarvis.toml.
Toml-only, like the other ``[trigger]``/``[dictation]`` writers: these keys
are not part of the drift-guard's reference snapshot, so a plain atomic
write is enough and the BUG-010 three-layer rule does not apply. The
caller validates the value against ``DictationConfig`` first — this writer
only refuses unknown KEYS, so a typo can never invent a config field.
"""
if key not in DICTATION_SETTING_KEYS:
raise ValueError(f"unknown dictation setting: {key!r}")
_patch_table(path, "dictation", key, value)
#: Keys ``[screen_context]`` accepts. An allowlist rather than a passthrough:
#: a typo must never invent a config field that silently does nothing (AP-31),
#: and a privacy feature is the last place to accept "whatever was posted".
SCREEN_CONTEXT_SETTING_KEYS: frozenset[str] = frozenset(
{
"enabled",
"denylist",
"sensitive_patterns",
"include_default_patterns",
"max_text_chars",
"ttl_s",
"ocr_enabled",
}
)
def set_screen_context_setting(
key: str,
value: str | bool | int | float | list,
*,
path: Path = DEFAULT_CONFIG_FILE,
) -> None:
"""Persist one ``[screen_context]`` key in jarvis.toml.
Same shape as :func:`set_dictation_setting`: TOML-only atomic write, keys
validated against an allowlist, values validated by the caller against
``ScreenContextConfig``. These keys are not part of the drift-guard's
reference snapshot, so the BUG-010 three-layer rule does not apply.
"""
set_screen_context_settings({key: value}, path=path)
def set_screen_context_settings(
values: dict[str, str | bool | int | float | list],
*,
path: Path = DEFAULT_CONFIG_FILE,
) -> None:
"""Persist a validated Screen Context patch in one atomic replacement."""
unknown = set(values).difference(SCREEN_CONTEXT_SETTING_KEYS)
if unknown:
raise ValueError(f"unknown screen_context setting(s): {sorted(unknown)!r}")
if not values:
return
path = _ensure_writable_config_path(path)
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
section = doc.get("screen_context")
if section is None:
section = tomlkit.table()
doc["screen_context"] = section
for key, value in values.items():
section[key] = value
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
#: Keys ``[appshot]`` accepts — same allowlist reasoning as Screen Context.
#: The master switch is ``[screen_context].enabled``, written by the setter above.
APPSHOT_SETTING_KEYS: frozenset[str] = frozenset(
{"keep_newest",
"hotkey", "region_hotkey", "region_keep_area", "recording_hotkey", "target", "sound",
"effect", "card_seconds", "library", "copy_to_clipboard", "recording_resolution",
"recording_fps", "recording_bitrate_mbps", "recording_system_audio"}
)
def set_appshot_settings(
values: dict[str, str | bool | int],
*,
path: Path = DEFAULT_CONFIG_FILE,
) -> None:
"""Persist a validated ``[appshot]`` patch in one atomic replacement."""
unknown = set(values).difference(APPSHOT_SETTING_KEYS)
if unknown:
raise ValueError(f"unknown appshot setting(s): {sorted(unknown)!r}")
if not values:
return
path = _ensure_writable_config_path(path)
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
section = doc.get("appshot")
if section is None:
section = tomlkit.table()
doc["appshot"] = section
for key, value in values.items():
section[key] = value
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
#: Keys ``[jarvisx]`` accepts (``dodaios.core.config.JarvisXConfig``). The
#: route validates types and hotkeys first; this allowlist keeps a typo from
#: ever landing in the file.
JARVISX_SETTING_KEYS: frozenset[str] = frozenset(
{
"enabled",
"hotkey_region",
"hotkey_window",
"hotkey_fullscreen",
"hotkey_record_region",
"hotkey_record_fullscreen",
"hotkey_stop_recording",
"thumbnail_persist",
"thumbnail_dismiss_s",
"save_dir",
"copy_to_clipboard",
"sound",
"effect",
"keep_newest",
}
)
def set_jarvisx_settings(
values: dict[str, str | bool | int],
*,
path: Path = DEFAULT_CONFIG_FILE,
) -> None:
"""Persist a validated ``[jarvisx]`` patch in one atomic replacement."""
unknown = set(values).difference(JARVISX_SETTING_KEYS)
if unknown:
raise ValueError(f"unknown jarvisx setting(s): {sorted(unknown)!r}")
if not values:
return
path = _ensure_writable_config_path(path)
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
section = doc.get("jarvisx")
if section is None:
section = tomlkit.table()
doc["jarvisx"] = section
for key, value in values.items():
section[key] = value
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
def set_missions_paid_api_fallback(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist ``[missions] paid_api_fallback`` (the paid-API fallback switch).
The only writer of this key. Called from the Settings route
(``PUT /api/mission-billing``) — the self-mod / voice path refuses the key
(``dodaios/core/self_mod/forbidden.py``). Read fresh by
``dodaios.missions.capacity.paid_api_fallback_enabled``, so the change
applies to the very next mission decision without a restart.
"""
if not isinstance(enabled, bool):
raise TypeError("paid_api_fallback must be a bool")
_patch_table(path, "missions", "paid_api_fallback", enabled)
def set_wiki_semantic_search(
enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE
) -> None:
"""Persist ``[wiki_context] semantic_search`` (search the wiki by meaning).
The only writer of this key, called from ``PUT /api/wiki/semantic-search``.
The route starts or stops the search engine itself, so the change applies
at once; this write makes it survive a restart.
"""
if not isinstance(enabled, bool):
raise TypeError("semantic_search must be a bool")
_patch_table(path, "wiki_context", "semantic_search", enabled)
def set_reply_language(name: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist the user-facing reply-language pin in ``[brain] reply_language``.
``name`` is one of ``auto`` | ``de`` | ``en`` | ``es`` (validated by the
caller). Takes effect as a boot default on the next ``load_config`` call — the
live switch happens via ``BrainManager.set_reply_language``.
"""
_patch_table(path, "brain", "reply_language", name)
def set_proactivity(level: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist the assistant's initiative level in ``[brain] proactivity``.
``level`` is one of ``off`` | ``balanced`` | ``high`` (validated by the
caller). The live switch happens via ``dodaios.brain.proactivity.apply_level``.
"""
_patch_table(path, "brain", "proactivity", level)
def set_ui_language(name: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist the interface (display) language in ``[ui] language``.
``name`` is one of ``en`` | ``de`` | ``es`` | ``pt`` | ``zh`` (validated by the
caller).
This is the backend home for what used to be a frontend-only localStorage value,
so a voice command / the Control API can change the visible app language and
the open UI switches live (the change is broadcast over /ws).
"""
_patch_table(path, "ui", "language", name)
def set_ui_theme(theme: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist the app's colour theme in ``[ui] theme``.
``theme`` is one of ``dark`` | ``light`` | ``system`` (validated by the
caller). Read at boot by the native window so the frame is painted in the
matching colour before the web view loads, and by the frontend so the
choice survives a cleared browser store.
"""
_patch_table(path, "ui", "theme", theme)
def set_preferred_opener(opener: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist the remembered "open with" choice in ``[ui] preferred_opener``.
``opener`` is an opener id (``default`` | ``browser`` | an editor key like
``code``) validated by the caller. Used by the Outputs view so a file opens
straight in the chosen app without re-prompting. Desktop-only setting.
"""
_patch_table(path, "ui", "preferred_opener", opener)
def set_wake_word(
phrase: str,
*,
engine: str | None = None,
custom_model_path: str | None = None,
fuzzy_match_ratio: float | None = None,
path: Path = DEFAULT_CONFIG_FILE,
) -> None:
"""Persist the user's wake word to ``[trigger.wake_word]`` in jarvis.toml.
Toml-only by design — and that is a deliberate decision, NOT an oversight of
the "user-switchable settings are written to all three layers" rule:
* The drift-guard only reverts keys it tracks in ``config-soll.json``, and # i18n-allow
``trigger.wake_word`` is intentionally NOT tracked there — so a plain
atomic toml write is never reverted. The three-layer rule exists to stop
the guard from rolling a UI switch back (BUG-010); with no soll entry # i18n-allow
there is nothing to roll back.
* Adding a nested ``wake_word`` object to ``config-soll.json`` would make # i18n-allow
the guard's scalar-only loops synthesise a garbage
``JARVIS__TRIGGER__WAKE_WORD`` user env var from a stringified dict
(BUG-018 class). And a stale ``JARVIS__*`` override would silently win
over a hand-edit of jarvis.toml — directly contradicting the
"edit `phrase` here" guidance in the file. So neither the soll nor the # i18n-allow
ENV layer is written for the wake word.
Takes effect on the next voice-pipeline bootstrap (a Jarvis restart): the
OWW model + phrase matcher are resolved once at SpeechPipeline construction.
"""
values: dict[str, object] = {"phrase": phrase}
if engine is not None:
values["engine"] = engine
if custom_model_path is not None:
values["custom_model_path"] = custom_model_path
if fuzzy_match_ratio is not None:
values["fuzzy_match_ratio"] = float(fuzzy_match_ratio)
_patch_wake_word_toml(path, values)
try:
_strip_persona_name(path)
except Exception as exc: # noqa: BLE001 — cleanup is best-effort, never breaks the save
log.debug("persona-name strip skipped: %s", exc)
def set_wake_language(language: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist the wake-word language pin to ``[trigger.wake_word] language``.
One of ``auto`` | ``de`` | ``en`` | ``es`` (validated by the caller). This is
the user's INDEPENDENT wake-word language: a concrete code pins which
acoustic model hears the wake word, decoupled from both the app display
language (``[ui] language``) and the general recognition language
(``[stt] language``); ``auto`` keeps the legacy cascade (stt -> ui ->
default). TOML-only by design, same rationale as :func:`set_wake_word`:
``trigger.wake_word`` is deliberately NOT tracked in ``config-soll.json``, # i18n-allow
so a plain atomic write is never reverted and no ENV layer applies.
"""
_patch_wake_word_toml(path, {"language": language})
def set_wake_word_enabled(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist the wake-word activation toggle to ``[trigger] wake_word_enabled``.
This is the "how do you activate Jarvis" master switch: True = always-on wake
word (which requires a local model that matches the user's word — see
``resolve_wake_plan``), False = Call shortcut only. It was previously
settable ONLY by hand-editing jarvis.toml (default False), so a fresh
downloader could never turn their wake word on in-app.
TOML-only by design, same as ``set_autostart``: ``trigger.wake_word_enabled``
is NOT tracked in ``config-soll.json`` (only ``trigger.single_turn_mode`` is), # i18n-allow
so the drift-guard never reverts it and a plain atomic write suffices.
Takes effect on the next voice-pipeline bootstrap (a Jarvis restart): the
detector enable-flags are resolved once at SpeechPipeline construction.
"""
_patch_table(path, "trigger", "wake_word_enabled", bool(enabled))
def set_autostart(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist the login-autostart toggle to ``[autostart] enabled`` in jarvis.toml.
Toml-only by design: ``autostart.enabled`` is NOT tracked in
``config-soll.json`` (verified absent), so the drift-guard never reverts it — # i18n-allow
a plain atomic write suffices and the 3-layer rule (which exists only to stop
the guard from rolling a UI switch back, BUG-010) does not apply.
This persists the *intent*. The actual OS entry (install/remove) is applied
by the caller via ``dodaios.autostart`` (live by the Settings route, or on the
next boot by ``reconcile_autostart``).
"""
_patch_table(path, "autostart", "enabled", bool(enabled))
def set_autostart_background_only(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist ``[autostart] background_only`` (login starts only the agent service).
Toml-only, same rationale as :func:`set_autostart`; the caller re-applies
the OS entry so its command line follows the new mode.
"""
_patch_table(path, "autostart", "background_only", bool(enabled))
def set_background_keep_running(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist ``[background] keep_agents_running`` in jarvis.toml.
Toml-only, same rationale as :func:`set_autostart`: the drift-guard does
not track it. Read at quit time, so it applies without a restart.
"""
_patch_table(path, "background", "keep_agents_running", bool(enabled))
def set_agent_server(
*, persistent: bool, server_url: str = "", path: Path = DEFAULT_CONFIG_FILE,
) -> None:
"""Select independent server ownership for the next desktop launch."""
from dodaios.core.server_endpoint import server_endpoint
origin = server_endpoint(server_url) if server_url.strip() else ""
_patch_table(
path, "background", "persistent_server", bool(persistent),
extra={"server_url": origin},
)
#: Keys ``[self_build]`` accepts from the Settings page (docs/self-build.md).
SELF_BUILD_SETTING_KEYS: frozenset[str] = frozenset(
{
"enabled", "silent_days", "memory", "skill", "routine", "agent", "code",
"trial_days", "trial_uses", "max_builds_per_day", "max_agents_per_week",
"max_open_trials", "max_code_runs_per_day", "max_rejections", "code_land_repos",
}
)
def set_self_build_settings(
values: dict[str, str | bool | int | list[str]], *, path: Path = DEFAULT_CONFIG_FILE
) -> None:
"""Persist a validated ``[self_build]`` patch in one atomic write.
The caller validates against ``SelfBuildConfig`` first. Toml-only: the
drift guard does not track the section, and the running loop reads the
in-memory config the route updates, so a change applies without a restart.
"""
unknown = set(values).difference(SELF_BUILD_SETTING_KEYS)
if unknown:
raise ValueError(f"unknown self_build setting(s): {sorted(unknown)!r}")
if not values:
return
first, *rest = values.items()
_patch_table(path, "self_build", first[0], first[1], extra=dict(rest))
def set_wiki_vault_root(vault_root: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist ``[wiki_integration] vault_root`` in jarvis.toml (AP-7).
Written when the Obsidian setup wizard registers the "existing vault"
mode (spec A6): the wiki subsystem is repointed to ``<vault>/Jarvis``
so every wiki write stays contained inside the user's own vault.
TOML-only by design: ``wiki_integration`` is NOT tracked in
``config-soll.json``, so the drift-guard never reverts it (same # i18n-allow
rationale as :func:`set_overlay_style`). Takes effect on the next app
restart — the running curator/FTS index still targets the old vault
until then.
"""
_patch_table(path, "wiki_integration", "vault_root", vault_root)
def set_overlay_style(style: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist the on-screen overlay style to ``[ui] orb_style`` in jarvis.toml.
``style`` is one of ``dodaios.ui.overlay_styles.OVERLAY_STYLES``
(``"jarvis_bar"`` / ``"mascot"`` / ``"voice_orb"`` / ``"none"``). TOML-only
by design: ``ui.orb_style`` is NOT in the drift-guard's reference snapshot, so the
drift-guard never reverts it (same rationale as :func:`set_autostart`). The
Settings route applies the change live; this persists the boot default.
"""
_patch_table(path, "ui", "orb_style", style)
def set_computer_use_engine(engine: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist the active Computer-Use engine to ``[computer_use] engine``.
``engine`` is ``"current"`` (the maintained engine) or ``"june13"`` (the
frozen 2026-06-10 / 352a784f snapshot kept as a reversible fallback).
TOML-only by design: ``computer_use.engine`` is NOT in the drift-guard's
reference snapshot, so it is never reverted (same rationale as
:func:`set_overlay_style`). The harness reads the value per mission, so the
switch applies on the next mission / restart without a code change.
"""
_patch_table(path, "computer_use", "engine", engine)
def set_voice_mode(mode: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist the active voice engine to ``[voice] mode``.
``mode`` is ``"pipeline"`` (classic STT->brain->TTS, the default) or
``"realtime"`` (full-duplex speech-to-speech). TOML-only by design:
``voice.mode`` is NOT in the drift-guard reference snapshot, so it is never
reverted (same rationale as :func:`set_computer_use_engine`). Read once per
voice session, so the switch applies on the next session / restart.
"""
_patch_table(path, "voice", "mode", mode)
def set_voice_profile(
profile: str,
*,
mode: str = "pipeline",
path: Path = DEFAULT_CONFIG_FILE,
) -> None:
"""Persist one session-scoped voice profile and its compatible engine.
Both keys land in the same atomic TOML rewrite. This prevents an upgrade
or interrupted settings write from leaving the subscription profile paired
with the experimental realtime engine.
"""
_patch_table(
path,
"voice",
"profile",
str(profile or "").strip(),
extra={"mode": str(mode or "pipeline").strip().lower()},
)
def set_realtime_voice_selection(
provider: str,
*,
profile: str,
mode: str,
path: Path = DEFAULT_CONFIG_FILE,
) -> None:
"""Persist one Realtime provider and its compatible voice state atomically.
This is the migration-safe writer for a Realtime provider switch that also
has to retire a classic voice profile. Keeping all three values in one TOML
replacement prevents a crash or write failure from leaving the selected
provider paired with a stale Pipeline-only profile.
"""
path = _ensure_writable_config_path(path)
normalized_provider = str(provider or "").strip()
normalized_profile = str(profile or "").strip()
normalized_mode = str(mode or "").strip().lower()
if not normalized_provider:
raise ValueError("A Realtime provider id is required.")
if normalized_mode not in {"pipeline", "realtime"}:
raise ValueError("Voice mode must be 'pipeline' or 'realtime'.")
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
brain = doc.get("brain")
if brain is None:
brain = tomlkit.table()
doc["brain"] = brain
realtime = brain.get("realtime")
if realtime is None:
realtime = tomlkit.table()
brain["realtime"] = realtime
realtime["provider"] = normalized_provider
voice = doc.get("voice")
if voice is None:
voice = tomlkit.table()
doc["voice"] = voice
voice["profile"] = normalized_profile
voice["mode"] = normalized_mode
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
def migrate_removed_codex_realtime_provider(*, path: Path = DEFAULT_CONFIG_FILE) -> bool:
"""Route a removed Codex Realtime selection onto the stable composition.
The ``codex-subscription-realtime`` adapter was removed 2026-08-10 (the
experimental Codex app-server realtime surface never held a dependable
call). A config still pinning it would boot into Realtime mode with no
resolvable provider and silently lose subscription voice. Instead, the
pin is cleared from every explicit slot and — when it was the PRIMARY
selection — the install lands on the classic subscription composition
(``voice.profile = "codex-subscription-voice"``, Pipeline mode), which
keeps voice on the same ChatGPT login. Configs not naming the removed
provider are never touched.
"""
if path == DEFAULT_CONFIG_FILE:
from dodaios.core.config import resolve_config_path
path = resolve_config_path()
if not path.exists():
return False
removed = "codex-subscription-realtime"
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
brain = doc.get("brain")
realtime = brain.get("realtime") if brain is not None else None
if realtime is None:
return False
slots = ("provider", "fallback_provider", "fallback_provider_2")
pinned = [slot for slot in slots if str(realtime.get(slot) or "").strip() == removed]
if not pinned:
return False
was_primary = "provider" in pinned
for slot in pinned:
realtime[slot] = ""
if was_primary:
voice = doc.get("voice")
if voice is None:
voice = tomlkit.table()
doc["voice"] = voice
voice["profile"] = "codex-subscription-voice"
voice["mode"] = "pipeline"
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
return True
def set_realtime_provider(provider: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist the active realtime-voice provider to ``[brain.realtime] provider``.
``provider`` is a realtime-tier id (e.g. ``"openai-realtime"``). TOML-only
by design: ``brain.realtime`` is NOT in the drift-guard's reference
snapshot, so it is never reverted (same rationale as :func:`set_voice_mode`).
Takes effect on the next voice session / restart — the realtime client is
not wired in yet (Phase 2).
"""
_patch_realtime_provider_toml(path, provider)
def set_realtime_fallback_provider(provider: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist ``[brain.realtime] fallback_provider``.
The factory tries the fallback after the primary during the SAME handshake
(dodaios/realtime/factory.py reads ``provider`` then ``fallback_provider``),
so an explicit fallback is how a subscription primary degrades honestly
instead of silently losing realtime voice. Same TOML-only rationale as
:func:`set_realtime_provider`.
"""
_patch_realtime_provider_toml(path, provider, key="fallback_provider")
def set_voice_engine_settings(
*,
tts: str | None = None,
llm_model: str | None = None,
path: Path = DEFAULT_CONFIG_FILE,
) -> None:
"""Persist the Local voice card's choices to ``[voice_engine]``.
``tts`` must be one of ``config.VOICE_ENGINE_VOICES``; ``llm_model`` is an
Ollama tag, and an empty string means "automatic". Both land in ONE atomic
write. Read by ``dodaios/plugins/realtime/local_voice.py``; the running
engine picks them up on its next start.
"""
values: dict[str, str | bool | int | float | list[str]] = {}
if tts is not None:
voice = tts.strip().lower()
if voice not in VOICE_ENGINE_VOICES:
raise ValueError(f"unknown local voice {tts!r}; expected one of {VOICE_ENGINE_VOICES}")
values["tts"] = voice
if llm_model is not None:
model = llm_model.strip()
if any(ch.isspace() for ch in model) or len(model) > 200:
raise ValueError(f"not an Ollama model tag: {llm_model!r}")
values["llm_model"] = model
if not values:
return
first_key, *rest = values
_patch_table(
path,
"voice_engine",
first_key,
values[first_key],
extra={key: values[key] for key in rest},
)
def set_silence_window_ms(ms: int, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist the voice silence window to ``[speech] vad_silence_ms`` in jarvis.toml.
Clamps exactly as the config field does: 0 means AUTOMATIC (every voice
engine keeps its own factory turn detection) and survives untouched, while
any positive value lands inside 500–5000 ms, so a stray value can never
wedge endpointing. TOML-only by design (not in the drift-guard's reference
snapshot, like :func:`set_overlay_style`); the Settings route applies the
change live, this persists the boot default.
"""
raw = int(ms)
clamped = 0 if raw <= 0 else max(500, min(5000, raw))
_patch_table(path, "speech", "vad_silence_ms", clamped)
def set_session_idle_timeout_s(seconds: float, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist ``[trigger] session_idle_timeout_s`` — the conversation-mode idle
auto-hangup window.
A value <= 0 DISABLES the auto-hangup entirely: the voice session then stays
active until a manual hangup ("auflegen" / the hangup hotkey). Negative input
is normalised to 0. Stored as a plain number; applies on the next voice
(re)start. TOML-only (not drift-guarded), like :func:`set_silence_window_ms`.
"""
value = max(0.0, float(seconds))
_patch_table(path, "trigger", "session_idle_timeout_s", value)
def set_local_idle_release_minutes(minutes: int, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist ``[voice] local_idle_release_minutes`` — how long the local voice
stack may sit idle before it releases the accelerator (0 = never).
Negative input is normalised to 0. Read by the local-realtime supervisor on
its next monitor tick; no restart needed. TOML-only, like
:func:`set_session_idle_timeout_s`.
"""
_patch_table(path, "voice", "local_idle_release_minutes", max(0, int(minutes)))
def set_bar_persistent(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist ``[ui] bar_persistent`` (the 'show bar at all times' toggle).
TOML-only (not drift-guarded); the Taskbar route applies it live.
"""
_patch_table(path, "ui", "bar_persistent", bool(enabled))
def set_bar_size_scale(scale: float, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist ``[ui] bar_size_scale`` (the 'Bar size' slider).
TOML-only (not drift-guarded); the Settings route applies it live to the
running bar. The value is clamped into the supported 0.5–2.0 range here so
a bad request can never write an out-of-range number to disk.
"""
try:
f = float(scale)
except (TypeError, ValueError):
f = 1.0
if f != f or f in (float("inf"), float("-inf")): # NaN / ±inf → default
f = 1.0
_patch_table(path, "ui", "bar_size_scale", max(0.5, min(2.0, f)))
def set_pet_id(pet_id: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist ``[ui] pet_id`` (the active desktop pet, docs/pets.md).
TOML-only (not drift-guarded); the pets route applies it live. Whether the
pet exists is the caller's check; a value that is not even id-shaped is
refused here, so a bad request can never put a path or garbage into the
shared file.
"""
from dodaios.core.config import normalize_pet_id # noqa: PLC0415
normalized = normalize_pet_id(pet_id)
if normalized is None:
raise ValueError(f"not a pet id: {pet_id!r}")
_patch_table(path, "ui", "pet_id", normalized)
def set_pet_scale(scale: float, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist ``[ui] pet_scale`` (the pet size slider), clamped to 0.5–2.0.
Same sanitizing as :func:`set_bar_size_scale` (``clamp_pet_scale``): a
non-numeric or non-finite value is stored as 1.0, never as an out-of-range
number.
"""
from dodaios.core.config import clamp_pet_scale # noqa: PLC0415
_patch_table(path, "ui", "pet_scale", clamp_pet_scale(scale))
def set_pet_bubble(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist ``[ui] pet_bubble`` (show the pet's status bubble)."""
_patch_table(path, "ui", "pet_bubble", bool(enabled))
def set_pet_strip_always(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist ``[ui] pet_strip_always`` (keep the pet's control strip up)."""
_patch_table(path, "ui", "pet_strip_always", bool(enabled))
def set_bar_follow_cursor_monitor(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist ``[ui] bar_follow_cursor_monitor`` (the 'follow the mouse to the
active monitor' toggle).
TOML-only (not drift-guarded); the Settings route applies it live to the
running bar.
"""
_patch_table(path, "ui", "bar_follow_cursor_monitor", bool(enabled))
def set_mute_music(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist ``[ducking] enabled`` (the 'mute music while dictating' toggle).
TOML-only (not drift-guarded); the Taskbar route applies it live.
"""
_patch_table(path, "ducking", "enabled", bool(enabled))
def set_preferred_music_service(service: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist ``[music] preferred_service`` — which connector a music request
that names no service goes to (``auto`` | ``spotify`` | ``youtube_music``).
Validated by the caller against ``dodaios.core.music_constants.MUSIC_SERVICES``
(the Settings route is the layer that knows the accepted set); this only
writes. TOML-only by design: not in the drift-guard's reference snapshot,
so the drift-guard never reverts it.
"""
_patch_table(path, "music", "preferred_service", service)
def set_music_playback(mode: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist ``[music] playback`` — where YouTube Music plays
(``background`` = the hidden in-app player, ``browser`` = the system browser).
Validated by the caller against ``MUSIC_PLAYBACK_MODES``; TOML-only, not
drift-guarded.
"""
_patch_table(path, "music", "playback", mode)
def set_sound_effects(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist ``[ui] sound_effects`` (the global earcon master switch).
TOML-only (not drift-guarded); the Settings route applies it live by
mutating the shared in-memory config the speech pipeline reads.
"""
_patch_table(path, "ui", "sound_effects", bool(enabled))
def set_require_browser_login(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist ``[ui] require_browser_login`` (the optional browser lock).
TOML-only (not drift-guarded); the Settings route applies it live by
updating the shared ``surface_security`` boundary flag in the same request.
"""
_patch_table(path, "ui", "require_browser_login", bool(enabled))
def set_team_proxy(
enabled: bool,
url: str,
local_providers: list[str],
*,
path: Path = DEFAULT_CONFIG_FILE,
) -> None:
"""Persist client-side team-proxy mode to ``[team_proxy]`` in jarvis.toml.
Writes ``enabled`` / ``url`` / ``local_providers`` (2026-06-20 team-proxy
spec §4). TOML-only (not drift-guarded), like :func:`set_autostart`; the
Settings route applies it live, this persists the boot default. The per-user
token is a SECRET and is NEVER written here — it lives in the Credential
Manager (slot ``team_proxy_token``).
"""
_patch_table(path, "team_proxy", "enabled", bool(enabled))
_patch_table(path, "team_proxy", "url", (url or "").strip())
_patch_table(
path,
"team_proxy",
"local_providers",
[str(p).strip() for p in local_providers if str(p).strip()],
)
def _ensure_writable_config_path(path: Path) -> Path:
"""Resolve a writable config path and create it if missing (M1, headless VPS).
The in-app config writers (channel toggles, provider switches, wiki curator)
default to ``DEFAULT_CONFIG_FILE`` (``/app/jarvis.toml``), which a headless
``python:3.11-slim`` container does not ship and ``/app`` is read-only. When the
caller passed that bundled default, honour ``JARVIS_CONFIG`` via
``resolve_config_path()``; then create the file (+ parent) if absent so an
in-app save/connect persists on EVERY OS instead of raising FileNotFoundError.
"""
from dodaios.core.config import (
DEFAULT_CONFIG_FILE as _DEFAULT,
)
from dodaios.core.config import (
resolve_config_path,
)
if path == _DEFAULT:
path = resolve_config_path()
path.parent.mkdir(parents=True, exist_ok=True)
if not path.exists():
path.write_text("", encoding="utf-8")
# Say it. Creating this file is either a first run or a configuration
# that has gone missing, and the two are indistinguishable from here —
# but the CONSEQUENCE is the same either way and it is severe: every
# writer below is a read-modify-write, so from an empty file onward the
# config is silently rebuilt from nothing but the individual keys later
# writes happen to touch. Everything the user had configured — provider
# pins included — is simply absent, and without this line there was no
# trace anywhere that it had ever existed (AP-30).
log.warning(
"Created a NEW empty configuration file at %s. If this is not a "
"first run, the previous configuration is gone and in-app settings "
"will be rebuilt from defaults as they are touched.",
path,
)
return path
def set_telegram_enabled(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist the Telegram channel toggle to ``[integrations.telegram] enabled``.
Written when the user connects/disconnects Telegram in the Plugin
Marketplace: the bot token itself lives in the Credential Manager
(``telegram_bot_token``); this flag tells the channel bootstrap to start it.
``[integrations.telegram]`` is a NESTED table, so ``_patch_table`` (single
level) does not fit — we walk/create the two levels here. Toml-only by
design: ``integrations.telegram.enabled`` is not tracked in
``config-soll.json``, so the drift-guard never reverts it. # i18n-allow
"""
path = _ensure_writable_config_path(path)
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
integrations = doc.get("integrations")
if integrations is None:
integrations = tomlkit.table()
doc["integrations"] = integrations
telegram = integrations.get("telegram")
if telegram is None:
telegram = tomlkit.table()
integrations["telegram"] = telegram
telegram["enabled"] = bool(enabled)
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
def add_telegram_allowed_user_id(user_id: int, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist a Telegram user id under ``[integrations.telegram]``.
Used by first-private-message pairing. The token remains a secret; the
numeric Telegram user id is not secret and belongs in the operational config
so the channel keeps working after restart. Idempotent and comment-preserving
like :func:`set_telegram_enabled`.
"""
path = _ensure_writable_config_path(path)
uid = int(user_id)
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
integrations = doc.get("integrations")
if integrations is None:
integrations = tomlkit.table()
doc["integrations"] = integrations
telegram = integrations.get("telegram")
if telegram is None:
telegram = tomlkit.table()
integrations["telegram"] = telegram
current = telegram.get("allowed_user_ids")
values = [int(v) for v in current] if current is not None else []
if uid not in values:
values.append(uid)
telegram["allowed_user_ids"] = values
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
def add_discord_allowed_user_id(user_id: int, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist a Discord user id under ``[integrations.discord]``.
Used by first-direct-message pairing. The token remains a secret; the
numeric Discord user id is not secret and belongs in the operational config
so the channel keeps working after restart. Idempotent and comment-preserving
like :func:`add_telegram_allowed_user_id`.
"""
path = _ensure_writable_config_path(path)
uid = int(user_id)
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
integrations = doc.get("integrations")
if integrations is None:
integrations = tomlkit.table()
doc["integrations"] = integrations
discord = integrations.get("discord")
if discord is None:
discord = tomlkit.table()
integrations["discord"] = discord
current = discord.get("allowed_user_ids")
values = [int(v) for v in current] if current is not None else []
if uid not in values:
values.append(uid)
discord["allowed_user_ids"] = values
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
def _set_integration_value(
platform: str, key: str, value: object, *, path: Path = DEFAULT_CONFIG_FILE
) -> None:
"""Set ``[integrations.<platform>] <key> = value`` in jarvis.toml.
Walks/creates the two-level nested table (``_patch_table`` only handles a
single level). Comment- and BOM-preserving, lock-guarded, atomic — same
contract as :func:`set_telegram_enabled`. Toml-only by design: these
operational integration flags are not tracked in ``config-soll.json``, so # i18n-allow
the drift-guard never reverts them.
"""
path = _ensure_writable_config_path(path)
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
integrations = doc.get("integrations")
if integrations is None:
integrations = tomlkit.table()
doc["integrations"] = integrations
table = integrations.get(platform)
if table is None:
table = tomlkit.table()
integrations[platform] = table
table[key] = value
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
def set_discord_enabled(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist the Discord channel toggle to ``[integrations.discord] enabled``.
Mirror of :func:`set_telegram_enabled`: written when the user
connects/disconnects Discord in the Plugin Marketplace. The bot token lives
in the Credential Manager (``discord_bot_token``); this flag tells the
channel bootstrap whether to start the bot.
"""
_set_integration_value("discord", "enabled", bool(enabled), path=path)
def set_telegram_pairing(on: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Toggle ``[integrations.telegram] pair_on_first_private_message``.
Turned off when the owner connects with an explicit user id, so the bot
never claims the allowlist for whoever messages first (owner-lock contract).
"""
_set_integration_value("telegram", "pair_on_first_private_message", bool(on), path=path)
def set_discord_pairing(on: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Toggle ``[integrations.discord] pair_on_first_dm``.
Turned off when the owner connects with an explicit user id, so the bot
never claims the allowlist for whoever DMs first (owner-lock contract).
"""
_set_integration_value("discord", "pair_on_first_dm", bool(on), path=path)
def set_brain_provider_defaults(
name: str,
*,
model: str | None = None,
deep_model: str | None = None,
auth_mode: str = "api_key",
path: Path = DEFAULT_CONFIG_FILE,
) -> None:
"""Ensure that the ``[brain.providers.<name>]`` block exists.
Idempotent: an already-existing block is NOT overwritten —
user overrides from jarvis.toml are preserved. If the block is absent it
is created with the supplied defaults (typically the tier defaults from
``BrainManager.TIER_DEFAULTS_BY_PROVIDER``).
Background: providers added after the setup wizard via the UI (e.g. openrouter)
often lack a ``[brain.providers.<name>]`` block. During a switch-persist we
ensure here that after an app restart the tier-default fallback logic in
BrainManager is not needed again — the block is then cleanly persisted.
"""
path = _ensure_writable_config_path(path)
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
brain = doc.get("brain")
if brain is None:
brain = tomlkit.table()
doc["brain"] = brain
providers = brain.get("providers")
if providers is None:
# tomlkit's Table.is_super_table is a METHOD; assigning a bool to it
# shadows the method and later dumps() crashes with "'bool' object is
# not callable". The super-table flag must go through the factory.
providers = tomlkit.table(True)
brain["providers"] = providers
if name in providers:
# Existing block — do not overwrite (user override wins).
return
block = tomlkit.table()
if model:
block["model"] = model
if deep_model:
block["deep_model"] = deep_model
block["auth_mode"] = auth_mode
providers[name] = block
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
# Provider defaults for the TTS switch. Written to the TOML, but only when
# the respective value does not already match the new provider.
#
# Every provider declared with tier="tts" in dodaios/ui/web/provider_spec.py
# MUST have an entry here, enforced by tests/unit/test_tts_defaults_parity.py.
# Without an entry, set_tts_provider() would pass an empty defaults dict and
# leave a stale model/voice from the previous provider in jarvis.toml.
_TTS_DEFAULTS: dict[str, dict[str, str]] = {
"inworld": {
# Inworld reads its per-language voices from the [tts.inworld] subtable
# (voice_de/voice_en/voice_es/voice_pt), NOT [tts].voice_de — same pattern as
# Cartesia. The scalar voice_de/voice_en are placeholders never consumed
# by the Inworld factory path. [tts].model is ignored too (the model
# comes from [tts.inworld].model or the plugin default inworld-tts-2), so
# model="" is skipped by _patch_tts_block's falsy gate. language_code=
# "auto" lets Inworld auto-detect the spoken language per turn.
"model": "",
"voice_de": "Charon", # placeholder; Inworld reads [tts.inworld].voice_de
"voice_en": "Charon", # placeholder; Inworld reads [tts.inworld].voice_en
"language_code": "auto",
},
"gemini-flash-tts": {
# model from dodaios/plugins/tts/gemini_flash_tts.py (factory line:
# tts_cfg.model or "gemini-3.1-flash-tts-preview")
"model": "gemini-3.1-flash-tts-preview",
"voice_de": "Charon",
"voice_en": "Charon",
"language_code": "de-DE",
},
"vertex-tts": {
"model": "gemini-3.1-flash-tts-preview",
"voice_de": "Charon",
"voice_en": "Charon",
"language_code": "de-DE",
},
"grok-voice": {
# model is ignored by the Grok plugin (no model param in GrokVoiceTTS).
# voice from dodaios/plugins/tts/grok_voice_tts.py: GROK_VOICE_LEO = "leo"
"model": "", # Grok ignores model — leave blank
"voice_de": "leo",
"voice_en": "leo",
"language_code": "auto",
},
"elevenlabs": {
# model + voice from dodaios/plugins/tts/elevenlabs_tts.py:
# model = tts_cfg.model or "eleven_flash_v2_5"
# default_voice = tts_cfg.voice_de or ELEVENLABS_VOICE_DANIEL
# ELEVENLABS_VOICE_DANIEL = "onwK4e9ZLuTAKqWW03F9"
"model": "eleven_flash_v2_5",
"voice_de": "onwK4e9ZLuTAKqWW03F9", # Daniel
"voice_en": "onwK4e9ZLuTAKqWW03F9",
"language_code": "de-DE",
},
"cartesia": {
# Cartesia reads voice UUIDs from [tts.cartesia].voice_id* (a subtable),
# NOT from [tts].voice_de/voice_en (dodaios/plugins/tts/__init__.py lines
# 103-116: ct = tts_cfg.model_extra["cartesia"]). The scalar [tts].voice_de
# and voice_en keys are never consumed by the Cartesia factory path; setting
# them to "Charon" keeps them consistent with config-soll.json's tts block # i18n-allow
# (which holds "Charon" as a carry-over from the Gemini era) so the
# drift-guard sees zero drift.
# model="" because [tts].model is not read by CartesiaTTS at all
# (DEFAULT_MODEL_ID comes from [tts.cartesia].model_id, not [tts].model).
# The empty-string gate in _patch_tts_block skips writing it, leaving any
# prior value untouched — harmless since Cartesia ignores [tts].model.
"model": "", # Cartesia ignores [tts].model — leave blank
"voice_de": "Charon", # placeholder; Cartesia reads [tts.cartesia].voice_id_de
"voice_en": "Charon", # placeholder; Cartesia reads [tts.cartesia].voice_id_en
"language_code": "auto",
},
"google-neural2": {
# google-neural2 plugin does not yet exist (no dodaios/plugins/tts/
# google_neural2_tts.py). The factory falls back to gemini-flash-tts.
# These are minimal safe defaults: empty model/voice strings are
# skipped by _patch_tts_block's falsy gate, so no values are written
# until a real plugin provides meaningful defaults. language_code="auto"
# avoids pinning a stale "de-DE" from a prior provider.
"model": "",
"voice_de": "",
"voice_en": "",
"language_code": "auto",
},
"openai-tts": {
# openai-tts plugin does not yet exist (no dodaios/plugins/tts/
# openai_tts.py). The factory falls back to gemini-flash-tts.
# Same strategy as google-neural2: empty strings are skipped by the
# falsy gate in _patch_tts_block. When a real plugin is added, update
# these to the correct model (e.g. "tts-1-hd") and voice (e.g.
# "onyx" for a masculine default — see OpenAI voice options).
"model": "",
"voice_de": "",
"voice_en": "",
"language_code": "auto",
},
"openrouter-tts": {
# OpenRouter TTS reuses the shared OpenRouter key and resolves its own
# model + voice defaults internally (dodaios/plugins/tts/openrouter_tts.py:
# MODEL_DEFAULT_VOICE / GENERIC_DEFAULT_VOICE). Leave these blank — the
# falsy gate in _patch_tts_block skips empty values, so the provider picks
# sensible per-model defaults. This entry exists so the provider-parity
# test passes and set_tts_provider() can reconcile the [tts] block on a
# switch to OpenRouter TTS.
"model": "",
"voice_de": "",
"voice_en": "",
"language_code": "auto",
},
"piper-local": {
# ``language_code`` is the load-bearing key here, not the voices. A Piper
# voice is MONOLINGUAL: the plugin is handed the turn's resolved language
# and picks the matching installed voice per turn. Inheriting a
# predecessor's pinned "de-DE" would therefore hard-wire every answer to
# the German voice, including the ones the resolver decided to speak in
# English, Spanish or Portuguese — the runtime-language doctrine broken by a leftover
# config value rather than by any code. "auto" keeps the decision where
# it belongs.
#
# The installer fetches one voice per reply language — German,
# English, Spanish and Portuguese (PIPER_DEFAULT_VOICES in
# dodaios/speech/local_models.py); the German and English ones fill the
# two voice keys below, and the plugin finds the others by language.
# They are named rather than left blank so switching away from a cloud provider does not
# leave "Charon" sitting in the block: the resolver tolerates an unknown
# name, but the settings screen would keep showing a voice this provider
# cannot speak with. There is no [tts].model concept for Piper.
"model": "",
"voice_de": "vits-piper-de_DE-thorsten-medium",
"voice_en": "vits-piper-en_US-ryan-medium",
"language_code": "auto",
},
}
# Per-provider voice allowlist — when the existing voice does not match the
# new provider, we overwrite with the provider default. Kept in sync with
# `dodaios/plugins/tts/__init__.py`.
_VOICES_FOR_PROVIDER: dict[str, frozenset[str]] = {
# Every catalogued local Piper voice, not only the two the installer fetches
# by default. Without this entry a switch to Piper would reset the voice to
# the default pair every time, silently undoing a user who downloaded Ramona
# or Amy and chose them — the allowlist is what tells the writer "this value
# is already valid for this provider, keep it".
"piper-local": frozenset(
{
"vits-piper-de_DE-thorsten-medium",
"vits-piper-de_DE-ramona-low",
"vits-piper-en_US-ryan-medium",
"vits-piper-en_US-amy-medium",
"vits-piper-es_ES-davefx-medium",
"vits-piper-es_ES-sharvard-medium",
"vits-piper-pt_PT-tugao-medium",
}
),
"gemini-flash-tts": frozenset(
{
"Charon",
"Orus",
"Iapetus",
"Rasalgethi",
"Algenib",
"Algieba",
"Kore",
"Fenrir",
"Aoede",
}
),
"grok-voice": frozenset({"leo", "rex", "sal", "ara", "eve"}),
# ElevenLabs uses voice IDs (cryptic hashes) — no whitelist.
}
def _patch_tts_block(path: Path, provider: str, defaults: dict[str, str]) -> dict[str, str]:
"""Write ``[tts] provider`` and ensure that dependent fields
(voice_de, voice_en, language_code, model) are compatible with the provider.
An existing voice value is only overwritten when it does *not* belong to the
new provider's allowlist. This preserves meaningful user edits
(e.g. ``voice_de = "Orus"`` for Gemini) while correcting nonsensical leftovers
such as ``voice_de = "Charon"`` for Grok.
Returns the dict of keys it ACTUALLY wrote to ``[tts]`` (always
``provider``; plus whichever of voice/language/model it set). The
config-soll drift-sync mirrors exactly these keys so the guard sees zero # i18n-allow
drift across the whole block.
"""
path = _ensure_writable_config_path(path)
whitelist = _VOICES_FOR_PROVIDER.get(provider.lower())
applied: dict[str, str] = {"provider": provider}
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
section = doc.get("tts")
if section is None:
section = tomlkit.table()
doc["tts"] = section
section["provider"] = provider
for key, default_value in defaults.items():
if key in ("voice_de", "voice_en") and whitelist is not None:
current = section.get(key)
if current is None or str(current) not in whitelist:
if default_value:
section[key] = default_value
applied[key] = default_value
elif current is not None:
# Voice is already valid for this provider — keep the user's
# value, but still record it so the config-soll drift-sync # i18n-allow
# agrees with the TOML (else the guard reverts it).
applied[key] = str(current)
continue
if key == "language_code":
# Always set language_code to the provider default so
# "auto" vs "de-DE" does not carry over between providers.
if default_value:
section[key] = default_value
applied[key] = default_value
continue
if key == "model":
# Only write model when non-empty — Grok has no model concept.
if default_value:
section[key] = default_value
applied[key] = default_value
continue
# Generic fall-through (e.g. voice_de/voice_en for a provider with no
# whitelist entry). Skip empty-string placeholders so a plugin-less
# provider (google-neural2 / openai-tts: empty voice defaults) never
# blanks the carried-over voice in the TOML.
if default_value:
section[key] = default_value
applied[key] = default_value
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
return applied
def set_brain_provider_model(
provider: str,
*,
model: str | None = None,
deep_model: str | None = None,
tool_model: str | None = None,
cu_model: str | None = None,
voice: str | None = None,
path: Path = DEFAULT_CONFIG_FILE,
) -> WriteReceipt:
"""Patch model selections under ``[brain.providers.<provider>]``.
Used by the per-provider model picker (``PUT /api/providers/{id}/model``),
the frontier auto-switch (Phase F.3), and the Realtime model+voice picker
(``PUT /api/providers/{id}/realtime-options``) so a change is persisted in
jarvis.toml — otherwise it is lost on the next ``cfg.load_config()``.
Three-layer persist (like ``set_brain_primary`` / ``set_worker_provider``):
``model`` / ``deep_model`` / ``tool_model`` / ``voice`` are pinned in
``config-soll.json``, so a TOML-only write would be reverted by the # i18n-allow
drift-guard within 5 minutes (BUG-010 class) — exactly the "I picked a model
and it flipped back" symptom. We therefore sync config-soll.json too. No ENV # i18n-allow
layer is written: per-provider model keys have no effective ``JARVIS__*``
override (the boot override only nests on ``__`` and the drift-guard's dotted
``JARVIS__BRAIN.PROVIDERS.*`` vars are inert), so adding one would only create
a new stale-override trap. Layer 2 is best-effort (cloud-first): a graceful
no-op on a headless Linux VPS, it never raises out of this function nor
breaks the TOML write.
Idempotent: if the block is absent it is created; ``None`` values change
nothing.
Returns a :class:`WriteReceipt`. After the baseline sync the file is
re-read and compared key by key; a mismatch (read-only file, a foreign
writer racing, a broken JSON) is logged at ERROR with the key and comes
back as ``baseline_ok=False`` so the caller can warn that the drift guard may
revert the pick. Existing callers may ignore the return value.
"""
path = _ensure_writable_config_path(path)
baseline_path = _config_soll_path() # i18n-allow
if (
model is None
and deep_model is None
and tool_model is None
and cu_model is None
and voice is None
):
return WriteReceipt(toml_ok=True, baseline_ok=True, baseline_path=str(baseline_path))
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
brain = doc.get("brain")
if brain is None:
brain = tomlkit.table()
doc["brain"] = brain
providers = brain.get("providers")
if providers is None:
# tomlkit's Table.is_super_table is a METHOD; assigning a bool to it
# shadows the method and later dumps() crashes with "'bool' object is
# not callable". The super-table flag must go through the factory.
providers = tomlkit.table(True)
brain["providers"] = providers
block = providers.get(provider)
if block is None:
block = tomlkit.table()
providers[provider] = block
if model is not None:
block["model"] = model
if deep_model is not None:
block["deep_model"] = deep_model
if tool_model is not None:
block["tool_model"] = tool_model
if cu_model is not None:
# "" is a meaningful value (UI "use my main model") distinct from
# None ("leave unchanged"), so write whatever non-None was given.
block["cu_model"] = cu_model
if voice is not None:
# "" is a meaningful value (UI "provider default") distinct from
# None ("leave unchanged"), mirroring cu_model's contract above.
block["voice"] = voice
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
# Layer 2 — best-effort drift-soll sync (never raises, never blocks the # i18n-allow
# TOML write). Only the keys actually written are synced so the guard sees
# zero drift across the block.
written: dict[str, object] = {}
if model is not None:
written["model"] = model
if deep_model is not None:
written["deep_model"] = deep_model
if tool_model is not None:
written["tool_model"] = tool_model
if cu_model is not None:
written["cu_model"] = cu_model
if voice is not None:
written["voice"] = voice
_sync_brain_provider_model_drift_soll( # i18n-allow
provider,
model=model,
deep_model=deep_model,
tool_model=tool_model,
cu_model=cu_model,
voice=voice,
)
baseline_ok = _verify_brain_provider_model_drift_soll(provider, written) # i18n-allow
return WriteReceipt(toml_ok=True, baseline_ok=baseline_ok, baseline_path=str(baseline_path))
def _verify_brain_provider_model_drift_soll( # i18n-allow
provider: str, written: dict[str, object]
) -> bool:
"""Re-read config-soll.json and confirm every written key landed there. # i18n-allow
An absent baseline file (headless VPS, fresh checkout) has nothing to
revert, so it counts as in sync. Every other divergence — an unreadable or
unparsable file, a key that never arrived, a value that differs — is logged
at ERROR with the key and answers ``False``. Never raises: the TOML write
is already done and the caller only needs the verdict.
"""
soll_path = _config_soll_path() # i18n-allow
if not soll_path.exists(): # i18n-allow
return True
try:
data = json.loads(soll_path.read_text(encoding="utf-8")) # i18n-allow
except Exception as exc: # noqa: BLE001 — verdict only, never propagate
log.error(
"Drift baseline %s could not be re-read after writing brain.providers.%s: %s",
soll_path, # i18n-allow: internal config-soll identifier
provider,
exc,
)
return False
section = data.get(f"brain.providers.{provider}")
if not isinstance(section, dict):
section = {}
ok = True
for key, value in written.items():
if section.get(key) != value:
ok = False
log.error(
"Drift baseline did not follow: brain.providers.%s.%s is %r there, "
"%r in jarvis.toml (%s) — the drift guard may revert this pick",
provider,
key,
section.get(key),
value,
soll_path, # i18n-allow: internal config-soll identifier
)
return ok
def set_provider_base_url(
provider: str, base_url: str | None, *, path: Path = DEFAULT_CONFIG_FILE
) -> None:
"""Persist (or clear) ``[brain.providers.<provider>].base_url``.
Backs the API-Keys card's server-URL field for local/self-hosted providers
(``PUT /api/providers/{id}/base-url``). ``None``/"" writes an EMPTY string
rather than deleting the key — "" is falsy everywhere the override is read
(``resolve_provider_endpoint``), and keeping the key present means the
drift-guard baseline layer and the TOML always agree (BUG-010 class). Atomic
discipline as every setter here (AP-7); tomlkit quotes hyphenated provider
ids (``[brain.providers."local-openai"]``) on its own.
"""
path = _ensure_writable_config_path(path)
cleaned = (base_url or "").strip()
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
brain = doc.get("brain")
if brain is None:
brain = tomlkit.table()
doc["brain"] = brain
providers = brain.get("providers")
if providers is None:
# Super-table flag via the factory (see set_brain_provider_model).
providers = tomlkit.table(True)
brain["providers"] = providers
block = providers.get(provider)
if block is None:
block = tomlkit.table()
providers[provider] = block
block["base_url"] = cleaned
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
# Best-effort drift-guard baseline sync (never raises, never blocks the write).
try:
_update_config_soll_section( # i18n-allow
f"brain.providers.{provider}", {"base_url": cleaned}
)
except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
log.warning(
"Could not sync brain.providers.%s base_url to config-soll.json: %s", # i18n-allow
provider,
exc,
)
#: Closed list of per-provider boolean flags :func:`set_provider_flag` may
#: write. Each entry is a real field on ``BrainProviderConfig`` with a reader;
#: adding one here without a reader is the AP-31 shape.
PROVIDER_FLAG_KEYS: tuple[str, ...] = ("hf_enabled", "autostart")
def _provider_block(doc: TOMLDocument, provider: str) -> tomlkit.items.Table:
"""``[brain.providers.<provider>]`` of ``doc``, created when absent.
``providers`` is a super-table via the factory (``tomlkit.table(True)``) —
assigning ``is_super_table`` shadows a METHOD and a later ``dumps()``
crashes (see :func:`set_brain_provider_model`).
"""
brain = doc.get("brain")
if brain is None:
brain = tomlkit.table()
doc["brain"] = brain
providers = brain.get("providers")
if providers is None:
providers = tomlkit.table(True)
brain["providers"] = providers
block = providers.get(provider)
if block is None:
block = tomlkit.table()
providers[provider] = block
return block
def _read_doc(path: Path) -> tuple[TOMLDocument, bool]:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
return tomlkit.parse(raw), had_bom
def set_live_profile(values: dict, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Guided opt-in: back up the old configuration and atomically select Live."""
from dodaios.live.config import LiveConfig
profile = LiveConfig.model_validate(values)
effective = profile.for_session()
if not profile.configured or not effective.backend_model.strip():
raise ValueError("Select a thinking model before enabling GPT-Live.")
path = _ensure_writable_config_path(path)
with _WRITE_LOCK:
doc, bom = _read_doc(path)
backup = path.with_name(path.name + ".pre-live.bak")
if not backup.exists():
_atomic_write(backup, path.read_text(encoding="utf-8"))
doc["live"] = profile.model_dump()
if "brain" not in doc:
doc["brain"] = tomlkit.table()
doc["brain"]["realtime"] = {"provider": profile.provider_id, "model": effective.model}
if "voice" not in doc:
doc["voice"] = tomlkit.table()
doc["voice"]["mode"] = "realtime"
_write_doc(path, doc, bom)
clear_config_cache()
_update_config_soll_section("live", profile.model_dump()) # i18n-allow
_update_config_soll_section( # i18n-allow
"brain.realtime", {"provider": profile.provider_id, "model": effective.model}
)
_update_config_soll_section("voice", {"mode": "realtime"}) # i18n-allow
def _write_doc(path: Path, doc: TOMLDocument, had_bom: bool) -> None:
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
def set_ollama_model_options(
model: str,
options: dict[str, object],
*,
provider: str = "ollama",
path: Path = DEFAULT_CONFIG_FILE,
) -> dict[str, object]:
"""Persist the per-model option table ``[brain.providers.ollama.models."<tag>"]``.
REPLACE semantics: ``options`` is the whole new option set for ``model``;
a key absent from it is removed from the table, and an empty (or all-
``None``) set removes the table like :func:`clear_ollama_model_options`.
Keys must come from the closed :data:`OLLAMA_MODEL_OPTION_KEYS` list —
anything else raises ``ValueError``.
Values pass through :class:`OllamaModelOptions`, so an out-of-range number
is clamped and a value of the wrong shape is dropped, never written — the
file holds only what the reader will accept. Returns the values written.
TOML-only by design, deliberately NOT pinned in ``config-soll.json``: the # i18n-allow
table is keyed by arbitrary model tags, and pinning it would bring back the
"flipped back" symptom (BUG-010 class) the first time a sync helper is
missed. The drift-guard therefore
never touches this table. Atomic write under the module lock (AP-7); the
tag is written as a quoted key (``"qwen3.5:9b"``) by tomlkit itself.
"""
tag = (model or "").strip()
if not tag:
raise ValueError("model tag must not be empty")
unknown = sorted(set(options) - set(OLLAMA_MODEL_OPTION_KEYS))
if unknown:
raise ValueError(
f"unknown Ollama model option key(s) {', '.join(unknown)} "
f"(allowed: {', '.join(OLLAMA_MODEL_OPTION_KEYS)})"
)
clamped = OllamaModelOptions.model_validate(options).model_dump(exclude_none=True)
values: dict[str, object] = {k: clamped[k] for k in OLLAMA_MODEL_OPTION_KEYS if k in clamped}
if not values:
clear_ollama_model_options(tag, provider=provider, path=path)
return {}
path = _ensure_writable_config_path(path)
with _WRITE_LOCK:
doc, had_bom = _read_doc(path)
block = _provider_block(doc, provider)
models = block.get("models")
if models is None:
models = tomlkit.table(True)
block["models"] = models
table = tomlkit.table()
for key, value in values.items():
table[key] = value
models[tag] = table
_write_doc(path, doc, had_bom)
clear_config_cache()
return values
def clear_ollama_model_options(
model: str,
*,
provider: str = "ollama",
path: Path = DEFAULT_CONFIG_FILE,
) -> bool:
"""Remove ``[brain.providers.ollama.models."<tag>"]``; ``True`` when it existed.
The "Reset" of the Tune sheet. A missing table is a no-op, not an error.
TOML-only for the same reason as :func:`set_ollama_model_options`.
"""
tag = (model or "").strip()
if not tag:
raise ValueError("model tag must not be empty")
path = _ensure_writable_config_path(path)
with _WRITE_LOCK:
doc, had_bom = _read_doc(path)
models = (doc.get("brain") or {}).get("providers", {}).get(provider, {}).get("models")
if models is None or tag not in models:
return False
del models[tag]
_write_doc(path, doc, had_bom)
clear_config_cache()
return True
def set_provider_flag(
provider: str, key: str, value: bool, *, path: Path = DEFAULT_CONFIG_FILE
) -> None:
"""Persist one boolean flag under ``[brain.providers.<provider>]``.
``key`` must come from the closed :data:`PROVIDER_FLAG_KEYS` list. TOML-
only: these flags are not pinned in ``config-soll.json`` (same rationale # i18n-allow
as :func:`set_ollama_model_options`), so a plain atomic write is final.
"""
if key not in PROVIDER_FLAG_KEYS:
raise ValueError(
f"unknown provider flag {key!r} (allowed: {', '.join(PROVIDER_FLAG_KEYS)})"
)
path = _ensure_writable_config_path(path)
with _WRITE_LOCK:
doc, had_bom = _read_doc(path)
block = _provider_block(doc, provider)
block[key] = bool(value)
_write_doc(path, doc, had_bom)
clear_config_cache()
def set_ollama_hf_enabled(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Switch Hugging Face GGUF browsing on the Ollama card on or off.
Thin wrapper over :func:`set_provider_flag`; read by
:func:`dodaios.core.config.ollama_hf_enabled`.
"""
set_provider_flag("ollama", "hf_enabled", bool(enabled), path=path)
def set_ollama_autostart(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Switch "start the local server with Jarvis" on or off.
Thin wrapper over :func:`set_provider_flag`; read by
:func:`dodaios.core.config.ollama_autostart`.
"""
set_provider_flag("ollama", "autostart", bool(enabled), path=path)
def set_local_realtime_launch_command(
launch_command: str, *, path: Path = DEFAULT_CONFIG_FILE
) -> None:
"""Persist the managed server's derived launch command (AD-4).
Written by the one-click install engine
(``dodaios/realtime/local_server/install.py``) after a successful smoke
boot; the realtime adapter reads it to start/revive the server. The
command is DERIVED from probed hardware + resolved brain and never
carries a secret. Also pins ``base_url`` to the served port so a fresh
install activates without a manual URL paste.
"""
path = _ensure_writable_config_path(path)
cleaned = (launch_command or "").strip()
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
brain = doc.get("brain")
if brain is None:
brain = tomlkit.table()
doc["brain"] = brain
providers = brain.get("providers")
if providers is None:
providers = tomlkit.table(True)
brain["providers"] = providers
block = providers.get("local-realtime")
if block is None:
block = tomlkit.table()
providers["local-realtime"] = block
block["launch_command"] = cleaned
# 127.0.0.1, not "localhost": the resolver tries ::1 first while the
# server binds IPv4 only, and that dead IPv6 attempt measured 2,050 ms
# per connect (2026-08-08) — the literal IP is the instant path.
current_base = str(block.get("base_url", "") or "").strip()
if not current_base or current_base == "http://localhost:8765":
block["base_url"] = "http://127.0.0.1:8765"
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
def _command_references_root(command: str, root: str, *, windows: bool | None = None) -> bool:
"""Whether a launch command points into the given directory.
Separator-normalized on every platform; case-INSENSITIVE only on
Windows — lowercasing both sides everywhere (the old behavior) made two
distinct case-sensitive POSIX paths compare equal. ``windows`` exists so
tests can pin the other platform's semantics without patching the global
``os`` module (which breaks pathlib mid-session).
"""
import os as _os
if windows is None:
windows = _os.name == "nt"
sep = "\\" if windows else "/"
needle = root.replace("/", sep).replace("\\", sep)
haystack = command.replace("/", sep).replace("\\", sep)
if windows:
needle = needle.lower()
haystack = haystack.lower()
return needle in haystack
def update_local_realtime_launch_model(
model: str, *, only_if_under: str = "", path: Path = DEFAULT_CONFIG_FILE
) -> bool:
"""Rewrite ONLY the ``--model_name`` value of the persisted launch command.
The model choice is baked into the derived command string, and before
this helper existed changing it meant a full reinstall of a
multi-gigabyte stack. ``only_if_under`` keeps the same autonomy guard as
the clear path: a bring-your-own command is never rewritten. Returns
``True`` when the command was changed.
"""
path = _ensure_writable_config_path(path)
cleaned = (model or "").strip()
if not cleaned:
return False
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
block = doc.get("brain", {}).get("providers", {}).get("local-realtime")
if block is None:
return False
command = str(block.get("launch_command", "") or "")
if not command or "--model_name " not in command:
return False
if only_if_under and not _command_references_root(command, only_if_under):
return False
prefix, _, tail = command.partition("--model_name ")
old_value, _, rest = tail.partition(" ")
if old_value == cleaned:
return False
rewritten = f"{prefix}--model_name {cleaned}"
if rest:
rewritten = f"{rewritten} {rest}"
block["launch_command"] = rewritten
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
return True
def clear_local_realtime_launch_command(
*, only_if_under: str = "", path: Path = DEFAULT_CONFIG_FILE
) -> None:
"""Clear the managed server's launch command after an uninstall.
``only_if_under`` guards user autonomy: when given, the command is only
cleared if it references that directory (the managed install tree) — a
hand-authored bring-your-own command stays untouched. The default
``base_url`` this module pinned is cleared alongside, so a removed
server stops looking "configured" to the activation path; a custom URL
survives.
"""
path = _ensure_writable_config_path(path)
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
block = doc.get("brain", {}).get("providers", {}).get("local-realtime")
if block is None:
return
command = str(block.get("launch_command", "") or "")
if not command:
return
if only_if_under and not _command_references_root(command, only_if_under):
return
block["launch_command"] = ""
# Both defaults this module ever pinned (localhost historically,
# 127.0.0.1 since 2026-08-08) count as ours; a custom URL survives.
if str(block.get("base_url", "") or "").strip() in (
"http://localhost:8765",
"http://127.0.0.1:8765",
):
block["base_url"] = ""
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
def set_telephony_config(values: dict[str, object], *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Patch ``[integrations.twilio]`` with the given non-secret fields.
Only the keys present in ``values`` are written (partial update); the
Twilio Auth Token is NEVER written here — it lives in the Credential
Manager (AP-12). Used by ``POST /api/telephony/config`` and
``/api/telephony/credentials`` (the latter only ever passes
``account_sid``).
Idempotent and comment-preserving via tomlkit, BOM-aware like the other
writers in this module.
"""
path = _ensure_writable_config_path(path)
if not values:
return
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
integrations = doc.get("integrations")
if integrations is None:
integrations = tomlkit.table()
doc["integrations"] = integrations
twilio = integrations.get("twilio")
if twilio is None:
twilio = tomlkit.table()
integrations["twilio"] = twilio
for key, value in values.items():
twilio[key] = value
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
def _patch_table(
path: Path,
table: str,
key: str,
value: str | bool | int | float | list[str],
*,
extra: dict[str, str | bool | int | float | list[str]] | None = None,
) -> None:
"""Set ``[table] key = value`` in the TOML file.
Creates the table if it is absent. Preserves comments and formatting via
tomlkit, including the optional BOM (see module docstring). ``value`` may be
a ``str``, a ``bool`` (serialised as ``true``/``false`` — used by the
autostart toggle), an ``int``/``float`` (the dictation delays and caps), or
a ``list[str]`` (serialised as a TOML array — used by ``[team_proxy]
local_providers``).
``extra`` writes further keys into the SAME table in the SAME atomic write.
It exists for values that must land together or not at all — the dictation
migration marker beside the shortcut it vouches for; two separate writes
could be interrupted between them and leave a shortcut the backfill would
then overwrite again.
"""
path = _ensure_writable_config_path(path)
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
section = doc.get(table)
if section is None:
section = tomlkit.table()
doc[table] = section
section[key] = value
for extra_key, extra_value in (extra or {}).items():
section[extra_key] = extra_value
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
def worker_provider_changed(previous: str | None, selected: str | None) -> bool:
"""Compare worker identities without treating transport aliases as switches."""
from dodaios.missions.worker_runtime.provider_map import (
CODEX_SUBAGENT_SLUGS,
GROK_BUILD_SUBAGENT_SLUGS,
canonical_worker_provider,
)
def identity(value: str | None) -> str | None:
canonical = canonical_worker_provider(value)
if canonical in CODEX_SUBAGENT_SLUGS:
return "openai-codex"
if canonical in GROK_BUILD_SUBAGENT_SLUGS:
return "grok-build"
return canonical
return identity(previous) != identity(selected)
def _patch_worker_provider_toml(
path: Path, name: str, *, previous_provider: str | None = None
) -> str:
"""Set ``[brain.worker] provider = name`` in the TOML.
Unlike :func:`_patch_table`, this walks the NESTED ``brain`` -> ``worker``
path instead of treating ``"brain.worker"`` as a flat top-level key
(``doc.get("brain.worker")`` would create a literal dotted key, not the
``[brain.worker]`` section). Creates either level if missing. Preserves
comments, sibling keys, and the optional BOM.
Renamed from ``_patch_sub_jarvis_provider_toml`` in the 2026-06-29
Jarvis-Agents rename. Writes to ``[brain.worker]`` so new config files
use the new section name; old ``[brain.sub_jarvis]`` blocks are still
read via BrainConfig.worker's AliasChoices back-compat alias.
"""
path = _ensure_writable_config_path(path)
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
brain = doc.get("brain")
if brain is None:
brain = tomlkit.table()
doc["brain"] = brain
sub = brain.get("worker")
if sub is None:
sub = tomlkit.table()
brain["worker"] = sub
effective_provider = os.environ.get(
_WORKER_PROVIDER_ENV,
os.environ.get("JARVIS__BRAIN__SUB_JARVIS__PROVIDER", sub.get("provider", "")),
)
model = os.environ.get(
_WORKER_MODEL_ENV,
os.environ.get("JARVIS__BRAIN__SUB_JARVIS__MODEL", str(sub.get("model", ""))),
)
if worker_provider_changed(effective_provider, name) or (
previous_provider is not None and worker_provider_changed(previous_provider, name)
):
model = ""
sub["provider"] = name
sub["model"] = model
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
return model
def _patch_realtime_provider_toml(path: Path, name: str, *, key: str = "provider") -> None:
"""Set ``[brain.realtime] <key> = name`` in the TOML.
Unlike :func:`_patch_table`, this walks the NESTED ``brain`` -> ``realtime``
path instead of treating ``"brain.realtime"`` as a flat top-level key
(``doc.get("brain.realtime")`` would create a literal dotted key, not the
``[brain.realtime]`` section) — mirrors :func:`_patch_worker_provider_toml`.
Creates either level if missing. Preserves comments, sibling keys, and the
optional BOM.
"""
path = _ensure_writable_config_path(path)
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
brain = doc.get("brain")
if brain is None:
brain = tomlkit.table()
doc["brain"] = brain
realtime = brain.get("realtime")
if realtime is None:
realtime = tomlkit.table()
brain["realtime"] = realtime
realtime[key] = name
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
def _patch_computer_use_provider_toml(path: Path, name: str) -> None:
"""Set ``[brain.computer_use] provider = name`` in the TOML.
Walks the NESTED ``brain`` -> ``computer_use`` path (like
:func:`_patch_worker_provider_toml` / :func:`_patch_realtime_provider_toml`)
instead of treating ``"brain.computer_use"`` as a flat top-level key.
Creates either level if missing. Preserves comments, sibling keys, and
the optional BOM.
"""
path = _ensure_writable_config_path(path)
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
brain = doc.get("brain")
if brain is None:
brain = tomlkit.table()
doc["brain"] = brain
cu = brain.get("computer_use")
if cu is None:
cu = tomlkit.table()
brain["computer_use"] = cu
cu["provider"] = name
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
def _patch_worker_key_toml(path: Path, key: str, value: object) -> None:
"""Set one key under the nested ``[brain.worker]`` table.
Generalised sibling of :func:`_patch_worker_provider_toml` (kept
untouched for parallel-session safety): walks ``brain`` -> ``worker``
(creating either level if missing), preserves comments, sibling keys, and
the optional BOM.
Renamed from ``_patch_sub_jarvis_key_toml`` in the 2026-06-29
Jarvis-Agents rename.
"""
path = _ensure_writable_config_path(path)
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
brain = doc.get("brain")
if brain is None:
brain = tomlkit.table()
doc["brain"] = brain
sub = brain.get("worker")
if sub is None:
sub = tomlkit.table()
brain["worker"] = sub
sub[key] = value
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
def _patch_wake_word_toml(path: Path, values: dict[str, object]) -> None:
"""Set keys under the nested ``[trigger.wake_word]`` table.
Walks ``trigger`` -> ``wake_word`` (creating either level if missing), sets
each key in ``values``, and preserves comments, sibling keys, and the
optional BOM (same contract as :func:`_patch_sub_jarvis_provider_toml`).
"""
path = _ensure_writable_config_path(path)
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
trigger = doc.get("trigger")
if trigger is None:
trigger = tomlkit.table()
doc["trigger"] = trigger
wake_word = trigger.get("wake_word")
if wake_word is None:
wake_word = tomlkit.table()
trigger["wake_word"] = wake_word
for key, value in values.items():
wake_word[key] = value
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
def _strip_persona_name(path: Path) -> None:
"""Remove a stale ``[persona] name`` entry (the legacy assistant-name override).
The wake word is now the single name source, so a leftover ``[persona] name``
from before the 2026-06-20 coupling must not linger. Best-effort: a missing
file/table/key is a no-op. Preserves comments and the optional BOM, exactly
like :func:`_patch_table`.
"""
if not path.exists():
return
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
persona = doc.get("persona")
if persona is None or "name" not in persona:
return
del persona["name"]
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)
class ConfigSectionLossError(RuntimeError):
"""A config write would have removed whole top-level entries.
Every writer in this module is a read-modify-write that sets or deletes a
single key: none of them may make a top-level table disappear. When one
would, the outgoing document is not an edit of the file on disk — it was
built from a partial or empty parse — and completing the write destroys
settings nobody asked to change.
"""
def _top_level_names(raw: str) -> set[str] | None:
"""Top-level table/key names in ``raw``, or ``None`` when unparsable.
``None`` deliberately disables the loss guard rather than blocking a write:
a file that cannot be parsed is exactly the file an in-app repair must
still be able to overwrite.
"""
text = raw[len(_BOM) :] if raw.startswith(_BOM) else raw
if not text.strip():
return set()
try:
return set(tomlkit.parse(text).keys())
except Exception: # noqa: BLE001 — an unparsable file is not a veto
log.debug("Config loss guard could not parse a TOML document.", exc_info=True)
return None
def _assert_no_top_level_loss(path: Path, content: str) -> None:
"""Refuse a write that would drop whole top-level entries.
The maintainer's live ``jarvis.toml`` went from 53 KB (2026-07-17 backup,
``[brain.realtime]`` included) to 183 bytes holding only the keys that boot
migrations and the wake/dictation writers happen to touch. No writer here
can produce that from a populated file — but an empty or half-read one
can, and nothing anywhere noticed. This guard turns that class of loss into
a refused write with a named cause instead of a silent deletion.
Legitimate removals stay legal: the worker-tier migration drops the NESTED
``[brain.sub_jarvis]`` table and the persona heal drops the NESTED
``[persona] name`` key, neither of which is a top-level entry.
"""
try:
existing = path.read_text(encoding="utf-8")
except OSError:
# No readable predecessor means nothing can be lost.
return
before = _top_level_names(existing)
if not before:
return
after = _top_level_names(content)
if after is None:
return
lost = before - after
if not lost:
return
raise ConfigSectionLossError(
f"Refusing to write {path}: it would remove the top-level "
f"configuration entries {sorted(lost)}. A config writer only ever "
"sets or clears a single key, so this write was built from an "
"incomplete read of the file."
)
def _atomic_write(path: Path, content: str) -> None:
"""Atomic tempfile + replace, read-only-aware.
``jarvis.toml`` carries a Windows read-only flag as the BUG-010 second
defense layer (parallel sessions cannot blindly overwrite the provider
config). The flag must be temporarily cleared for ``os.replace`` to
succeed; otherwise the call fails with ``[WinError 5] Zugriff
verweigert``. We restore the flag in ``finally`` so the defense holds
even if the write itself raises.
Before anything touches the file, :func:`_assert_no_top_level_loss` rejects
a document that would delete top-level entries — the failure mode that
silently took a provider pin (and everything else) off this machine.
"""
_assert_no_top_level_loss(path, content)
tmp = _write_unique_temp(path, content)
was_read_only = False
if path.exists():
mode = path.stat().st_mode
was_read_only = not bool(mode & stat.S_IWRITE)
if was_read_only:
os.chmod(path, mode | stat.S_IWRITE)
try:
_replace_with_retry(tmp, path, ensure_target_writable=True)
finally:
tmp.unlink(missing_ok=True)
if was_read_only and path.exists():
current_mode = path.stat().st_mode
os.chmod(path, current_mode & ~stat.S_IWRITE)
# Announce the write rather than leaving the reader to notice it. The
# parsed-TOML cache does check the file's identity, but a rewrite
# landing inside one filesystem timestamp tick that happens to keep the
# byte count — flipping a flag is exactly that — would be invisible to
# it, and serving a stale config after a save is the BUG-010 class of
# failure this module exists to prevent. In ``finally`` because a
# replace that raised may still have gone through.
clear_config_cache()
def _write_unique_temp(path: Path, content: str) -> Path:
"""Write and flush a unique sibling tempfile for an atomic replacement.
A fixed ``jarvis.toml.tmp`` name is unsafe across processes: the desktop,
drift guard, and another CLI can overwrite or replace the same tempfile.
A unique file in the target directory preserves same-filesystem atomicity.
"""
with tempfile.NamedTemporaryFile(
mode="w",
encoding="utf-8",
newline="",
prefix=f".{path.name}.",
suffix=".tmp",
dir=path.parent,
delete=False,
) as handle:
handle.write(content)
handle.flush()
os.fsync(handle.fileno())
return Path(handle.name)
def _replace_with_retry(
tmp: Path,
path: Path,
*,
ensure_target_writable: bool,
) -> None:
"""Replace ``path`` atomically, tolerating short-lived sharing locks.
Windows antivirus, indexers, and concurrent config readers can hold the
destination briefly and surface ``PermissionError``/WinError 5 or 32. The
bounded retry is also safe on POSIX; other error classes still fail fast.
"""
last_error: PermissionError | None = None
for delay_s in _ATOMIC_REPLACE_RETRY_DELAYS_S:
if delay_s:
time.sleep(delay_s)
if ensure_target_writable and path.exists():
current_mode = path.stat().st_mode
if not current_mode & stat.S_IWRITE:
os.chmod(path, current_mode | stat.S_IWRITE)
try:
os.replace(tmp, path)
return
except PermissionError as exc:
last_error = exc
if last_error is not None:
raise last_error
# ----------------------------------------------------------------------
# Layer 2 + 3 — config-soll.json + ENV sync (best-effort, cloud-first safe) # i18n-allow
# ----------------------------------------------------------------------
#: Overrides the drift baseline path (tests point it at a temp copy).
DRIFT_BASELINE_FILE_ENV = "JARVIS_DRIFT_BASELINE_FILE"
def _config_soll_path() -> Path: # i18n-allow
"""Locate ``scripts/config-soll.json`` relative to the repo root. # i18n-allow
Derived from the same ``PROJECT_ROOT`` resolution that anchors
``DEFAULT_CONFIG_FILE`` so the two paths stay consistent. On a headless
Linux VPS this file usually does not exist — callers must treat a missing
file as a graceful no-op.
``JARVIS_DRIFT_BASELINE_FILE`` points it elsewhere: the test suite sets it to
a temp copy so a provider switch under test never rewrites the tracked
file. Unset (every real run), the path is the checkout's file.
"""
override = os.environ.get(DRIFT_BASELINE_FILE_ENV, "").strip()
if override:
return Path(override)
return PROJECT_ROOT / "scripts" / "config-soll.json" # i18n-allow
def _sync_brain_primary_drift_soll(name: str) -> None: # i18n-allow
"""Best-effort sync of ``brain.primary`` into the drift-soll + ENV layers. # i18n-allow
NEVER raises and NEVER breaks the (already-completed) TOML write. Two
independent best-effort steps:
(a) Update ``scripts/config-soll.json`` ``brain.primary`` so the # i18n-allow
drift-guard daemon (5-min cron) does not revert the switch. Graceful
no-op when the file is absent (cloud-first / headless VPS).
(b) Set the User-scope ``JARVIS__BRAIN__PRIMARY`` ENV var (Windows
registry) so a fresh boot's ``JARVIS__*`` override matches the new
choice instead of reverting it; also update ``os.environ`` so the
live process and any child it spawns are immediately consistent.
The registry write is gated behind ``sys.platform == "win32"``.
"""
# (a) config-soll.json — graceful no-op if the file does not exist. # i18n-allow
try:
_update_config_soll_brain_primary(name) # i18n-allow
except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
log.warning("Could not sync brain.primary to config-soll.json: %s", exc) # i18n-allow
# (b) ENV var — winreg gated to win32, os.environ updated cross-platform.
try:
_set_user_env_var(_BRAIN_PRIMARY_ENV, name)
except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
log.warning("Could not sync %s to the User environment: %s", _BRAIN_PRIMARY_ENV, exc)
def _sync_worker_provider_drift_soll(name: str) -> None: # i18n-allow
"""Best-effort sync of ``brain.worker.provider`` into config-soll + ENV. # i18n-allow
NEVER raises and NEVER breaks the (already-completed) TOML write. Same
two-step shape as :func:`_sync_brain_primary_drift_soll`. # i18n-allow
Renamed from ``_sync_sub_jarvis_provider_drift_soll`` in the 2026-06-29 # i18n-allow
Jarvis-Agents rename.
"""
try:
_update_config_soll_worker_provider(name) # i18n-allow
except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
log.warning("Could not sync worker provider to config-soll.json: %s", exc) # i18n-allow
try:
_set_user_env_var(_WORKER_PROVIDER_ENV, name)
if "JARVIS__BRAIN__SUB_JARVIS__PROVIDER" in os.environ:
_set_user_env_var("JARVIS__BRAIN__SUB_JARVIS__PROVIDER", name)
except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
log.warning(
"Could not sync %s to the User environment: %s",
_WORKER_PROVIDER_ENV,
exc,
)
def _sync_computer_use_provider_drift_soll(name: str) -> None: # i18n-allow
"""Best-effort sync of ``brain.computer_use.provider`` into config-soll + # i18n-allow
ENV.
NEVER raises and NEVER breaks the (already-completed) TOML write. Same
two-step shape as :func:`_sync_worker_provider_drift_soll`. # i18n-allow: internal identifier
"""
try:
_update_config_soll_computer_use_provider(name) # i18n-allow
except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
log.warning(
"Could not sync computer_use provider to " # i18n-allow: literal filename
"config-soll.json: %s", # i18n-allow: literal filename
exc,
)
try:
_set_user_env_var(_CU_PROVIDER_ENV, name)
except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
log.warning(
"Could not sync %s to the User environment: %s",
_CU_PROVIDER_ENV,
exc,
)
def _sync_worker_model_drift_soll(model: str) -> None: # i18n-allow
"""Best-effort sync of ``brain.worker.model`` into config-soll + ENV. # i18n-allow
NEVER raises and NEVER breaks the (already-completed) TOML write. Same
two-step shape as :func:`_sync_worker_provider_drift_soll`. # i18n-allow
Renamed from ``_sync_sub_jarvis_model_drift_soll`` in the 2026-06-29 # i18n-allow
Jarvis-Agents rename.
"""
try:
_update_config_soll_worker_key("model", model) # i18n-allow
except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
log.warning("Could not sync worker model to config-soll.json: %s", exc) # i18n-allow
try:
_set_user_env_var(_WORKER_MODEL_ENV, model)
# The loader migrates a nonempty legacy value over an empty modern value.
# Keep an existing legacy override aligned, including an explicit reset.
if "JARVIS__BRAIN__SUB_JARVIS__MODEL" in os.environ:
_set_user_env_var("JARVIS__BRAIN__SUB_JARVIS__MODEL", model)
except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
log.warning(
"Could not sync %s to the User environment: %s",
_WORKER_MODEL_ENV,
exc,
)
def _sync_tts_provider_drift_soll(applied: dict[str, str]) -> None: # i18n-allow
"""Best-effort sync of the TTS block into the drift-soll + ENV layers. # i18n-allow
NEVER raises and NEVER breaks the (already-completed) TOML write. ``applied``
is the exact set of ``[tts]`` keys the TOML write touched (provider + any
provider-dependent voice/language/model), so config-soll ends up byte-for-byte # i18n-allow
in agreement and the drift-guard reverts nothing. The ENV layer only pins the
provider (the single value a stale boot override could revert).
"""
try:
_update_config_soll_section("tts", applied) # i18n-allow
except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
log.warning("Could not sync tts.* to config-soll.json: %s", exc) # i18n-allow
provider_name = applied["provider"] # always present — set in _patch_tts_block
try:
_set_user_env_var(_TTS_PROVIDER_ENV, provider_name)
except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
log.warning("Could not sync %s to the User environment: %s", _TTS_PROVIDER_ENV, exc)
def _sync_stt_provider_drift_soll(name: str) -> None: # i18n-allow
"""Best-effort sync of ``stt.provider`` into the drift-soll + ENV layers. # i18n-allow
NEVER raises and NEVER breaks the (already-completed) TOML write. Same
two-step shape as :func:`_sync_brain_primary_drift_soll`. # i18n-allow
"""
try:
_update_config_soll_section("stt", {"provider": name}) # i18n-allow
except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
log.warning("Could not sync stt.provider to config-soll.json: %s", exc) # i18n-allow
try:
_set_user_env_var(_STT_PROVIDER_ENV, name)
except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
log.warning("Could not sync %s to the User environment: %s", _STT_PROVIDER_ENV, exc)
def _sync_brain_provider_model_drift_soll( # i18n-allow
provider: str,
*,
model: str | None,
deep_model: str | None,
tool_model: str | None = None,
cu_model: str | None = None,
voice: str | None = None,
) -> None:
"""Best-effort sync of ``brain.providers.<p>`` model keys into the drift-soll. # i18n-allow
NEVER raises and NEVER breaks the (already-completed) TOML write. Only the
keys actually written (non-``None``) are synced, so config-soll ends up in # i18n-allow
agreement with the TOML and the drift-guard reverts nothing. No ENV layer:
per-provider model keys have no effective ``JARVIS__*`` boot override (see
the docstring of :func:`set_brain_provider_model`). The flat dotted top-level
key ``brain.providers.<p>`` is exactly how the soll file stores it. # i18n-allow
"""
values: dict[str, object] = {}
if model is not None:
values["model"] = model
if deep_model is not None:
values["deep_model"] = deep_model
if tool_model is not None:
values["tool_model"] = tool_model
if cu_model is not None:
values["cu_model"] = cu_model
if voice is not None:
values["voice"] = voice
if not values:
return
try:
_update_config_soll_section(f"brain.providers.{provider}", values) # i18n-allow
except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
log.warning(
"Could not sync brain.providers.%s model to config-soll.json: %s", # i18n-allow
provider,
exc,
)
def _update_config_soll_section(top: str, values: dict[str, object]) -> None: # i18n-allow
"""Atomically merge ``values`` into ``data[top]`` in config-soll.json. # i18n-allow
Preserves every other key (``_comment``, ``_updated``, other keys in the
same section, other top-level tables). Atomic tempfile + ``os.replace``,
UTF-8, ``indent=2``. Graceful no-op when the file is absent (cloud-first)
or when the section already matches every value (avoid a needless rewrite).
MUST NOT be called while ``_WRITE_LOCK`` is held — it acquires that lock
itself and ``_WRITE_LOCK`` is a non-reentrant ``threading.Lock`` (it would
deadlock). Today's callers acquire it only sequentially, never nested.
"""
soll_path = _config_soll_path() # i18n-allow
if not soll_path.exists(): # i18n-allow
log.debug(
"config-soll.json absent (%s) — skipping drift-soll sync", # i18n-allow
soll_path, # i18n-allow: internal config-soll identifier
)
return
with _WRITE_LOCK:
raw = soll_path.read_text(encoding="utf-8") # i18n-allow
data = json.loads(raw)
section = data.get(top)
if not isinstance(section, dict):
section = {}
data[top] = section
if all(section.get(k) == v for k, v in values.items()):
return # already in sync — avoid a needless rewrite
section.update(values)
out = json.dumps(data, indent=2, ensure_ascii=False) + "\n"
_atomic_write_text(soll_path, out) # i18n-allow
def _update_config_soll_brain_primary(name: str) -> None: # i18n-allow
"""Atomically set ``data["brain"]["primary"] = name`` in config-soll.json. # i18n-allow
Preserves all other keys (``_comment``, ``_updated``, other ``brain.*``
keys, other top-level tables). Atomic tempfile + ``os.replace``, UTF-8,
``indent=2``. Graceful no-op when the file is absent.
"""
soll_path = _config_soll_path() # i18n-allow
if not soll_path.exists(): # i18n-allow
log.debug(
"config-soll.json absent (%s) — skipping drift-soll sync", # i18n-allow
soll_path, # i18n-allow: internal config-soll identifier
)
return
with _WRITE_LOCK:
raw = soll_path.read_text(encoding="utf-8") # i18n-allow
data = json.loads(raw)
brain = data.get("brain")
if not isinstance(brain, dict):
brain = {}
data["brain"] = brain
if brain.get("primary") == name:
return # already in sync — avoid a needless rewrite
brain["primary"] = name
out = json.dumps(data, indent=2, ensure_ascii=False) + "\n"
_atomic_write_text(soll_path, out) # i18n-allow
def _update_config_soll_worker_provider(name: str) -> None: # i18n-allow
"""Atomically set ``data["brain.worker"]["provider"] = name`` in
config-soll.json. # i18n-allow
Note the FLAT dotted key ``"brain.worker"`` — that is how the drift-guard
soll file stores the sub-table (see scripts/config-soll.json), NOT a nested # i18n-allow
``data["brain"]["worker"]``. Preserves all other keys (``_comment``, the
fallback chain, other tables). Graceful no-op when the file is absent.
Renamed from ``_update_config_soll_sub_jarvis_provider`` in the 2026-06-29 # i18n-allow
Jarvis-Agents rename; now writes to the ``"brain.worker"`` flat key.
"""
soll_path = _config_soll_path() # i18n-allow
if not soll_path.exists(): # i18n-allow
log.debug(
"config-soll.json absent (%s) — skipping drift-soll sync", # i18n-allow
soll_path, # i18n-allow: internal config-soll identifier
)
return
with _WRITE_LOCK:
raw = soll_path.read_text(encoding="utf-8") # i18n-allow
data = json.loads(raw)
block = data.get("brain.worker")
if not isinstance(block, dict):
block = {}
data["brain.worker"] = block
if block.get("provider") == name:
return # already in sync — avoid a needless rewrite
block["provider"] = name
out = json.dumps(data, indent=2, ensure_ascii=False) + "\n"
_atomic_write_text(soll_path, out) # i18n-allow
def _update_config_soll_computer_use_provider(name: str) -> None: # i18n-allow
"""Atomically set ``data["brain.computer_use"]["provider"] = name`` in
config-soll.json. # i18n-allow
Note the FLAT dotted key ``"brain.computer_use"`` — same layout as
``"brain.worker"`` (see :func:`_update_config_soll_worker_provider`), # i18n-allow
not a nested table. # i18n-allow: internal config-soll identifier reference
Preserves all other keys.
Graceful no-op when the file is absent.
"""
soll_path = _config_soll_path() # i18n-allow
if not soll_path.exists(): # i18n-allow
log.debug("config-soll.json absent (%s) — skip drift-soll sync", soll_path) # i18n-allow
return
with _WRITE_LOCK:
raw = soll_path.read_text(encoding="utf-8") # i18n-allow
data = json.loads(raw)
block = data.get("brain.computer_use")
if not isinstance(block, dict):
block = {}
data["brain.computer_use"] = block
if block.get("provider") == name:
return # already in sync — avoid a needless rewrite
block["provider"] = name
out = json.dumps(data, indent=2, ensure_ascii=False) + "\n"
_atomic_write_text(soll_path, out) # i18n-allow
def _update_config_soll_worker_key(key: str, value: str) -> None: # i18n-allow
"""Atomically set ``data["brain.worker"][key] = value`` in config-soll.json. # i18n-allow
Generalised sibling of :func:`_update_config_soll_worker_provider` # i18n-allow
(same FLAT dotted-key layout, same preservation guarantees, same graceful
no-op when the file is absent).
Renamed from ``_update_config_soll_sub_jarvis_key`` in the 2026-06-29 # i18n-allow
Jarvis-Agents rename.
"""
soll_path = _config_soll_path() # i18n-allow
if not soll_path.exists(): # i18n-allow
log.debug(
"config-soll.json absent (%s) — skipping drift-soll sync", # i18n-allow
soll_path, # i18n-allow: internal config-soll identifier
)
return
with _WRITE_LOCK:
raw = soll_path.read_text(encoding="utf-8") # i18n-allow
data = json.loads(raw)
block = data.get("brain.worker")
if not isinstance(block, dict):
block = {}
data["brain.worker"] = block
if block.get(key) == value:
return # already in sync — avoid a needless rewrite
block[key] = value
out = json.dumps(data, indent=2, ensure_ascii=False) + "\n"
_atomic_write_text(soll_path, out) # i18n-allow
def _atomic_write_text(path: Path, content: str) -> None:
"""Atomic tempfile + replace for a plain UTF-8 text file (no read-only flag).
Used for config-soll.json, which — unlike jarvis.toml — does not carry the # i18n-allow
BUG-010 read-only defense flag.
"""
tmp = _write_unique_temp(path, content)
try:
_replace_with_retry(tmp, path, ensure_target_writable=False)
finally:
tmp.unlink(missing_ok=True)
def _set_user_env_var(name: str, value: str) -> None:
"""Persist a User-scope ENV var and update the live ``os.environ``.
The persistent (registry) write is Windows-only and gated behind
``sys.platform == "win32"``. ``os.environ`` is always updated so the live
process and any child it spawns immediately observe the new value — this
is the cross-platform part that also benefits a Linux VPS.
"""
# Always update the live process (and inherited children).
os.environ[name] = value
if sys.platform != "win32":
return
_set_user_env_var_winreg(name, value)
def _set_user_env_var_winreg(name: str, value: str) -> None:
"""Write ``name=value`` to ``HKCU\\Environment`` (REG_SZ) and broadcast.
Windows-only. Imported lazily so the module imports cleanly on Linux.
Best-effort broadcast of ``WM_SETTINGCHANGE`` so new processes pick up the
change without a logout; a broadcast failure is non-fatal.
"""
import winreg # local import: Windows-only module
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment", 0, winreg.KEY_SET_VALUE) as key:
winreg.SetValueEx(key, name, 0, winreg.REG_SZ, value)
# Best-effort: tell already-running shells/processes the env block changed.
try:
import ctypes
HWND_BROADCAST = 0xFFFF
WM_SETTINGCHANGE = 0x001A
SMTO_ABORTIFHANG = 0x0002
ctypes.windll.user32.SendMessageTimeoutW(
HWND_BROADCAST,
WM_SETTINGCHANGE,
0,
"Environment",
SMTO_ABORTIFHANG,
1000,
None,
)
except Exception as exc: # noqa: BLE001 — broadcast is a nicety, not required
log.debug("WM_SETTINGCHANGE broadcast failed (non-fatal): %s", exc)
def set_wiki_curator_provider(
name: str,
*,
model: str = "",
path: Path = DEFAULT_CONFIG_FILE,
) -> None:
"""Persist the Wiki-curator model picker in ``[memory.wiki.curator]``.
Writes ``provider`` and ``model`` together. Empty strings are persisted
verbatim — they are the documented fallback sentinels resolved at runtime
by ``dodaios.memory.wiki.curator_llm._resolve_provider_and_model``
(``provider=""`` -> ``brain.primary``; ``model=""`` -> the provider's
cheap/fast router model). Takes effect as a boot default on the next
``load_config``; the live switch happens in the settings route by resetting
the running ``WikiCuratorLLM``'s cached brain.
"""
_patch_wiki_curator_toml(path, {"provider": name, "model": model})
def _patch_wiki_curator_toml(path: Path, values: dict[str, object]) -> None:
"""Set keys under the nested ``[memory.wiki.curator]`` table.
Walks ``memory`` -> ``wiki`` -> ``curator`` (creating any missing level),
sets each key in ``values``, and preserves comments, sibling keys, and the
optional BOM (same contract as :func:`_patch_sub_jarvis_provider_toml`).
"""
path = _ensure_writable_config_path(path)
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
had_bom = raw.startswith(_BOM)
if had_bom:
raw = raw[len(_BOM) :]
doc: TOMLDocument = tomlkit.parse(raw)
memory = doc.get("memory")
if memory is None:
memory = tomlkit.table()
doc["memory"] = memory
wiki = memory.get("wiki")
if wiki is None:
wiki = tomlkit.table()
memory["wiki"] = wiki
curator = wiki.get("curator")
if curator is None:
curator = tomlkit.table()
wiki["curator"] = curator
for key, value in values.items():
curator[key] = value
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
_atomic_write(path, out)