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
fix(society): keep unattended routines and reviews off per-token keys once a subscription is connected (#756)
Ruben Lütke6d6d18eb9069
diff --git a/docs/routines.md b/docs/routines.mdindex 51070652b6..15ac7ccc17 100644--- a/docs/routines.md+++ b/docs/routines.md@@ -18,6 +18,37 @@ editor has a Model section (provider, model, effort, account) with a "followthe agent" choice that clears the pin so the routine tracks the owner's liveseat again. Title, prompt or schedule edits keep the pinned seat untouched.+### Unattended runs and API keys++Background work follows one billing rule (`dodaios/brain/background_policy.py`):+once a subscription is connected (a subscription login seen within the last+30 days), work nobody started by hand never bills a per-token API key. For+routines this means:++- **Scheduled, triggered and webhook runs** on a seat that answers through an+ API key are skipped while a subscription is connected. The run starts no+ model turn and opens no routine chat; the Runs tab records it as skipped+ with the reason, the owner's chat gets one line saying why, and a recurring+ routine fires again at its next occurrence (a one-shot routine ends as+ failed with that reason; a webhook delivery is marked failed and is not+ replayed automatically). The routine is not moved to another seat: pick a+ subscription or local model for it to keep it running unattended.+- **Run now** is the person's own start: it runs on the routine's seat as+ chosen, key included.+- **Subscription and local seats** run as before.+- **An install that never connected a subscription** keeps billing the seat it+ picked, so a single-key setup still runs its routines.++Routines an agent set up on its own (autonomous follow-ups) are stricter: they+wait for a subscription or local seat whenever their seat would bill a key.++The same rule covers an agent's unattended memory work (the post-turn review+and skill learning, `dodaios/society/seat_brain.py`): with a subscription+connected, an agent whose chat bills a key does not review on that key. The+review stays pending under its bounded retries and the agent's knowledge+status (`last_review.reason`) says why; an explicit "remember that" request is+still saved without a model call.+## Configuring routines by chatExamples of supported requests:diff --git a/docs/self_mod.md b/docs/self_mod.mdindex d8f37642ef..84da419d5f 100644--- a/docs/self_mod.md+++ b/docs/self_mod.md@@ -139,19 +139,31 @@ docstring before adding any path there.`dodaios/voice/config_readback.py`); REST/CLI keep the SAFE-auto / ASK-confirmsplit (`auto_apply="safe_only"`).-## 6. Skill authoring (Plan §7.5)--A voice command like "Erstelle einen Skill, der Spotify pausiert wenn ich <!-- i18n-allow -->-rede" (Create a skill that pauses Spotify when I speak) → main Dodaios-calls the `spawn_skill_author` tool → a Dodaios-Agent (Opus 4.7) generates-SKILL.md → forces `state=draft`. The draft lands in-`~/.jarvis/skills/<slug>/` and is visible in the hot-reload pool, but is-**not active**.+## 6. Skill authoring++A voice or chat request like "Create a skill that pauses the music when I+speak" reaches the router tool `create-skill`+(`dodaios/plugins/tool/create_skill.py`). It makes one bounded call, never a+worker spawn: `SkillCreatorService.author`+(`dodaios/skills/creator_service.py`) builds the authoring context (attached+tools and installed skills), asks the brain ladder (active provider, then the+Tool Model, quality and frontier tiers) for a complete SKILL.md, and commits it+through the shared skill writer with `state: draft` forced (AP-15). When no+model can write the draft, the tool fails honestly and nothing lands on disk.+The Skills view's creator dialog uses the same service over+`POST /api/skills/creator/{draft,refine,validate,commit,author}`.++The draft lands in the user skills directory and is visible in the hot-reload+pool, but is **not active**.++`spawn_skill_author` (`dodaios/brain/tools/skill_authoring.py`), the earlier+plan for a mission-based author, is **not wired**: it is not in+`ROUTER_TOOLS` and its constructor needs a runner the tool loader cannot+supply. Its module docstring explains why it stays unregistered.Manual activation:-- Web UI: `SkillsView` → draft badge "ENTWURF — vor Aktivierung review"- (DRAFT — review before activation) → click "Aktivieren" (Activate)- (Phase 7.6+, UI under construction).+- Web UI: the Skills view shows the draft; enabling it+ (`POST /api/skills/{name}/enable`) promotes a healthy draft.- CLI: `python -m dodaios.skills.cli --promote <slug>`.The pre-promote lint blocks `eval/exec/os.system/subprocess(shell=True)`@@ -175,9 +187,10 @@ skill-authoring path must keep these:- **Backups live outside the watched config directory** (AP-SM13), or thehot reload loops.- **Discrete tools** (`list_mutable_settings`, `get_config_value`,- `set_config_value`, `spawn_skill_author`), no universal setter (AP-SM8).- Skill authoring runs as a mission, not as file writes inside the Dodaios- process (AP-SM7).+ `set_config_value`, `create-skill`), no universal setter (AP-SM8).+ Skill authoring writes only through the skill registry's writer, and only+ drafts (AP-SM7; the mission-based `spawn_skill_author` route is not wired,+ see §6).- **Yes/no confirmation is a deterministic pattern match**, not an LLM call(AP-SM12).- **Generated skills stay drafts**: the writer forces `state=draft` even if thediff --git a/dodaios/society/review.py b/dodaios/society/review.pyindex d33cc9b923..ed4d8e5d55 100644--- a/dodaios/society/review.py+++ b/dodaios/society/review.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport asyncioimport jsonimport logging+from contextvars import ContextVarfrom typing import Anyfrom dodaios.core.protocols import BrainMessage, BrainRequest@@ -14,6 +15,10 @@ from .learning import TurnDigestlog = logging.getLogger(__name__)+#: Why the last review attempt in this context could not ask its seat, for the+#: review status record (``review:last:<agent>``). ``""`` = no recorded reason.+_wait_reason: ContextVar[str] = ContextVar("society_review_wait_reason", default="")+# Portions adapted from NousResearch/hermes-agent @ e473f5a# (agent/background_review.py: the skill-update order and the "do not capture"# list), MIT License, Copyright (c) 2025 Nous Research.@@ -71,10 +76,17 @@ async def _ask(runtime: Any, agent: Any, prompt: str) -> dict[str, Any] | None:"""from dodaios.brain.streaming import aggregate- from .seat_brain import SeatUnavailable, agent_brain+ from .seat_brain import SeatDeferred, SeatUnavailable, agent_braintry:brain = await agent_brain(runtime.config(), agent, caller="society-review")+ except SeatDeferred as exc:+ # Unattended work on a per-token key while a subscription is connected+ # (``brain.background_policy``): nothing is billed and the reason is+ # kept for the agent's review status.+ log.info("society review: %s waits (%s)", agent.agent_id, exc)+ _wait_reason.set(str(exc))+ return Noneexcept SeatUnavailable as exc:log.info("society review: %s has no usable seat (%s)", agent.agent_id, exc)return None@@ -113,13 +125,20 @@ async def review_turn(runtime: Any, pending: dict[str, Any]) -> bool:key = f"review:last:{agent_id}"record = {"turn_id": pending["turn_id"], "updated_ms": now_ms(), "state": "reviewing"}await runtime.store.set_meta(key, json.dumps(record))+ reason_token = _wait_reason.set("")try:done = await _review_turn(runtime, pending)except (Exception, asyncio.CancelledError):record.update(state="pending", updated_ms=now_ms())await runtime.store.set_meta(key, json.dumps(record))raise+ else:+ reason = _wait_reason.get()+ finally:+ _wait_reason.reset(reason_token)record.update(state="done" if done else "pending", updated_ms=now_ms())+ if not done and reason:+ record["reason"] = reasonawait runtime.store.set_meta(key, json.dumps(record))return donediff --git a/dodaios/society/routine_runner.py b/dodaios/society/routine_runner.pyindex 17baf022b2..33c6a59e74 100644--- a/dodaios/society/routine_runner.py+++ b/dodaios/society/routine_runner.py@@ -131,6 +131,35 @@ async def _seat_for_run(runtime: Any, agent: Any, task_id: str) -> tuple[str, streturn provider, model, effort, account_id+async def _hold_unattended_run_off_keys(provider: str, account_id: str) -> None:+ """Apply the background billing rule to a run nobody started by hand.++ Once a subscription is connected (``brain.background_policy``), unattended+ work never bills a per-token API key: a scheduled, triggered or webhook run+ whose seat answers through a key is skipped with a readable reason+ (:class:`~dodaios.brain.background_policy.BackgroundDeferred`; the task+ runner records it and a recurring routine fires again at its next+ occurrence). The seat is not swapped for another one: the routine stays+ on its model. A "Run now" click is the person's own start and runs on the+ seat as chosen; an install that never connected a subscription keeps+ billing the seat it picked, so a single-key download still works.+ """+ from dodaios.core.protocols import current_started_by_user++ if current_started_by_user.get() or not _billed_via_api(provider, account_id):+ return+ from dodaios.brain.background_policy import BackgroundDeferred, subscription_mode++ if not await asyncio.to_thread(subscription_mode, (provider,)):+ return+ log.info("routine: skipping an unattended run on the per-token seat %s", provider)+ raise BackgroundDeferred(+ f"A subscription is connected, so this scheduled run did not bill the routine's "+ f"API-key seat ({provider}). Pick a subscription or local model for the routine, "+ "or start it with Run now."+ )++def _run_runtime(agent: Any, provider: str) -> str:"""Which runtime a routine run uses.@@ -181,6 +210,7 @@ async def run_owned_routine(raise RoutineDeferred("Background work is waiting for a subscription or local model on its owner's seat")+ await _hold_unattended_run_off_keys(provider, account_id)permission_mode = "bypass"if autonomous:from .autonomous_routines import ORIGIN_PERMISSION_TAG, ORIGIN_SESSION_TAGdiff --git a/dodaios/society/seat_brain.py b/dodaios/society/seat_brain.pyindex 67748ad292..3045f2eff4 100644--- a/dodaios/society/seat_brain.py+++ b/dodaios/society/seat_brain.py@@ -9,6 +9,13 @@ a chain of other providers and landed on keys nobody chose for that work: oneagent's own key answered 401 and its reviews fell through to an unrelatedper-token key for a month.+The background billing rule (``brain.background_policy``) still applies to+an agent's seat: Society reviews and skill learning are unattended, so once a+subscription is connected an agent whose chat bills a per-token API key does+not have that key billed for its memory work. :func:`agent_brain` raises+:class:`SeatDeferred` instead (and no other seat is asked); on an install+that never connected a subscription the key seat answers as before.+A seat that cannot be resolved, or that fails, raises here and the caller'sown bounded retry applies (the Society review queue, the learning loop'sbackoff); after that the work is dropped. There is no fallback to another@@ -52,9 +59,12 @@ __all__ = ["Seat","SeatBrain","SeatCallFailed",+ "SeatDeferred","SeatUnavailable","agent_brain","agent_seat",+ "bills_per_token",+ "hold_to_background_policy","jarvis_seat","seat_brain",]@@ -70,6 +80,15 @@ class SeatUnavailable(RuntimeError):"""+class SeatDeferred(SeatUnavailable):+ """The seat bills a per-token key and background work may not bill it now.++ Raised for unattended Society work while a subscription is connected+ (``brain.background_policy``). The message is app-authored and names the+ reason, so a status line can show it.+ """++class SeatCallFailed(RuntimeError):"""A call on the seat failed. Carries the exception type, never its text:a provider error body must not reach a log line (AP-34)."""@@ -239,11 +258,53 @@ async def agent_brain(config: Any, agent: Any, *, caller: str) -> SeatBrain:"""A Society agent's own seat as a Brain. Raises ``SeatUnavailable``."""def resolve() -> SeatBrain:- return _build(config, agent_seat(config, agent), caller)+ seat = agent_seat(config, agent)+ hold_to_background_policy(seat)+ return _build(config, seat, caller)return await asyncio.to_thread(resolve)+def bills_per_token(seat: Seat) -> bool:+ """Whether a call on ``seat`` spends a per-token API key.++ A CLI runner answers on its subscription; a keyed runner on a keyless+ local provider (by its provider card or its chat-catalog row) bills+ nothing. Decided from cards and rows, never a provider name (AP-21).+ """+ if not seat.keyed:+ return False+ from dodaios.brain.background_policy import keyless_local++ if keyless_local(seat.provider):+ return False+ try:+ from dodaios.agent_chat.catalog import provider_row+ except Exception: # noqa: BLE001 - without the catalog a keyed seat counts as billed+ return True+ row = provider_row(seat.provider)+ return not (row is not None and bool(getattr(row, "keyless", False)))+++def hold_to_background_policy(seat: Seat) -> None:+ """Refuse a per-token seat for unattended work once a subscription is connected.++ Blocking (the login probe): call it in a thread. Raises+ :class:`SeatDeferred`; returns quietly for a subscription or local seat+ and on an install that never connected a subscription.+ """+ if not bills_per_token(seat):+ return+ from dodaios.brain.background_policy import subscription_mode++ if subscription_mode((seat.provider,)):+ raise SeatDeferred(+ f"a subscription is connected, so background memory work does not bill "+ f"this agent's API key ({seat.provider}); put the agent on a subscription "+ "or local model for it to learn from its chats"+ )++class SeatBrain:"""One seat's brain: every call runs under that seat's credential and iswritten to the usage ledger under ``caller``.diff --git a/dodaios/tasks/runner.py b/dodaios/tasks/runner.pyindex 6a0a8fd0a1..8c2fa28a07 100644--- a/dodaios/tasks/runner.py+++ b/dodaios/tasks/runner.py@@ -619,7 +619,9 @@ class TaskRunner:if self._owned_agent_runner is not None and tags:try:owned_result = await self._owned_agent_runner(task_id, tags, prompt, cancel_token)- except (RoutineDeferred, _Cancelled):+ except (RoutineDeferred, CapacityDeferred, _Cancelled):+ # A deferral started no provider turn: it is recorded as such+ # (a skip), never wrapped into a seat failure.raiseexcept asyncio.CancelledError:raise _Cancelled(diff --git a/tests/unit/society/test_unattended_key_billing.py b/tests/unit/society/test_unattended_key_billing.pynew file mode 100644index 0000000000..c330d5e864--- /dev/null+++ b/tests/unit/society/test_unattended_key_billing.py@@ -0,0 +1,276 @@+"""Unattended Society work never bills a per-token key once a subscription is connected.++The background billing rule (``dodaios.brain.background_policy``): with a+subscription connected, work nobody started by hand runs on subscriptions and+local models only, or waits. Society routines and the post-turn memory work+(review, skill learning) used to bypass it: a routine or an agent pinned to an+API-key seat billed that key while nobody was at the machine. These tests pin+the closed hole and the cases that keep working as before: a "Run now" click,+subscription and local seats, and an install that never connected a+subscription (a single-key download).+"""++from __future__ import annotations++import asyncio+import json+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import pytest++from dodaios.brain import background_policy+from dodaios.brain.background_policy import BackgroundDeferred+from dodaios.control.cancel import CancelToken+from dodaios.core.bus import EventBus+from dodaios.core.protocols import started_by_user+from dodaios.society import routine_runner, seat_brain+from dodaios.society.review import _ask, review_turn+from dodaios.society.runtime import SocietyRuntime+from dodaios.tasks.runner import TaskRunner+from dodaios.tasks.schema import AgentAction, TaskSpec, TriggerEvery+from dodaios.tasks.store import TaskStore+from tests.fakes.fake_seat_registry import RecordingRegistry+++def _connect_a_subscription() -> None:+ """A subscription login was seen: the install is in subscription mode."""+ background_policy.note_connected("claude-cli")+++# ── routines ─────────────────────────────────────────────────────────────────+++class _SessionStarted(Exception):+ """The run got past every billing gate and opened its routine chat."""+++def _routine_runtime() -> SimpleNamespace:+ agent = SimpleNamespace(+ agent_id="scout", state="active", session_id="society:scout", runtime="jarvis",+ provider="gemini", account_id="", name="Scout",+ )++ async def kill_switch() -> bool:+ return False++ async def get(_agent_id: str) -> Any:+ return agent++ def create_session(**_kwargs: Any) -> Any:+ raise _SessionStarted++ service = SimpleNamespace(store=SimpleNamespace(create_session=create_session))+ return SimpleNamespace(+ store=SimpleNamespace(kill_switch=kill_switch),+ roster=SimpleNamespace(get=get),+ chat_service=lambda: service,+ config=lambda: None,+ )+++def routine_seat(monkeypatch: pytest.MonkeyPatch) -> dict[str, bool]:+ """The routine runs on a pinned seat; ``billed`` says whether it is a key."""+ state = {"billed": True}++ async def seat_for_run(runtime: Any, agent: Any, task_id: str) -> tuple[str, str, str, str]:+ return "gemini", "gemini-chosen", "", ""++ monkeypatch.setattr(routine_runner, "_seat_for_run", seat_for_run)+ monkeypatch.setattr(routine_runner, "_workspace", lambda cfg, agent: "workspace")+ monkeypatch.setattr(+ routine_runner, "_billed_via_api", lambda provider, account_id="": state["billed"]+ )+ return state+++async def _run(runtime: SimpleNamespace) -> None:+ await routine_runner.run_owned_routine(+ runtime, "t1", ("society", "agent:scout"), "Check the inbox."+ )+++async def test_a_scheduled_run_on_a_key_seat_is_skipped_once_a_subscription_is_connected(+ routine_seat: dict[str, bool],+) -> None:+ _connect_a_subscription()+ with pytest.raises(BackgroundDeferred) as caught:+ await _run(_routine_runtime()) # no session is opened: nothing was billed+ message = str(caught.value)+ assert "gemini" in message and "Run now" in message+++async def test_run_now_on_a_key_seat_is_the_persons_own_start(+ routine_seat: dict[str, bool],+) -> None:+ _connect_a_subscription()+ with started_by_user(), pytest.raises(_SessionStarted):+ await _run(_routine_runtime())+++async def test_a_key_seat_still_runs_on_an_install_without_a_subscription(+ routine_seat: dict[str, bool],+) -> None:+ with pytest.raises(_SessionStarted):+ await _run(_routine_runtime())+++async def test_a_subscription_or_local_seat_runs_unattended(+ routine_seat: dict[str, bool],+) -> None:+ _connect_a_subscription()+ routine_seat["billed"] = False+ with pytest.raises(_SessionStarted):+ await _run(_routine_runtime())+++async def task_store(tmp_path: Path):+ store = TaskStore(tmp_path / "runner.db")+ await store.init()+ try:+ yield store+ finally:+ await store.close()+++async def test_the_task_runner_records_a_routine_deferral_as_a_skip(+ task_store: TaskStore,+) -> None:+ """The deferral is not wrapped into a "seat failed" error: no seat was asked."""++ async def owned_runner(task_id: str, tags: tuple[str, ...], prompt: str, cancel: Any) -> str:+ raise BackgroundDeferred("A subscription is connected, so this run did not bill a key.")++ delivered: list[tuple[tuple[str, ...], str, str]] = []++ async def sink(tags: tuple[str, ...], text: str, status: str) -> None:+ delivered.append((tags, text, status))++ runner = TaskRunner(task_store, EventBus(), owned_agent_runner=owned_runner, result_sink=sink)+ task_id = await task_store.insert(+ TaskSpec(+ title="[agent:Scout] Inbox sweep",+ trigger=TriggerEvery(interval_seconds=86400),+ action=AgentAction(prompt="Sort the inbox."),+ tags=("society", "agent:scout"),+ )+ )+ await asyncio.wait_for(runner.run(task_id, CancelToken()), timeout=2.0)++ row = await task_store.get(task_id)+ assert row is not None and row["state"] == "scheduled"+ assert "did not bill a key" in (row["last_error"] or "")+ assert "not rerouted" not in (row["last_error"] or "")+ events = [step["payload"] for step in row["steps"]]+ assert any(e.get("event") == "skipped" and e.get("reason") == "waiting_capacity"+ for e in events)+ assert not any(e.get("event") == "owner_seat_failed" for e in events)+ assert delivered and "did not bill a key" in delivered[0][1]+++# ── post-turn review and skill learning ──────────────────────────────────────+++def registry(monkeypatch: pytest.MonkeyPatch) -> RecordingRegistry:+ from dodaios.brain import resolver+ from dodaios.core import config, runtime_refs++ reg = RecordingRegistry(["gemini", "openai", "codex", "claude-cli", "ollama"])+ monkeypatch.setattr(resolver, "_get_registry", lambda: reg)+ monkeypatch.setattr(config, "get_jarvis_agent_secret", lambda provider: f"agent-key-{provider}")+ monkeypatch.setattr(runtime_refs, "get_brain_manager", lambda: None)+ return reg+++def _agent(provider: str, model: str = "") -> SimpleNamespace:+ return SimpleNamespace(+ provider=provider, model=model, effort="", agent_id="scout", account_id=""+ )+++def _review_runtime() -> SimpleNamespace:+ return SimpleNamespace(config=lambda: None, skills_for=lambda agent_id: None)+++async def test_a_review_does_not_bill_the_agents_key_once_a_subscription_is_connected(+ registry: RecordingRegistry,+) -> None:+ _connect_a_subscription()+ assert await _ask(_review_runtime(), _agent("gemini", "gemini-chosen"), "Evidence") is None+ assert registry.built == [] # nothing was built, so nothing could bill+++async def test_skill_learning_refuses_a_key_seat_the_same_way(+ registry: RecordingRegistry,+) -> None:+ _connect_a_subscription()+ with pytest.raises(seat_brain.SeatDeferred):+ await seat_brain.agent_brain(+ None, _agent("gemini", "gemini-chosen"), caller="society-skill"+ )+ assert registry.built == []+++async def test_a_review_on_a_key_seat_still_runs_without_a_subscription(+ registry: RecordingRegistry,+) -> None:+ assert await _ask(_review_runtime(), _agent("gemini", "gemini-chosen"), "Evidence") == {+ "memories": [], "skill": None,+ }+ assert registry.built_names() == ["gemini"]++[email protected](("provider", "built"), [("openai-codex", "codex"), ("ollama", "ollama")])+async def test_subscription_and_local_seats_keep_reviewing(+ registry: RecordingRegistry, provider: str, built: str+) -> None:+ _connect_a_subscription()+ await _ask(_review_runtime(), _agent(provider, "chosen"), "Evidence")+ assert registry.built_names() == [built]+++def test_the_seat_billing_check_follows_the_runner_not_the_name() -> None:+ assert seat_brain.bills_per_token(seat_brain.Seat("gemini", runner="brain"))+ # A per-token provider card reached through its CLI runs on the subscription.+ assert not seat_brain.bills_per_token(seat_brain.Seat("openai-codex", runner="codex-cli"))+ # A keyless local runtime behind a brain plugin bills nothing.+ assert not seat_brain.bills_per_token(seat_brain.Seat("ollama", runner="brain"))+++async def society(tmp_path: Path):+ cfg = SimpleNamespace(wiki=SimpleNamespace(vault_root=str(tmp_path / "vault")))+ runtime = SocietyRuntime(tmp_path, cfg=lambda: cfg, seed_starter_team=False)+ await runtime.ensure_started()+ await runtime.roster.create(name="Scout", description="Draft only.")+ try:+ yield runtime+ finally:+ await runtime.close()+++async def test_a_deferred_review_stays_pending_with_a_reason_the_ui_can_show(+ society: SocietyRuntime, monkeypatch: pytest.MonkeyPatch+) -> None:+ async def deferred(config: Any, agent: Any, *, caller: str) -> Any:+ raise seat_brain.SeatDeferred("a subscription is connected; the key is not billed")++ monkeypatch.setattr(seat_brain, "agent_brain", deferred)+ pending = {+ "session": "society:scout",+ "turn_id": "turn-1",+ "direct_user": True,+ "events": [+ {"kind": "user_message", "payload": {"text": "Check the dates."}},+ {"kind": "assistant_text", "payload": {"text": "Done."}},+ {"kind": "turn_finished", "payload": {"status": "done"}},+ ],+ }+ assert not await review_turn(society, pending)+ record = json.loads(await society.store.get_meta("review:last:scout"))+ assert record["state"] == "pending"+ assert record["reason"] == "a subscription is connected; the key is not billed"