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(missions): explicit per-mission approval for paid API use
Dennis Heide de Ramirez76a91741bf6a
diff --git a/jarvis/missions/capacity.py b/jarvis/missions/capacity.pyindex 7e4627f609..8adc0dcaf9 100644--- a/jarvis/missions/capacity.py+++ b/jarvis/missions/capacity.py@@ -28,12 +28,16 @@ import osimport randomimport tempfilefrom collections.abc import Awaitable, Callable+from dataclasses import dataclassfrom pathlib import Path-from typing import Any, Literal+from typing import Any, Literal, Protocollog = logging.getLogger(__name__)-CapacityWaitReason = Literal["provider_quota", "provider_auth", "provider_unavailable"]+CapacityWaitReason = Literal[+ "provider_quota", "provider_auth", "provider_unavailable", "paid_cap_reached"+]+CapacityDecision = Literal["wait", "approve_paid", "cancel"]#: Written into ``<mission_dir>/`` when a mission is parked. Its presence also#: keeps the mission directory out of the age-based cleanup sweep.@@ -51,6 +55,62 @@ RESUME_INTERVAL_S = 300.0#: (AP-33).RESUME_JITTER_S = 60.0+#: Hard spend ceiling of ONE approved paid run (user decision 2026-10-04: $2+#: per mission on an approved API key). Reaching it parks the mission again.+PAID_MISSION_CAP_USD = 2.0++#: Token volume assumed per open step for the up-front estimate. Deliberately+#: generous: a worker re-reads its workspace every turn, and one trivial+#: mission once used 1.3M input tokens exploring a repository.+ESTIMATE_INPUT_TOKENS_PER_STEP = 400_000+ESTIMATE_OUTPUT_TOKENS_PER_STEP = 30_000+++@dataclass(frozen=True)+class PaidOffer:+ """What the user is asked to approve before any paid API use: which+ provider and model, what it will roughly cost, the hard cap, and why."""++ provider: str+ model: str+ estimated_cost_usd: float+ cost_cap_usd: float+ reason: str+ open_steps: int+++class PaidOption(Protocol):+ """Builds the paid alternative for a parked mission (wired in+ ``jarvis.missions.init``). ``offer`` never calls a provider."""++ def offer(self, *, pinned_family: str | None, open_steps: int, reason: str) -> PaidOffer | None:+ ...++ def worker(self, offer: PaidOffer, *, remaining_usd: float, task_text: str) -> Any:+ ...+++def estimate_paid_cost_usd(model: str, open_steps: int) -> float | None:+ """Rough USD for ``open_steps`` steps on ``model``, or None when the model+ has no known price — an unpriced model is never offered for paid use,+ because neither the estimate nor the cap could be trusted."""+ from jarvis.brain.cost import resolve_rates++ rates = resolve_rates(model)+ if rates is None or rates == (0.0, 0.0):+ return None+ rate_in, rate_out = rates+ steps = max(open_steps, 1)+ return round(+ steps+ * (+ ESTIMATE_INPUT_TOKENS_PER_STEP * rate_in+ + ESTIMATE_OUTPUT_TOKENS_PER_STEP * rate_out+ )+ / 1_000_000,+ 4,+ )+class WorkerCapacityUnavailable(RuntimeError):"""Raised by the worker factory instead of picking a worker that would bill@@ -68,6 +128,12 @@ class WorkerCapacityUnavailable(RuntimeError):self.detail = detail+class CapacityDecisionRejected(RuntimeError):+ """A capacity decision that cannot apply: the mission is no longer+ parked, there is no paid option, or the option changed since it was+ shown. Nothing was decided or billed."""++def pinned_to_subscription(*, configured_is_subscription: bool) -> bool:"""Whether this mission must stay on its configured worker.@@ -159,11 +225,19 @@ async def capacity_resume_loop(__all__ = ["CHECKPOINT_NAME","CHECKPOINT_VERSION",+ "ESTIMATE_INPUT_TOKENS_PER_STEP",+ "ESTIMATE_OUTPUT_TOKENS_PER_STEP",+ "PAID_MISSION_CAP_USD","RESUME_INTERVAL_S","RESUME_JITTER_S",+ "CapacityDecision",+ "CapacityDecisionRejected","CapacityWaitReason",+ "PaidOffer",+ "PaidOption","WorkerCapacityUnavailable","capacity_resume_loop",+ "estimate_paid_cost_usd","pinned_to_subscription","read_checkpoint","worker_family",diff --git a/jarvis/missions/events.py b/jarvis/missions/events.pyindex 40b1878e52..1037127717 100644--- a/jarvis/missions/events.py+++ b/jarvis/missions/events.py@@ -163,6 +163,7 @@ CAPACITY_WAIT_REASONS: Final[frozenset[str]] = frozenset({"provider_quota", # usage/session window or credit spent"provider_auth", # subscription login expired"provider_unavailable", # the worker cannot run without a paid fallback+ "paid_cap_reached", # an approved paid run hit its spend ceiling})@@ -174,7 +175,9 @@ class MissionWaitingCapacity(_PayloadBase):"""event_type: Literal["MissionWaitingCapacity"] = "MissionWaitingCapacity"- reason: Literal["provider_quota", "provider_auth", "provider_unavailable"]+ reason: Literal[+ "provider_quota", "provider_auth", "provider_unavailable", "paid_cap_reached"+ ]provider: str | None = Nonesteps_done: int = 0steps_total: int = 0@@ -188,6 +191,31 @@ class MissionWaitingCapacity(_PayloadBase):repeat: bool = False+class MissionCapacityDecision(_PayloadBase):+ """The user's answer to a parked mission's paid-API offer — the audit+ record of exactly what was shown and decided. An approval covers this one+ mission and this one run, never anything else."""++ event_type: Literal["MissionCapacityDecision"] = "MissionCapacityDecision"+ decision: Literal["wait", "approve_paid", "cancel"]+ provider: str | None = None+ model: str | None = None+ estimated_cost_usd: float | None = None+ cost_cap_usd: float | None = None+ reason: str = ""+++class MissionPaidUsage(_PayloadBase):+ """What an approved paid run actually cost, logged when the run ends."""++ event_type: Literal["MissionPaidUsage"] = "MissionPaidUsage"+ provider: str+ model: str+ cost_usd: float+ cost_cap_usd: float+ estimated_cost_usd: float++class MissionCancelled(_PayloadBase):event_type: Literal["MissionCancelled"] = "MissionCancelled"cascade: bool = False@@ -242,7 +270,9 @@ Payload = Annotated[| MissionStateChanged| BusStats| MissionBudgetWarning- | MissionWaitingCapacity,+ | MissionWaitingCapacity+ | MissionCapacityDecision+ | MissionPaidUsage,Field(discriminator="event_type"),]diff --git a/jarvis/missions/init.py b/jarvis/missions/init.pyindex 84d3b172aa..8772d19928 100644--- a/jarvis/missions/init.py+++ b/jarvis/missions/init.py@@ -34,7 +34,13 @@ from typing import Anyfrom jarvis.core.bus import EventBus as _SpeechEventBusfrom .budget import BudgetTracker-from .capacity import WorkerCapacityUnavailable, pinned_to_subscription+from .capacity import (+ PAID_MISSION_CAP_USD,+ PaidOffer,+ WorkerCapacityUnavailable,+ estimate_paid_cost_usd,+ pinned_to_subscription,+)from .cleanup import daily_cleanup_task, startup_sweepfrom .critic.runner import CriticRunnerfrom .event_bus import MissionBus@@ -789,6 +795,71 @@ def _pinned_codex_worker(capability_inventory: WorkerCapabilityInventory | None)return CodexDirectWorker(capability_inventory=capability_inventory, backend_fallback=False)+# The API-key family of the same vendor as a subscription worker: the paid+# alternative offered first for a mission parked on that subscription.+_PAID_FAMILY_FOR_SUBSCRIPTION: dict[str, str] = {+ "claude": "claude-api",+ "codex": "openai",+ "antigravity": "gemini",+ "gemini": "gemini",+ "grok-build": "grok",+}+_PAID_FAMILY_ORDER: tuple[str, ...] = (+ "claude-api", "gemini", "openrouter", "openai", "grok", "nvidia",+)+++class ApiKeyPaidOption:+ """The paid alternative for a parked mission: the in-process API worker+ on one of the user's own keys. Offered, never used, until the user+ approves it for one mission (jarvis/missions/capacity.py).++ The same vendor's key comes first; a model without a known price is never+ offered, since neither its estimate nor the cost cap could be trusted.+ Reads keys and config only — never calls a provider.+ """++ def offer(+ self, *, pinned_family: str | None, open_steps: int, reason: str+ ) -> PaidOffer | None:+ from jarvis.missions.workers.api_agent_worker import (+ _resolve_worker_model,+ supports_api_agent_worker,+ )++ preferred = _PAID_FAMILY_FOR_SUBSCRIPTION.get(pinned_family or "")+ order = dict.fromkeys(p for p in (preferred, *_PAID_FAMILY_ORDER) if p)+ # A mission parked on an API key gets a DIFFERENT key, not the one+ # that just ran out.+ order.pop(pinned_family or "", None)+ for provider in order:+ if not supports_api_agent_worker(provider):+ continue+ if not _api_key_family_viable(provider):+ continue+ model = _resolve_worker_model(provider, "")+ estimate = estimate_paid_cost_usd(model, open_steps)+ if estimate is None:+ continue+ return PaidOffer(+ provider=provider,+ model=model,+ estimated_cost_usd=estimate,+ cost_cap_usd=PAID_MISSION_CAP_USD,+ reason=reason,+ open_steps=open_steps,+ )+ return None++ def worker(self, offer: PaidOffer, *, remaining_usd: float, task_text: str) -> Any:+ return ApiAgentWorker(+ offer.provider,+ capability_inventory=_assemble_worker_capability_inventory(task_text),+ pinned_model=offer.model,+ cost_cap_usd=max(remaining_usd, 0.0),+ )++def _resolve_api_agent_worker(provider: str,task_text: str,@@ -1412,6 +1483,7 @@ async def bootstrap_missions(max_workers=max_workers,safety_enabled=safety_enabled,extra_blocked_globs=extra_blocked_globs,+ paid_option=ApiKeyPaidOption(),)# 8. VoiceListener / Announcer — mutually exclusive (2026-05-27 findingdiff --git a/jarvis/missions/kontrollierer/orchestrator.py b/jarvis/missions/kontrollierer/orchestrator.pyindex b898af9afa..b99a419456 100644--- a/jarvis/missions/kontrollierer/orchestrator.py+++ b/jarvis/missions/kontrollierer/orchestrator.py@@ -32,12 +32,17 @@ import threadingimport timefrom collections.abc import Callablefrom contextlib import suppress+from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Final, Literalfrom ...core.process_utils import NO_WINDOW_CREATIONFLAGSfrom ..budget import BudgetExceeded, BudgetTrackerfrom ..capacity import (+ CapacityDecision,+ CapacityDecisionRejected,+ PaidOffer,+ PaidOption,WorkerCapacityUnavailable,read_checkpoint,worker_family,@@ -58,7 +63,9 @@ from ..events import (EventEnvelope,MissionApproved,MissionCancelled,+ MissionCapacityDecision,MissionFailed,+ MissionPaidUsage,MissionPlanReady,MissionWaitingCapacity,WorkerCorrectionRequired,@@ -408,6 +415,17 @@ def _real_diff_is_empty(diff_text: str) -> bool:_EXTERNAL_VERIFY_MAX_CHARS: Final[int] = 8000+@dataclass(frozen=True)+class _ResumeClaim:+ """A parked mission this caller moved to RUNNING, ready to continue."""++ prompt: str+ plan: MissionPlan+ done: frozenset[str]+ restore_dirs: dict[str, Path]+ checkpoint: dict[str, Any]++def _plan_from_checkpoint(checkpoint: dict[str, Any] | None) -> MissionPlan | None:"""The plan a parked mission was running, or None if the checkpoint has none."""raw = checkpoint.get("plan") if checkpoint else None@@ -840,8 +858,13 @@ class Kontrollierer:# Phase-5 safety hooks (all optional — None = no-op):safety_enabled: bool = True,extra_blocked_globs: tuple[str, ...] = (),+ # The paid-API alternative offered for a parked mission (None = no+ # offer is ever made). Used only after the user approves it for one+ # mission — see `decide_capacity`.+ paid_option: PaidOption | None = None,) -> None:self._manager = manager+ self._paid_option = paid_optionself._decomposer = decomposerself._runner = critic_runnerself._worktrees = worktree_mgr@@ -890,6 +913,14 @@ class Kontrollierer:self._resume_family: dict[str, str] = {}self._resume_attempt: dict[str, int] = {}self._resume_done_before: dict[str, int] = {}+ # Approved paid runs: the exact offer the user accepted, and what the+ # run has spent so far. In memory on purpose — an approval covers one+ # run of one mission and dies with it (or with the process).+ self._paid_approval: dict[str, PaidOffer] = {}+ self._paid_spent: dict[str, float] = {}+ # Paid runs started by an approval; referenced so they are not+ # garbage-collected mid-flight.+ self._background_runs: set[asyncio.Task[Any]] = set()# Per-mission worker answers for read-only/informational tasks (empty# diff + tool evidence). Surfaced as MissionApproved.summary_de so the# voice readback speaks the actual answer instead of "Mission@@ -1498,8 +1529,7 @@ class Kontrollierer:# Worker spawn (real or fake depending on the factory). A factory# that refuses to switch to a billing fallback parks the task.try:- worker = self._worker_factory(step)- self._check_resume_family(mission_id, worker)+ worker = self._make_worker(mission_id, step)except WorkerCapacityUnavailable as exc:logger.warning("Task %s iter %d: no worker capacity (%s) — parking the "@@ -1543,6 +1573,29 @@ class Kontrollierer:return TaskOutcome.ERRORcontinue+ approval = self._paid_approval.get(mission_id)+ if approval is not None:+ spent = self._paid_spent.get(mission_id, 0.0) + float(+ spawn_result.cost_usd or 0.0+ )+ self._paid_spent[mission_id] = spent+ if spent >= approval.cost_cap_usd:+ # The approved ceiling is hard: stop before the critic and+ # park; the work so far is archived with the checkpoint.+ logger.warning(+ "Task %s iter %d: approved paid run reached its cap "+ "($%.4f of $%.2f) — parking the mission",+ step.task_id, iteration, spent, approval.cost_cap_usd,+ )+ self._capacity_wait[mission_id] = {+ "reason": "paid_cap_reached",+ "provider": approval.provider,+ "error_detail": None,+ }+ # No iteration diff recorded: the task's final archive+ # falls back to a fresh diff of the worktree.+ return TaskOutcome.WAITING_CAPACITY+# git add/diff/ls-files over the whole worktree: off the loop.diff_text = await asyncio.to_thread(self._capture_diff, worktree)log_text = self._read_stream_log(log_dir)@@ -3072,24 +3125,23 @@ class Kontrollierer:in ``_running_missions`` like ``run_mission`` so cancel and shutdownreach it."""+ claim = await self._claim_resume(mission_id)+ if isinstance(claim, MissionState):+ return claim+ return await self._run_claimed_resume(mission_id, claim, paid=None)++ async def _claim_resume(self, mission_id: str) -> _ResumeClaim | MissionState:+ """Take a parked mission out of WAITING_CAPACITY for exactly one run.++ Returns the claim, or the mission's current state when it is not+ resumable by this caller (not parked, already running here, or its+ checkpoint is unusable — then it is failed honestly).+ """if mission_id in self._running_missions:- # Already running here (a resume or a run) — that caller owns the- # mission and its tracking; a second resume must not touch either.+ # Already running here — that caller owns the mission and its+ # tracking; a second resume must not touch either.view = await self._manager.mission(mission_id)return view.state if view is not None else MissionState.FAILED- task = asyncio.current_task()- if task is not None:- self._running_missions[mission_id] = task- try:- return await self._resume_mission_inner(mission_id)- finally:- if self._running_missions.get(mission_id) is task:- self._running_missions.pop(mission_id, None)- self._resume_family.pop(mission_id, None)- self._resume_attempt.pop(mission_id, None)- self._resume_done_before.pop(mission_id, None)-- async def _resume_mission_inner(self, mission_id: str) -> MissionState:view = await self._manager.mission(mission_id)if view is None:raise KeyError(f"Mission not found: {mission_id}")@@ -3131,30 +3183,232 @@ class Kontrollierer:await self._manager.store.touch_heartbeat(mission_id, now_ms())except Exception as hb_exc: # noqa: BLE001 - ownership stamp is advisorylogger.debug("Resume heartbeat failed (non-fatal): %s", hb_exc)+ return _ResumeClaim(+ prompt=view.prompt,+ plan=plan,+ done=frozenset(done),+ restore_dirs=restore_dirs,+ checkpoint=checkpoint,+ )++ async def _run_claimed_resume(+ self, mission_id: str, claim: _ResumeClaim, *, paid: PaidOffer | None+ ) -> MissionState:+ """Run a claimed mission's open steps. ``paid`` is the offer the user+ approved for this one run; it exists only inside this call."""+ task = asyncio.current_task()+ if task is not None:+ self._running_missions[mission_id] = task+ try:+ checkpoint = claim.checkpoint+ pinned = checkpoint.get("provider")+ if isinstance(pinned, str) and pinned:+ self._resume_family[mission_id] = pinned+ attempts = checkpoint.get("resume_attempts")+ self._resume_attempt[mission_id] = (+ attempts if isinstance(attempts, int) else 0+ ) + 1+ self._resume_done_before[mission_id] = len(claim.done)+ answers = checkpoint.get("task_answers")+ if isinstance(answers, list) and answers:+ self._task_answers[mission_id] = [str(a) for a in answers]+ if paid is not None:+ self._paid_approval[mission_id] = paid+ self._paid_spent[mission_id] = 0.0++ logger.info(+ "resume_mission: %s resumes on %s — %d/%d step(s) already done, "+ "%d with partial work to restore (attempt %d)",+ mission_id,+ f"{paid.provider}/{paid.model} (approved paid run)" if paid else pinned,+ len(claim.done), len(claim.plan.steps), len(claim.restore_dirs),+ self._resume_attempt[mission_id],+ )+ try:+ return await self._execute_plan(+ mission_id,+ claim.prompt,+ claim.plan,+ done_task_ids=claim.done,+ restore_dirs=claim.restore_dirs,+ )+ finally:+ await self._record_paid_usage(mission_id)+ finally:+ if self._running_missions.get(mission_id) is task:+ self._running_missions.pop(mission_id, None)+ self._resume_family.pop(mission_id, None)+ self._resume_attempt.pop(mission_id, None)+ self._resume_done_before.pop(mission_id, None)+ self._paid_approval.pop(mission_id, None)+ self._paid_spent.pop(mission_id, None)++ # --- Paid-API approval ---------------------------------------------------++ async def paid_offer(self, mission_id: str) -> PaidOffer | None:+ """The paid alternative for a parked mission, or None.+ Computed fresh on every call and never stored: an offer is only what+ the user is looking at right now. No provider is called.+ """+ if self._paid_option is None:+ return None+ view = await self._manager.mission(mission_id)+ if view is None or view.state != MissionState.WAITING_CAPACITY:+ return None+ mission_dir = self._isolation_root / f"mission_{mission_id[:13]}"+ checkpoint = await asyncio.to_thread(read_checkpoint, mission_dir)+ plan = _plan_from_checkpoint(checkpoint)+ if checkpoint is None or plan is None:+ return None+ open_steps = len(plan.steps) - len(_done_task_ids(checkpoint))pinned = checkpoint.get("provider")- if isinstance(pinned, str) and pinned:- self._resume_family[mission_id] = pinned- attempts = checkpoint.get("resume_attempts")- self._resume_attempt[mission_id] = (attempts if isinstance(attempts, int) else 0) + 1- self._resume_done_before[mission_id] = len(done)- answers = checkpoint.get("task_answers")- if isinstance(answers, list) and answers:- self._task_answers[mission_id] = [str(a) for a in answers]+ reason = checkpoint.get("reason")+ return await asyncio.to_thread(+ self._paid_option.offer,+ pinned_family=pinned if isinstance(pinned, str) else None,+ open_steps=max(open_steps, 1),+ reason=reason if isinstance(reason, str) else "provider_quota",+ )++ async def decide_capacity(+ self,+ mission_id: str,+ decision: CapacityDecision,+ *,+ provider: str | None = None,+ model: str | None = None,+ ) -> MissionState:+ """Apply the user's answer to a parked mission's paid-API offer.+ - ``wait``: logged; the mission stays parked and keeps waiting for its+ own subscription.+ - ``cancel``: logged; the mission is cancelled, its work stays saved.+ - ``approve_paid``: only for the offer the user saw — ``provider`` and+ ``model`` must match the current offer, or nothing happens. The+ approval covers this one run of this one mission; it is never+ stored, and reaching the cost cap parks the mission again.++ Raises :class:`CapacityDecisionRejected` when the decision cannot apply.+ """+ view = await self._manager.mission(mission_id)+ if view is None:+ raise KeyError(f"Mission not found: {mission_id}")+ if view.state != MissionState.WAITING_CAPACITY:+ raise CapacityDecisionRejected(+ f"mission is {view.state.value}, not waiting for capacity"+ )+ offer = await self.paid_offer(mission_id)+ if decision == "approve_paid":+ if offer is None:+ raise CapacityDecisionRejected("no paid option is available for this mission")+ if (provider, model) != (offer.provider, offer.model):+ raise CapacityDecisionRejected(+ "the paid option changed since it was shown; review it again"+ )+ mission_dir = self._isolation_root / f"mission_{mission_id[:13]}"+ checkpoint = await asyncio.to_thread(read_checkpoint, mission_dir) or {}+ reason = checkpoint.get("reason")+ await self._manager.store.append_and_publish(+ EventEnvelope(+ mission_id=mission_id,+ source_actor="ui",+ ts_ms=now_ms(),+ payload=MissionCapacityDecision(+ decision=decision,+ provider=offer.provider if offer else None,+ model=offer.model if offer else None,+ estimated_cost_usd=offer.estimated_cost_usd if offer else None,+ cost_cap_usd=offer.cost_cap_usd if offer else None,+ reason=reason if isinstance(reason, str) else "",+ ),+ )+ )logger.info(- "resume_mission: %s resumes on %s — %d/%d step(s) already done, "- "%d with partial work to restore (attempt %d)",- mission_id, pinned or "<unknown>", len(done), len(plan.steps),- len(restore_dirs), self._resume_attempt[mission_id],+ "Mission %s capacity decision: %s (offer=%s)", mission_id, decision,+ f"{offer.provider}/{offer.model} est=${offer.estimated_cost_usd:.2f} "+ f"cap=${offer.cost_cap_usd:.2f}" if offer else "none",)- return await self._execute_plan(- mission_id,- view.prompt,- plan,- done_task_ids=frozenset(done),- restore_dirs=restore_dirs,+ if decision == "wait":+ return MissionState.WAITING_CAPACITY+ if decision == "cancel":+ if not await self._safe_transition(+ mission_id, MissionState.CANCELLED, "ui_cancel"+ ):+ current = await self._manager.mission(mission_id)+ return current.state if current is not None else MissionState.FAILED+ await self._manager.store.append_and_publish(+ EventEnvelope(+ mission_id=mission_id,+ source_actor="ui",+ ts_ms=now_ms(),+ payload=MissionCancelled(cascade=False, reason="ui_cancel"),+ )+ )+ return MissionState.CANCELLED++ assert offer is not None # approve_paid was validated above+ claim = await self._claim_resume(mission_id)+ if isinstance(claim, MissionState):+ return claim+ run = asyncio.create_task(+ self._run_claimed_resume(mission_id, claim, paid=offer),+ name=f"mission-paid-resume-{mission_id[:13]}",)+ self._background_runs.add(run)+ run.add_done_callback(self._background_runs.discard)+ return MissionState.RUNNING++ def _make_worker(self, mission_id: str, step: Step) -> Any:+ """The worker for one iteration. An approved paid run uses exactly the+ approved provider and model, within what is left of its cost cap;+ anything else goes through the factory and its capacity rules."""+ approval = self._paid_approval.get(mission_id)+ if approval is None:+ worker = self._worker_factory(step)+ self._check_resume_family(mission_id, worker)+ return worker+ spent = self._paid_spent.get(mission_id, 0.0)+ if spent >= approval.cost_cap_usd:+ raise WorkerCapacityUnavailable(+ "paid_cap_reached",+ approval.provider,+ f"spent ${spent:.2f} of the approved ${approval.cost_cap_usd:.2f}",+ )+ if self._paid_option is None:+ raise WorkerCapacityUnavailable("provider_unavailable", approval.provider)+ return self._paid_option.worker(+ approval, remaining_usd=approval.cost_cap_usd - spent, task_text=step.prompt+ )++ async def _record_paid_usage(self, mission_id: str) -> None:+ """Log what an approved paid run actually cost (event + log line)."""+ approval = self._paid_approval.get(mission_id)+ if approval is None:+ return+ spent = round(self._paid_spent.get(mission_id, 0.0), 6)+ logger.info(+ "Mission %s paid run on %s/%s cost $%.4f (estimate $%.2f, cap $%.2f)",+ mission_id, approval.provider, approval.model, spent,+ approval.estimated_cost_usd, approval.cost_cap_usd,+ )+ try:+ await self._manager.store.append_and_publish(+ EventEnvelope(+ mission_id=mission_id,+ source_actor="kontrollierer",+ ts_ms=now_ms(),+ payload=MissionPaidUsage(+ provider=approval.provider,+ model=approval.model,+ cost_usd=spent,+ cost_cap_usd=approval.cost_cap_usd,+ estimated_cost_usd=approval.estimated_cost_usd,+ ),+ )+ )+ except Exception: # noqa: BLE001 - the log line above still records it+ logger.exception("Mission %s: paid-usage event could not be stored", mission_id)def _check_resume_family(self, mission_id: str, worker: Any) -> None:"""A resumed mission runs only on the provider family it was parked@@ -3280,7 +3534,10 @@ class Kontrollierer:"mission_id": mission_id,"prompt": prompt,"reason": reason,- "provider": provider,+ # The family the mission waits for. A paid run that parks+ # again keeps waiting for its original subscription — never+ # for the paid key, which needs a fresh approval.+ "provider": self._resume_family.get(mission_id) or provider,"error_detail": error_detail,"created_ms": now_ms(),"resume_attempts": attempt,diff --git a/jarvis/missions/voice/readback.py b/jarvis/missions/voice/readback.pyindex 545e237182..12ebcd04bb 100644--- a/jarvis/missions/voice/readback.py+++ b/jarvis/missions/voice/readback.py@@ -320,6 +320,9 @@ CAPACITY_WAIT_PHRASES: Final[dict[str, dict[str, str]]] = {"provider_quota": "{provider}-Kapazität momentan ausgeschöpft.", # i18n-allow"provider_auth": "Die {provider}-Anmeldung ist abgelaufen.", # i18n-allow"provider_unavailable": "{provider} ist momentan nicht nutzbar.", # i18n-allow+ "paid_cap_reached": (+ "Die freigegebene Kostengrenze für {provider} ist erreicht." # i18n-allow+ ),"saved": "Der bisherige Stand wurde gesichert.", # i18n-allow"progress": "{done} von {total} Teilschritten erledigt, {open} offen.", # i18n-allow"progress_single": "Die Aufgabe selbst ist noch offen.", # i18n-allow@@ -328,13 +331,15 @@ CAPACITY_WAIT_PHRASES: Final[dict[str, dict[str, str]]] = {"wait": "Die Mission wartet, bis wieder Kapazität verfügbar ist.", # i18n-allow"wait_auth": "Die Mission wartet, bis du dich wieder anmeldest.", # i18n-allow"paid": (- "Kostenpflichtige API-Nutzung nur mit deiner ausdrücklichen Freigabe." # i18n-allow+ "Kostenpflichtige API-Nutzung nur mit deiner ausdrücklichen " # i18n-allow+ "Freigabe in der Missionsansicht." # i18n-allow),},"en": {"provider_quota": "{provider} capacity is used up for now.","provider_auth": "The {provider} sign-in has expired.","provider_unavailable": "{provider} cannot be used right now.",+ "paid_cap_reached": "The approved cost limit for {provider} is reached.","saved": "The progress so far has been saved.","progress": "{done} of {total} steps done, {open} open.","progress_single": "The task itself is still open.",@@ -342,7 +347,7 @@ CAPACITY_WAIT_PHRASES: Final[dict[str, dict[str, str]]] = {"files": "{files} files saved.","wait": "The mission is waiting until capacity is available again.","wait_auth": "The mission is waiting until you sign in again.",- "paid": "Paid API use only with your explicit approval.",+ "paid": "Paid API use only with your explicit approval in the Missions view.",},}diff --git a/jarvis/missions/workers/api_agent_worker.py b/jarvis/missions/workers/api_agent_worker.pyindex b3530c5498..0288917d3b 100644--- a/jarvis/missions/workers/api_agent_worker.py+++ b/jarvis/missions/workers/api_agent_worker.py@@ -140,6 +140,23 @@ _DEFAULT_MODEL: dict[str, str] = {_DEFAULT_MODEL["vertex"] = _DEFAULT_MODEL["gemini"]+class _CostCapReached(RuntimeError):+ """An approved paid run spent its ceiling; the loop stops right here."""+++def _usage_cost_usd(model: str, usage: dict[str, int]) -> float:+ """USD for one call's usage block (canonical keys: uncached input,+ output, cache hits)."""+ from jarvis.brain.cost import calculate_cost_usd++ return calculate_cost_usd(+ model,+ int(usage.get("input_tokens") or 0),+ int(usage.get("output_tokens") or 0),+ int(usage.get("cache_hit_tokens") or 0),+ )++def _resolve_worker_model(provider: str, explicit: str) -> str:"""Model for the in-process API worker, honoring the user's PICK.@@ -243,8 +260,16 @@ class ApiAgentWorker:provider: str,*,capability_inventory: WorkerCapabilityInventory | None = None,+ pinned_model: str = "",+ cost_cap_usd: float | None = None,) -> None:self.provider = (provider or "").strip().lower()+ # The exact model a user approved for paid use on this mission+ # (jarvis/missions/capacity.py). Wins over every other model source.+ self.pinned_model = (pinned_model or "").strip()+ # Hard spend ceiling of an approved paid run: the loop stops after the+ # call that reaches it. None = no ceiling (the user's own key choice).+ self.cost_cap_usd = cost_cap_usdself.last_pid: int | None = Noneself.last_session_id: str | None = Noneself.capability_inventory = capability_inventory or WorkerCapabilityInventory.build()@@ -317,7 +342,7 @@ class ApiAgentWorker:session_id = str(uuid.uuid4())self.last_pid = Noneself.last_session_id = session_id- resolved_model = _resolve_worker_model(self.provider, model)+ resolved_model = _resolve_worker_model(self.provider, self.pinned_model or model)log_dir.mkdir(parents=True, exist_ok=True) # noqa: ASYNC240 — trivial sync mkdir (mirrors sibling workers)stream_path = log_dir / "stream.jsonl"# The orchestrator reuses one log directory across critic iterations.@@ -326,6 +351,9 @@ class ApiAgentWorker:with suppress(OSError):stream_path.write_text("", encoding="utf-8")written: list[str] = []+ # What this spawn cost, from the usage each call reports — carried on+ # the terminal result so a paid mission can log its real spend.+ spent_usd = 0.0broker_specs = broker_binding.tool_specs if broker_binding is not None else ()local_names = {str(spec["name"]) for spec in WORKER_TOOL_SPECS}all_tool_specs = WORKER_TOOL_SPECS + tuple(@@ -441,6 +469,8 @@ class ApiAgentWorker:with usage_context("mission-worker"):_stream = brain.complete(req)async for delta in _stream:+ if delta.usage:+ spent_usd += _usage_cost_usd(resolved_model, delta.usage)if delta.content:text_parts.append(delta.content)if delta.tool_call:@@ -467,6 +497,7 @@ class ApiAgentWorker:res = ClaudeResult(subtype="error_during_execution",is_error=True,+ cost_usd=round(spent_usd, 6),session_id=session_id,duration_ms=int((time.perf_counter() - t0) * 1000),result=_tool_incapable_message(@@ -478,6 +509,12 @@ class ApiAgentWorker:returnraise+ if self.cost_cap_usd is not None and spent_usd >= self.cost_cap_usd:+ raise _CostCapReached(+ f"approved cost cap of ${self.cost_cap_usd:.2f} reached "+ f"(${spent_usd:.2f} spent)"+ )+assistant_text = "".join(text_parts).strip()if assistant_text:final_text = assistant_text@@ -571,6 +608,7 @@ class ApiAgentWorker:res = ClaudeResult(subtype="success",is_error=False,+ cost_usd=round(spent_usd, 6),session_id=session_id,num_turns=turns,duration_ms=wall_ms,@@ -587,7 +625,8 @@ class ApiAgentWorker:except Exception as exc: # noqa: BLE001wall_ms = int((time.perf_counter() - t0) * 1000)logger.warning("ApiAgentWorker[%s] failed: %s", worker_id, exc, exc_info=True)- if _error_means_family_unusable(str(exc)):+ # The cost cap is the approval's limit, not a broken key.+ if not isinstance(exc, _CostCapReached) and _error_means_family_unusable(str(exc)):# Remember that THIS key cannot run right now, fingerprinted so# a freshly saved key lifts the block instantly. The factory's# family walk skips the family on the retry and crosses to the@@ -615,6 +654,7 @@ class ApiAgentWorker:res = ClaudeResult(subtype="error_during_execution",is_error=True,+ cost_usd=round(spent_usd, 6),session_id=session_id,num_turns=turns,duration_ms=wall_ms,diff --git a/jarvis/ui/web/frontend/src/components/missions/CapacityDecisionPanel.test.tsx b/jarvis/ui/web/frontend/src/components/missions/CapacityDecisionPanel.test.tsxnew file mode 100644index 0000000000..a75044fcf0--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/missions/CapacityDecisionPanel.test.tsx@@ -0,0 +1,125 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";++import { CapacityDecisionPanel } from "@/components/missions/CapacityDecisionPanel";+import { useI18nStore } from "@/i18n";+import type { MissionState, PaidOffer } from "@/types/missions";++const MISSION_ID = "mission-1";++const OFFER: PaidOffer = {+ provider: "claude-api",+ model: "claude-sonnet-4-6",+ estimated_cost_usd: 1.65,+ cost_cap_usd: 2,+ reason: "provider_quota",+ open_steps: 1,+};++beforeEach(() => {+ useI18nStore.getState().setUi("en", { push: false });+});++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++function jsonResponse(body: unknown, status = 200): Response {+ return { ok: status >= 200 && status < 300, status, json: async () => body } as Response;+}++function stubServer(offer: PaidOffer | null) {+ const fetchMock = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {+ if (init?.method === "POST") {+ const body = JSON.parse(String(init.body));+ return jsonResponse({+ ok: true,+ mission_id: MISSION_ID,+ decision: body.decision,+ state: body.decision === "approve_paid" ? "RUNNING" : "WAITING_CAPACITY",+ });+ }+ return jsonResponse({ mission_id: MISSION_ID, state: "WAITING_CAPACITY", offer });+ });+ vi.stubGlobal("fetch", fetchMock);+ return fetchMock;+}++function posts(fetchMock: ReturnType<typeof stubServer>) {+ return fetchMock.mock.calls+ .filter((call) => call[1]?.method === "POST")+ .map((call) => JSON.parse(String(call[1]?.body)));+}++function renderPanel(state: MissionState | null = "WAITING_CAPACITY") {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ return render(+ <QueryClientProvider client={client}>+ <CapacityDecisionPanel missionId={MISSION_ID} state={state} />+ </QueryClientProvider>,+ );+}++describe("CapacityDecisionPanel", () => {+ it("shows provider, model, estimate, cap and reason before anything is billed", async () => {+ const fetchMock = stubServer(OFFER);+ renderPanel();++ expect(await screen.findByText("claude-api")).toBeTruthy();+ expect(screen.getByText("claude-sonnet-4-6")).toBeTruthy();+ expect(screen.getByText("about $1.65 for 1 open steps")).toBeTruthy();+ expect(screen.getByText("$2.00")).toBeTruthy();+ expect(screen.getByText("Subscription capacity used up")).toBeTruthy();+ expect(posts(fetchMock)).toHaveLength(0);+ });++ it("approves only after an explicit confirmation and echoes the shown offer", async () => {+ const fetchMock = stubServer(OFFER);+ renderPanel();++ await screen.findByText("claude-api"); // the button stays disabled until the offer loads+ fireEvent.click(screen.getByRole("button", { name: "Approve paid API for this mission" }));+ expect(posts(fetchMock)).toHaveLength(0);+ expect(+ screen.getByText("Use claude-api / claude-sonnet-4-6 for this mission, at most $2.00?"),+ ).toBeTruthy();++ fireEvent.click(screen.getByRole("button", { name: "Confirm" }));+ await waitFor(() =>+ expect(posts(fetchMock)).toEqual([+ { decision: "approve_paid", provider: "claude-api", model: "claude-sonnet-4-6" },+ ]),+ );+ });++ it("waits with one click and never sends an offer along", async () => {+ const fetchMock = stubServer(OFFER);+ renderPanel();++ fireEvent.click(await screen.findByRole("button", { name: "Wait" }));+ await waitFor(() =>+ expect(posts(fetchMock)).toEqual([{ decision: "wait", provider: null, model: null }]),+ );+ });++ it("cannot approve when there is no priced paid option", async () => {+ stubServer(null);+ renderPanel();++ expect(await screen.findByText(/No paid API access with a known price/)).toBeTruthy();+ const approve = screen.getByRole("button", { name: "Approve paid API for this mission" });+ expect((approve as HTMLButtonElement).disabled).toBe(true);+ });++ it("renders nothing for a mission that is not waiting", () => {+ const fetchMock = stubServer(OFFER);+ const { container } = renderPanel("RUNNING");+ expect(container.textContent).toBe("");+ expect(fetchMock).not.toHaveBeenCalled();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/missions/CapacityDecisionPanel.tsx b/jarvis/ui/web/frontend/src/components/missions/CapacityDecisionPanel.tsxnew file mode 100644index 0000000000..9897bdabb3--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/missions/CapacityDecisionPanel.tsx@@ -0,0 +1,178 @@+/**+ * Decision for a mission parked in WAITING_CAPACITY: wait for its own+ * subscription, approve paid API use for THIS mission only, or cancel.+ *+ * Nothing here is automatic. The offer (provider, model, estimated cost, hard+ * cap, reason) is shown before any paid use; an approval needs a second,+ * explicit confirmation and echoes exactly the offer shown, so a changed+ * offer is rejected by the server instead of silently billed.+ */+import { useEffect, useState } from "react";+import { AlertTriangle, Clock3, CreditCard, Loader2, X } from "lucide-react";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";++import { Button } from "@/components/ui/button";+import { fill, useT } from "@/i18n";+import type { CapacityDecision, MissionState, PaidOffer } from "@/types/missions";+import { decideCapacity, fetchPaidOffer, paidOfferQueryKey } from "./api";++const OFFER_REFRESH_MS = 15_000;++function usd(value: number): string {+ return `$${value.toFixed(2)}`;+}++export function CapacityDecisionPanel({+ missionId,+ state,+}: {+ missionId: string | null;+ state: MissionState | null;+}) {+ const t = useT();+ const queryClient = useQueryClient();+ const waiting = missionId !== null && state === "WAITING_CAPACITY";+ const [confirming, setConfirming] = useState<CapacityDecision | null>(null);+ useEffect(() => setConfirming(null), [missionId, state]);++ const offerQuery = useQuery({+ queryKey: paidOfferQueryKey(missionId),+ queryFn: () => fetchPaidOffer(missionId as string),+ enabled: waiting,+ refetchInterval: waiting ? OFFER_REFRESH_MS : false,+ });+ const offer: PaidOffer | null = offerQuery.data?.offer ?? null;++ const decision = useMutation({+ mutationFn: (choice: CapacityDecision) =>+ decideCapacity(+ missionId as string,+ choice,+ choice === "approve_paid" && offer+ ? { provider: offer.provider, model: offer.model }+ : undefined,+ ),+ onSuccess: () => setConfirming(null),+ onSettled: () => {+ void queryClient.invalidateQueries({ queryKey: ["missions"] });+ },+ });++ if (!waiting) return null;++ const busy = decision.isPending;+ const overCap = offer !== null && offer.estimated_cost_usd > offer.cost_cap_usd;++ return (+ <section+ aria-label={t("capacity_decision.title")}+ className="space-y-2.5 border-b border-border p-3 text-xs"+ >+ <div className="flex items-center gap-1.5 font-medium text-warning">+ <Clock3 className="h-3.5 w-3.5" />+ {t("capacity_decision.title")}+ </div>++ {offerQuery.isLoading ? (+ <p className="flex items-center gap-1.5 text-muted-foreground">+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ {t("capacity_decision.loading")}+ </p>+ ) : offer ? (+ <dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 rounded-md border border-border bg-card/40 p-2.5">+ <dt className="text-muted-foreground">{t("capacity_decision.provider")}</dt>+ <dd className="font-mono text-foreground">{offer.provider}</dd>+ <dt className="text-muted-foreground">{t("capacity_decision.model")}</dt>+ <dd className="break-all font-mono text-foreground">{offer.model}</dd>+ <dt className="text-muted-foreground">{t("capacity_decision.estimate")}</dt>+ <dd className="font-mono text-foreground">+ {fill(t("capacity_decision.estimate_value"), {+ cost: usd(offer.estimated_cost_usd),+ steps: offer.open_steps,+ })}+ </dd>+ <dt className="text-muted-foreground">{t("capacity_decision.cap")}</dt>+ <dd className="font-mono text-foreground">{usd(offer.cost_cap_usd)}</dd>+ <dt className="text-muted-foreground">{t("capacity_decision.reason")}</dt>+ <dd className="text-foreground">+ {t(`capacity_decision.reasons.${offer.reason}`)}+ </dd>+ </dl>+ ) : (+ <p className="rounded-md border border-border bg-card/40 p-2.5 text-muted-foreground">+ {t("capacity_decision.no_offer")}+ </p>+ )}++ {overCap && (+ <p className="flex items-start gap-1.5 text-warning">+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />+ {t("capacity_decision.over_cap")}+ </p>+ )}++ <p className="text-muted-foreground">{t("capacity_decision.scope")}</p>++ {confirming === null ? (+ <div className="flex flex-wrap gap-2">+ <Button size="sm" variant="outline" disabled={busy} onClick={() => decision.mutate("wait")}>+ <Clock3 className="mr-1.5 h-3.5 w-3.5" />+ {t("capacity_decision.wait")}+ </Button>+ <Button+ size="sm"+ disabled={busy || offer === null}+ onClick={() => setConfirming("approve_paid")}+ >+ <CreditCard className="mr-1.5 h-3.5 w-3.5" />+ {t("capacity_decision.approve")}+ </Button>+ <Button+ size="sm"+ variant="outline"+ disabled={busy}+ onClick={() => setConfirming("cancel")}+ >+ <X className="mr-1.5 h-3.5 w-3.5" />+ {t("capacity_decision.cancel")}+ </Button>+ </div>+ ) : (+ <div className="space-y-2 rounded-md border border-warning/40 bg-warning/10 p-2.5">+ <p className="text-foreground">+ {confirming === "approve_paid" && offer+ ? fill(t("capacity_decision.confirm_approve"), {+ provider: offer.provider,+ model: offer.model,+ cap: usd(offer.cost_cap_usd),+ })+ : t("capacity_decision.confirm_cancel")}+ </p>+ <div className="flex flex-wrap gap-2">+ <Button+ size="sm"+ variant={confirming === "cancel" ? "destructive" : "default"}+ disabled={busy}+ onClick={() => decision.mutate(confirming)}+ >+ {busy && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}+ {t("capacity_decision.confirm")}+ </Button>+ <Button size="sm" variant="outline" disabled={busy} onClick={() => setConfirming(null)}>+ {t("capacity_decision.back")}+ </Button>+ </div>+ </div>+ )}++ {decision.isError && (+ <p className="text-destructive">+ {fill(t("capacity_decision.error"), { detail: decision.error.message })}+ </p>+ )}+ {decision.isSuccess && decision.data.decision === "wait" && (+ <p className="text-muted-foreground">{t("capacity_decision.waiting_ack")}</p>+ )}+ </section>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/missions/api.ts b/jarvis/ui/web/frontend/src/components/missions/api.tsindex c0cf19b470..c5f0575977 100644--- a/jarvis/ui/web/frontend/src/components/missions/api.ts+++ b/jarvis/ui/web/frontend/src/components/missions/api.ts@@ -4,6 +4,8 @@* WS hooks so React Query can cache the list/detail queries.*/import type {+ CapacityDecision,+ CapacityDecisionResponse,CriticVerdictReady,EventEnvelope,MissionChanges,@@ -13,6 +15,7 @@ import type {MissionToolApprovalDecision,MissionToolApprovalsResponse,JarvisAgentWorkerSnapshot,+ PaidOfferResponse,} from "@/types/missions";export interface MissionsListResponse {@@ -95,6 +98,39 @@ export async function denyMissionToolCall();}+export function paidOfferQueryKey(missionId: string | null) {+ return ["missions", "paid-offer", missionId] as const;+}++/** The paid-API alternative for a mission waiting for capacity (read-only). */+export async function fetchPaidOffer(missionId: string): Promise<PaidOfferResponse> {+ return requestJson(`${API_BASE}/${encodeURIComponent(missionId)}/paid-offer`);+}++/**+ * Wait, approve paid API use for this one mission, or cancel. An approval+ * echoes the provider and model of the offer the user saw; the server+ * rejects it (409) if the offer changed in between.+ */+export async function decideCapacity(+ missionId: string,+ decision: CapacityDecision,+ offer?: { provider: string; model: string },+): Promise<CapacityDecisionResponse> {+ return requestJson(+ `${API_BASE}/${encodeURIComponent(missionId)}/capacity-decision`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ decision,+ provider: offer?.provider ?? null,+ model: offer?.model ?? null,+ }),+ },+ );+}+export async function cancelMission(id: string): Promise<void> {const res = await fetch(`${API_BASE}/${encodeURIComponent(id)}/cancel`, {method: "POST",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex be6c43d283..c12b44d542 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -4194,7 +4194,8 @@"files": "Gespeicherte Dateien: {files}.","wait": "Die Mission wartet, bis wieder Kapazität verfügbar ist.","wait_auth": "Die Mission wartet, bis du dich wieder anmeldest.",- "paid": "Kostenpflichtige API-Nutzung nur mit deiner ausdrücklichen Freigabe."+ "paid": "Kostenpflichtige API-Nutzung nur mit deiner ausdrücklichen Freigabe im Tab „Freigaben“.",+ "paid_cap_reached": "Die freigegebene Kostengrenze für {provider} ist erreicht."}},"mission_tool_approvals": {@@ -7036,5 +7037,40 @@"create": "Pet erstellen","creating": "Wird erstellt…"}+ },+ "capacity_decision": {+ "title": "Mission wartet auf Kapazität – deine Entscheidung",+ "loading": "Kostenpflichtige Alternative wird geprüft …",+ "provider": "Anbieter",+ "model": "Modell",+ "estimate": "Geschätzte Kosten",+ "estimate_value": "ca. {cost} für {steps} offene Teilschritte",+ "cap": "Harte Kostengrenze",+ "reason": "Grund",+ "reasons": {+ "provider_quota": "Abo-Kapazität ausgeschöpft",+ "provider_auth": "Abo-Anmeldung abgelaufen",+ "provider_unavailable": "Abo momentan nicht nutzbar",+ "paid_cap_reached": "Freigegebene Kostengrenze erreicht"+ },+ "no_offer": "Kein kostenpflichtiger API-Zugang mit bekanntem Preis verfügbar. Die Mission wartet auf ihr Abo.",+ "over_cap": "Die Schätzung liegt über der Kostengrenze. Die Mission pausiert, sobald die Grenze erreicht ist; der Stand bleibt gesichert.",+ "scope": "Eine Freigabe gilt nur für diese Mission und diesen einen Lauf – keine dauerhafte oder globale Freigabe. Ohne Freigabe wird nichts berechnet.",+ "wait": "Warten",+ "approve": "Kostenpflichtige API für diese Mission freigeben",+ "cancel": "Mission abbrechen",+ "confirm_approve": "{provider} / {model} für diese Mission nutzen, höchstens {cap}?",+ "confirm_cancel": "Mission abbrechen? Der gesicherte Stand bleibt erhalten.",+ "confirm": "Bestätigen",+ "back": "Zurück",+ "error": "Entscheidung nicht übernommen: {detail}",+ "waiting_ack": "Die Mission wartet weiter auf ihr Abo.",+ "logged": {+ "wait": "Entscheidung: warten.",+ "approve_paid": "Entscheidung: kostenpflichtige API freigegeben.",+ "cancel": "Entscheidung: abgebrochen."+ },+ "logged_offer": "{provider} / {model}, geschätzt {cost}, Grenze {cap}.",+ "paid_usage": "Kostenpflichtiger Lauf auf {provider} / {model}: tatsächlich {cost} (geschätzt {estimate}, Grenze {cap})."}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 3a72b4ade4..e3618ac734 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -4194,7 +4194,8 @@"files": "Files saved: {files}.","wait": "The mission is waiting until capacity is available again.","wait_auth": "The mission is waiting until you sign in again.",- "paid": "Paid API use only with your explicit approval."+ "paid": "Paid API use only with your explicit approval in the Approvals tab.",+ "paid_cap_reached": "The approved cost limit for {provider} is reached."}},"mission_tool_approvals": {@@ -7036,5 +7037,40 @@"create": "Create pet","creating": "Creating…"}+ },+ "capacity_decision": {+ "title": "Mission waiting for capacity – your decision",+ "loading": "Checking for a paid alternative …",+ "provider": "Provider",+ "model": "Model",+ "estimate": "Estimated cost",+ "estimate_value": "about {cost} for {steps} open steps",+ "cap": "Hard cost cap",+ "reason": "Reason",+ "reasons": {+ "provider_quota": "Subscription capacity used up",+ "provider_auth": "Subscription sign-in expired",+ "provider_unavailable": "Subscription cannot be used right now",+ "paid_cap_reached": "Approved cost cap reached"+ },+ "no_offer": "No paid API access with a known price is available. The mission waits for its subscription.",+ "over_cap": "The estimate is above the cost cap. The mission pauses once the cap is reached; its progress stays saved.",+ "scope": "An approval covers only this mission and this one run – no permanent or global approval. Nothing is billed without it.",+ "wait": "Wait",+ "approve": "Approve paid API for this mission",+ "cancel": "Cancel mission",+ "confirm_approve": "Use {provider} / {model} for this mission, at most {cap}?",+ "confirm_cancel": "Cancel the mission? The saved progress is kept.",+ "confirm": "Confirm",+ "back": "Back",+ "error": "Decision not applied: {detail}",+ "waiting_ack": "The mission keeps waiting for its subscription.",+ "logged": {+ "wait": "Decision: wait.",+ "approve_paid": "Decision: paid API approved.",+ "cancel": "Decision: cancelled."+ },+ "logged_offer": "{provider} / {model}, estimated {cost}, cap {cap}.",+ "paid_usage": "Paid run on {provider} / {model}: actual {cost} (estimated {estimate}, cap {cap})."}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 5dde2b9fe5..25daf6209f 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -4194,7 +4194,8 @@"files": "Archivos guardados: {files}.","wait": "La misión espera hasta que vuelva a haber capacidad.","wait_auth": "La misión espera hasta que vuelvas a iniciar sesión.",- "paid": "Uso de API de pago solo con tu aprobación explícita."+ "paid": "Uso de API de pago solo con tu aprobación explícita en la pestaña de aprobaciones.",+ "paid_cap_reached": "Se alcanzó el límite de coste aprobado para {provider}."}},"mission_tool_approvals": {@@ -7036,5 +7037,40 @@"create": "Crear mascota","creating": "Creando…"}+ },+ "capacity_decision": {+ "title": "La misión espera capacidad – tu decisión",+ "loading": "Buscando una alternativa de pago …",+ "provider": "Proveedor",+ "model": "Modelo",+ "estimate": "Coste estimado",+ "estimate_value": "aprox. {cost} para {steps} pasos pendientes",+ "cap": "Límite de coste estricto",+ "reason": "Motivo",+ "reasons": {+ "provider_quota": "Capacidad de la suscripción agotada",+ "provider_auth": "Sesión de la suscripción caducada",+ "provider_unavailable": "La suscripción no se puede usar ahora",+ "paid_cap_reached": "Límite de coste aprobado alcanzado"+ },+ "no_offer": "No hay acceso de pago a la API con precio conocido. La misión espera a su suscripción.",+ "over_cap": "La estimación supera el límite de coste. La misión se pausa al alcanzarlo; el progreso queda guardado.",+ "scope": "Una aprobación vale solo para esta misión y esta ejecución – nunca permanente ni global. Sin ella no se cobra nada.",+ "wait": "Esperar",+ "approve": "Aprobar API de pago para esta misión",+ "cancel": "Cancelar misión",+ "confirm_approve": "¿Usar {provider} / {model} para esta misión, como máximo {cap}?",+ "confirm_cancel": "¿Cancelar la misión? El progreso guardado se conserva.",+ "confirm": "Confirmar",+ "back": "Atrás",+ "error": "Decisión no aplicada: {detail}",+ "waiting_ack": "La misión sigue esperando a su suscripción.",+ "logged": {+ "wait": "Decisión: esperar.",+ "approve_paid": "Decisión: API de pago aprobada.",+ "cancel": "Decisión: cancelada."+ },+ "logged_offer": "{provider} / {model}, estimado {cost}, límite {cap}.",+ "paid_usage": "Ejecución de pago en {provider} / {model}: real {cost} (estimado {estimate}, límite {cap})."}}diff --git a/jarvis/ui/web/frontend/src/types/missions.ts b/jarvis/ui/web/frontend/src/types/missions.tsindex a9cbcb0814..5e3231309e 100644--- a/jarvis/ui/web/frontend/src/types/missions.ts+++ b/jarvis/ui/web/frontend/src/types/missions.ts@@ -45,7 +45,9 @@ export type EventType =| "MissionStateChanged"| "BusStats"| "MissionBudgetWarning"- | "MissionWaitingCapacity";+ | "MissionWaitingCapacity"+ | "MissionCapacityDecision"+ | "MissionPaidUsage";export interface BasePayload {event_type: EventType;@@ -197,7 +199,56 @@ export interface BusStats extends BasePayload {}/** Mirror of CAPACITY_WAIT_REASONS in jarvis/missions/events.py. */-export type CapacityWaitReason = "provider_quota" | "provider_auth" | "provider_unavailable";+export type CapacityWaitReason =+ | "provider_quota"+ | "provider_auth"+ | "provider_unavailable"+ | "paid_cap_reached";++/** Mirror of jarvis.missions.capacity.CapacityDecision. */+export type CapacityDecision = "wait" | "approve_paid" | "cancel";++export interface MissionCapacityDecision extends BasePayload {+ event_type: "MissionCapacityDecision";+ decision: CapacityDecision;+ provider: string | null;+ model: string | null;+ estimated_cost_usd: number | null;+ cost_cap_usd: number | null;+ reason: string;+}++export interface MissionPaidUsage extends BasePayload {+ event_type: "MissionPaidUsage";+ provider: string;+ model: string;+ cost_usd: number;+ cost_cap_usd: number;+ estimated_cost_usd: number;+}++/** GET /api/missions/{id}/paid-offer — what an approval would cover. */+export interface PaidOffer {+ provider: string;+ model: string;+ estimated_cost_usd: number;+ cost_cap_usd: number;+ reason: string;+ open_steps: number;+}++export interface PaidOfferResponse {+ mission_id: string;+ state: MissionState;+ offer: PaidOffer | null;+}++export interface CapacityDecisionResponse {+ ok: boolean;+ mission_id: string;+ decision: CapacityDecision;+ state: MissionState;+}export interface MissionWaitingCapacity extends BasePayload {event_type: "MissionWaitingCapacity";@@ -234,6 +285,8 @@ export type AnyPayload =| MissionTimedOut| MissionStateChanged| MissionWaitingCapacity+ | MissionCapacityDecision+ | MissionPaidUsage| BusStats| MissionBudgetWarning;diff --git a/jarvis/ui/web/frontend/src/views/MissionsView.tsx b/jarvis/ui/web/frontend/src/views/MissionsView.tsxindex 2e4c8ef8dc..f2dff1ba44 100644--- a/jarvis/ui/web/frontend/src/views/MissionsView.tsx+++ b/jarvis/ui/web/frontend/src/views/MissionsView.tsx@@ -38,6 +38,7 @@ import { Badge } from "@/components/ui/badge";import { cn } from "@/lib/utils";import { fetchMissions, fetchMissionDetail } from "@/components/missions/api";import { EventTimeline } from "@/components/missions/EventTimeline";+import { CapacityDecisionPanel } from "@/components/missions/CapacityDecisionPanel";import { GlobalKillButton } from "@/components/missions/GlobalKillButton";import { MissionTree } from "@/components/missions/MissionTree";import { JarvisAgentPanel } from "@/components/missions/JarvisAgentPanel";@@ -75,10 +76,17 @@ export function MissionsView() {const totalCount = useMissionsStore(useShallow((s) => Object.keys(s.missions).length));const activeCount = useMissionsStore(useShallow(selectActiveCount));const toolApprovalsQuery = useMissionToolApprovals(selectedMissionId);- const pendingApprovalCount =+ const selectedState = useMissionsStore((s) =>+ s.selectedMissionId ? (s.missions[s.selectedMissionId]?.state ?? null) : null,+ );+ // A mission waiting for capacity has one decision pending: wait, approve+ // paid use for it, or cancel (CapacityDecisionPanel).+ const capacityDecisionPending = selectedState === "WAITING_CAPACITY" ? 1 : 0;+ const pendingToolApprovalCount =toolApprovalsQuery.data?.approvals.filter((approval) => approval.expires_at_ns / 1_000_000 > Date.now(),).length ?? 0;+ const pendingApprovalCount = pendingToolApprovalCount + capacityDecisionPending;const listQuery = useQuery({queryKey: ["missions"],@@ -222,11 +230,17 @@ export function MissionsView() {<TabsContent value="jarvis-agent" className="m-0 flex-1 overflow-hidden"><JarvisAgentPanel /></TabsContent>- <TabsContent value="approvals" className="m-0 flex-1 overflow-hidden">- <ToolApprovalPanel- missionId={selectedMissionId}- query={toolApprovalsQuery}- />+ <TabsContent+ value="approvals"+ className="m-0 flex flex-1 flex-col overflow-hidden data-[state=inactive]:hidden"+ >+ <CapacityDecisionPanel missionId={selectedMissionId} state={selectedState} />+ <div className="min-h-0 flex-1">+ <ToolApprovalPanel+ missionId={selectedMissionId}+ query={toolApprovalsQuery}+ />+ </div></TabsContent></Tabs></div>@@ -297,7 +311,9 @@ function ReasoningPanel() {e.payload.event_type === "WorkerCorrectionRequired" ||// A resume that parked again with no new step done repeats the// card already shown.- (e.payload.event_type === "MissionWaitingCapacity" && !e.payload.repeat),+ (e.payload.event_type === "MissionWaitingCapacity" && !e.payload.repeat) ||+ e.payload.event_type === "MissionCapacityDecision" ||+ e.payload.event_type === "MissionPaidUsage",);}),);@@ -382,6 +398,46 @@ function ReasoningPanel() {</li>);}+ if (env.payload.event_type === "MissionCapacityDecision") {+ const p = env.payload;+ return (+ <li+ key={`${env.event_id}-${idx}`}+ className="rounded border border-border/60 bg-card/30 p-2 text-xs"+ >+ <p className="text-foreground/90">+ {t(`capacity_decision.logged.${p.decision}`)}+ {p.decision === "approve_paid" && p.provider && p.model+ ? ` ${fill(t("capacity_decision.logged_offer"), {+ provider: p.provider,+ model: p.model,+ cost: `$${(p.estimated_cost_usd ?? 0).toFixed(2)}`,+ cap: `$${(p.cost_cap_usd ?? 0).toFixed(2)}`,+ })}`+ : ""}+ </p>+ </li>+ );+ }+ if (env.payload.event_type === "MissionPaidUsage") {+ const p = env.payload;+ return (+ <li+ key={`${env.event_id}-${idx}`}+ className="rounded border border-border/60 bg-card/30 p-2 text-xs"+ >+ <p className="text-foreground/90">+ {fill(t("capacity_decision.paid_usage"), {+ provider: p.provider,+ model: p.model,+ cost: `$${p.cost_usd.toFixed(4)}`,+ estimate: `$${p.estimated_cost_usd.toFixed(2)}`,+ cap: `$${p.cost_cap_usd.toFixed(2)}`,+ })}+ </p>+ </li>+ );+ }return null;})}</ul>diff --git a/jarvis/ui/web/missions_routes.py b/jarvis/ui/web/missions_routes.pyindex c100295bd2..9c1af331c5 100644--- a/jarvis/ui/web/missions_routes.py+++ b/jarvis/ui/web/missions_routes.py@@ -127,6 +127,18 @@ class RerunBody(BaseModel):confirmed: bool = False+class CapacityDecisionBody(BaseModel):+ """The user's answer to a parked mission's paid-API offer.++ ``provider``/``model`` echo the offer the user saw; an approval only+ applies when they still match the current offer.+ """++ decision: Literal["wait", "approve_paid", "cancel"]+ provider: str | None = None+ model: str | None = None++class DenyToolApprovalBody(BaseModel):"""Optional audit reason for denying one paused supervisor tool call."""@@ -534,6 +546,68 @@ async def cancel_mission(mission_id: str, request: Request) -> dict[str, Any]:}+def _offer_json(offer: Any) -> dict[str, Any] | None:+ if offer is None:+ return None+ return {+ "provider": offer.provider,+ "model": offer.model,+ "estimated_cost_usd": offer.estimated_cost_usd,+ "cost_cap_usd": offer.cost_cap_usd,+ "reason": offer.reason,+ "open_steps": offer.open_steps,+ }++[email protected]("/{mission_id}/paid-offer")+async def get_paid_offer(mission_id: str, request: Request) -> dict[str, Any]:+ """The paid-API alternative for a mission waiting for capacity.++ Shows provider, model, estimated cost, the hard cost cap and why the+ mission stopped. Read-only: nothing is approved or billed here. ``offer``+ is null when the mission is not waiting or no priced API key is usable.+ """+ mgr = _require_manager(request)+ view = await mgr.mission(mission_id)+ if view is None:+ raise HTTPException(status_code=404, detail="Mission not found")+ kontrollierer = _optional_kontrollierer(request)+ offer_fn = getattr(kontrollierer, "paid_offer", None)+ offer = await offer_fn(mission_id) if offer_fn is not None else None+ return {"mission_id": mission_id, "state": view.state.value, "offer": _offer_json(offer)}+++ "/{mission_id}/capacity-decision", openapi_extra={"x-jarvis-dangerous": True}+)+async def decide_capacity(+ mission_id: str, body: CapacityDecisionBody, request: Request+) -> dict[str, Any]:+ """Wait, approve paid API use for THIS mission only, or cancel.++ An approval must name the provider and model of the offer currently+ shown; it covers one run of this one mission and is never stored or+ reused. Returns ``409`` when the mission is no longer waiting or the+ offer changed — nothing is decided or billed then.+ """+ from jarvis.missions.capacity import CapacityDecisionRejected++ mgr = _require_manager(request)+ if await mgr.mission(mission_id) is None:+ raise HTTPException(status_code=404, detail="Mission not found")+ kontrollierer = _optional_kontrollierer(request)+ decide = getattr(kontrollierer, "decide_capacity", None)+ if decide is None:+ raise HTTPException(status_code=503, detail="Mission runner is not available")+ try:+ state = await decide(+ mission_id, body.decision, provider=body.provider, model=body.model+ )+ except CapacityDecisionRejected as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from None+ return {"ok": True, "mission_id": mission_id, "decision": body.decision, "state": state.value}++# States from which a mission may be re-run. APPROVED is deliberately excluded# (a successful mission has nothing to continue/restart). The terminal source# mission is never mutated — the re-run is a fresh PENDING mission linked backdiff --git a/tests/fakes/fake_mission_runtime.py b/tests/fakes/fake_mission_runtime.pyindex 4fc6b781ff..efd87c6794 100644--- a/tests/fakes/fake_mission_runtime.py+++ b/tests/fakes/fake_mission_runtime.py@@ -14,6 +14,7 @@ from pathlib import Pathfrom typing import Anyfrom jarvis.missions.budget import BudgetTracker+from jarvis.missions.capacity import PaidOfferfrom jarvis.missions.critic.verdict import REQUIRED_AXES, CriticAxis, CriticVerdictfrom jarvis.missions.kontrollierer.decomposer import MissionPlan, Stepfrom jarvis.missions.kontrollierer.orchestrator import Kontrollierer@@ -57,8 +58,10 @@ class FakeMissionWorker:quota: bool = False,writes: dict[str, str] | None = None,on_spawn: Callable[[str, Path], None] | None = None,+ cost_usd: float = 0.0,) -> None:self.family = family+ self.cost_usd = cost_usdself.quota = quotaself.writes = dict(writes or {})self.on_spawn = on_spawn@@ -78,10 +81,13 @@ class FakeMissionWorker:_write_log(log_dir)if self.quota:yield ResultEvent(- is_error=True, subtype="error_during_execution", result=SESSION_LIMIT_ERROR+ is_error=True,+ subtype="error_during_execution",+ result=SESSION_LIMIT_ERROR,+ cost_usd=self.cost_usd,)else:- yield ResultEvent()+ yield ResultEvent(cost_usd=self.cost_usd)class ApprovingCritic:@@ -141,12 +147,34 @@ class DirWorktrees:shutil.rmtree(path, ignore_errors=True)+class FakePaidOption:+ """A fixed paid offer; its workers report ``cost_per_spawn`` USD each."""++ def __init__(self, offer: PaidOffer | None, *, cost_per_spawn: float = 0.25) -> None:+ self._offer = offer+ self.cost_per_spawn = cost_per_spawn+ self.offer_calls: list[dict[str, Any]] = []+ self.workers: list[FakeMissionWorker] = []+ self.remaining: list[float] = []++ def offer(self, **kwargs: Any) -> PaidOffer | None:+ self.offer_calls.append(kwargs)+ return self._offer++ def worker(self, offer: PaidOffer, *, remaining_usd: float, task_text: str) -> Any:+ self.remaining.append(remaining_usd)+ worker = FakeMissionWorker(family=offer.provider, cost_usd=self.cost_per_spawn)+ self.workers.append(worker)+ return worker++def make_kontrollierer(manager: MissionManager,tmp_path: Path,plan: MissionPlan,factory: Callable[[Step], Any],critic: Any | None = None,+ paid_option: Any | None = None,) -> Kontrollierer:return Kontrollierer(manager=manager,@@ -158,4 +186,5 @@ def make_kontrollierer(worker_factory=factory,job_factory=NoopJob,isolation_root=tmp_path / "missions",+ paid_option=paid_option,)diff --git a/tests/missions/test_capacity_approval.py b/tests/missions/test_capacity_approval.pynew file mode 100644index 0000000000..8a4a0d5359--- /dev/null+++ b/tests/missions/test_capacity_approval.py@@ -0,0 +1,437 @@+"""Explicit, per-mission approval of paid API use for a parked mission.++The user's rules (2026-10-06): never switch to a paid API on its own; show+provider, model, estimated cost and reason first; options wait / approve for+this mission / cancel; an approval covers this one mission only and is never+stored or global; log the decision and the real cost; a declined mission+stays safely parked.+"""+from __future__ import annotations++from collections.abc import AsyncIterator+from pathlib import Path+from typing import Any++import httpx+import pytest+from fastapi import FastAPI++from jarvis.core.protocols import BrainDelta, BrainRequest+from jarvis.missions import init as mi+from jarvis.missions.capacity import (+ PAID_MISSION_CAP_USD,+ CapacityDecisionRejected,+ PaidOffer,+ WorkerCapacityUnavailable,+ estimate_paid_cost_usd,+ read_checkpoint,+)+from jarvis.missions.events import (+ MissionCancelled,+ MissionCapacityDecision,+ MissionPaidUsage,+ MissionWaitingCapacity,+)+from jarvis.missions.kontrollierer.decomposer import MissionPlan, Step+from jarvis.missions.manager import MissionManager+from jarvis.missions.state_machine import MissionState+from jarvis.missions.workers.api_agent_worker import ApiAgentWorker+from jarvis.ui.web.missions_routes import router+from tests.fakes.fake_mission_runtime import (+ FakeMissionWorker,+ FakePaidOption,+ make_kontrollierer,+)++OFFER = PaidOffer(+ provider="claude-api",+ model="claude-sonnet-4-6",+ estimated_cost_usd=1.65,+ cost_cap_usd=PAID_MISSION_CAP_USD,+ reason="provider_quota",+ open_steps=1,+)+++async def manager(tmp_missions_db: Path):+ m = MissionManager(tmp_missions_db)+ await m.start()+ yield m+ await m.stop()+++class SubscriptionFactory:+ """The subscription worker factory; ``capacity`` False parks every call."""++ def __init__(self) -> None:+ self.capacity = False+ self.built = 0++ def __call__(self, _step: Step) -> FakeMissionWorker:+ if not self.capacity:+ raise WorkerCapacityUnavailable("provider_quota", "claude")+ self.built += 1+ return FakeMissionWorker(family="claude")+++async def _parked(+ manager: MissionManager,+ tmp_path: Path,+ *,+ paid: FakePaidOption | None,+) -> tuple[Any, str, SubscriptionFactory]:+ factory = SubscriptionFactory()+ plan = MissionPlan(steps=[Step(slug="task", prompt="write it")], n_workers=1)+ k = make_kontrollierer(manager, tmp_path, plan, factory, paid_option=paid)+ mission_id = await manager.dispatch(prompt="write the report")+ assert await k.run_mission(mission_id) == MissionState.WAITING_CAPACITY+ return k, mission_id, factory+++async def _payloads(manager: MissionManager, mission_id: str) -> list[Any]:+ return [e.payload for e in await manager.store.events_for_mission(mission_id)]+++async def _state(manager: MissionManager, mission_id: str) -> MissionState:+ view = await manager.mission(mission_id)+ assert view is not None+ return view.state+++async def _wait_paid_runs(k: Any) -> None:+ for run in list(k._background_runs):+ await run+++# --- The offer: shown before anything is billed -------------------------------+++async def test_offer_names_provider_model_cost_cap_and_reason(+ manager: MissionManager, tmp_path: Path+) -> None:+ paid = FakePaidOption(OFFER)+ k, mission_id, _f = await _parked(manager, tmp_path, paid=paid)++ offer = await k.paid_offer(mission_id)++ assert offer == OFFER+ assert paid.offer_calls == [+ {"pinned_family": "claude", "open_steps": 1, "reason": "provider_quota"}+ ]+ assert paid.workers == [] # looking at an offer never builds a worker+++async def test_no_offer_without_a_paid_option_or_when_not_parked(+ manager: MissionManager, tmp_path: Path+) -> None:+ k, mission_id, _f = await _parked(manager, tmp_path, paid=None)+ assert await k.paid_offer(mission_id) is None++ k2, mission_id2, _f2 = await _parked(manager, tmp_path / "b", paid=FakePaidOption(OFFER))+ await k2.decide_capacity(mission_id2, "cancel")+ assert await k2.paid_offer(mission_id2) is None+++# --- Decisions -------------------------------------------------------------------+++async def test_wait_keeps_the_mission_parked_and_logs_it(+ manager: MissionManager, tmp_path: Path+) -> None:+ paid = FakePaidOption(OFFER)+ k, mission_id, factory = await _parked(manager, tmp_path, paid=paid)++ assert await k.decide_capacity(mission_id, "wait") == MissionState.WAITING_CAPACITY++ assert await _state(manager, mission_id) == MissionState.WAITING_CAPACITY+ decisions = [+ p for p in await _payloads(manager, mission_id) if isinstance(p, MissionCapacityDecision)+ ]+ assert [d.decision for d in decisions] == ["wait"]+ assert decisions[0].provider == "claude-api" # the offer that was declined+ assert paid.workers == [] and factory.built == 0+ assert k._paid_approval == {}+++async def test_cancel_ends_the_mission_and_logs_it(+ manager: MissionManager, tmp_path: Path+) -> None:+ paid = FakePaidOption(OFFER)+ k, mission_id, _f = await _parked(manager, tmp_path, paid=paid)++ assert await k.decide_capacity(mission_id, "cancel") == MissionState.CANCELLED++ payloads = await _payloads(manager, mission_id)+ assert [p.decision for p in payloads if isinstance(p, MissionCapacityDecision)] == ["cancel"]+ assert any(isinstance(p, MissionCancelled) for p in payloads)+ assert paid.workers == []+++async def test_approval_must_match_the_offer_that_was_shown(+ manager: MissionManager, tmp_path: Path+) -> None:+ paid = FakePaidOption(OFFER)+ k, mission_id, _f = await _parked(manager, tmp_path, paid=paid)++ with pytest.raises(CapacityDecisionRejected):+ await k.decide_capacity(+ mission_id, "approve_paid", provider="claude-api", model="claude-opus-5-5"+ )++ assert await _state(manager, mission_id) == MissionState.WAITING_CAPACITY+ assert not any(+ isinstance(p, MissionCapacityDecision) for p in await _payloads(manager, mission_id)+ )+ assert paid.workers == []+++async def test_approval_needs_an_offer(manager: MissionManager, tmp_path: Path) -> None:+ k, mission_id, _f = await _parked(manager, tmp_path, paid=FakePaidOption(None))+ with pytest.raises(CapacityDecisionRejected):+ await k.decide_capacity(+ mission_id, "approve_paid", provider=OFFER.provider, model=OFFER.model+ )+ assert await _state(manager, mission_id) == MissionState.WAITING_CAPACITY+++async def test_approved_run_uses_exactly_the_approved_offer_and_logs_real_cost(+ manager: MissionManager, tmp_path: Path+) -> None:+ paid = FakePaidOption(OFFER, cost_per_spawn=0.42)+ k, mission_id, factory = await _parked(manager, tmp_path, paid=paid)++ state = await k.decide_capacity(+ mission_id, "approve_paid", provider=OFFER.provider, model=OFFER.model+ )+ assert state == MissionState.RUNNING+ await _wait_paid_runs(k)++ assert await _state(manager, mission_id) == MissionState.APPROVED+ assert [w.family for w in paid.workers] == ["claude-api"]+ assert paid.remaining == [OFFER.cost_cap_usd]+ assert factory.built == 0 # no subscription worker, no other provider+ payloads = await _payloads(manager, mission_id)+ decision = next(p for p in payloads if isinstance(p, MissionCapacityDecision))+ assert (decision.decision, decision.provider, decision.model) == (+ "approve_paid", "claude-api", "claude-sonnet-4-6",+ )+ assert decision.estimated_cost_usd == OFFER.estimated_cost_usd+ usage = [p for p in payloads if isinstance(p, MissionPaidUsage)]+ assert len(usage) == 1+ assert usage[0].cost_usd == pytest.approx(0.42)+ assert usage[0].cost_cap_usd == OFFER.cost_cap_usd+ # The approval died with the run.+ assert k._paid_approval == {} and k._paid_spent == {}+++async def test_cost_cap_parks_the_run_and_keeps_waiting_for_the_subscription(+ manager: MissionManager, tmp_path: Path+) -> None:+ paid = FakePaidOption(OFFER, cost_per_spawn=2.5)+ k, mission_id, factory = await _parked(manager, tmp_path, paid=paid)++ await k.decide_capacity(mission_id, "approve_paid", provider=OFFER.provider, model=OFFER.model)+ await _wait_paid_runs(k)++ assert await _state(manager, mission_id) == MissionState.WAITING_CAPACITY+ payloads = await _payloads(manager, mission_id)+ wait = [p for p in payloads if isinstance(p, MissionWaitingCapacity)][-1]+ assert (wait.reason, wait.provider) == ("paid_cap_reached", "claude-api")+ assert [p.cost_usd for p in payloads if isinstance(p, MissionPaidUsage)] == [2.5]+ # The checkpoint still waits for the ORIGINAL subscription, not the key.+ checkpoint = read_checkpoint(tmp_path / "missions" / f"mission_{mission_id[:13]}")+ assert checkpoint is not None and checkpoint["provider"] == "claude"+++async def test_an_approval_is_never_reused(manager: MissionManager, tmp_path: Path) -> None:+ """After a paid run parks, the automatic resume path waits for the+ subscription again and never runs the paid worker without a new approval."""+ paid = FakePaidOption(OFFER, cost_per_spawn=2.5)+ k, mission_id, factory = await _parked(manager, tmp_path, paid=paid)+ await k.decide_capacity(mission_id, "approve_paid", provider=OFFER.provider, model=OFFER.model)+ await _wait_paid_runs(k)+ paid_workers_before = len(paid.workers)++ assert await k.resume_waiting_missions() == [] # subscription still spent+ assert len(paid.workers) == paid_workers_before+ assert await _state(manager, mission_id) == MissionState.WAITING_CAPACITY++ factory.capacity = True # the subscription is back: resume on it, unpaid+ assert await k.resume_waiting_missions() == [mission_id]+ assert len(paid.workers) == paid_workers_before+ assert factory.built == 2 # one capacity probe, one real run+ assert await _state(manager, mission_id) == MissionState.APPROVED+++async def test_approval_on_another_mission_does_not_apply(+ manager: MissionManager, tmp_path: Path+) -> None:+ paid = FakePaidOption(OFFER)+ k, first, _f = await _parked(manager, tmp_path, paid=paid)+ second = await manager.dispatch(prompt="second job")+ assert await k.run_mission(second) == MissionState.WAITING_CAPACITY++ await k.decide_capacity(first, "approve_paid", provider=OFFER.provider, model=OFFER.model)+ await _wait_paid_runs(k)++ assert await _state(manager, first) == MissionState.APPROVED+ assert await _state(manager, second) == MissionState.WAITING_CAPACITY+ assert len(paid.workers) == 1+++async def test_decisions_need_a_parked_mission(manager: MissionManager, tmp_path: Path) -> None:+ paid = FakePaidOption(OFFER)+ k, mission_id, _f = await _parked(manager, tmp_path, paid=paid)+ await k.decide_capacity(mission_id, "cancel")+ with pytest.raises(CapacityDecisionRejected):+ await k.decide_capacity(mission_id, "wait")+++# --- The real paid option (API keys) ----------------------------------------------+++def _keys(monkeypatch: pytest.MonkeyPatch, viable: set[str], models: dict[str, str]) -> None:+ monkeypatch.setattr(mi, "_api_key_family_viable", lambda p: p in viable)+ monkeypatch.setattr(+ "jarvis.missions.workers.api_agent_worker._resolve_worker_model",+ lambda provider, _explicit: models.get(provider, ""),+ )+++def test_same_vendor_key_is_offered_first(monkeypatch: pytest.MonkeyPatch) -> None:+ _keys(+ monkeypatch,+ {"claude-api", "openai"},+ {"claude-api": "claude-sonnet-4-6", "openai": "gpt-5.5"},+ )+ offer = mi.ApiKeyPaidOption().offer(+ pinned_family="claude", open_steps=2, reason="provider_quota"+ )+ assert offer is not None+ assert (offer.provider, offer.model) == ("claude-api", "claude-sonnet-4-6")+ assert offer.estimated_cost_usd == estimate_paid_cost_usd("claude-sonnet-4-6", 2)+ assert offer.cost_cap_usd == PAID_MISSION_CAP_USD+++def test_unpriced_models_are_never_offered(monkeypatch: pytest.MonkeyPatch) -> None:+ _keys(monkeypatch, {"claude-api"}, {"claude-api": "no-such-model-xyz"})+ assert mi.ApiKeyPaidOption().offer(pinned_family="claude", open_steps=1, reason="r") is None+++def test_no_viable_key_means_no_offer(monkeypatch: pytest.MonkeyPatch) -> None:+ _keys(monkeypatch, set(), {"claude-api": "claude-sonnet-4-6"})+ assert mi.ApiKeyPaidOption().offer(pinned_family="claude", open_steps=1, reason="r") is None+++def test_a_spent_api_key_is_not_offered_again(monkeypatch: pytest.MonkeyPatch) -> None:+ _keys(+ monkeypatch,+ {"openrouter", "claude-api"},+ {"openrouter": "claude-sonnet-4-6", "claude-api": "claude-sonnet-4-6"},+ )+ offer = mi.ApiKeyPaidOption().offer(pinned_family="openrouter", open_steps=1, reason="r")+ assert offer is not None and offer.provider == "claude-api"+++def test_paid_worker_is_pinned_to_the_approved_model_and_cap(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(mi, "_assemble_worker_mcp_servers", lambda **_k: ())+ worker = mi.ApiKeyPaidOption().worker(OFFER, remaining_usd=1.25, task_text="t")+ assert isinstance(worker, ApiAgentWorker)+ assert (worker.provider, worker.pinned_model, worker.cost_cap_usd) == (+ "claude-api", "claude-sonnet-4-6", 1.25,+ )+++# --- The API worker stops at the cap and reports its spend --------------------------+++class _UsageBrain:+ """Every turn asks for a tool and reports a fixed usage block."""++ def __init__(self) -> None:+ self.calls = 0++ async def complete(self, _req: BrainRequest) -> AsyncIterator[BrainDelta]:+ self.calls += 1+ yield BrainDelta(+ tool_call={"id": f"c{self.calls}", "name": "Write",+ "input": {"file_path": f"f{self.calls}.txt", "content": "x"}}+ )+ yield BrainDelta(+ finish_reason="tool_use",+ usage={"input_tokens": 200_000, "output_tokens": 10_000, "cache_hit_tokens": 0},+ )+++async def test_api_worker_stops_at_the_cost_cap(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ brain = _UsageBrain()+ monkeypatch.setattr(+ "jarvis.missions.workers.api_agent_worker._build_brain", lambda _p, _m: brain+ )+ per_call = estimate_paid_cost_usd("claude-sonnet-4-6", 1) or 0.0+ assert per_call > 0+ worker = ApiAgentWorker(+ "claude-api", pinned_model="claude-sonnet-4-6", cost_cap_usd=1.0+ )+ events = [+ ev+ async for ev in worker.spawn(+ "go", worktree=tmp_path, env={}, job=None, worker_id="w",+ log_dir=tmp_path / "logs", model="ignored-model",+ )+ ]++ result = events[-1]+ assert result.is_error is True+ assert "cost cap" in result.result+ assert result.cost_usd is not None and result.cost_usd >= 1.0+ # 200k in + 10k out on Sonnet is about $0.75 a call: it stops on call two.+ assert brain.calls == 2+++# --- REST -------------------------------------------------------------------------+++def _app(manager: MissionManager, k: Any) -> FastAPI:+ app = FastAPI()+ app.include_router(router)+ app.state.mission_manager = manager+ app.state.kontrollierer = k+ return app+++async def test_rest_shows_the_offer_and_applies_decisions(+ manager: MissionManager, tmp_path: Path+) -> None:+ paid = FakePaidOption(OFFER)+ k, mission_id, _f = await _parked(manager, tmp_path, paid=paid)+ transport = httpx.ASGITransport(app=_app(manager, k))+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:+ shown = await client.get(f"/api/missions/{mission_id}/paid-offer")+ mismatch = await client.post(+ f"/api/missions/{mission_id}/capacity-decision",+ json={"decision": "approve_paid", "provider": "openai", "model": "gpt-5.5"},+ )+ waited = await client.post(+ f"/api/missions/{mission_id}/capacity-decision", json={"decision": "wait"}+ )+ missing = await client.get("/api/missions/does-not-exist/paid-offer")++ assert shown.status_code == 200+ assert shown.json()["offer"] == {+ "provider": "claude-api",+ "model": "claude-sonnet-4-6",+ "estimated_cost_usd": 1.65,+ "cost_cap_usd": PAID_MISSION_CAP_USD,+ "reason": "provider_quota",+ "open_steps": 1,+ }+ assert mismatch.status_code == 409+ assert waited.status_code == 200 and waited.json()["state"] == "WAITING_CAPACITY"+ assert missing.status_code == 404+ assert paid.workers == []diff --git a/tests/missions/test_capacity_wait.py b/tests/missions/test_capacity_wait.pyindex 5506092f14..fe298a327f 100644--- a/tests/missions/test_capacity_wait.py+++ b/tests/missions/test_capacity_wait.py@@ -411,4 +411,4 @@ def test_readback_keeps_the_options_under_the_length_cap() -> None:language="de",)assert len(text) <= MAX_VOICE_CHARS- assert text.endswith("Freigabe.") # i18n-allow: German TTS phrase under test+ assert text.endswith("Missionsansicht.") # i18n-allow: German TTS phrase under testdiff --git a/tests/missions/test_capacity_wait_parity.py b/tests/missions/test_capacity_wait_parity.pyindex 4a2c48065c..92e32f1bb2 100644--- a/tests/missions/test_capacity_wait_parity.py+++ b/tests/missions/test_capacity_wait_parity.py@@ -97,3 +97,40 @@ def test_repeated_pause_is_not_announced_again() -> None:assert listener._render(env(first), "de")assert listener._render(env(again), "de") == ""++[email protected]("name", ["MissionCapacityDecision", "MissionPaidUsage"])+def test_decision_events_python_ts_parity(name: str) -> None:+ from jarvis.missions import events++ m = re.search(rf"export interface {name} extends BasePayload \{{([^}}]+)\}}", _MISSIONS_TS)+ assert m, f"{name} interface not found in missions.ts"+ ts_fields = set(re.findall(r"^\s*(\w+):", m.group(1), re.MULTILINE))+ assert ts_fields == set(getattr(events, name).model_fields)+ assert name in _ts_union("EventType")+++def test_decision_vocabulary_python_ts_parity() -> None:+ from jarvis.missions.capacity import CapacityDecision+ from jarvis.missions.events import MissionCapacityDecision++ py = set(get_args(CapacityDecision))+ assert py == set(get_args(MissionCapacityDecision.model_fields["decision"].annotation))+ assert _ts_union("CapacityDecision") == py+++def test_decision_dialog_locales_match() -> None:+ def flat(node: dict, prefix: str = "") -> set[str]:+ out: set[str] = set()+ for key, value in node.items():+ path = f"{prefix}.{key}" if prefix else key+ out |= flat(value, path) if isinstance(value, dict) else {path}+ return out++ keys = [flat(_locale(lang)["capacity_decision"]) for lang in _LOCALES]+ assert all(k == keys[0] for k in keys)+ reasons = set(_locale("en")["capacity_decision"]["reasons"])+ assert reasons == set(CAPACITY_WAIT_REASONS)+ from jarvis.missions.capacity import CapacityDecision++ assert set(_locale("en")["capacity_decision"]["logged"]) == set(get_args(CapacityDecision))