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
feat(modes): REST routes and a jarvis modes CLI group
rubenluetke10-beepa88311e96499
diff --git a/jarvis/cli_ctl/__main__.py b/jarvis/cli_ctl/__main__.pyindex 79c2043320..6532725963 100644--- a/jarvis/cli_ctl/__main__.py+++ b/jarvis/cli_ctl/__main__.py@@ -34,6 +34,7 @@ from jarvis.cli_ctl.commands import ide as ide_cmdfrom jarvis.cli_ctl.commands import marketplace as marketplace_cmdfrom jarvis.cli_ctl.commands import mcps as mcps_cmdfrom jarvis.cli_ctl.commands import missions as missions_cmd+from jarvis.cli_ctl.commands import modes as modes_cmdfrom jarvis.cli_ctl.commands import outputs as outputs_cmdfrom jarvis.cli_ctl.commands import permissions as permissions_cmdfrom jarvis.cli_ctl.commands import sessions as sessions_cmd@@ -114,6 +115,7 @@ app.add_typer(commands_cmd.app, name="commands")app.add_typer(computer_use_cmd.app, name="computer-use")app.add_typer(config_cmd.app, name="config")app.add_typer(missions_cmd.app, name="missions")+app.add_typer(modes_cmd.app, name="modes")app.add_typer(wiki_cmd.app, name="wiki")app.add_typer(sessions_cmd.app, name="sessions")app.add_typer(skills_cmd.app, name="skills")diff --git a/jarvis/cli_ctl/commands/modes.py b/jarvis/cli_ctl/commands/modes.pynew file mode 100644index 0000000000..08a11ca1b2--- /dev/null+++ b/jarvis/cli_ctl/commands/modes.py@@ -0,0 +1,86 @@+"""modes: switch how the assistant behaves (/api/modes).++A mode is the assistant's character — Assistant, Friend, Coach, Focus, Coding,+or one you wrote yourself. Switching applies on the next turn, in voice and in+chat, with no restart.+"""++from __future__ import annotations++import typer++from jarvis.cli_ctl import invoke++app = typer.Typer(+ no_args_is_help=True,+ help="Assistant modes: list, show, use, create, delete, restore.",+)++[email protected]("list")+def list_modes() -> None:+ """List every mode and show which one is active."""+ invoke.run("GET", "/api/modes")+++def show(slug: str = typer.Argument(..., help="Mode id, e.g. friend")) -> None:+ """Show one mode in full, including its character text."""+ invoke.run("GET", f"/api/modes/{slug}")+++def use(slug: str = typer.Argument(..., help="Mode id to switch to")) -> None:+ """Switch the active mode. Applies on the next turn — no restart."""+ invoke.run("PUT", "/api/modes/active", body={"slug": slug})+++def create(+ name: str = typer.Argument(..., help="Display name, e.g. 'Night Owl'"),+ character: str = typer.Option(..., "--character", "-c", help="How it should behave"),+ slug: str = typer.Option("", "--slug", help="Mode id (derived from the name if omitted)"),+ emoji: str = typer.Option("", "--emoji", help="Shown on the mode card"),+ description: str = typer.Option("", "--description", "-d", help="One line for the card"),+ voice: str = typer.Option("", "--voice", help="TTS voice id this mode speaks in"),+ verbosity: str = typer.Option("normal", "--verbosity", help="brief | normal | rich"),+ proactivity: str = typer.Option(+ "normal", "--proactivity", help="reactive | normal | forward"+ ),+) -> None:+ """Create or replace a mode. Does NOT switch to it — use `modes use` for that."""+ invoke.run(+ "POST",+ "/api/modes",+ body={+ "slug": slug,+ "name": name,+ "character": character,+ "emoji": emoji,+ "description": description,+ "voice": voice,+ "verbosity": verbosity,+ "proactivity": proactivity,+ },+ )+++def delete(slug: str = typer.Argument(..., help="Mode id to delete")) -> None:+ """Delete a mode you created. Built-ins are refused; a copy of one is not.++ Destructive and not undoable — the mode's character text is gone with it.+ Deleting the active mode falls back to the default rather than leaving the+ assistant pointing at something that is not there.+ """+ invoke.run("DELETE", f"/api/modes/{slug}", dangerous=True)+++def restore(slug: str = typer.Argument(..., help="Built-in mode id to restore")) -> None:+ """Throw away your edits to a built-in mode and bring the shipped one back.++ Destructive in one direction only: your edited copy is deleted, and the+ packaged mode is always recoverable because it was never touched.+ """+ invoke.run("POST", f"/api/modes/{slug}/restore", dangerous=True)diff --git a/jarvis/cli_ctl/reserved.py b/jarvis/cli_ctl/reserved.pyindex d22319ef25..3a0d1a90d0 100644--- a/jarvis/cli_ctl/reserved.py+++ b/jarvis/cli_ctl/reserved.py@@ -47,6 +47,7 @@ RESERVED_CONTROL_NAMES: frozenset[str] = frozenset("docs","frontier","ide",+ "modes",})diff --git a/jarvis/ui/web/modes_routes.py b/jarvis/ui/web/modes_routes.pynew file mode 100644index 0000000000..5ca43f77d1--- /dev/null+++ b/jarvis/ui/web/modes_routes.py@@ -0,0 +1,159 @@+"""REST API for assistant modes — the shelf of characters the user picks from.++Every action is an endpoint (the CLI-first contract): the modes screen, the+voice interviewer and the ``jarvis modes`` commands all drive these same+routes, so what the UI can do and what a spoken command can do never drift+apart.++Endpoints (prefix ``/api/modes``):++* ``GET /`` → every mode + which one is active+* ``GET /{slug}`` → one mode in full+* ``PUT /active`` → switch the active mode (applies next turn)+* ``POST /`` → create or replace a mode+* ``DELETE /{slug}`` → delete a user mode (or a user copy of a built-in)+* ``POST /{slug}/restore`` → drop the user copy, bring the built-in back++Anti-drift (``docs/anti-drift-three-layer.md``): the ``Verbosity`` and+``Proactivity`` Literals below are asserted against ``modes.VERBOSITIES`` /+``modes.PROACTIVITIES`` at import time, so adding a value in one place and+forgetting the other fails at startup rather than on the one request that+happens to carry the new string.+"""++from __future__ import annotations++import logging+from typing import Literal, get_args++from fastapi import APIRouter, HTTPException+from pydantic import BaseModel, Field++from jarvis.brain import modes++log = logging.getLogger(__name__)++router = APIRouter(prefix="/api/modes", tags=["modes"])++Verbosity = Literal["brief", "normal", "rich"]+Proactivity = Literal["reactive", "normal", "forward"]++# D2 of the anti-drift doc: an import-time assertion, not a test somebody has to+# remember to run.+assert set(get_args(Verbosity)) == set(modes.VERBOSITIES), (+ "Verbosity Literal drifted from modes.VERBOSITIES"+)+assert set(get_args(Proactivity)) == set(modes.PROACTIVITIES), (+ "Proactivity Literal drifted from modes.PROACTIVITIES"+)+++class ActiveModeBody(BaseModel):+ slug: str = Field(..., min_length=1, max_length=64)+++class ModeBody(BaseModel):+ """One mode as the UI and the voice interviewer submit it."""++ # Optional: a mode created by voice has a NAME the user said out loud and no+ # slug at all, so the server derives one rather than making the caller+ # guess the grammar.+ slug: str = Field("", max_length=64)+ name: str = Field(..., min_length=1, max_length=80)+ character: str = Field(..., min_length=1, max_length=20_000)+ emoji: str = Field("", max_length=16)+ description: str = Field("", max_length=280)+ voice: str = Field("", max_length=80)+ verbosity: Verbosity = "normal"+ proactivity: Proactivity = "normal"+++def _payload() -> dict[str, object]:+ active = modes.active_slug()+ return {+ "modes": [m.to_payload() for m in modes.list_modes()],+ "active": active,+ # What the section override is doing, if anything. The UI needs to be+ # able to say "coding mode is on because you are in the Agentic IDE"+ # rather than showing a switch the user did not touch and cannot+ # explain — an unexplained mode is exactly what this feature replaced.+ "section_override": modes.section_override() or "",+ "verbosities": list(modes.VERBOSITIES),+ "proactivities": list(modes.PROACTIVITIES),+ }++[email protected]("", summary="Every mode and which one is active")+async def list_modes() -> dict[str, object]:+ """The full shelf, built-ins first, plus the active slug."""+ return _payload()++[email protected]("/{slug}", summary="One mode in full")+async def get_mode(slug: str) -> dict[str, object]:+ mode = modes.get_mode(slug)+ if mode is None:+ raise HTTPException(status_code=404, detail=f"No mode called {slug!r}.")+ return mode.to_payload()++[email protected]("/active", summary="Switch the active mode")+async def set_active(body: ActiveModeBody) -> dict[str, object]:+ """Switch modes. Applies on the next turn — voice and chat alike, no restart.++ A section override (the Agentic IDE) still wins while it is in force, so the+ response reports the slug ACTUALLY in effect, not the one that was asked+ for. Reporting the request back would be a small lie the UI would then show.+ """+ try:+ mode = modes.set_active(body.slug)+ except modes.ModeError as exc:+ raise HTTPException(status_code=404, detail=str(exc)) from exc+ return {"ok": True, "chosen": mode.slug, "restart_required": False, **_payload()}++[email protected]("", summary="Create or replace a mode")+async def save_mode(body: ModeBody) -> dict[str, object]:+ """Write a mode. Creating one does not switch to it — that is a separate act."""+ try:+ slug = modes.normalize_slug(body.slug or body.name)+ except modes.ModeError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc++ try:+ mode = modes.save_mode(+ slug=slug,+ name=body.name,+ character=body.character,+ emoji=body.emoji,+ description=body.description,+ voice=body.voice,+ verbosity=body.verbosity,+ proactivity=body.proactivity,+ )+ except modes.ModeError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ except OSError as exc:+ raise HTTPException(status_code=500, detail=f"Could not save: {exc}") from exc++ return {"ok": True, "mode": mode.to_payload(), **_payload()}++[email protected]("/{slug}", summary="Delete a user mode")+async def delete_mode(slug: str) -> dict[str, object]:+ """Remove a user mode. Built-ins are refused; a user COPY of one is allowed."""+ try:+ removed = modes.delete_mode(slug)+ except modes.ModeError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ return {"ok": True, "removed": removed, **_payload()}++[email protected]("/{slug}/restore", summary="Restore a built-in mode")+async def restore_builtin(slug: str) -> dict[str, object]:+ """Throw away the user's edits to a built-in and bring the packaged one back."""+ try:+ restored = modes.restore_builtin(slug)+ except modes.ModeError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ return {"ok": True, "restored": restored, **_payload()}diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex 480acc1a14..08c2ab6893 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -368,6 +368,7 @@ class WebServer:from .missions_ws_routes import (router as missions_ws_router,)+ from .modes_routes import router as modes_routerfrom .onboarding_routes import router as onboarding_routerfrom .outputs_routes import router as outputs_routerfrom .permissions_routes import router as permissions_router@@ -423,6 +424,7 @@ class WebServer:app.include_router(desktop_router)app.include_router(profile_router)app.include_router(settings_router)+ app.include_router(modes_router)app.include_router(permissions_router)# In-app updater (GET status / POST apply). Managed-install only — see# jarvis/ui/web/update_routes.py; refuses to self-reset a dev checkout.diff --git a/tests/integration/test_modes_routes.py b/tests/integration/test_modes_routes.pynew file mode 100644index 0000000000..62f21a6173--- /dev/null+++ b/tests/integration/test_modes_routes.py@@ -0,0 +1,115 @@+"""Integration tests for /api/modes — the assistant's shelf of characters.++These go through the real WebServer, so they also prove the router is actually+mounted: a modes screen talking to a route nobody registered fails as a blank+page, which is the least diagnosable failure this feature has.+"""+from __future__ import annotations++from collections.abc import Iterator++import pytest+from fastapi.testclient import TestClient++import jarvis.core.config as core_config+from jarvis.brain import modes+from jarvis.core.bus import EventBus+from jarvis.core.config import JarvisConfig+from jarvis.ui.web.server import WebServer++[email protected](autouse=True)+def _isolate(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+ """User modes go to a throwaway dir; the pointer never reaches jarvis.toml."""+ monkeypatch.setattr(core_config, "DATA_DIR", tmp_path)+ stored: dict[str, str] = {}+ monkeypatch.setattr(modes, "_configured_slug", lambda: stored.get("slug", modes.DEFAULT_MODE))+ monkeypatch.setattr(+ "jarvis.core.config_writer.set_active_mode",+ lambda slug, **_kw: stored.__setitem__("slug", slug),+ )+ modes.set_section_override(None)+++def client() -> Iterator[TestClient]:+ cfg = JarvisConfig()+ cfg.ui.dev_mode = True+ bus = EventBus()+ server = WebServer(cfg, bus=bus)+ server.app.state.config = cfg+ server.app.state.bus = bus+ with TestClient(server.app) as c:+ yield c+++def test_router_is_mounted_and_lists_the_builtins(client: TestClient) -> None:+ resp = client.get("/api/modes")+ assert resp.status_code == 200+ body = resp.json()+ assert [m["slug"] for m in body["modes"]][:5] == list(modes.BUILTIN_SLUGS)+ assert body["active"] == modes.DEFAULT_MODE+++def test_switching_the_active_mode_round_trips(client: TestClient) -> None:+ resp = client.put("/api/modes/active", json={"slug": "friend"})+ assert resp.status_code == 200+ assert resp.json()["active"] == "friend"+ assert resp.json()["restart_required"] is False+ assert client.get("/api/modes").json()["active"] == "friend"+++def test_switching_to_an_unknown_mode_is_a_404(client: TestClient) -> None:+ assert client.put("/api/modes/active", json={"slug": "nope"}).status_code == 404+++def test_a_mode_created_by_name_alone_gets_a_slug(client: TestClient) -> None:+ """The voice interviewer submits a spoken NAME and no slug — the server derives one."""+ resp = client.post(+ "/api/modes",+ json={"name": "Night Owl", "character": "Speak quietly. It is late."},+ )+ assert resp.status_code == 200+ assert resp.json()["mode"]["slug"] == "night-owl"+++def test_creating_a_mode_does_not_switch_to_it(client: TestClient) -> None:+ """Two separate acts — building a character is not the same as becoming it."""+ client.post("/api/modes", json={"name": "Night Owl", "character": "Quietly."})+ assert client.get("/api/modes").json()["active"] == modes.DEFAULT_MODE+++def test_an_unknown_knob_value_is_rejected(client: TestClient) -> None:+ """The Literal guard: a value the backend does not know never reaches disk."""+ resp = client.post(+ "/api/modes",+ json={"name": "Loud", "character": "Shout.", "verbosity": "very-loud"},+ )+ assert resp.status_code == 422+++def test_a_path_shaped_name_is_refused(client: TestClient) -> None:+ resp = client.post("/api/modes", json={"name": "../escape", "character": "x"})+ assert resp.status_code == 400+++def test_builtins_cannot_be_deleted_but_a_copy_can(client: TestClient) -> None:+ assert client.delete("/api/modes/friend").status_code == 400++ client.post("/api/modes", json={"name": "Friend", "character": "My own words."})+ assert client.get("/api/modes/friend").json()["character"] == "My own words."++ assert client.post("/api/modes/friend/restore").json()["restored"] is True+ assert "not serving a client" in client.get("/api/modes/friend").json()["character"]+++def test_the_response_reports_the_mode_actually_in_force(client: TestClient) -> None:+ """A section override wins; echoing the request back would be a small lie."""+ modes.set_section_override(modes.MODE_CODING)+ try:+ body = client.put("/api/modes/active", json={"slug": "friend"}).json()+ assert body["chosen"] == "friend"+ assert body["active"] == modes.MODE_CODING+ assert body["section_override"] == modes.MODE_CODING+ finally:+ modes.set_section_override(None)