Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(missions): close the capacity review findings and gate paid fallback on consent

rubenluetke10-beepb023612c9f13
diff --git a/docs/mission-capacity.md b/docs/mission-capacity.md
new file mode 100644
index 0000000000..af3a31593b
--- /dev/null
+++ b/docs/mission-capacity.md
@@ -0,0 +1,101 @@
+# Mission capacity and paid API fallback
+
+How a mission behaves when the provider it runs on has no capacity left (a
+spent usage window, an expired login, a provider that cannot run), and when it
+may spend money on an API key. Code: `jarvis/missions/capacity.py`; worker
+choice: `jarvis/missions/init.py`; orchestration:
+`jarvis/missions/kontrollierer/orchestrator.py`; critic:
+`jarvis/missions/critic/runner.py`.
+
+## Who is affected
+
+A **subscription install** is one that connected a subscription recently (the
+sticky signal of `jarvis/brain/background_policy.py`) or has a usable
+subscription login right now (the `claude` CLI login, codex over the ChatGPT
+login). A CLI that is merely installed does not count.
+
+An **API-key-only install** is everything else. Its keys are its primary
+provider: the cross-family worker chain is unchanged, the Anthropic key is not
+stripped from the CLI environment, and missions never park for capacity. The
+paid-fallback setting has no effect there.
+
+## Order of choice (subscription install)
+
+Every decision — dispatch, retry, resume, critic — goes through one rule,
+`decide_route`:
+
+1. The configured subscription, else **another connected subscription**
+ (claude ↔ codex). Moving between subscriptions costs nothing extra and needs
+ no approval, for the worker and the critic.
+2. An **active manual approval** of this mission run (the offer shown in the
+ app). It covers worker and critic calls and grants up to `$2` more than the
+ mission already paid.
+3. The **paid-fallback setting** `[missions] paid_api_fallback` (default
+ `false`). When on, the mission continues on the user's own API key — in
+ process, never through a CLI on a classic key — within the caps below.
+4. Otherwise the mission **parks** in `WAITING_CAPACITY` with a checkpoint.
+
+Antigravity and grok build run when they are the configured worker, but they
+are never a silent fallback target: nothing offline can tell whether they have
+capacity.
+
+## Caps (hard, fail closed)
+
+| Cap | Value | Scope |
+| --- | --- | --- |
+| Per mission | `$2` | Cumulative over every paid call of the mission — parallel steps, retries, resumes, worker and critic. Automatic use never resets; each manual approval grants `$2` more. |
+| Per day | `$10` | Rolling 24 h over all automatic (setting-based) paid use. Manual approvals are recorded there for reporting but never blocked by it. |
+
+Every paid call reserves its maximum possible cost first (request bytes as an
+upper bound on input tokens, priced as cache writes, plus the full output
+budget), then books the actual cost from the usage report. A call without a
+usage report is charged its whole reservation. Cache reads and writes are
+counted. Parallel steps share one ledger, so they cannot overshoot together.
+The daily ledger lives in the user data directory
+(`data/mission_paid_ledger.json`), written atomically; an unreadable ledger
+blocks automatic paid use.
+
+## Consent per call
+
+The paid worker and the paid critic call a gate before **each** model call.
+It re-reads the setting (no cache, no restart needed) and checks for an
+active approval. Switching the setting off stops automatic paid use at the
+next call; the mission parks with reason `paid_consent_revoked` and keeps its
+checkpoint.
+
+## Parking and resuming
+
+Reasons (`CapacityWaitReason`): `provider_quota`, `provider_auth`,
+`provider_unavailable`, `paid_cap_reached`, `paid_daily_cap_reached`,
+`paid_consent_revoked`.
+
+A background loop (every 5 minutes plus jitter, never on the boot path)
+resumes a parked mission when a subscription can run its open step, when a
+critic has capacity for a step whose review is pending, or — setting on and
+caps left — on the paid key. A mission that parks again without finishing
+anything new backs off: 5 minutes, doubling to an hour, jittered. A failed
+claim puts the mission back into `WAITING_CAPACITY`; an app shutdown parks a
+resumed mission again instead of cancelling it. The checkpoint is deleted when
+the mission reaches a terminal state.
+
+## HTTP
+
+- `GET /api/mission-billing` — the switch, `subscription_mode`, both caps,
+ `spent_last_24h_usd` (automatic use) and the key that would be used first
+ (`paid_provider`, or `null`). Reads keys, config, login files and the local
+ ledger only; never calls a provider and never returns a secret.
+- `PUT /api/mission-billing` with `{"paid_api_fallback": true|false}` (strict
+ boolean) — persisted through `config_writer.set_missions_paid_api_fallback`,
+ returns the `GET` shape. Marked `x-jarvis-dangerous`, so the CLI asks for
+ `--yes`.
+- `GET /api/missions/{id}/paid-offer` — the per-mission offer, including
+ `spent_usd` (what the mission already paid) and `covers_critic: true`.
+- `POST /api/missions/{id}/capacity-decision` — `wait`, `approve_paid` (must
+ echo the shown provider and model) or `cancel`.
+
+Both billing routes sit behind the global `SurfaceSecurity` boundary like every
+`/api` route: a credential is required, and a browser write needs a trusted
+`Origin`. The setting can never be changed by voice, chat or an agent: the
+config path is in `jarvis/core/self_mod/forbidden.py`, and both the billing
+routes and the capacity decision are excluded from the brain's app-action
+catalog (`jarvis/app_actions/catalog.py`).
diff --git a/jarvis/app_actions/catalog.py b/jarvis/app_actions/catalog.py
index a3ae288cdb..e6ab4886ff 100644
--- a/jarvis/app_actions/catalog.py
+++ b/jarvis/app_actions/catalog.py
@@ -18,12 +18,15 @@ _METHODS: Final[tuple[str, ...]] = ("get", "post", "put", "patch", "delete")
#: Never offered to the brain: credentials and sign-ins (voice must never carry
#: a secret, AP-2), the raw control plane, webhooks, self-modification, the
-#: action policy itself — Jarvis never edits its own permissions — and the
-#: main-brain switch, which only the person may flip (the provider lock).
+#: action policy itself — Jarvis never edits its own permissions — the
+#: main-brain switch, which only the person may flip (the provider lock), and
+#: consent to spend money: the missions' paid-API fallback switch and a
+#: mission's paid-use approval (jarvis/missions/capacity.py).
_EXCLUDED: Final[re.Pattern[str]] = re.compile(
r"(secret|api-?keys?|/keys?(/|$)|install-key|host-key|use-key|token|password|"
r"credential|oauth|/auth(/|$)|login|pairing|/callback|/hooks/|openapi|/ws$|"
- r"^/api/control/|^/api/self-mod|^/api/app-actions|^/api/brain/switch$)",
+ r"^/api/control/|^/api/self-mod|^/api/app-actions|^/api/brain/switch$|"
+ r"^/api/mission-billing|/capacity-decision$)",
re.IGNORECASE,
)
diff --git a/jarvis/codex_auth_state.py b/jarvis/codex_auth_state.py
index 98f380e887..235fb975ab 100644
--- a/jarvis/codex_auth_state.py
+++ b/jarvis/codex_auth_state.py
@@ -9,42 +9,105 @@ provider every mission and falling back twice (worker + critic), which doubled
the Claude Max load and threw the critic into flaky ``critic_loop_exhausted``
under sustained use (forensic: 2026-06-09 codex verify run, 1/3 approved).
-Cleared on a codex success (``turn.completed``) or an explicit ``codex login``,
-so a re-authenticated codex runs natively again. Process-local + in-memory: the
-live app and a verify run are each one process, so a module global is enough;
-it resets on restart (then re-detected on the next dead-codex mission). The
-file-backed + UI-surfaced version is the fuller Wave-C1 follow-up.
+FINGERPRINTED, like ``claude_auth_state``: the flag remembers a hash of the
+codex login file (``<CODEX_HOME>/auth.json``) that produced the failure. As
+soon as that file differs — the user ran ``codex login``, or codex itself
+refreshed the session — the flag no longer applies and codex re-enters
+rotation, without waiting for a codex success. That matters for a mission
+parked on codex (jarvis/missions/capacity.py): no codex run happens while it
+waits, so a success-only clear would keep it parked until the next restart.
+
+Also cleared on a codex success (``turn.completed``). Process-local +
+in-memory: the live app and a verify run are each one process, so a module
+global is enough; it resets on restart (then re-detected on the next
+dead-codex mission).
"""
from __future__ import annotations
+import hashlib
+import logging
+import os
import threading
+from pathlib import Path
+
+log = logging.getLogger(__name__)
_lock = threading.Lock()
_needs_reauth = False
+_dead_fingerprint: str | None = None
+
+
+def codex_auth_file() -> Path:
+ """The codex login file the mission workers use (``$CODEX_HOME`` or
+ ``~/.codex``) — the same home :class:`jarvis.codex_auth.CodexAuthService`
+ reads."""
+ override = os.environ.get("CODEX_HOME")
+ home = Path(override) if override and override.strip() else Path.home() / ".codex"
+ return home / "auth.json"
+
+def codex_auth_fingerprint(path: Path | None = None) -> str | None:
+ """A short, non-reversible fingerprint of the codex login file, or None
+ when it is absent or unreadable. Never the token itself."""
+ target = path or codex_auth_file()
+ try:
+ data = target.read_bytes()
+ except FileNotFoundError: # no login file is a normal answer
+ return None
+ except OSError:
+ log.debug("codex auth file unreadable for fingerprinting", exc_info=True)
+ return None
+ if not data:
+ return None
+ return hashlib.sha256(data).hexdigest()[:16]
-def mark_codex_needs_reauth() -> None:
- """Record that the Codex ChatGPT OAuth session is dead (proven by a 400/401)."""
- global _needs_reauth
+
+def mark_codex_needs_reauth(*, fingerprint: str | None = None) -> None:
+ """Record that the Codex ChatGPT OAuth session is dead (proven by a 400/401).
+
+ ``fingerprint`` identifies the login that failed; by default the current
+ login file. ``None`` with no readable file flags codex until a success.
+ """
+ global _needs_reauth, _dead_fingerprint
+ fp = fingerprint if fingerprint is not None else codex_auth_fingerprint()
with _lock:
_needs_reauth = True
+ _dead_fingerprint = fp
def clear_codex_needs_reauth() -> None:
"""Clear the flag after a codex success or a fresh ``codex login``."""
- global _needs_reauth
+ global _needs_reauth, _dead_fingerprint
with _lock:
_needs_reauth = False
+ _dead_fingerprint = None
+
+def codex_needs_reauth(*, current_fingerprint: str | None = None) -> bool:
+ """True when a codex subprocess proved the CURRENT ChatGPT login dead.
-def codex_needs_reauth() -> bool:
- """True when a codex subprocess proved the ChatGPT login dead this session."""
+ A login file that changed since the failure (a fresh ``codex login``)
+ lifts the flag. ``current_fingerprint`` defaults to the file on disk.
+ """
with _lock:
- return _needs_reauth
+ if not _needs_reauth:
+ return False
+ dead = _dead_fingerprint
+ if dead is None:
+ return True
+ current = (
+ current_fingerprint if current_fingerprint is not None else codex_auth_fingerprint()
+ )
+ if current is not None and current != dead:
+ clear_codex_needs_reauth()
+ return False
+ return True
__all__ = [
- "mark_codex_needs_reauth",
"clear_codex_needs_reauth",
+ "codex_auth_file",
+ "codex_auth_fingerprint",
"codex_needs_reauth",
+ "mark_codex_needs_reauth",
]
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index 17d39f1f97..a300c89cc4 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -4403,6 +4403,24 @@ class Phase6Config(BaseModel):
safety: Phase6SafetyConfig = Field(default_factory=Phase6SafetyConfig)
+class MissionsConfig(BaseModel):
+ """``[missions]`` — how missions may spend money.
+
+ ``paid_api_fallback``: when no connected subscription has capacity, a
+ mission on a subscription install continues on the user's own API key
+ (within the per-mission and daily caps of ``jarvis/missions/capacity.py``)
+ instead of waiting. Default OFF. Read fresh on every paid decision, written
+ only through ``config_writer.set_missions_paid_api_fallback`` from the
+ Settings route — never by voice, chat or an agent tool (the path is in
+ ``jarvis/core/self_mod/forbidden.py``). No effect on an API-key-only
+ install, whose keys are its primary provider anyway.
+ """
+
+ model_config = ConfigDict(extra="allow")
+
+ paid_api_fallback: bool = False
+
+
class GlmCodingPlanConfig(BaseModel):
"""Where a GLM pane sends its traffic, and which model ids it asks for.
@@ -4679,6 +4697,8 @@ class JarvisConfig(BaseModel):
review: ReviewConfig = Field(default_factory=ReviewConfig)
# Phase 6 — mission subsystem ([phase6.safety] typed; rest raw, AP-16).
phase6: Phase6Config = Field(default_factory=Phase6Config)
+ # [missions] — paid API fallback switch for missions (capacity policy).
+ missions: MissionsConfig = Field(default_factory=MissionsConfig)
# Latency sprint 1 (2026-04-30) — master switches for performance levers.
performance: PerformanceConfig = Field(default_factory=PerformanceConfig)
# Wave 0 (omni-latency) — hot-path latency span instrumentation toggle.
diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.py
index 80d8e1f6bf..5a3934eda8 100644
--- a/jarvis/core/config_writer.py
+++ b/jarvis/core/config_writer.py
@@ -1089,6 +1089,20 @@ def set_jarvisx_settings(
_atomic_write(path, out)
+def set_missions_paid_api_fallback(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
+ """Persist ``[missions] paid_api_fallback`` (the paid-API fallback switch).
+
+ The only writer of this key. Called from the Settings route
+ (``PUT /api/mission-billing``) — the self-mod / voice path refuses the key
+ (``jarvis/core/self_mod/forbidden.py``). Read fresh by
+ ``jarvis.missions.capacity.paid_api_fallback_enabled``, so the change
+ applies to the very next mission decision without a restart.
+ """
+ if not isinstance(enabled, bool):
+ raise TypeError("paid_api_fallback must be a bool")
+ _patch_table(path, "missions", "paid_api_fallback", enabled)
+
+
def set_reply_language(name: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist the user-facing reply-language pin in ``[brain] reply_language``.
diff --git a/jarvis/core/self_mod/forbidden.py b/jarvis/core/self_mod/forbidden.py
index e8d34bdc12..f9dbe97c9b 100644
--- a/jarvis/core/self_mod/forbidden.py
+++ b/jarvis/core/self_mod/forbidden.py
@@ -40,6 +40,10 @@ FORBIDDEN_PATTERNS: tuple[str, ...] = (
# vector. These change by file-edit + code-review only, never voice/chat/
# self-mod or the Control API. Guarded by tests/review/test_self_mod_excludes_review.py.
"review.*",
+ # Paid API fallback for missions — spends the user's money. Only the
+ # Settings route (x-jarvis-dangerous) or an explicit CLI call may flip it,
+ # never voice, chat, self-mod or an agent (jarvis/missions/capacity.py).
+ "missions.paid_api_fallback",
"*_api_key",
"*_token",
"*_secret",
diff --git a/jarvis/missions/capacity.py b/jarvis/missions/capacity.py
index 6bc1769274..70c4676343 100644
--- a/jarvis/missions/capacity.py
+++ b/jarvis/missions/capacity.py
@@ -1,23 +1,33 @@
-"""Capacity policy for mission workers: wait, never switch to something that bills.
+"""Capacity policy for mission workers: subscriptions first, paid use only by consent.
When a mission's worker has no capacity left — the subscription's usage window
-is spent, its login expired, or it cannot run at all — the mission is parked in
-``MissionState.WAITING_CAPACITY`` with a checkpoint of the work done so far. It
-is NOT failed, and it is NOT moved to another subscription or to a per-token
-API key: the user decided (2026-10-04) that paid API use happens only after an
-explicit approval for that one mission, and that a subscription install never
-silently changes vendor.
-
-Who is "pinned":
-
-- a mission whose configured worker is itself a subscription CLI (the ``claude``
- CLI, codex over the ChatGPT login, agy, grok build), or
-- any install that has connected a subscription recently — the same sticky
- signal :mod:`jarvis.brain.background_policy` uses for background work.
-
-An install that never connected a subscription keeps its cross-family fallback
-chain, so a single-key download still works (AGENTS.md "any single key must
-work", AP-22).
+is spent, its login expired, or it cannot run at all — the mission first moves
+to ANOTHER connected subscription (codex over the ChatGPT login, the ``claude``
+CLI login): that costs the user nothing extra and needs no approval, for the
+worker and the critic alike. When no subscription can run, there are exactly
+two ways onward:
+
+- the user's persisted setting ``[missions] paid_api_fallback`` (default
+ ``false``): ON lets the mission continue on the user's own API key, within a
+ hard per-mission cap (:data:`PAID_MISSION_CAP_USD`, cumulative) and a rolling
+ 24 h cap across all automatic use (:data:`PAID_DAILY_CAP_USD`);
+- an explicit per-mission approval of the offer shown in the app (each approval
+ grants up to :data:`PAID_MISSION_CAP_USD` more, worker and critic calls).
+
+Anything else parks the mission in ``MissionState.WAITING_CAPACITY`` with a
+checkpoint of the work done so far. It is NOT failed. Consent is re-checked in
+front of EVERY paid model call (:class:`PaidCallGate`), so switching the
+setting off stops automatic paid use at the next call.
+
+Who is "pinned" (subject to all of the above): an install with a real
+subscription — the sticky signal :mod:`jarvis.brain.background_policy` uses for
+background work, or a positive login probe right now. An install that never
+connected a subscription keeps its cross-family fallback chain, its API keys
+are its primary, and it never parks for capacity (AGENTS.md "any single key
+must work", AP-22). The paid-fallback setting has no effect there.
+
+Every decision — dispatch, resume, retry, critic — goes through
+:func:`decide_route`.
"""
from __future__ import annotations
@@ -27,20 +37,31 @@ import logging
import os
import random
import tempfile
+import threading
+import time
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from pathlib import Path
-from typing import Any, Literal, Protocol
+from typing import Any, Literal, Protocol, get_args
log = logging.getLogger(__name__)
CapacityWaitReason = Literal[
- "provider_quota", "provider_auth", "provider_unavailable", "paid_cap_reached"
+ "provider_quota",
+ "provider_auth",
+ "provider_unavailable",
+ "paid_cap_reached",
+ "paid_daily_cap_reached",
+ "paid_consent_revoked",
]
CapacityDecision = Literal["wait", "approve_paid", "cancel"]
+#: The reason vocabulary as a set (mirrors events.CAPACITY_WAIT_REASONS).
+CAPACITY_WAIT_REASON_VALUES: frozenset[str] = frozenset(get_args(CapacityWaitReason))
+
#: Written into ``<mission_dir>/`` when a mission is parked. Its presence also
-#: keeps the mission directory out of the age-based cleanup sweep.
+#: keeps the mission directory out of the age-based cleanup sweep; it is
+#: deleted once the mission reaches a terminal state.
CHECKPOINT_NAME = "checkpoint.json"
#: Bumped when the checkpoint layout changes incompatibly.
@@ -55,16 +76,49 @@ 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.
+#: A mission that parks again without finishing anything new waits longer
+#: before the next try: 5 min after the first such park, doubling up to an
+#: hour, jittered by +/- :data:`RESUME_BACKOFF_JITTER`.
+RESUME_BACKOFF_BASE_S = 300.0
+RESUME_BACKOFF_MAX_S = 3600.0
+RESUME_BACKOFF_JITTER = 0.2
+
+#: Hard spend ceiling of paid API use for ONE mission (user decision
+#: 2026-10-04). Automatic (setting-based) use is cumulative over the whole
+#: mission and never resets; each manual approval grants up to this much more.
PAID_MISSION_CAP_USD = 2.0
+#: Rolling 24 h ceiling across all AUTOMATIC paid mission use on this install.
+PAID_DAILY_CAP_USD = 10.0
+
+#: The rolling window of the daily cap.
+DAILY_WINDOW_S = 24 * 3600.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
+#: Reservation sizing for one paid call. A byte-level tokenizer never makes
+#: more tokens than the UTF-8 bytes it reads, so bytes are an upper bound on
+#: input tokens; a few tokens per message cover the framing. Every input
+#: token is priced as a prompt-cache WRITE (the most expensive input kind).
+RESERVE_OVERHEAD_TOKENS = 512
+CACHE_WRITE_PREMIUM = 1.25
+
+#: Provider families billed by a flat subscription (no per-token cost). Every
+#: other family — claude-api, openai, gemini, openrouter, grok, nvidia, any
+#: other api_agent provider — is metered.
+SUBSCRIPTION_FAMILIES: frozenset[str] = frozenset(
+ {"claude", "codex", "antigravity", "grok-build"}
+)
+
+
+def is_subscription_family(family: str | None) -> bool:
+ """True when ``family`` bills a subscription, not per token."""
+ return (family or "").strip().lower() in SUBSCRIPTION_FAMILIES
+
@dataclass(frozen=True)
class PaidOffer:
@@ -86,7 +140,7 @@ class PaidOption(Protocol):
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 worker(self, offer: PaidOffer, *, gate: PaidCallGate, task_text: str) -> Any:
...
@@ -112,9 +166,64 @@ def estimate_paid_cost_usd(model: str, open_steps: int) -> float | None:
)
+def max_call_cost_usd(model: str, *, input_bytes: int, max_output_tokens: int) -> float | None:
+ """Upper bound in USD for ONE model call, reserved before it is made.
+
+ Input tokens are bounded by the request's UTF-8 bytes (plus
+ :data:`RESERVE_OVERHEAD_TOKENS`) and billed as if every one were a cache
+ write; output at the full ``max_output_tokens``. None for an unpriced model
+ (never called on a cap).
+ """
+ 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
+ input_tokens = max(input_bytes, 0) + RESERVE_OVERHEAD_TOKENS
+ return (
+ input_tokens * rate_in * CACHE_WRITE_PREMIUM
+ + max(max_output_tokens, 0) * rate_out
+ ) / 1_000_000
+
+
+_INPUT_KEYS = ("input_tokens", "prompt_tokens")
+_OUTPUT_KEYS = ("output_tokens", "completion_tokens")
+_CACHE_READ_KEYS = ("cache_hit_tokens", "cache_read_input_tokens", "cached_input_tokens")
+_CACHE_WRITE_KEYS = ("cache_write_tokens", "cache_creation_input_tokens")
+
+
+def usage_cost_usd(model: str, usage: dict[str, Any]) -> float:
+ """USD for one usage block: uncached input, output, cache reads at the
+ vendor's read rate and cache writes at :data:`CACHE_WRITE_PREMIUM`."""
+ from jarvis.brain.cost import calculate_cost_usd, resolve_rates
+
+ def first(keys: tuple[str, ...]) -> int:
+ for key in keys:
+ value = usage.get(key)
+ if value is not None:
+ try:
+ return max(0, int(value))
+ except (TypeError, ValueError):
+ # A non-numeric count says nothing; the reservation's fail
+ # closed rule covers a call that reported nothing usable.
+ return 0
+ return 0
+
+ cost = calculate_cost_usd(
+ model, first(_INPUT_KEYS), first(_OUTPUT_KEYS), first(_CACHE_READ_KEYS)
+ )
+ written = first(_CACHE_WRITE_KEYS)
+ if written:
+ rates = resolve_rates(model)
+ if rates is not None:
+ cost += written * rates[0] * CACHE_WRITE_PREMIUM / 1_000_000
+ return cost
+
+
class WorkerCapacityUnavailable(RuntimeError):
"""Raised by the worker factory instead of picking a worker that would bill
- another subscription or an API key."""
+ a per-token API key nobody consented to."""
def __init__(
self,
@@ -129,9 +238,8 @@ class WorkerCapacityUnavailable(RuntimeError):
class CriticCapacityUnavailable(RuntimeError):
- """The critic's own subscription has no capacity (spent window, dead or
- missing login). Raised instead of grading on another family or a paid
- key — a worker's paid approval never covers critic calls."""
+ """No critic can grade right now: neither the configured subscription nor
+ another connected one, and no consented paid critic call."""
def __init__(self, reason: CapacityWaitReason, provider: str, detail: str = "") -> None:
super().__init__(f"critic {provider}: {reason}" + (f" ({detail})" if detail else ""))
@@ -152,36 +260,499 @@ class CapacityDecisionRejected(RuntimeError):
shown. Nothing was decided or billed."""
-def pinned_to_subscription(*, configured_is_subscription: bool) -> bool:
- """Whether this mission must stay on its configured worker.
+def pinned_to_subscription(*, login_probe: Callable[[], bool] | None = None) -> bool:
+ """Whether this install is a subscription install (missions pinned).
- Fails closed: if the subscription signal cannot be read, the mission waits
- rather than risk billing a key nobody approved.
+ True when a subscription was seen connected recently (the sticky
+ background-policy signal) or ``login_probe`` reports a usable subscription
+ login right now. A CLI that is merely installed is NOT a subscription: a
+ key-only user with Claude Code installed but never logged in keeps the
+ cross-family chain (AP-22).
+
+ Fails closed on an unreadable sticky signal: the mission waits rather than
+ risk billing a key nobody approved. A failing login probe only means "no
+ positive answer".
"""
- if configured_is_subscription:
- return True
try:
from jarvis.brain.background_policy import subscription_mode
- return subscription_mode()
+ if subscription_mode():
+ return True
except Exception: # noqa: BLE001 - unreadable signal: waiting is the safe answer
log.warning(
"capacity: subscription signal unreadable — pinning the mission "
- "to its configured worker",
+ "to its subscription",
exc_info=True,
)
return True
+ if login_probe is None:
+ return False
+ try:
+ return bool(login_probe())
+ except Exception: # noqa: BLE001 - a probe error is "no positive login", logged
+ log.warning("capacity: subscription login probe failed", exc_info=True)
+ return False
-def worker_family(worker: object) -> str:
- """The provider family a worker bills — the identity a parked mission is
- pinned to. Every built-in worker declares ``family``; anything else falls
- back to its ``provider``/``cli`` attribute."""
- for attr in ("family", "provider", "cli"):
- value = getattr(worker, attr, None)
- if isinstance(value, str) and value.strip():
- return value.strip().lower()
- return type(worker).__name__
+def paid_api_fallback_enabled() -> bool:
+ """The persisted ``[missions] paid_api_fallback`` switch, read fresh.
+
+ No cache: a toggle applies to the very next decision. Fails closed — an
+ unreadable config never enables paid use.
+ """
+ try:
+ from jarvis.core.config import load_config
+
+ missions = getattr(load_config(), "missions", None)
+ return bool(getattr(missions, "paid_api_fallback", False) is True)
+ except Exception: # noqa: BLE001 - unreadable config: paid use stays off, logged
+ log.warning("capacity: [missions] config unreadable — paid fallback OFF", exc_info=True)
+ return False
+
+
+# --- Decision -----------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class RouteDecision:
+ """Where the next model call of a pinned mission goes.
+
+ ``subscription``: a subscription (configured or another connected one).
+ ``paid``: the user's API key — ``automatic`` True for the setting-based
+ path, False for a manual per-mission approval. ``park``: wait, ``reason``.
+ """
+
+ route: Literal["subscription", "paid", "park"]
+ reason: CapacityWaitReason | None = None
+ automatic: bool = False
+
+
+def decide_route(
+ *,
+ subscription_ok: bool,
+ unavailable_reason: CapacityWaitReason,
+ manual_approval: bool,
+ paid_fallback_enabled: bool,
+ paid_option_available: bool,
+ mission_remaining_usd: float,
+ daily_remaining_usd: float,
+) -> RouteDecision:
+ """The one routing rule for dispatch, resume, retry and critic calls.
+
+ 1. Any subscription with capacity wins (free).
+ 2. An active manual approval for this mission run: paid, within what that
+ approval left of its cap.
+ 3. The paid-fallback setting ON: paid, within the per-mission cap and the
+ rolling daily cap.
+ 4. Otherwise: park with the subscription's reason.
+ """
+ if subscription_ok:
+ return RouteDecision("subscription")
+ if manual_approval:
+ if mission_remaining_usd <= 0:
+ return RouteDecision("park", "paid_cap_reached")
+ return RouteDecision("paid", automatic=False)
+ if paid_fallback_enabled and paid_option_available:
+ if mission_remaining_usd <= 0:
+ return RouteDecision("park", "paid_cap_reached")
+ if daily_remaining_usd <= 0:
+ return RouteDecision("park", "paid_daily_cap_reached")
+ return RouteDecision("paid", automatic=True)
+ return RouteDecision("park", unavailable_reason)
+
+
+# --- Ledgers ------------------------------------------------------------------
+
+
+class MissionPaidLedger:
+ """Cumulative paid spend of ONE mission, shared by all its parallel steps,
+ retries, resumes, worker and critic calls.
+
+ Every paid call reserves its maximum possible cost first; a reservation
+ that would cross the cap is refused, so parallel callers cannot overshoot.
+ The automatic limit is :data:`PAID_MISSION_CAP_USD` over the whole
+ mission; a manual approval sets a limit of what was spent at approval time
+ plus :data:`PAID_MISSION_CAP_USD`.
+ """
+
+ def __init__(self, spent_usd: float = 0.0) -> None:
+ self._lock = threading.Lock()
+ self._spent = max(float(spent_usd), 0.0)
+ self._reserved = 0.0
+ self._manual_limit: float | None = None
+
+ @property
+ def spent_usd(self) -> float:
+ with self._lock:
+ return self._spent
+
+ @property
+ def manual_active(self) -> bool:
+ with self._lock:
+ return self._manual_limit is not None
+
+ def grant_manual(self) -> None:
+ """A manual approval: up to :data:`PAID_MISSION_CAP_USD` more."""
+ with self._lock:
+ self._manual_limit = self._spent + PAID_MISSION_CAP_USD
+
+ def revoke_manual(self) -> None:
+ with self._lock:
+ self._manual_limit = None
+
+ def _limit(self, automatic: bool) -> float:
+ if automatic:
+ return PAID_MISSION_CAP_USD
+ return self._manual_limit if self._manual_limit is not None else 0.0
+
+ def remaining(self, *, automatic: bool) -> float:
+ with self._lock:
+ return max(self._limit(automatic) - self._spent - self._reserved, 0.0)
+
+ def try_reserve(self, amount_usd: float, *, automatic: bool) -> bool:
+ amount = max(float(amount_usd), 0.0)
+ with self._lock:
+ if self._spent + self._reserved + amount > self._limit(automatic) + 1e-9:
+ return False
+ self._reserved += amount
+ return True
+
+ def release(self, amount_usd: float) -> None:
+ with self._lock:
+ self._reserved = max(self._reserved - max(float(amount_usd), 0.0), 0.0)
+
+ def settle(self, reserved_usd: float, actual_usd: float) -> None:
+ """Replace a reservation by the actual cost of the call."""
+ with self._lock:
+ self._reserved = max(self._reserved - max(float(reserved_usd), 0.0), 0.0)
+ self._spent += max(float(actual_usd), 0.0)
+
+ def charge(self, amount_usd: float) -> None:
+ """Count spend that was never reserved (a worker that reported its
+ cost only at the end). Fail closed: always counted."""
+ with self._lock:
+ self._spent += max(float(amount_usd), 0.0)
+
+
+def _default_daily_ledger_path() -> Path:
+ from jarvis.core.paths import user_data_dir
+
+ return user_data_dir() / "data" / "mission_paid_ledger.json"
+
+
+class DailyPaidLedger:
+ """Rolling 24 h record of paid mission use, persisted as small JSON.
+
+ Automatic (setting-based) calls reserve against :data:`PAID_DAILY_CAP_USD`;
+ manual approvals are recorded for reporting and never blocked by it. The
+ file is rewritten atomically under a lock and pruned to the window; an
+ unreadable file fails closed (no automatic budget left) until it is
+ rewritten.
+ """
+
+ def __init__(
+ self,
+ path: Path | None = None,
+ *,
+ cap_usd: float = PAID_DAILY_CAP_USD,
+ clock: Callable[[], float] = time.time,
+ ) -> None:
+ self._path_override = path
+ self._cap = cap_usd
+ self._clock = clock
+ self._lock = threading.Lock()
+ self._reserved = 0.0
+
+ @property
+ def cap_usd(self) -> float:
+ return self._cap
+
+ def _path(self) -> Path:
+ return self._path_override or _default_daily_ledger_path()
+
+ def _entries(self) -> list[dict[str, Any]] | None:
+ """Entries inside the window, or None when the file is unreadable."""
+ try:
+ raw = json.loads(self._path().read_text(encoding="utf-8"))
+ except FileNotFoundError: # nothing recorded yet
+ return []
+ except (OSError, ValueError):
+ log.warning("capacity: daily paid ledger unreadable — automatic paid use blocked",
+ exc_info=True)
+ return None
+ entries = raw.get("entries") if isinstance(raw, dict) else None
+ if not isinstance(entries, list):
+ return None
+ cutoff = self._clock() - DAILY_WINDOW_S
+ return [
+ e for e in entries
+ if isinstance(e, dict)
+ and isinstance(e.get("ts"), (int, float))
+ and isinstance(e.get("usd"), (int, float))
+ and e["ts"] >= cutoff
+ ]
+
+ def _write(self, entries: list[dict[str, Any]]) -> None:
+ path = self._path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".mission_paid_ledger.")
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ json.dump({"version": 1, "entries": entries}, handle)
+ os.replace(tmp, path)
+ except BaseException:
+ Path(tmp).unlink(missing_ok=True)
+ raise
+
+ @staticmethod
+ def _sum(entries: list[dict[str, Any]], *, automatic_only: bool) -> float:
+ return sum(
+ float(e["usd"]) for e in entries
+ if not automatic_only or e.get("automatic") is True
+ )
+
+ def spent_last_24h(self, *, automatic_only: bool = True) -> float:
+ """USD spent in the last 24 h (automatic use only by default — what
+ the daily cap counts)."""
+ with self._lock:
+ entries = self._entries()
+ if entries is None:
+ return self._cap
+ return round(self._sum(entries, automatic_only=automatic_only), 6)
+
+ def remaining(self) -> float:
+ with self._lock:
+ entries = self._entries()
+ if entries is None:
+ return 0.0
+ return max(self._cap - self._sum(entries, automatic_only=True) - self._reserved, 0.0)
+
+ def try_reserve(self, amount_usd: float) -> bool:
+ amount = max(float(amount_usd), 0.0)
+ with self._lock:
+ entries = self._entries()
+ if entries is None:
+ return False
+ spent = self._sum(entries, automatic_only=True)
+ if spent + self._reserved + amount > self._cap + 1e-9:
+ return False
+ self._reserved += amount
+ return True
+
+ def release(self, amount_usd: float) -> None:
+ with self._lock:
+ self._reserved = max(self._reserved - max(float(amount_usd), 0.0), 0.0)
+
+ def record(
+ self,
+ actual_usd: float,
+ *,
+ automatic: bool,
+ mission_id: str,
+ reserved_usd: float = 0.0,
+ ) -> None:
+ """Book a call's actual cost (and drop its reservation, if any)."""
+ with self._lock:
+ self._reserved = max(self._reserved - max(float(reserved_usd), 0.0), 0.0)
+ cost = max(float(actual_usd), 0.0)
+ if cost <= 0:
+ return
+ entries = self._entries() or []
+ entries.append({
+ "ts": self._clock(),
+ "usd": round(cost, 6),
+ "automatic": automatic,
+ "mission_id": mission_id,
+ })
+ try:
+ self._write(entries)
+ except OSError:
+ # The in-memory mission ledger still caps this mission; the
+ # daily view just misses the entry. Logged, never silent.
+ log.exception("capacity: daily paid ledger write failed")
+
+
+_DEFAULT_DAILY: DailyPaidLedger | None = None
+_DEFAULT_DAILY_LOCK = threading.Lock()
+
+
+def default_daily_ledger() -> DailyPaidLedger:
+ """The process-wide daily ledger (shared by the runner and the routes)."""
+ global _DEFAULT_DAILY
+ with _DEFAULT_DAILY_LOCK:
+ if _DEFAULT_DAILY is None:
+ _DEFAULT_DAILY = DailyPaidLedger()
+ return _DEFAULT_DAILY
+
+
+class CapacityPolicy:
+ """The live answers capacity decisions need, read fresh on every call.
+
+ ``pinned`` / ``paid_fallback`` are injectable for tests (plain callables,
+ no mocks); production uses the install's subscription signal and the
+ persisted setting.
+ """
+
+ def __init__(
+ self,
+ *,
+ pinned: Callable[[], bool] | None = None,
+ paid_fallback: Callable[[], bool] | None = None,
+ daily: DailyPaidLedger | None = None,
+ ) -> None:
+ self._pinned = pinned
+ self._paid_fallback = paid_fallback or paid_api_fallback_enabled
+ self.daily = daily or default_daily_ledger()
+
+ def pinned(self) -> bool:
+ if self._pinned is not None:
+ return bool(self._pinned())
+ from jarvis.missions.init import install_is_pinned
+
+ return install_is_pinned()
+
+ def paid_fallback_enabled(self) -> bool:
+ return bool(self._paid_fallback())
+
+
+# --- The per-call gate --------------------------------------------------------
+
+
+class PaidCallRefused(RuntimeError):
+ """A paid call was refused before it was made: consent gone or a cap hit."""
+
+ def __init__(self, reason: CapacityWaitReason, provider: str) -> None:
+ super().__init__(f"paid {provider} call refused: {reason}")
+ self.reason: CapacityWaitReason = reason
+ self.provider = provider
+
+
+@dataclass(frozen=True)
+class PaidReservation:
+ amount_usd: float
+ automatic: bool
+
+
+class PaidCallGate:
+ """Consent + caps in front of every paid model call of one mission.
+
+ ``reserve`` re-runs the routing decision (``authorize``) — the setting is
+ read fresh, a manual approval must still be active — then reserves the
+ call's maximum cost on the mission ledger and, for automatic use, on the
+ daily ledger. ``commit`` books the actual cost; a call that reported no
+ usage counts its full reservation (fail closed).
+ """
+
+ def __init__(
+ self,
+ *,
+ mission_id: str,
+ offer: PaidOffer,
+ ledger: MissionPaidLedger,
+ daily: DailyPaidLedger,
+ authorize: Callable[[], RouteDecision],
+ on_charge: Callable[[PaidOffer, bool, float], None] | None = None,
+ ) -> None:
+ self.mission_id = mission_id
+ self.offer = offer
+ self._ledger = ledger
+ self._daily = daily
+ self._authorize = authorize
+ self._on_charge = on_charge
+ self._lock = threading.Lock()
+ self.charged_usd = 0.0
+ self.calls = 0
+ self.refusal: CapacityWaitReason | None = None
+ self.last_automatic: bool | None = None
+
+ @property
+ def provider(self) -> str:
+ return self.offer.provider
+
+ @property
+ def model(self) -> str:
+ return self.offer.model
+
+ def remaining_usd(self) -> float:
+ """What this mission may still spend on its current consent."""
+ decision = self._authorize()
+ if decision.route != "paid":
+ return 0.0
+ remaining = self._ledger.remaining(automatic=decision.automatic)
+ if decision.automatic:
+ remaining = min(remaining, self._daily.remaining())
+ return remaining
+
+ def _refuse(self, reason: CapacityWaitReason) -> PaidCallRefused:
+ with self._lock:
+ self.refusal = reason
+ log.warning(
+ "capacity: paid %s call for mission %s refused (%s)",
+ self.offer.provider, self.mission_id, reason,
+ )
+ return PaidCallRefused(reason, self.offer.provider)
+
+ def reserve(self, max_cost_usd: float | None) -> PaidReservation:
+ if max_cost_usd is None:
+ # Unpriced: neither the reservation nor the cap could be trusted.
+ raise self._refuse("provider_unavailable")
+ decision = self._authorize()
+ if decision.route != "paid":
+ reason = decision.reason
+ if reason not in ("paid_cap_reached", "paid_daily_cap_reached"):
+ reason = "paid_consent_revoked"
+ raise self._refuse(reason)
+ amount = max(float(max_cost_usd), 0.0)
+ if not self._ledger.try_reserve(amount, automatic=decision.automatic):
+ raise self._refuse("paid_cap_reached")
+ if decision.automatic and not self._daily.try_reserve(amount):
+ self._ledger.release(amount)
+ raise self._refuse("paid_daily_cap_reached")
+ with self._lock:
+ self.calls += 1
+ self.last_automatic = decision.automatic
+ return PaidReservation(amount_usd=amount, automatic=decision.automatic)
+
+ def commit(self, reservation: PaidReservation, actual_usd: float | None) -> float:
+ """Book the call. ``actual_usd`` None (no usage reported) counts the
+ whole reservation. Returns the booked amount."""
+ cost = reservation.amount_usd if actual_usd is None else max(float(actual_usd), 0.0)
+ if actual_usd is not None and cost > reservation.amount_usd + 1e-9:
+ log.warning(
+ "capacity: paid call for mission %s cost $%.4f, above its $%.4f "
+ "reservation", self.mission_id, cost, reservation.amount_usd,
+ )
+ self._ledger.settle(reservation.amount_usd, cost)
+ self._daily.record(
+ cost,
+ automatic=reservation.automatic,
+ mission_id=self.mission_id,
+ reserved_usd=reservation.amount_usd if reservation.automatic else 0.0,
+ )
+ self._book(reservation.automatic, cost)
+ return cost
+
+ def settle_reported(self, reported_usd: float | None, *, automatic: bool) -> float:
+ """Charge what a worker reported beyond what its gated calls booked —
+ a worker that never used the gate is charged its whole report.
+ Returns the extra amount charged."""
+ with self._lock:
+ extra = max(float(reported_usd or 0.0) - self.charged_usd, 0.0)
+ if extra <= 0:
+ return 0.0
+ self._ledger.charge(extra)
+ self._daily.record(extra, automatic=automatic, mission_id=self.mission_id)
+ self._book(automatic, extra)
+ return extra
+
+ def _book(self, automatic: bool, cost: float) -> None:
+ with self._lock:
+ self.charged_usd += cost
+ if self._on_charge is not None:
+ self._on_charge(self.offer, automatic, cost)
+
+
+# --- Checkpoint ---------------------------------------------------------------
def write_checkpoint(mission_dir: Path, data: dict[str, Any]) -> Path:
@@ -213,6 +784,39 @@ def read_checkpoint(mission_dir: Path) -> dict[str, Any] | None:
return data if isinstance(data, dict) else None
+def delete_checkpoint(mission_dir: Path) -> None:
+ """Drop the checkpoint of a mission that reached a terminal state, so the
+ age-based cleanup may sweep its directory again."""
+ try:
+ (mission_dir / CHECKPOINT_NAME).unlink(missing_ok=True)
+ except OSError:
+ log.warning("capacity: could not delete checkpoint in %s", mission_dir, exc_info=True)
+
+
+def resume_backoff_s(
+ idle_parks: int,
+ *,
+ jitter: Callable[[float, float], float] = random.uniform,
+) -> float:
+ """Extra wait before the next automatic resume of a mission that parked
+ ``idle_parks`` times in a row without finishing anything new."""
+ if idle_parks <= 0:
+ return 0.0
+ base = min(RESUME_BACKOFF_BASE_S * (2 ** (idle_parks - 1)), RESUME_BACKOFF_MAX_S)
+ return base * jitter(1.0 - RESUME_BACKOFF_JITTER, 1.0 + RESUME_BACKOFF_JITTER)
+
+
+def worker_family(worker: object) -> str:
+ """The provider family a worker bills — the identity a parked mission is
+ pinned to. Every built-in worker declares ``family``; anything else falls
+ back to its ``provider``/``cli`` attribute."""
+ for attr in ("family", "provider", "cli"):
+ value = getattr(worker, attr, None)
+ if isinstance(value, str) and value.strip():
+ return value.strip().lower()
+ return type(worker).__name__
+
+
async def capacity_resume_loop(
resume_pass: Callable[[], Awaitable[list[str]]],
*,
@@ -241,25 +845,47 @@ async def capacity_resume_loop(
__all__ = [
+ "CACHE_WRITE_PREMIUM",
+ "CAPACITY_WAIT_REASON_VALUES",
"CHECKPOINT_NAME",
"CHECKPOINT_VERSION",
+ "DAILY_WINDOW_S",
"ESTIMATE_INPUT_TOKENS_PER_STEP",
"ESTIMATE_OUTPUT_TOKENS_PER_STEP",
+ "MAX_REVIEW_RETRIES",
+ "PAID_DAILY_CAP_USD",
"PAID_MISSION_CAP_USD",
+ "RESUME_BACKOFF_BASE_S",
+ "RESUME_BACKOFF_MAX_S",
"RESUME_INTERVAL_S",
"RESUME_JITTER_S",
+ "SUBSCRIPTION_FAMILIES",
"CapacityDecision",
"CapacityDecisionRejected",
+ "CapacityPolicy",
"CapacityWaitReason",
"CriticCapacityUnavailable",
- "MAX_REVIEW_RETRIES",
+ "DailyPaidLedger",
+ "MissionPaidLedger",
+ "PaidCallGate",
+ "PaidCallRefused",
"PaidOffer",
"PaidOption",
+ "PaidReservation",
+ "RouteDecision",
"WorkerCapacityUnavailable",
"capacity_resume_loop",
+ "decide_route",
+ "default_daily_ledger",
+ "delete_checkpoint",
"estimate_paid_cost_usd",
+ "is_subscription_family",
+ "max_call_cost_usd",
+ "paid_api_fallback_enabled",
"pinned_to_subscription",
"read_checkpoint",
+ "resume_backoff_s",
+ "usage_cost_usd",
"worker_family",
"write_checkpoint",
]
diff --git a/jarvis/missions/critic/runner.py b/jarvis/missions/critic/runner.py
index 098380727e..efcc729029 100644
--- a/jarvis/missions/critic/runner.py
+++ b/jarvis/missions/critic/runner.py
@@ -34,6 +34,13 @@ from typing import Any, Final
from pydantic import ValidationError
from jarvis.costs.ledger import usage_context
+from jarvis.missions.capacity import (
+ CapacityWaitReason,
+ CriticCapacityUnavailable,
+ PaidCallGate,
+ PaidCallRefused,
+ PaidReservation,
+)
from ..stream_evidence import (
capability_refusal_answer,
@@ -832,6 +839,7 @@ class CriticRunner:
security_tag: bool = False,
prior_confidence: float | None = None,
_capability_check: bool = True,
+ paid_gate: PaidCallGate | None = None,
) -> CriticVerdict:
"""Execute one Critic iteration and return the validated verdict.
@@ -845,6 +853,9 @@ class CriticRunner:
env: env dict from build_worker_env (allowlist only).
security_tag: True when the mission touches auth/crypto/db -> Opus forced.
prior_confidence: From the previous iteration; <0.4 -> Opus forced.
+ paid_gate: Consent + caps for a paid critic call on a subscription
+ install whose subscriptions all have no capacity
+ (jarvis/missions/capacity.py). None = no paid critic.
Returns:
Validated `CriticVerdict`.
@@ -1118,6 +1129,7 @@ class CriticRunner:
schema_json=schema_json,
use_bare=use_bare,
adversarial_reframe=False,
+ paid_gate=paid_gate,
)
# Aggregation check FIRST (deterministic):
@@ -1168,6 +1180,7 @@ class CriticRunner:
schema_json=schema_json,
use_bare=use_bare,
adversarial_reframe=True,
+ paid_gate=paid_gate,
)
# After retry: check aggregation downgrade again (deterministic).
@@ -1464,6 +1477,7 @@ class CriticRunner:
schema_json: str,
use_bare: bool,
adversarial_reframe: bool,
+ paid_gate: PaidCallGate | None = None,
) -> CriticVerdict | None:
"""Spawns the critic subprocess once; returns the verdict or None on JSON error.
@@ -1513,12 +1527,11 @@ class CriticRunner:
)
primary_provider, primary_model = _resolve_critic_provider_model()
- # Capacity policy (jarvis/missions/capacity.py): a mission pinned to a
- # subscription is graded on that subscription's critic ONLY. The
- # cross-family walk below (codex, then per-token API critics) would
- # bill a key nobody approved exactly when the subscription is spent —
- # and a worker's paid approval never covers critic calls.
- self._capacity_signal: tuple[str, str, str] | None = None
+ # Capacity policy (jarvis/missions/capacity.py): on a subscription
+ # install the critic grades on a subscription (the configured one, else
+ # another connected one — free), and on a per-token key only through a
+ # consented paid gate. The cross-family walk below would bill a key
+ # nobody approved exactly when the subscription is spent.
if _critic_subscription_only(primary_provider):
return await self._invoke_pinned_critic(
primary_provider=primary_provider,
@@ -1530,6 +1543,7 @@ class CriticRunner:
env=env,
iteration=iteration,
adversarial_reframe=adversarial_reframe,
+ paid_gate=paid_gate,
)
# Auth-viability gate (2026-07-07, mission 019f3d18 / BUG-042 defect 5):
# this branch used to spawn `claude --print` UNCONDITIONALLY — with a
@@ -1707,6 +1721,19 @@ class CriticRunner:
primary, _model = _resolve_critic_provider_model()
return _critic_family(primary)
+ def capacity_available(self) -> bool:
+ """Whether a critic can grade right now without paid use (offline:
+ login files, quota/auth flags, key viability — never a provider
+ call). The resume loop asks this for steps whose review is pending."""
+ primary, _model = _resolve_critic_provider_model()
+ if not _critic_subscription_only(primary):
+ return True
+ family = _critic_family(primary)
+ return any(
+ _critic_family_unavailable(fam) is None
+ for fam in dict.fromkeys((family, *_CRITIC_SUBSCRIPTION_FALLBACK))
+ )
+
async def _invoke_pinned_critic(
self,
*,
@@ -1719,107 +1746,124 @@ class CriticRunner:
env: dict[str, str],
iteration: int,
adversarial_reframe: bool,
+ paid_gate: PaidCallGate | None = None,
) -> CriticVerdict | None:
- """Grade on the pinned subscription's own critic, or nowhere.
+ """Grade on the configured subscription, else on another connected
+ subscription (free), else on a consented paid key — or nowhere.
- No codex/claude cross-over and no per-token API critic. A critic that
- has no capacity raises :class:`CriticCapacityUnavailable` so the
- mission parks; any other failure returns None as before.
+ A family that is out of capacity (offline probe, or the CLI said so)
+ hands over to the next one. When none can grade and no ``paid_gate``
+ permits a paid call, :class:`CriticCapacityUnavailable` parks the
+ mission. Any other failure returns None as before.
"""
- from jarvis.missions.capacity import CriticCapacityUnavailable
+ configured = _critic_family(primary_provider)
+ first: tuple[CapacityWaitReason, str, str] | None = None
+ for family in dict.fromkeys((configured, *_CRITIC_SUBSCRIPTION_FALLBACK)):
+ reason = _critic_family_unavailable(family)
+ if reason is not None:
+ if first is None:
+ first = (reason, family, "")
+ continue
+ if first is not None:
+ logger.warning(
+ "CriticRunner: %s critic has no capacity (%s) — grading on the "
+ "%s subscription instead (no extra cost).",
+ first[1], first[0], family,
+ )
+ signals: list[tuple[CapacityWaitReason, str]] = []
+ verdict = await self._grade_on_family(
+ family,
+ configured=configured,
+ primary_provider=primary_provider,
+ primary_model=primary_model,
+ model=model,
+ prompt=prompt,
+ codex_prompt=codex_prompt,
+ worktree=worktree,
+ env=env,
+ iteration=iteration,
+ adversarial_reframe=adversarial_reframe,
+ capacity_signals=signals,
+ )
+ if verdict is not None:
+ return verdict
+ if not signals:
+ return None # not a capacity problem: the caller's retry handles it
+ if first is None:
+ first = (signals[0][0], family, signals[0][1])
+ if paid_gate is not None:
+ logger.warning(
+ "CriticRunner: no subscription critic has capacity — grading on "
+ "%s/%s within the mission's paid-use consent and caps.",
+ paid_gate.provider, paid_gate.model,
+ )
+ try:
+ return await self._invoke_via_api_critic(
+ prompt=prompt,
+ model=paid_gate.model,
+ provider=paid_gate.provider,
+ iteration=iteration,
+ adversarial_reframe=adversarial_reframe,
+ paid_gate=paid_gate,
+ )
+ except PaidCallRefused as exc:
+ raise CriticCapacityUnavailable(exc.reason, exc.provider) from None
+ reason, family, detail = first or ("provider_unavailable", configured, "")
+ raise CriticCapacityUnavailable(reason, family, detail)
- family = _critic_family(primary_provider)
+ async def _grade_on_family(
+ self,
+ family: str,
+ *,
+ configured: str,
+ primary_provider: str | None,
+ primary_model: str | None,
+ model: str,
+ prompt: str,
+ codex_prompt: str,
+ worktree: Path,
+ env: dict[str, str],
+ iteration: int,
+ adversarial_reframe: bool,
+ capacity_signals: list[tuple[CapacityWaitReason, str]],
+ ) -> CriticVerdict | None:
+ """One critic call on ``family`` (claude, codex, or the configured
+ API provider's own key)."""
if family == "codex":
- from jarvis.codex_auth_state import codex_needs_reauth
- from jarvis.codex_quota_state import codex_in_quota_cooldown
from jarvis.missions.workers.codex_direct_worker import (
_normalize_model_for_codex,
)
- if codex_needs_reauth():
- raise CriticCapacityUnavailable("provider_auth", "codex")
- if codex_in_quota_cooldown():
- raise CriticCapacityUnavailable("provider_quota", "codex")
- verdict = await self._invoke_via_codex_direct(
+ # A fallback from another family runs codex on its CLI default:
+ # a foreign model id would be rejected.
+ codex_model = (primary_model or model) if configured == "codex" else ""
+ return await self._invoke_via_codex_direct(
prompt=codex_prompt,
worktree=worktree,
env=env,
- model=_normalize_model_for_codex(primary_model or model),
+ model=_normalize_model_for_codex(codex_model),
iteration=iteration,
adversarial_reframe=adversarial_reframe,
+ capacity_signals=capacity_signals,
)
- elif family == "claude":
- from jarvis.claude_quota_state import claude_in_quota_cooldown
- from jarvis.missions.workers.claude_direct_worker import (
- _resolve_claude_binary,
- )
-
- if _resolve_claude_binary() is None:
- raise CriticCapacityUnavailable(
- "provider_unavailable", "claude", "the claude CLI is not installed"
- )
- if claude_in_quota_cooldown():
- raise CriticCapacityUnavailable("provider_quota", "claude")
- # The mission env never carries a per-token Anthropic key for a
- # pinned install (missions/init.py), so a viable CLI here means
- # the subscription login; a dead one parks the mission.
- if not _claude_cli_critic_viable():
- raise CriticCapacityUnavailable("provider_auth", "claude")
- verdict = await self._invoke_via_claude_direct(
+ if family == "claude":
+ return await self._invoke_via_claude_direct(
prompt=prompt,
worktree=worktree,
env=env,
model=(primary_model or model) if primary_provider == "claude-api" else model,
iteration=iteration,
adversarial_reframe=adversarial_reframe,
+ capacity_signals=capacity_signals,
)
- else:
- # A pinned install whose worker is an API provider the user chose
- # grades on that same provider only — never on another family.
- api_provider, api_model = _resolve_api_critic_provider(
- primary_provider, primary_model, excluded_providers=set()
- )
- if not api_provider or api_provider != primary_provider:
- raise CriticCapacityUnavailable("provider_unavailable", family)
- verdict = await self._invoke_via_api_critic(
- prompt=prompt,
- model=api_model,
- provider=api_provider,
- iteration=iteration,
- adversarial_reframe=adversarial_reframe,
- )
- if verdict is not None:
- return verdict
- signal = self._capacity_signal
- if signal is not None:
- reason, signal_family, detail = signal
- raise CriticCapacityUnavailable(reason, signal_family, detail) # type: ignore[arg-type]
- return None
-
- def _note_capacity_signal(self, family: str, text: str) -> None:
- """Remember that a critic CLI said it has no capacity, and arm the
- family's cooldown so an automatic resume waits for it."""
- low = (text or "").lower()
- if any(marker in low for marker in _CRITIC_AUTH_MARKERS):
- reason = "provider_auth"
- elif any(marker in low for marker in _CRITIC_QUOTA_MARKERS):
- reason = "provider_quota"
- else:
- return
- self._capacity_signal = (reason, family, (text or "").strip()[:200])
- if reason == "provider_quota":
- if family == "claude":
- from jarvis.claude_quota_state import mark_claude_quota_cooldown
-
- mark_claude_quota_cooldown()
- elif family == "codex":
- from jarvis.codex_quota_state import mark_codex_quota_cooldown
-
- mark_codex_quota_cooldown()
- elif family == "codex":
- from jarvis.codex_auth_state import mark_codex_needs_reauth
-
- mark_codex_needs_reauth()
+ # The API provider the user chose for this install, on its own key.
+ return await self._invoke_via_api_critic(
+ prompt=prompt,
+ model=primary_model,
+ provider=family,
+ iteration=iteration,
+ adversarial_reframe=adversarial_reframe,
+ )
# --- Internal: direct claude --print path (CRIT-1, 2026-05-17) ---
@@ -1832,9 +1876,13 @@ class CriticRunner:
model: str,
iteration: int,
adversarial_reframe: bool,
+ capacity_signals: list[tuple[CapacityWaitReason, str]] | None = None,
) -> CriticVerdict | None:
"""Spawn ``claude --print`` directly with the prompt on stdin.
+ ``capacity_signals`` (per call, never shared) collects a "no capacity"
+ notice the CLI printed instead of a review.
+
Mirrors ``ClaudeDirectWorker`` semantics minus the writes:
* ``--permission-mode plan`` — Critic is read-only by design.
* ``--add-dir <worktree>`` so claude can still read files the
@@ -1991,12 +2039,15 @@ class CriticRunner:
model="",
iteration=iteration,
adversarial_reframe=adversarial_reframe,
+ capacity_signals=capacity_signals,
)
logger.warning(
"CriticRunner: claude-direct returncode=%d wall_ms=%d stderr=%r",
proc.returncode, wall_ms, stderr_text,
)
- self._note_capacity_signal("claude", stderr_text + " " + stdout_text[:1000])
+ _note_capacity_signal(
+ "claude", stderr_text + " " + stdout_text[:1000], capacity_signals
+ )
return None
stdout_text = stdout_b.decode("utf-8", errors="replace")
@@ -2026,7 +2077,7 @@ class CriticRunner:
# a short output counts: a long one is a review that merely mentions
# quotas or rate limits.
if len(stdout_text.strip()) <= _CAPACITY_NOTICE_MAX_CHARS:
- self._note_capacity_signal("claude", stdout_text)
+ _note_capacity_signal("claude", stdout_text, capacity_signals)
return None
# --- Internal: direct codex exec path (Welle 6, 2026-05-18) ---
@@ -2039,6 +2090,7 @@ class CriticRunner:
provider: str,
iteration: int,
adversarial_reframe: bool,
+ paid_gate: PaidCallGate | None = None,
) -> CriticVerdict | None:
"""Grade the mission IN-PROCESS via the provider's own BrainProvider.
@@ -2046,7 +2098,14 @@ class CriticRunner:
backend so a mission's review never requires the absent `claude` binary
(open-source AP-22, B2). Returns ``None`` on any failure so the caller's
claude-direct fallback / adversarial retry still runs.
+
+ With ``paid_gate`` (a consented paid fallback) the call reserves its
+ maximum cost first — :class:`PaidCallRefused` propagates when consent
+ is gone or a cap is reached — and books its actual cost after; a call
+ without usage data counts its whole reservation.
"""
+ reservation: PaidReservation | None = None
+ call_usd: float | None = None
try:
from jarvis.brain.provider_registry import BrainProviderRegistry
from jarvis.core.config import (
@@ -2074,17 +2133,35 @@ class CriticRunner:
max_tokens=2048,
)
parts: list[str] = []
+ if paid_gate is not None:
+ from jarvis.missions.capacity import max_call_cost_usd
+
+ reservation = paid_gate.reserve(
+ max_call_cost_usd(
+ model or "",
+ input_bytes=len(prompt.encode("utf-8"))
+ + len((req.system or "").encode("utf-8")),
+ max_output_tokens=req.max_tokens or 2048,
+ )
+ )
async with asyncio.timeout(self._timeout):
with override_provider_secrets({provider: worker_key}):
with usage_context("mission-critic"):
_stream = brain.complete(req)
async for delta in _stream:
+ usage = getattr(delta, "usage", None)
+ if usage and paid_gate is not None:
+ from jarvis.missions.capacity import usage_cost_usd
+
+ call_usd = (call_usd or 0.0) + usage_cost_usd(model or "", usage)
chunk = getattr(delta, "content", None)
if chunk:
parts.append(chunk)
return _parse_verdict_from_text(
"".join(parts), iteration=iteration, adversarial_reframe=adversarial_reframe,
)
+ except PaidCallRefused:
+ raise
except TimeoutError:
logger.warning(
"CriticRunner: API critic (%s) timed out after %.0fs.",
@@ -2097,6 +2174,9 @@ class CriticRunner:
provider, exc,
)
return None
+ finally:
+ if paid_gate is not None and reservation is not None:
+ paid_gate.commit(reservation, call_usd)
async def _invoke_via_codex_direct(
self,
@@ -2107,6 +2187,7 @@ class CriticRunner:
model: str,
iteration: int,
adversarial_reframe: bool,
+ capacity_signals: list[tuple[CapacityWaitReason, str]] | None = None,
) -> CriticVerdict | None:
"""Spawn ``codex exec --json`` directly with the prompt on stdin.
@@ -2273,7 +2354,9 @@ class CriticRunner:
"returncode=%d wall_ms=%d stderr=%r",
proc.returncode, wall_ms, stderr_text,
)
- self._note_capacity_signal("codex", stderr_text + " " + stdout_text[:1000])
+ _note_capacity_signal(
+ "codex", stderr_text + " " + stdout_text[:1000], capacity_signals
+ )
return None
if proc.returncode != 0 and not terminal_ok:
@@ -2284,7 +2367,9 @@ class CriticRunner:
"returncode=%d wall_ms=%d stderr=%r",
proc.returncode, wall_ms, stderr_text,
)
- self._note_capacity_signal("codex", stderr_text + " " + stdout_text[:1000])
+ _note_capacity_signal(
+ "codex", stderr_text + " " + stdout_text[:1000], capacity_signals
+ )
return None
# Last agent_message wins. With --output-schema codex returns the
@@ -2312,18 +2397,83 @@ class CriticRunner:
# --- Helpers ---
-#: Critic CLI output that means "no capacity", not "bad review".
-_CRITIC_QUOTA_MARKERS: tuple[str, ...] = (
- "session limit", "usage limit", "rate limit", "rate_limit", "too many requests",
- "429", "out of credits", "out_of_credits", "credit balance", "quota", "overloaded",
+#: Critic CLI output that means the subscription window or credit is SPENT.
+#: Anchored phrases from the vendors' own notices — never a bare "429",
+#: "quota" or "rate limit", which a transient throttle or an ordinary review
+#: also prints. A transient overload / 5xx / rate limit is NOT a capacity
+#: signal: it must not arm a quota cooldown or park a mission.
+_CRITIC_QUOTA_PATTERNS: tuple[re.Pattern[str], ...] = tuple(
+ re.compile(p)
+ for p in (
+ r"\byou'?ve (?:hit|reached) your (?:session|usage|weekly|daily|monthly) limit\b",
+ r"\b(?:session|usage|weekly) limit (?:reached|exceeded)\b",
+ r"\bclaude ai usage limit reached\b",
+ r"\binsufficient_quota\b",
+ r"\bcredit balance is too low\b",
+ r"\bout of credits\b",
+ r"\bpurchase more credits\b",
+ )
)
-_CRITIC_AUTH_MARKERS: tuple[str, ...] = (
- "not logged in", "please log in", "log in again", "/login", "401",
- "authentication_error", "invalid api key", "oauth token has expired",
+#: Critic CLI output that means the subscription LOGIN is dead.
+_CRITIC_AUTH_PATTERNS: tuple[re.Pattern[str], ...] = tuple(
+ re.compile(p)
+ for p in (
+ r"\bnot logged in\b",
+ r"\bplease (?:run )?/login\b",
+ r"\bplease log ?in again\b",
+ r"\boauth token has expired\b",
+ r"\binvalid authentication credentials\b",
+ r"\bauthentication_error\b",
+ r"\b(?:api error|http|status(?: code)?):? 401\b",
+ )
)
#: A limit notice is one short line; longer output is a review.
_CAPACITY_NOTICE_MAX_CHARS = 400
+#: Subscriptions a pinned critic may move to for free, after the configured
+#: family — the same set the worker factory uses (missions/init.py).
+_CRITIC_SUBSCRIPTION_FALLBACK: tuple[str, ...] = ("claude", "codex")
+
+
+def _capacity_signal(text: str) -> tuple[CapacityWaitReason, str] | None:
+ """``(reason, detail)`` when critic CLI output says the subscription has
+ no capacity (spent window / dead login), else None."""
+ low = (text or "").lower()
+ if any(p.search(low) for p in _CRITIC_AUTH_PATTERNS):
+ return "provider_auth", (text or "").strip()[:200]
+ if any(p.search(low) for p in _CRITIC_QUOTA_PATTERNS):
+ return "provider_quota", (text or "").strip()[:200]
+ return None
+
+
+def _note_capacity_signal(
+ family: str,
+ text: str,
+ sink: list[tuple[CapacityWaitReason, str]] | None,
+) -> None:
+ """Record a "no capacity" notice for THIS call (``sink``) and arm the
+ family's flag so the worker factory and the resume loop wait for it."""
+ signal = _capacity_signal(text)
+ if signal is None:
+ return
+ reason, detail = signal
+ if sink is not None:
+ sink.append((reason, detail))
+ if reason == "provider_quota":
+ if family == "claude":
+ from jarvis.claude_quota_state import mark_claude_quota_cooldown
+
+ mark_claude_quota_cooldown()
+ elif family == "codex":
+ from jarvis.codex_quota_state import mark_codex_quota_cooldown
+
+ mark_codex_quota_cooldown()
+ elif family == "codex":
+ # Fingerprinted to the codex login file: a fresh `codex login` lifts it.
+ from jarvis.codex_auth_state import mark_codex_needs_reauth
+
+ mark_codex_needs_reauth()
+
def _critic_family(primary_provider: str | None) -> str:
"""The subscription family behind a critic provider slug."""
@@ -2334,22 +2484,50 @@ def _critic_family(primary_provider: str | None) -> str:
return primary_provider or "claude"
-def _critic_subscription_only(primary_provider: str | None) -> bool:
- """Whether the critic must stay on the mission's own subscription.
+def _critic_family_unavailable(family: str) -> CapacityWaitReason | None:
+ """Why ``family`` cannot grade on a subscription install right now, or
+ None when it can. Offline only."""
+ try:
+ if family == "codex":
+ from jarvis.codex_auth_state import codex_needs_reauth
+ from jarvis.codex_quota_state import codex_in_quota_cooldown
+ from jarvis.missions.workers.codex_direct_worker import _codex_oauth_available
- Same rule as the worker factory: the claude CLI or codex as the configured
- backend pins the critic, and so does any install that connected a
- subscription. Fails closed — an unreadable signal never opens paid keys.
- """
+ if not _codex_oauth_available() or codex_needs_reauth():
+ return "provider_auth"
+ if codex_in_quota_cooldown():
+ return "provider_quota"
+ return None
+ if family == "claude":
+ from jarvis.claude_quota_state import claude_in_quota_cooldown
+ from jarvis.missions.workers.claude_direct_worker import _resolve_claude_binary
+
+ if _resolve_claude_binary() is None:
+ return "provider_unavailable"
+ if claude_in_quota_cooldown():
+ return "provider_quota"
+ if not _claude_cli_critic_viable():
+ return "provider_auth"
+ return None
+ from jarvis.api_family_quota_state import api_family_in_cooldown
+ from jarvis.missions.init import _api_key_family_viable
+
+ if _api_key_family_viable(family):
+ return None
+ return "provider_quota" if api_family_in_cooldown(family) else "provider_unavailable"
+ except Exception: # noqa: BLE001 - an unreadable probe means "not now", logged
+ logger.warning("CriticRunner: capacity probe for %s failed", family, exc_info=True)
+ return "provider_unavailable"
+
+
+def _critic_subscription_only(primary_provider: str | None) -> bool:
+ """Whether the critic is bound by the capacity policy (a subscription
+ install). Same question as the worker factory and the env builder:
+ :func:`jarvis.missions.init.install_is_pinned`. Fails closed."""
try:
- from jarvis.missions.capacity import pinned_to_subscription
- from jarvis.missions.workers.claude_direct_worker import _resolve_claude_binary
+ from jarvis.missions.init import install_is_pinned
- family = _critic_family(primary_provider)
- configured = family == "codex" or (
- family == "claude" and _resolve_claude_binary() is not None
- )
- return pinned_to_subscription(configured_is_subscription=configured)
+ return install_is_pinned()
except Exception: # noqa: BLE001 - logged; waiting is the safe answer
logger.warning("CriticRunner: pinning signal unreadable — pinned critic", exc_info=True)
return True
@@ -2363,14 +2541,25 @@ def _claude_cli_critic_viable() -> bool:
``claude --print`` critic exits 1 — two attempts per mission →
``critic_unavailable`` kills a mission whose worker already delivered.
Reuses the worker factory's shared auth probe so worker and critic agree.
+ On a subscription install the mission env carries no classic Anthropic key
+ (missions/init.py strips it), so only the subscription login counts there —
+ a stored key the CLI never sees is not viability.
"""
try:
- from jarvis.missions.init import _claude_cli_auth_viable
+ from jarvis.missions.init import (
+ _claude_cli_auth_viable,
+ _claude_subscription_login_state,
+ install_is_pinned,
+ )
from jarvis.missions.workers.claude_direct_worker import (
_resolve_claude_binary,
)
- return _resolve_claude_binary() is not None and _claude_cli_auth_viable()
+ if _resolve_claude_binary() is None:
+ return False
+ if install_is_pinned():
+ return _claude_subscription_login_state() is True
+ return _claude_cli_auth_viable()
except Exception: # noqa: BLE001 — unreadable probe => not viable
return False
diff --git a/jarvis/missions/events.py b/jarvis/missions/events.py
index 1037127717..712529b657 100644
--- a/jarvis/missions/events.py
+++ b/jarvis/missions/events.py
@@ -163,7 +163,9 @@ 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
+ "paid_cap_reached", # the mission's paid spend reached its ceiling
+ "paid_daily_cap_reached", # automatic paid use hit the rolling 24 h ceiling
+ "paid_consent_revoked", # paid fallback switched off mid-run, no approval
})
@@ -176,7 +178,12 @@ class MissionWaitingCapacity(_PayloadBase):
event_type: Literal["MissionWaitingCapacity"] = "MissionWaitingCapacity"
reason: Literal[
- "provider_quota", "provider_auth", "provider_unavailable", "paid_cap_reached"
+ "provider_quota",
+ "provider_auth",
+ "provider_unavailable",
+ "paid_cap_reached",
+ "paid_daily_cap_reached",
+ "paid_consent_revoked",
]
provider: str | None = None
steps_done: int = 0
@@ -206,7 +213,8 @@ class MissionCapacityDecision(_PayloadBase):
class MissionPaidUsage(_PayloadBase):
- """What an approved paid run actually cost, logged when the run ends."""
+ """What paid API use actually cost in one mission run, logged when the
+ run ends — one event per provider/model and consent kind."""
event_type: Literal["MissionPaidUsage"] = "MissionPaidUsage"
provider: str
@@ -214,6 +222,9 @@ class MissionPaidUsage(_PayloadBase):
cost_usd: float
cost_cap_usd: float
estimated_cost_usd: float
+ # True: the [missions] paid_api_fallback setting allowed it; False: a
+ # manual per-mission approval.
+ automatic: bool = False
class MissionCancelled(_PayloadBase):
diff --git a/jarvis/missions/init.py b/jarvis/missions/init.py
index 048bd85cea..0f17ab88e6 100644
--- a/jarvis/missions/init.py
+++ b/jarvis/missions/init.py
@@ -36,6 +36,7 @@ from jarvis.core.bus import EventBus as _SpeechEventBus
from .budget import BudgetTracker
from .capacity import (
PAID_MISSION_CAP_USD,
+ PaidCallGate,
PaidOffer,
WorkerCapacityUnavailable,
estimate_paid_cost_usd,
@@ -517,16 +518,19 @@ def _live_subagent_provider(boot_snapshot: str | None) -> str | None:
return boot_snapshot
-def _anthropic_key_for_cli_env(key: str | None, *, cli_present: bool) -> str | None:
+def _anthropic_key_for_cli_env(
+ key: str | None, *, cli_present: bool, pinned: bool
+) -> str | None:
"""The Anthropic credential a mission's ``claude`` CLI may see, or None.
- With the CLI installed, missions are pinned to its subscription login
- (jarvis/missions/capacity.py), so only that login's OAuth bearer may
- reach the process — worker and critic alike. A classic per-token key in
+ On a subscription install (``pinned``, jarvis/missions/capacity.py) with
+ the CLI installed, only the subscription login's OAuth bearer may reach
+ the process — worker and critic alike. A classic per-token key in
``ANTHROPIC_API_KEY`` would make the CLI bill it silently; paid use runs
- only in an approved run, in-process, never through this environment.
+ only on consent, in-process, never through this environment. A key-only
+ install keeps its key: it is that install's primary credential (AP-22).
"""
- if key and cli_present and not key.startswith("sk-ant-oat"):
+ if key and cli_present and pinned and not key.startswith("sk-ant-oat"):
return None
return key
@@ -570,6 +574,33 @@ def _claude_subscription_login_state() -> bool | None:
return None
+def _positive_subscription_login() -> bool:
+ """True when a subscription login is usable RIGHT NOW: the ``claude`` CLI's
+ subscription login (never a classic key) or codex over the ChatGPT login.
+
+ Offline: file reads and the process-cached CLI login probes. A merely
+ installed CLI is not a login.
+ """
+ from jarvis.missions.workers.claude_direct_worker import _resolve_claude_binary
+
+ try:
+ if _resolve_claude_binary() is not None and _claude_subscription_login_state() is True:
+ return True
+ except Exception: # noqa: BLE001 - an unreadable probe is "no positive login", logged
+ logger.debug("missions: claude subscription login probe failed", exc_info=True)
+ from jarvis.missions.workers.codex_direct_worker import _codex_oauth_available
+
+ return bool(_codex_oauth_available())
+
+
+def install_is_pinned() -> bool:
+ """Whether missions on this install are pinned to subscriptions
+ (jarvis/missions/capacity.py): a subscription seen connected recently
+ (sticky) or a positive login probe now. Worker factory, env builder and
+ critic all ask this one question."""
+ return pinned_to_subscription(login_probe=_positive_subscription_login)
+
+
def _claude_cli_auth_viable() -> bool:
"""True when the ``claude`` CLI has a REACHABLE auth surface for a worker.
@@ -798,10 +829,17 @@ def _pinned_claude_worker(
def _pinned_codex_worker(capability_inventory: WorkerCapabilityInventory | None) -> Any:
- """The codex worker for a pinned mission, or a WorkerCapacityUnavailable."""
+ """The codex worker for a pinned mission, or a WorkerCapacityUnavailable.
+
+ Only over the ChatGPT login: without it codex would run on
+ ``OPENAI_API_KEY``, which bills per token.
+ """
from jarvis.codex_auth_state import codex_needs_reauth
from jarvis.codex_quota_state import codex_in_quota_cooldown
+ from jarvis.missions.workers.codex_direct_worker import _codex_oauth_available
+ if not _codex_oauth_available():
+ raise WorkerCapacityUnavailable("provider_auth", "codex", "no ChatGPT login")
if codex_needs_reauth():
raise WorkerCapacityUnavailable("provider_auth", "codex")
if codex_in_quota_cooldown():
@@ -809,6 +847,70 @@ def _pinned_codex_worker(capability_inventory: WorkerCapabilityInventory | None)
return CodexDirectWorker(capability_inventory=capability_inventory, backend_fallback=False)
+def _pinned_claude_from_probes(capability_inventory: WorkerCapabilityInventory | None) -> Any:
+ """:func:`_pinned_claude_worker` on the live binary and login probes."""
+ from jarvis.missions.workers.claude_direct_worker import _resolve_claude_binary
+
+ binary_present = _resolve_claude_binary() is not None
+ login = _claude_subscription_login_state() if binary_present else None
+ return _pinned_claude_worker(
+ capability_inventory, binary_present=binary_present, login=login
+ )
+
+
+#: Subscription families a pinned mission may move between for free, in the
+#: order they are tried after the configured one. Only families whose login
+#: and spent-window state can be read offline (login file + the process-local
+#: quota/auth flags); antigravity and grok build run when configured but are
+#: never a silent fallback target, since nothing here can tell whether they
+#: have capacity.
+_SUBSCRIPTION_FALLBACK_ORDER: tuple[str, ...] = ("claude", "codex")
+#: Builder per family, by name so the module attribute is looked up per call.
+_SUBSCRIPTION_BUILDERS: dict[str, str] = {
+ "claude": "_pinned_claude_from_probes",
+ "codex": "_pinned_codex_worker",
+}
+
+
+def _subscription_worker(
+ preferred: str | None,
+ capability_inventory: WorkerCapabilityInventory | None,
+ *,
+ first_error: WorkerCapacityUnavailable | None = None,
+) -> Any:
+ """A worker on the configured subscription, else on another connected
+ subscription (costs the user nothing extra, no approval needed).
+
+ Raises the configured family's :class:`WorkerCapacityUnavailable` (or
+ ``first_error``) when no subscription can run — the orchestrator then
+ decides between paid use by consent and parking.
+ """
+ order = [
+ f for f in (preferred, *_SUBSCRIPTION_FALLBACK_ORDER) if f in _SUBSCRIPTION_BUILDERS
+ ]
+ first = first_error
+ for family in dict.fromkeys(order):
+ try:
+ builder: Callable[[WorkerCapabilityInventory | None], Any] = globals()[
+ _SUBSCRIPTION_BUILDERS[family]
+ ]
+ worker = builder(capability_inventory)
+ except WorkerCapacityUnavailable as exc: # kept: raised below if no family can run
+ if first is None:
+ first = exc
+ continue
+ if first is not None:
+ logger.warning(
+ "Mission worker -> %s subscription: %s has no capacity (%s); "
+ "moving to another connected subscription (no extra cost).",
+ family, first.provider, first.reason,
+ )
+ return worker
+ if first is None: # pragma: no cover - the order is never empty
+ first = WorkerCapacityUnavailable("provider_unavailable", preferred or "subscription")
+ raise first
+
+
# 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] = {
@@ -865,12 +967,14 @@ class ApiKeyPaidOption:
)
return None
- def worker(self, offer: PaidOffer, *, remaining_usd: float, task_text: str) -> Any:
+ def worker(self, offer: PaidOffer, *, gate: PaidCallGate, task_text: str) -> Any:
+ """The in-process API worker on exactly the offered provider and
+ model; ``gate`` checks consent and caps before each of its calls."""
return ApiAgentWorker(
offer.provider,
capability_inventory=_assemble_worker_capability_inventory(task_text),
pinned_model=offer.model,
- cost_cap_usd=max(remaining_usd, 0.0),
+ paid_gate=gate,
)
@@ -906,13 +1010,19 @@ def _resolve_api_agent_worker(
)
return ApiAgentWorker(provider, capability_inventory=inventory)
if pinned:
- # A subscription install never crosses to another family on its own
- # (jarvis/missions/capacity.py): park the mission instead.
+ # A subscription install never crosses to another METERED family on
+ # its own (jarvis/missions/capacity.py): another connected
+ # subscription is free and fine; otherwise the orchestrator decides
+ # between paid use by consent and parking.
from jarvis.api_family_quota_state import api_family_in_cooldown
- raise WorkerCapacityUnavailable(
- "provider_quota" if api_family_in_cooldown(provider) else "provider_unavailable",
- provider,
+ return _subscription_worker(
+ None,
+ inventory,
+ first_error=WorkerCapacityUnavailable(
+ "provider_quota" if api_family_in_cooldown(provider) else "provider_unavailable",
+ provider,
+ ),
)
logger.warning(
"Mission worker: subagent provider %r has no API key configured, "
@@ -1197,7 +1307,13 @@ async def bootstrap_missions(
# path, but needs it to cross to Gemini API billing when no OAuth
# login exists. Suppressing it here made key-only Antigravity look
# selectable and then fail at execution time.
- if live_provider in {"gemini", "google", "antigravity"}:
+ # On a subscription install (jarvis/missions/capacity.py) that
+ # cross-over to Gemini API billing is an automatic paid switch, so
+ # the antigravity worker gets no key there: without its OAuth login
+ # it fails honestly instead of billing the key unapproved.
+ if live_provider in {"gemini", "google"} or (
+ live_provider == "antigravity" and not install_is_pinned()
+ ):
gemini_key = get_jarvis_agent_secret("gemini")
# Grok / xAI: Jarvis stores under ``grok_api_key`` in the
# credential manager (ENV fallback ``GROK_API_KEY``); we set
@@ -1261,8 +1377,11 @@ async def bootstrap_missions(
_resolve_claude_binary,
)
+ cli_present = _resolve_claude_binary() is not None
anthropic_key = _anthropic_key_for_cli_env(
- anthropic_key, cli_present=_resolve_claude_binary() is not None
+ anthropic_key,
+ cli_present=cli_present,
+ pinned=cli_present and install_is_pinned(),
)
return build_worker_env(
@@ -1337,19 +1456,13 @@ async def bootstrap_missions(
)
# Capacity policy (jarvis/missions/capacity.py): on a subscription
- # install the mission stays on Claude's subscription login — a spent
- # window or a dead login parks it in WAITING_CAPACITY instead of
- # moving it to codex, another family, or the Anthropic API key.
- # Pinned whenever the CLI exists — NOT only when the login probe
- # answers: a logged-out or unreadable subscription login (probe ->
- # None) must park the mission too, never reopen the legacy chain
- # that runs the CLI on a stored per-token Anthropic key.
- binary_present = _resolve_claude_binary() is not None
- login = _claude_subscription_login_state() if binary_present else None
- if pinned_to_subscription(configured_is_subscription=binary_present):
- return _pinned_claude_worker(
- capability_inventory, binary_present=binary_present, login=login
- )
+ # install (sticky subscription signal or a positive login probe —
+ # NOT merely an installed CLI) the mission runs on Claude's
+ # subscription login, else on another connected subscription; with
+ # none it never falls to the Anthropic API key here — the
+ # orchestrator decides between consented paid use and parking.
+ if install_is_pinned():
+ return _subscription_worker("claude", capability_inventory)
# B3 (open-source AP-22): an Anthropic-API-key-only user has NO `claude`
# CLI binary — run the heavy worker IN-PROCESS via ApiAgentWorker on the
# API key instead of failing on the missing binary. The CLI stays
@@ -1400,9 +1513,10 @@ async def bootstrap_missions(
# claude-cli MCP config so it can issue the plugin tool calls (AD-OE4).
return ClaudeDirectWorker(capability_inventory=capability_inventory)
if kind == "codex_direct":
- # The ChatGPT login is a subscription: pinned like Claude above.
- if pinned_to_subscription(configured_is_subscription=True):
- return _pinned_codex_worker(capability_inventory)
+ # The ChatGPT login is a subscription: pinned like Claude above,
+ # with the free move to the Claude subscription restored.
+ if install_is_pinned():
+ return _subscription_worker("codex", capability_inventory)
# If a codex subprocess already proved the ChatGPT login dead this
# session, skip codex entirely and run on Claude Max directly (one
# path, like grok) — re-spawning the dead provider + double-falling-
@@ -1448,7 +1562,7 @@ async def bootstrap_missions(
provider,
task_text,
capability_inventory,
- pinned=pinned_to_subscription(configured_is_subscription=False),
+ pinned=install_is_pinned(),
)
if kind == "gemini":
# B4 (open-source AP-22): no Gemini CLI but a Gemini API key → run the
@@ -1489,7 +1603,7 @@ async def bootstrap_missions(
cross = _cross_family_last_resort_worker(
task_text,
capability_inventory,
- allow_metered=not pinned_to_subscription(configured_is_subscription=False),
+ allow_metered=not install_is_pinned(),
)
if cross is not None:
return cross
diff --git a/jarvis/missions/kontrollierer/orchestrator.py b/jarvis/missions/kontrollierer/orchestrator.py
index 1e1b134856..7efcb88a40 100644
--- a/jarvis/missions/kontrollierer/orchestrator.py
+++ b/jarvis/missions/kontrollierer/orchestrator.py
@@ -39,14 +39,25 @@ from typing import Any, Final, Literal
from ...core.process_utils import NO_WINDOW_CREATIONFLAGS
from ..budget import BudgetExceeded, BudgetTracker
from ..capacity import (
+ CAPACITY_WAIT_REASON_VALUES,
MAX_REVIEW_RETRIES,
+ PAID_MISSION_CAP_USD,
CapacityDecision,
CapacityDecisionRejected,
+ CapacityPolicy,
+ CapacityWaitReason,
CriticCapacityUnavailable,
+ MissionPaidLedger,
+ PaidCallGate,
PaidOffer,
PaidOption,
+ RouteDecision,
WorkerCapacityUnavailable,
+ decide_route,
+ delete_checkpoint,
+ is_subscription_family,
read_checkpoint,
+ resume_backoff_s,
worker_family,
write_checkpoint,
)
@@ -864,13 +875,18 @@ 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`.
+ # The paid-API alternative for a mission no subscription can run
+ # (None = paid use never happens). Used on the user's consent only:
+ # the [missions] paid_api_fallback setting or a per-mission approval
+ # — see jarvis/missions/capacity.py and `decide_capacity`.
paid_option: PaidOption | None = None,
+ # Live answers for capacity decisions (pinned install, paid-fallback
+ # setting, daily paid ledger). None = the install's real ones.
+ capacity_policy: CapacityPolicy | None = None,
) -> None:
self._manager = manager
self._paid_option = paid_option
+ self._policy = capacity_policy or CapacityPolicy()
self._decomposer = decomposer
self._runner = critic_runner
self._worktrees = worktree_mgr
@@ -924,11 +940,25 @@ class Kontrollierer:
# ``_review_failures`` counts non-capacity critic failures per step.
self._pending_review: dict[str, set[str]] = {}
self._review_failures: dict[str, 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).
+ # Approved paid runs: the exact offer the user accepted. 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] = {}
+ # Per-mission paid-use ledger, shared by parallel steps, worker and
+ # critic calls (reservation before every paid call). Opened per run
+ # from the mission's recorded MissionPaidUsage, so the cap is
+ # cumulative over every run of the mission.
+ self._ledgers: dict[str, MissionPaidLedger] = {}
+ # What this run paid, per (provider, model, automatic) — one
+ # MissionPaidUsage event each when the run ends.
+ self._run_paid: dict[str, dict[tuple[str, str, bool], dict[str, float]]] = {}
+ # The subscription family a mission lacked capacity on (what a park
+ # waits for — never the paid key it may have moved to).
+ self._wait_family: dict[str, str] = {}
+ # Resume backoff bookkeeping: consecutive parks without progress and
+ # how many steps were pending review when the run started.
+ self._resume_idle_parks: dict[str, int] = {}
+ self._resume_pending_before: dict[str, int] = {}
# Paid runs started by an approval; referenced so they are not
# garbage-collected mid-flight.
self._background_runs: set[asyncio.Task[Any]] = set()
@@ -970,6 +1000,9 @@ class Kontrollierer:
the dying task cannot race the user's decision (``_safe_transition``
and ``_fail_mission`` both tolerate the already-terminal state).
"""
+ # The caller made the mission terminal (CANCELLED): a parked mission's
+ # checkpoint has nothing left to resume.
+ self._drop_checkpoint(mission_id)
task = self._running_missions.get(mission_id)
if task is None or task.done():
return False
@@ -1013,6 +1046,14 @@ class Kontrollierer:
task = self._running_missions.get(mission_id)
if task is None or task.done():
continue
+ # A mission resumed from a capacity checkpoint is parked again,
+ # not cancelled: its checkpoint still holds the work, and the
+ # next start resumes it (jarvis/missions/capacity.py).
+ if await self._repark_on_shutdown(mission_id, reason):
+ task.cancel()
+ tasks.append(task)
+ finalized.append(mission_id)
+ continue
transitioned = False
try:
await self._manager.transition_state(
@@ -1127,6 +1168,43 @@ class Kontrollierer:
done_task_ids: frozenset[str] = frozenset(),
restore_dirs: dict[str, Path] | None = None,
review_only_task_ids: frozenset[str] = frozenset(),
+ ) -> MissionState:
+ """One run of a mission's plan, with its paid-use ledger open.
+
+ The ledger starts from what the mission already paid in earlier runs
+ (cumulative cap); a manual approval of this run grants up to
+ ``PAID_MISSION_CAP_USD`` more. What this run paid is logged as
+ ``MissionPaidUsage`` when it ends.
+ """
+ ledger = MissionPaidLedger(await self._mission_paid_spent(mission_id))
+ if mission_id in self._paid_approval:
+ ledger.grant_manual()
+ self._ledgers[mission_id] = ledger
+ self._run_paid[mission_id] = {}
+ try:
+ return await self._execute_plan_steps(
+ mission_id,
+ prompt,
+ plan,
+ done_task_ids=done_task_ids,
+ restore_dirs=restore_dirs,
+ review_only_task_ids=review_only_task_ids,
+ )
+ finally:
+ await self._record_paid_usage(mission_id)
+ self._ledgers.pop(mission_id, None)
+ self._run_paid.pop(mission_id, None)
+ self._wait_family.pop(mission_id, None)
+
+ async def _execute_plan_steps(
+ self,
+ mission_id: str,
+ prompt: str,
+ plan: MissionPlan,
+ *,
+ done_task_ids: frozenset[str] = frozenset(),
+ restore_dirs: dict[str, Path] | None = None,
+ review_only_task_ids: frozenset[str] = frozenset(),
) -> MissionState:
"""Run the plan's open steps, then aggregate every step's outcome.
@@ -1388,6 +1466,27 @@ class Kontrollierer:
self._restore_task_workspace, worktree, restore_dir
)
+ if review_only and not restored:
+ # Only the review is owed and the delivered result could not
+ # be put back: re-running the worker would redo (and possibly
+ # re-bill) finished work. Park; after MAX_REVIEW_RETRIES such
+ # failures the step fails honestly as critic_unavailable.
+ logger.warning(
+ "Task %s: the saved result for its pending review could not "
+ "be restored — parking instead of re-running the worker",
+ step.task_id,
+ )
+ try:
+ return self._park_for_review(
+ mission_id, step, "provider_unavailable", self._critic_family(),
+ "the saved result could not be restored for review",
+ counts_as_failure=True,
+ )
+ finally:
+ await asyncio.shield(
+ asyncio.to_thread(self._remove_worktree_only, worktree)
+ )
+
try:
return await self._run_iterations(
mission_id=mission_id,
@@ -1418,6 +1517,15 @@ class Kontrollierer:
with self._worktree_lock:
return self._worktrees.create(**kwargs)
+ def _remove_worktree_only(self, worktree: Path) -> None:
+ """Remove a workspace WITHOUT archiving it — its archive must keep the
+ earlier, delivered result. Worker thread only."""
+ try:
+ with self._worktree_lock:
+ self._worktrees.remove(worktree, force=True)
+ except Exception: # noqa: BLE001
+ logger.warning("worktree cleanup failed for %s", worktree, exc_info=True)
+
def _finish_task_workspace(
self, *, worktree: Path, mission_dir: Path, task_id: str
) -> None:
@@ -1550,6 +1658,7 @@ class Kontrollierer:
# is still archived. Only the review is missing — run it, never
# the worker again (and never on a paid approval).
worker = None
+ paid_gate: PaidCallGate | None = None
spawn_result = self._SpawnResult(
worker_id=f"review-{step.task_id[:13]}",
cost_usd=0.0,
@@ -1560,7 +1669,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._make_worker(mission_id, step)
+ worker, paid_gate = self._make_worker(mission_id, step)
except WorkerCapacityUnavailable as exc:
logger.warning(
"Task %s iter %d: no worker capacity (%s) — parking the "
@@ -1603,23 +1712,29 @@ class Kontrollierer:
return TaskOutcome.ERROR
continue
- 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.
+ if paid_gate is not None:
+ # Whatever the worker reported beyond its gated calls is
+ # charged too (fail closed), then: consent gone or a cap hit
+ # mid-run parks the mission; the work so far is archived
+ # with the checkpoint and restored on resume.
+ automatic = paid_gate.last_automatic
+ if automatic is None: # the worker never went through the gate
+ automatic = mission_id not in self._paid_approval
+ paid_gate.settle_reported(spawn_result.cost_usd, automatic=automatic)
+ refusal = paid_gate.refusal
+ if refusal is None and spawn_result.worker_error and self._paid_exhausted(
+ mission_id
+ ):
+ refusal = "paid_cap_reached"
+ if refusal is not None:
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,
+ "Task %s iter %d: paid run on %s stopped (%s) — parking "
+ "the mission",
+ step.task_id, iteration, paid_gate.provider, refusal,
)
self._capacity_wait[mission_id] = {
- "reason": "paid_cap_reached",
- "provider": approval.provider,
+ "reason": refusal,
+ "provider": paid_gate.provider,
"error_detail": None,
}
# No iteration diff recorded: the task's final archive
@@ -1851,8 +1966,10 @@ class Kontrollierer:
if is_timeout:
return TaskOutcome.TIMED_OUT
# A spent quota window is not a fault of the work: park
- # the mission with its checkpoint instead of failing it.
- if error_class == "provider_quota":
+ # the mission with its checkpoint instead of failing it —
+ # on a subscription install. A key-only install keeps its
+ # fail-or-cross behaviour (AP-22); it never parks.
+ if error_class == "provider_quota" and self._policy.pinned():
self._capacity_wait[mission_id] = {
"reason": "provider_quota",
"provider": worker_family(worker),
@@ -1942,6 +2059,13 @@ class Kontrollierer:
f"{spawn_result.supervisor_tool_refusals}\n"
)
env = self._env_builder(mission_dir)
+ # A paid critic call is possible only on consent (setting or an
+ # approval of this run); the gate re-checks it per call. Off the
+ # loop: it reads the config and the key store.
+ critic_gate = await asyncio.to_thread(self._critic_gate, mission_id)
+ critic_kwargs: dict[str, Any] = (
+ {"paid_gate": critic_gate} if critic_gate is not None else {}
+ )
try:
verdict = await self._runner.run(
mission_prompt=mission_prompt,
@@ -1952,12 +2076,13 @@ class Kontrollierer:
worktree=worktree,
env=env,
security_tag=_detect_security_tag(step.prompt),
+ **critic_kwargs,
)
except CriticCapacityUnavailable as exc:
- # The critic's own subscription has no capacity. The worker's
- # result is kept (archived with the checkpoint) and only the
- # review resumes later — no worker re-run, no other family,
- # no paid critic.
+ # No critic can grade: no subscription has capacity and no
+ # consented paid call was possible. The worker's result is kept
+ # (archived with the checkpoint) and only the review resumes
+ # later — no worker re-run.
logger.warning(
"Task %s iter %d: critic has no capacity (%s) — parking the "
"mission with the review pending",
@@ -3138,24 +3263,63 @@ class Kontrollierer:
return resumed
async def _capacity_is_back(self, mission_id: str) -> bool:
- """Whether the worker a parked mission is pinned to can run again.
+ """Whether a parked mission can make progress now, offline.
+
+ - Its backoff (repeat parks without progress) must have expired.
+ - A step that still needs its worker: the worker factory answers on a
+ subscription (any — moving between subscriptions is free) or on the
+ metered provider the mission was configured for.
+ - A step whose review is pending: a critic has capacity.
+ - Otherwise: consented automatic paid use (setting ON, caps left).
- Asks the worker factory — the same offline rules (quota cooldowns,
- login state, key viability) that parked the mission, so the check
- never calls a provider. A factory answer on a DIFFERENT provider
- family is not capacity: switching needs the user's approval.
+ Never calls a provider: the factory and critic probes read login
+ files, quota/auth flags and key viability only.
"""
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 True # resume_mission fails it honestly (checkpoint_missing)
+ next_ms = checkpoint.get("next_resume_ms")
+ if isinstance(next_ms, (int, float)) and not isinstance(next_ms, bool):
+ if now_ms() < next_ms:
+ return False
done = _done_task_ids(checkpoint)
open_steps = [step for step in plan.steps if step.task_id not in done]
if not open_steps:
return True
+ pending = {
+ str(entry.get("task_id"))
+ for entry in checkpoint.get("steps") or []
+ if isinstance(entry, dict) and entry.get("pending_review") is True
+ }
+ work_steps = [step for step in open_steps if step.task_id not in pending]
+ review_steps = [step for step in open_steps if step.task_id in pending]
+ pinned = checkpoint.get("provider")
+ pinned_family = pinned if isinstance(pinned, str) and pinned else None
+ if work_steps and await self._worker_capacity_back(
+ mission_id, work_steps[0], pinned_family
+ ):
+ return True
+ if review_steps and await asyncio.to_thread(self._critic_capacity_back):
+ return True
+ raw_reason = checkpoint.get("reason")
+ reason: CapacityWaitReason = (
+ raw_reason # type: ignore[assignment]
+ if raw_reason in CAPACITY_WAIT_REASON_VALUES
+ else "provider_quota"
+ )
+ spent = await self._mission_paid_spent(mission_id)
+ decision = await asyncio.to_thread(
+ self._automatic_paid_decision, reason, pinned_family, spent
+ )
+ return decision.route == "paid"
+
+ async def _worker_capacity_back(
+ self, mission_id: str, step: Step, pinned_family: str | None
+ ) -> bool:
try:
- worker = await asyncio.to_thread(self._worker_factory, open_steps[0])
+ worker = await asyncio.to_thread(self._worker_factory, step)
except WorkerCapacityUnavailable: # still no capacity: stay parked, ask again next tick
return False
except Exception: # noqa: BLE001 - a broken probe means "not yet", logged
@@ -3164,16 +3328,47 @@ class Kontrollierer:
exc_info=True,
)
return False
- pinned = checkpoint.get("provider")
family = worker_family(worker)
- if isinstance(pinned, str) and pinned and family != pinned:
- logger.warning(
- "Mission %s stays parked: it is pinned to %s, the configured "
- "worker is now %s — switching provider needs approval",
- mission_id, pinned, family,
- )
+ if is_subscription_family(family) or family == pinned_family:
+ return True
+ if not await asyncio.to_thread(self._policy.pinned):
+ return True # a key-only install's keys are its primary (AP-22)
+ logger.info(
+ "Mission %s stays parked: the configured worker is now the metered "
+ "%s, which needs the user's consent", mission_id, family,
+ )
+ return False
+
+ def _critic_capacity_back(self) -> bool:
+ probe = getattr(self._runner, "capacity_available", None)
+ if not callable(probe):
+ return True
+ try:
+ return bool(probe())
+ except Exception: # noqa: BLE001 - a broken probe means "not yet", logged
+ logger.warning("critic capacity probe failed — staying parked", exc_info=True)
return False
- return True
+
+ def _automatic_paid_decision(
+ self, reason: CapacityWaitReason, pinned_family: str | None, spent_usd: float
+ ) -> RouteDecision:
+ """Would the paid-fallback SETTING let a parked mission go on now?
+ (A manual approval resumes through ``decide_capacity`` instead.)"""
+ enabled = self._policy.paid_fallback_enabled()
+ offer = None
+ if enabled and self._paid_option is not None and self._policy.pinned():
+ offer = self._paid_option.offer(
+ pinned_family=pinned_family, open_steps=1, reason=reason
+ )
+ return decide_route(
+ subscription_ok=False,
+ unavailable_reason=reason,
+ manual_approval=False,
+ paid_fallback_enabled=enabled,
+ paid_option_available=offer is not None,
+ mission_remaining_usd=max(PAID_MISSION_CAP_USD - spent_usd, 0.0),
+ daily_remaining_usd=self._policy.daily.remaining() if enabled else 0.0,
+ )
async def resume_mission(self, mission_id: str) -> MissionState:
"""Continue a WAITING_CAPACITY mission exactly from its checkpoint.
@@ -3238,6 +3433,30 @@ class Kontrollierer:
):
current = await self._manager.mission(mission_id)
return current.state if current is not None else MissionState.FAILED
+ try:
+ return await self._finish_claim(
+ mission_id, view.prompt, plan, done, restore_dirs, checkpoint
+ )
+ except BaseException:
+ # The claim moved the mission to RUNNING; nobody will run it now.
+ # Put it back so the next tick (or the user) can resume it.
+ logger.exception("resume_mission: %s claim failed — parking it again", mission_id)
+ await self._safe_transition(
+ mission_id, MissionState.WAITING_CAPACITY, "capacity:resume_claim_failed"
+ )
+ raise
+
+ async def _finish_claim(
+ self,
+ mission_id: str,
+ prompt: str,
+ plan: MissionPlan,
+ done: set[str],
+ restore_dirs: dict[str, Path],
+ checkpoint: dict[str, Any],
+ ) -> _ResumeClaim:
+ """The part of a claim that runs after the RUNNING transition."""
+ plan_ids = {step.task_id for step in plan.steps}
try:
await self._manager.store.touch_heartbeat(mission_id, now_ms())
except Exception as hb_exc: # noqa: BLE001 - ownership stamp is advisory
@@ -3254,7 +3473,7 @@ class Kontrollierer:
if isinstance(failures, int) and failures > 0:
review_failures[task_id] = failures
return _ResumeClaim(
- prompt=view.prompt,
+ prompt=prompt,
plan=plan,
done=frozenset(done),
restore_dirs=restore_dirs,
@@ -3281,12 +3500,16 @@ class Kontrollierer:
attempts if isinstance(attempts, int) else 0
) + 1
self._resume_done_before[mission_id] = len(claim.done)
+ self._resume_pending_before[mission_id] = len(claim.review_only)
+ idle = checkpoint.get("idle_parks")
+ self._resume_idle_parks[mission_id] = (
+ idle if isinstance(idle, int) and not isinstance(idle, bool) else 0
+ )
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
if claim.review_failures:
self._review_failures[mission_id] = dict(claim.review_failures)
@@ -3298,25 +3521,23 @@ class Kontrollierer:
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,
- review_only_task_ids=claim.review_only,
- )
- finally:
- await self._record_paid_usage(mission_id)
+ return await self._execute_plan(
+ mission_id,
+ claim.prompt,
+ claim.plan,
+ done_task_ids=claim.done,
+ restore_dirs=claim.restore_dirs,
+ review_only_task_ids=claim.review_only,
+ )
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._resume_pending_before.pop(mission_id, None)
+ self._resume_idle_parks.pop(mission_id, None)
self._paid_approval.pop(mission_id, None)
- self._paid_spent.pop(mission_id, None)
self._pending_review.pop(mission_id, None)
self._review_failures.pop(mission_id, None)
@@ -3348,6 +3569,40 @@ class Kontrollierer:
reason=reason if isinstance(reason, str) else "provider_quota",
)
+ @property
+ def capacity_policy(self) -> CapacityPolicy:
+ """The live capacity answers this runner decides with (read-only)."""
+ return self._policy
+
+ @property
+ def paid_option(self) -> PaidOption | None:
+ """The paid alternative this runner offers, if any (read-only)."""
+ return self._paid_option
+
+ async def paid_spent_usd(self, mission_id: str) -> float:
+ """What this mission has paid for API use so far, across all runs."""
+ ledger = self._ledgers.get(mission_id)
+ if ledger is not None:
+ return round(ledger.spent_usd, 6)
+ return round(await self._mission_paid_spent(mission_id), 6)
+
+ async def _mission_paid_spent(self, mission_id: str) -> float:
+ """Sum of the mission's recorded ``MissionPaidUsage`` events. Fails
+ closed: an unreadable history counts as a spent automatic cap."""
+ try:
+ events = await self._manager.store.events_for_mission(mission_id)
+ except Exception: # noqa: BLE001 - logged; the cap must not open on a read error
+ logger.warning(
+ "Mission %s: paid-usage history unreadable — treating the "
+ "automatic cap as spent", mission_id, exc_info=True,
+ )
+ return PAID_MISSION_CAP_USD
+ return sum(
+ float(e.payload.cost_usd)
+ for e in events
+ if isinstance(e.payload, MissionPaidUsage)
+ )
+
async def decide_capacity(
self,
mission_id: str,
@@ -3422,6 +3677,7 @@ class Kontrollierer:
payload=MissionCancelled(cascade=False, reason="ui_cancel"),
)
)
+ self._drop_checkpoint(mission_id)
return MissionState.CANCELLED
assert offer is not None # approve_paid was validated above
@@ -3436,56 +3692,217 @@ class Kontrollierer:
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:
+ def _make_worker(self, mission_id: str, step: Step) -> tuple[Any, PaidCallGate | None]:
+ """The worker for one iteration, and its paid-call gate if it bills.
+
+ Subscriptions first — the factory moves between connected
+ subscriptions itself. Only when none can run does the capacity rule
+ (:func:`decide_route`) allow a paid worker: on an active approval of
+ this run, or on the paid-fallback setting within the caps. Anything
+ else raises :class:`WorkerCapacityUnavailable` and the mission parks.
+ """
+ try:
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:
+ self._check_resume_billing(mission_id, worker)
+ return worker, None
+ except WorkerCapacityUnavailable as exc: # decided below: paid by consent, or re-raised
+ unavailable = exc
+ self._wait_family.setdefault(mission_id, unavailable.provider)
+ pinned_family = self._resume_family.get(mission_id) or unavailable.provider
+ decision, offer = self._paid_route(
+ mission_id, reason=unavailable.reason, pinned_family=pinned_family
+ )
+ if decision.route != "paid" or offer is None or self._paid_option is None:
+ reason = decision.reason or unavailable.reason
+ if reason == unavailable.reason:
+ raise unavailable
raise WorkerCapacityUnavailable(
- "paid_cap_reached",
- approval.provider,
- f"spent ${spent:.2f} of the approved ${approval.cost_cap_usd:.2f}",
+ reason, offer.provider if offer is not None else unavailable.provider
)
- 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
+ logger.warning(
+ "Mission %s: no subscription has capacity (%s) — continuing on %s/%s "
+ "(%s paid use, capped)",
+ mission_id, unavailable.reason, offer.provider, offer.model,
+ "automatic" if decision.automatic else "approved",
+ )
+ gate = self._make_gate(mission_id, offer)
+ return self._paid_option.worker(offer, gate=gate, task_text=step.prompt), gate
+
+ def _ledger(self, mission_id: str) -> MissionPaidLedger:
+ ledger = self._ledgers.get(mission_id)
+ if ledger is None:
+ # Outside a run (never on the normal path): start empty but
+ # remember it, so parallel callers still share one ledger.
+ ledger = self._ledgers.setdefault(mission_id, MissionPaidLedger())
+ return ledger
+
+ def _authorize_paid(self, mission_id: str) -> RouteDecision:
+ """The consent check in front of every paid call (fresh each time)."""
+ approval = self._paid_approval.get(mission_id)
+ ledger = self._ledger(mission_id)
+ enabled = approval is None and self._policy.paid_fallback_enabled()
+ return decide_route(
+ subscription_ok=False,
+ unavailable_reason="paid_consent_revoked",
+ manual_approval=approval is not None,
+ paid_fallback_enabled=enabled,
+ paid_option_available=True,
+ mission_remaining_usd=ledger.remaining(automatic=approval is None),
+ daily_remaining_usd=self._policy.daily.remaining() if enabled else 0.0,
)
- async def _record_paid_usage(self, mission_id: str) -> None:
- """Log what an approved paid run actually cost (event + log line)."""
+ def _paid_route(
+ self, mission_id: str, *, reason: CapacityWaitReason, pinned_family: str | None
+ ) -> tuple[RouteDecision, PaidOffer | None]:
+ """Decide paid-vs-park for a mission no subscription can serve."""
approval = self._paid_approval.get(mission_id)
+ offer: PaidOffer | None = approval
+ enabled = False
if approval is None:
+ enabled = self._policy.paid_fallback_enabled()
+ if enabled and self._paid_option is not None and self._policy.pinned():
+ offer = self._paid_option.offer(
+ pinned_family=pinned_family, open_steps=1, reason=reason
+ )
+ ledger = self._ledger(mission_id)
+ decision = decide_route(
+ subscription_ok=False,
+ unavailable_reason=reason,
+ manual_approval=approval is not None,
+ paid_fallback_enabled=enabled,
+ paid_option_available=offer is not None,
+ mission_remaining_usd=ledger.remaining(automatic=approval is None),
+ daily_remaining_usd=self._policy.daily.remaining() if enabled else 0.0,
+ )
+ return decision, offer
+
+ def _make_gate(self, mission_id: str, offer: PaidOffer) -> PaidCallGate:
+ return PaidCallGate(
+ mission_id=mission_id,
+ offer=offer,
+ ledger=self._ledger(mission_id),
+ daily=self._policy.daily,
+ authorize=lambda: self._authorize_paid(mission_id),
+ on_charge=lambda o, automatic, cost: self._note_paid_charge(
+ mission_id, o, automatic, cost
+ ),
+ )
+
+ def _critic_gate(self, mission_id: str) -> PaidCallGate | None:
+ """A paid-critic gate when consent exists right now (an approval of
+ this run, or the setting on a subscription install), else None."""
+ approval = self._paid_approval.get(mission_id)
+ if approval is not None:
+ return self._make_gate(mission_id, approval)
+ if self._paid_option is None or not self._policy.paid_fallback_enabled():
+ return None
+ if not self._policy.pinned():
+ return None
+ offer = self._paid_option.offer(
+ pinned_family=self._critic_family(), open_steps=1, reason="provider_quota"
+ )
+ return self._make_gate(mission_id, offer) if offer is not None else None
+
+ def _paid_exhausted(self, mission_id: str) -> bool:
+ """True when this mission cannot spend another cent on its consent."""
+ approval = self._paid_approval.get(mission_id)
+ return self._ledger(mission_id).remaining(automatic=approval is None) <= 0
+
+ def _note_paid_charge(
+ self, mission_id: str, offer: PaidOffer, automatic: bool, cost: float
+ ) -> None:
+ run = self._run_paid.setdefault(mission_id, {})
+ entry = run.setdefault(
+ (offer.provider, offer.model, automatic),
+ {"cost": 0.0, "estimate": float(offer.estimated_cost_usd)},
+ )
+ entry["cost"] += cost
+
+ async def _record_paid_usage(self, mission_id: str) -> None:
+ """Log what this run paid (event + log line), one event per provider,
+ model and consent kind. An approved run is always logged, even when
+ its approval ended up unused."""
+ run = dict(self._run_paid.get(mission_id) or {})
+ approval = self._paid_approval.get(mission_id)
+ if approval is not None:
+ run.setdefault(
+ (approval.provider, approval.model, False),
+ {"cost": 0.0, "estimate": float(approval.estimated_cost_usd)},
+ )
+ for (provider, model, automatic), entry in run.items():
+ spent = round(entry["cost"], 6)
+ logger.info(
+ "Mission %s paid %s use on %s/%s cost $%.4f (cap $%.2f)",
+ mission_id, "automatic" if automatic else "approved",
+ provider, model, spent, PAID_MISSION_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=provider,
+ model=model,
+ cost_usd=spent,
+ cost_cap_usd=PAID_MISSION_CAP_USD,
+ estimated_cost_usd=round(entry["estimate"], 6),
+ automatic=automatic,
+ ),
+ )
+ )
+ 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 _drop_checkpoint(self, mission_id: str) -> None:
+ """Delete a terminal mission's checkpoint. ``getattr``: bare test
+ fixtures build the class without __init__."""
+ root = getattr(self, "_isolation_root", None)
+ if root 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,
+ delete_checkpoint(root / f"mission_{mission_id[:13]}")
+
+ async def _repark_on_shutdown(self, mission_id: str, reason: str) -> bool:
+ """Shutdown path for a running mission that HAS a capacity checkpoint:
+ park it again (its checkpoint resumes it after the restart) instead of
+ cancelling it. False when it has none or cannot be parked."""
+ mission_dir = self._isolation_root / f"mission_{mission_id[:13]}"
+ checkpoint = await asyncio.to_thread(read_checkpoint, mission_dir)
+ if checkpoint is None:
+ return False
+ if not await self._safe_transition(
+ mission_id, MissionState.WAITING_CAPACITY, f"capacity:{reason}"
+ ):
+ return False
+ raw_reason = checkpoint.get("reason")
+ wait_reason = (
+ raw_reason if raw_reason in CAPACITY_WAIT_REASON_VALUES else "provider_unavailable"
)
+ steps = [e for e in checkpoint.get("steps") or [] if isinstance(e, dict)]
+ provider = checkpoint.get("provider")
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,
+ payload=MissionWaitingCapacity(
+ reason=wait_reason, # type: ignore[arg-type]
+ provider=provider if isinstance(provider, str) else None,
+ steps_done=sum(1 for e in steps if e.get("done") is True),
+ steps_total=len(steps),
+ checkpoint_path=str(mission_dir / "checkpoint.json"),
+ resume_attempt=int(checkpoint.get("resume_attempts") or 0),
+ # Nothing new for the voice layer: the app is stopping.
+ repeat=True,
),
)
)
- except Exception: # noqa: BLE001 - the log line above still records it
- logger.exception("Mission %s: paid-usage event could not be stored", mission_id)
+ except Exception: # noqa: BLE001 - the state flip already parked it
+ logger.exception("Mission %s: re-park event could not be stored", mission_id)
+ logger.info("Mission %s parked again on %s (checkpoint kept)", mission_id, reason)
+ return True
def _drop_review_state(self, mission_id: str) -> None:
"""Forget a mission's pending-review bookkeeping (terminal paths).
@@ -3538,19 +3955,21 @@ class Kontrollierer:
}
return TaskOutcome.WAITING_CAPACITY
- def _check_resume_family(self, mission_id: str, worker: Any) -> None:
- """A resumed mission runs only on the provider family it was parked
- on; anything else parks it again instead of switching unasked."""
+ def _check_resume_billing(self, mission_id: str, worker: Any) -> None:
+ """A resumed mission may move to ANY subscription (free) or run on the
+ metered provider it was configured for; a different metered family is
+ a billing switch and goes through the capacity rule instead."""
pinned = self._resume_family.get(mission_id)
if pinned is None:
return
family = worker_family(worker)
- if family != pinned:
- raise WorkerCapacityUnavailable(
- "provider_unavailable",
- pinned,
- f"the configured worker is now {family}; switching needs approval",
- )
+ if is_subscription_family(family) or family == pinned:
+ return
+ raise WorkerCapacityUnavailable(
+ "provider_unavailable",
+ pinned,
+ f"the configured worker is now the metered {family}; that needs consent",
+ )
def _restore_task_workspace(self, worktree: Path, artifacts: Path) -> bool:
"""Put a parked step's archived work back into its fresh workspace.
@@ -3627,6 +4046,8 @@ class Kontrollierer:
self._mission_failure_context.pop(mission_id, None)
attempt = self._resume_attempt.get(mission_id, 0)
done_before = self._resume_done_before.get(mission_id, 0)
+ pending_before = self._resume_pending_before.get(mission_id, 0)
+ idle_before = self._resume_idle_parks.get(mission_id, 0)
wait = self._capacity_wait.pop(mission_id, {})
reason = wait.get("reason") or "provider_quota"
provider = wait.get("provider")
@@ -3657,6 +4078,19 @@ class Kontrollierer:
"artifacts_dir": str(files_dir.parent),
})
steps_done = sum(1 for st in steps if st["done"])
+ # Backoff: a resume that parked again without finishing a step or
+ # delivering a new result for review waits longer before the next try
+ # (5 min doubling to 60 min, jittered) instead of churning.
+ # A paid run that hit its consent or cap limit is a new condition,
+ # not churn: it never adds backoff.
+ progressed = (
+ steps_done > done_before
+ or len(pending_review) > pending_before
+ or str(reason).startswith("paid_")
+ )
+ idle_parks = idle_before + 1 if attempt > 0 and not progressed else 0
+ backoff_s = resume_backoff_s(idle_parks)
+ ledger = self._ledgers.get(mission_id)
checkpoint_path = ""
try:
@@ -3670,10 +4104,17 @@ class Kontrollierer:
# 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,
+ "provider": (
+ self._resume_family.get(mission_id)
+ or self._wait_family.get(mission_id)
+ or provider
+ ),
"error_detail": error_detail,
"created_ms": now_ms(),
"resume_attempts": attempt,
+ "idle_parks": idle_parks,
+ "next_resume_ms": now_ms() + int(backoff_s * 1000) if backoff_s else 0,
+ "paid_spent_usd": round(ledger.spent_usd, 6) if ledger else None,
"plan": plan.model_dump(mode="json"),
"steps": steps,
"task_answers": task_answers,
@@ -3731,6 +4172,7 @@ class Kontrollierer:
)
if not transitioned:
return
+ self._drop_checkpoint(mission_id)
# Point `result_uri` at the real mission directory so the Outputs
# view and any voice-readback consumer can resolve it to actual
# files (diff.patch + untracked file copies persisted by
@@ -3866,6 +4308,7 @@ class Kontrollierer:
return
if not await self._safe_transition(mission_id, MissionState.FAILED, reason):
return
+ self._drop_checkpoint(mission_id)
env = EventEnvelope(
mission_id=mission_id,
source_actor="kontrollierer",
diff --git a/jarvis/missions/voice/readback.py b/jarvis/missions/voice/readback.py
index 383fb16bda..7c8524d156 100644
--- a/jarvis/missions/voice/readback.py
+++ b/jarvis/missions/voice/readback.py
@@ -321,7 +321,13 @@ CAPACITY_WAIT_PHRASES: Final[dict[str, dict[str, str]]] = {
"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
+ "Die Kostengrenze dieser Mission für {provider} ist erreicht." # i18n-allow
+ ),
+ "paid_daily_cap_reached": (
+ "Das Tageslimit für automatische {provider}-Nutzung ist erreicht." # i18n-allow
+ ),
+ "paid_consent_revoked": (
+ "Die automatische {provider}-Nutzung wurde ausgeschaltet." # i18n-allow
),
"saved": "Der bisherige Stand wurde gesichert.", # i18n-allow
"progress": "{done} von {total} Teilschritten erledigt, {open} offen.", # i18n-allow
@@ -339,7 +345,9 @@ CAPACITY_WAIT_PHRASES: Final[dict[str, dict[str, str]]] = {
"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.",
+ "paid_cap_reached": "This mission's cost limit for {provider} is reached.",
+ "paid_daily_cap_reached": "The daily limit for automatic {provider} use is reached.",
+ "paid_consent_revoked": "Automatic {provider} use was switched off.",
"saved": "The progress so far has been saved.",
"progress": "{done} of {total} steps done, {open} open.",
"progress_single": "The task itself is still open.",
diff --git a/jarvis/missions/workers/api_agent_worker.py b/jarvis/missions/workers/api_agent_worker.py
index 0288917d3b..3846fc1aa5 100644
--- a/jarvis/missions/workers/api_agent_worker.py
+++ b/jarvis/missions/workers/api_agent_worker.py
@@ -41,6 +41,13 @@ from typing import Any, Literal
from jarvis.core.protocols import BrainMessage, BrainRequest
from jarvis.costs.ledger import usage_context
+from jarvis.missions.capacity import (
+ PaidCallGate,
+ PaidCallRefused,
+ PaidReservation,
+ max_call_cost_usd,
+ usage_cost_usd,
+)
from .api_agent_tools import WORKER_TOOL_SPECS, execute_worker_tool_async
from .capabilities import WorkerCapabilityInventory
@@ -140,21 +147,33 @@ _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 _book_call(
+ gate: PaidCallGate | None, reservation: PaidReservation | None, call_usd: float | None
+) -> float:
+ """USD to add to a spawn's spend for one model call. A gated (paid) call
+ is booked on the mission ledger — its whole reservation when it reported
+ no usage; an ungated call counts what it reported."""
+ if gate is None or reservation is None:
+ return call_usd or 0.0
+ return gate.commit(reservation, call_usd)
-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
+def _request_bytes(req: BrainRequest) -> int:
+ """UTF-8 bytes a request sends (messages, system prompt, tool specs) —
+ the input side of a paid call's reservation."""
- 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 size(value: Any) -> int:
+ text = value if isinstance(value, str) else json.dumps(
+ value, ensure_ascii=False, default=str
+ )
+ return len(text.encode("utf-8"))
+
+ total = size(req.system or "")
+ for message in req.messages:
+ total += size(message.content)
+ if req.tools:
+ total += size(list(req.tools))
+ return total
def _resolve_worker_model(provider: str, explicit: str) -> str:
@@ -261,15 +280,17 @@ class ApiAgentWorker:
*,
capability_inventory: WorkerCapabilityInventory | None = None,
pinned_model: str = "",
- cost_cap_usd: float | None = None,
+ paid_gate: PaidCallGate | 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.
+ # The exact model of a paid fallback run (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_usd
+ # Consent + caps in front of EVERY model call of a paid fallback run:
+ # each call reserves its maximum cost first and stops the loop when
+ # consent is gone or a cap is reached. None = the user's own chosen
+ # provider (no fallback), billed as configured.
+ self.paid_gate = paid_gate
self.last_pid: int | None = None
self.last_session_id: str | None = None
self.capability_inventory = capability_inventory or WorkerCapabilityInventory.build()
@@ -352,8 +373,10 @@ class ApiAgentWorker:
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.
+ # the terminal result so a paid mission can log its real spend. A paid
+ # call that reports no usage counts its whole reservation.
spent_usd = 0.0
+ gate = self.paid_gate
broker_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(
@@ -461,6 +484,19 @@ class ApiAgentWorker:
)
text_parts: list[str] = []
tool_calls: list[dict[str, Any]] = []
+ reservation: PaidReservation | None = None
+ if gate is not None:
+ # Raises PaidCallRefused — consent revoked or a cap hit —
+ # BEFORE anything is billed; the orchestrator parks.
+ reservation = gate.reserve(
+ max_call_cost_usd(
+ resolved_model,
+ input_bytes=_request_bytes(req),
+ max_output_tokens=_MAX_TOKENS,
+ )
+ )
+ call_usd: float | None = None
+ booked = False
try:
# Override credential lookup only for this awaited provider
# call. ContextVar isolation keeps concurrent Brain and
@@ -470,7 +506,9 @@ class ApiAgentWorker:
_stream = brain.complete(req)
async for delta in _stream:
if delta.usage:
- spent_usd += _usage_cost_usd(resolved_model, delta.usage)
+ call_usd = (call_usd or 0.0) + usage_cost_usd(
+ resolved_model, delta.usage
+ )
if delta.content:
text_parts.append(delta.content)
if delta.tool_call:
@@ -494,6 +532,8 @@ class ApiAgentWorker:
or ("404" in low and "tool" in low)
)
if turn == 0 and no_tool_endpoints:
+ spent_usd += _book_call(gate, reservation, call_usd)
+ booked = True
res = ClaudeResult(
subtype="error_during_execution",
is_error=True,
@@ -508,12 +548,12 @@ class ApiAgentWorker:
yield res
return
raise
-
- 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)"
- )
+ finally:
+ # A call that died mid-stream may still have billed:
+ # without a usage report its whole reservation counts.
+ if not booked:
+ spent_usd += _book_call(gate, reservation, call_usd)
+ booked = True
assistant_text = "".join(text_parts).strip()
if assistant_text:
@@ -625,8 +665,8 @@ class ApiAgentWorker:
except Exception as exc: # noqa: BLE001
wall_ms = int((time.perf_counter() - t0) * 1000)
logger.warning("ApiAgentWorker[%s] failed: %s", worker_id, exc, exc_info=True)
- # The cost cap is the approval's limit, not a broken key.
- if not isinstance(exc, _CostCapReached) and _error_means_family_unusable(str(exc)):
+ # A refused paid call is the consent/cap rule, not a broken key.
+ if not isinstance(exc, PaidCallRefused) 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
diff --git a/jarvis/plugins/brain/_anthropic_base.py b/jarvis/plugins/brain/_anthropic_base.py
index 3e38311734..d60a9c85af 100644
--- a/jarvis/plugins/brain/_anthropic_base.py
+++ b/jarvis/plugins/brain/_anthropic_base.py
@@ -350,5 +350,10 @@ async def stream_complete(
# cache hits were invisible in cost and telemetry and
# cache regressions could not be measured.
"cache_hit_tokens": int(getattr(usage, "cache_read_input_tokens", 0) or 0),
+ # Cache writes bill above the input rate; a mission's
+ # paid-use cap counts them (jarvis/missions/capacity.py).
+ "cache_write_tokens": int(
+ getattr(usage, "cache_creation_input_tokens", 0) or 0
+ ),
}
yield BrainDelta(finish_reason=finish, usage=usage_d or None)
diff --git a/jarvis/ui/web/mission_billing_routes.py b/jarvis/ui/web/mission_billing_routes.py
new file mode 100644
index 0000000000..6f77070dc0
--- /dev/null
+++ b/jarvis/ui/web/mission_billing_routes.py
@@ -0,0 +1,126 @@
+"""``/api/mission-billing`` — the paid-API fallback switch for missions.
+
+``GET`` reports the switch, whether this install is a subscription install
+(the switch has no effect otherwise: an API-key-only install already runs on
+its keys), the hard caps, the automatic paid spend of the last 24 h and which
+key would be used first. ``PUT`` flips ``[missions] paid_api_fallback`` through
+``jarvis/core/config_writer.py``; the next mission decision reads it fresh
+(jarvis/missions/capacity.py).
+
+The PUT spends money on the user's behalf from then on, so it is marked
+``x-jarvis-dangerous`` (the CLI demands ``--yes``) and the path is excluded
+from the brain's app-action catalog: no voice, chat or agent tool can flip it.
+The global ``SurfaceSecurity`` boundary guards both routes like every other
+``/api`` route (credential required, trusted Origin for a browser write).
+
+Reading never calls a provider: keys, config, login files and the local
+ledger only. No response carries a secret — provider slug and model id at
+most.
+"""
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from fastapi import APIRouter, HTTPException, Request
+from pydantic import BaseModel, ConfigDict, StrictBool
+
+logger = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/api/mission-billing", tags=["missions"])
+
+
+class MissionBillingBody(BaseModel):
+ """The one writable field: the paid-API fallback switch."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ # Strict: "yes", 1 or "true" never switch spending on by coercion.
+ paid_api_fallback: StrictBool
+
+
+def _policy(request: Request) -> Any:
+ """The running Kontrollierer's capacity policy (shares the in-memory
+ daily reservations), else a fresh one on the same persisted ledger."""
+ kontrollierer = getattr(request.app.state, "kontrollierer", None)
+ policy = getattr(kontrollierer, "capacity_policy", None)
+ if policy is not None:
+ return policy
+ from jarvis.missions.capacity import CapacityPolicy
+
+ return CapacityPolicy()
+
+
+def _paid_provider(request: Request) -> dict[str, Any] | None:
+ """The key a paid fallback would use first (same order as the offer),
+ or None when no priced key is usable."""
+ kontrollierer = getattr(request.app.state, "kontrollierer", None)
+ option = getattr(kontrollierer, "paid_option", None)
+ if option is None:
+ from jarvis.missions.init import ApiKeyPaidOption
+
+ option = ApiKeyPaidOption()
+ try:
+ offer = option.offer(pinned_family=None, open_steps=1, reason="provider_quota")
+ except Exception: # noqa: BLE001 - a broken key read means "no key shown", logged
+ logger.warning("mission-billing: paid provider lookup failed", exc_info=True)
+ return None
+ if offer is None:
+ return None
+ return {"provider": offer.provider, "model": offer.model, "price_known": True}
+
+
+def _billing_state(request: Request) -> dict[str, Any]:
+ from jarvis.missions.capacity import (
+ PAID_DAILY_CAP_USD,
+ PAID_MISSION_CAP_USD,
+ paid_api_fallback_enabled,
+ )
+
+ policy = _policy(request)
+ try:
+ subscription_mode = bool(policy.pinned())
+ except Exception: # noqa: BLE001 - shown as a key-only install, logged
+ logger.warning("mission-billing: subscription signal unreadable", exc_info=True)
+ subscription_mode = False
+ return {
+ "paid_api_fallback": paid_api_fallback_enabled(),
+ "subscription_mode": subscription_mode,
+ "per_mission_cap_usd": PAID_MISSION_CAP_USD,
+ "daily_cap_usd": PAID_DAILY_CAP_USD,
+ "spent_last_24h_usd": round(policy.daily.spent_last_24h(), 6),
+ "paid_provider": _paid_provider(request),
+ }
+
+
+def get_mission_billing(request: Request) -> dict[str, Any]:
+ """Paid-API fallback switch, caps, automatic spend of the last 24 h, and
+ the key that would be used first. Read-only; never calls a provider."""
+ return _billing_state(request)
+
+
[email protected]("", openapi_extra={"x-jarvis-dangerous": True})
+def put_mission_billing(body: MissionBillingBody, request: Request) -> dict[str, Any]:
+ """Turn automatic paid API use for missions on or off.
+
+ ON: when no connected subscription has capacity, a mission continues on
+ your own API key, within $2 per mission and $10 per rolling 24 h. OFF
+ (default): it waits for a subscription; a one-off approval per mission
+ stays possible. Applies to the next decision, no restart. No effect on an
+ API-key-only install.
+ """
+ from jarvis.core.config_writer import set_missions_paid_api_fallback
+
+ try:
+ set_missions_paid_api_fallback(body.paid_api_fallback)
+ except (OSError, ValueError) as exc:
+ logger.exception("mission-billing: could not persist the paid fallback switch")
+ raise HTTPException(
+ status_code=500, detail="The setting could not be saved."
+ ) from exc
+ logger.warning(
+ "mission-billing: paid API fallback for missions turned %s",
+ "ON" if body.paid_api_fallback else "OFF",
+ )
+ return _billing_state(request)
diff --git a/jarvis/ui/web/missions_routes.py b/jarvis/ui/web/missions_routes.py
index 9c1af331c5..ed7141f41b 100644
--- a/jarvis/ui/web/missions_routes.py
+++ b/jarvis/ui/web/missions_routes.py
@@ -546,7 +546,7 @@ async def cancel_mission(mission_id: str, request: Request) -> dict[str, Any]:
}
-def _offer_json(offer: Any) -> dict[str, Any] | None:
+def _offer_json(offer: Any, *, spent_usd: float = 0.0) -> dict[str, Any] | None:
if offer is None:
return None
return {
@@ -556,6 +556,11 @@ def _offer_json(offer: Any) -> dict[str, Any] | None:
"cost_cap_usd": offer.cost_cap_usd,
"reason": offer.reason,
"open_steps": offer.open_steps,
+ # Already paid by this mission (every run, worker and critic); an
+ # approval grants up to ``cost_cap_usd`` MORE on top of it.
+ "spent_usd": round(float(spent_usd), 6),
+ # An approval covers the mission's critic calls too (same cap).
+ "covers_critic": True,
}
@@ -574,7 +579,13 @@ async def get_paid_offer(mission_id: str, request: Request) -> dict[str, Any]:
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)}
+ spent_fn = getattr(kontrollierer, "paid_spent_usd", None)
+ spent = await spent_fn(mission_id) if offer is not None and spent_fn is not None else 0.0
+ return {
+ "mission_id": mission_id,
+ "state": view.state.value,
+ "offer": _offer_json(offer, spent_usd=spent),
+ }
@router.post(
@@ -586,9 +597,10 @@ async def decide_capacity(
"""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.
+ shown; it covers one run of this one mission — worker and critic calls,
+ up to the offer's cost cap more than the mission already paid — 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
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index e37203e5bf..3a9c42f73a 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -524,6 +524,7 @@ class WebServer:
from .marketplace_publish_routes import router as marketplace_publish_router
from .marketplace_routes import router as marketplace_router
from .mcp_routes import router as mcp_router
+ from .mission_billing_routes import router as mission_billing_router
from .missions_auth import router as missions_auth_router
from .missions_pty_routes import router as missions_pty_router
from .missions_routes import router as missions_router
@@ -794,6 +795,8 @@ class WebServer:
# mission WS and PTY then perform their narrower hello-frame auth too.
app.include_router(missions_auth_router)
app.include_router(missions_router)
+ # Paid-API fallback switch for missions (Settings; never voice/agents).
+ app.include_router(mission_billing_router)
app.include_router(missions_ws_router)
app.include_router(missions_pty_router)
# Computer-Use run control (deep-dive 2026-07-15, H-09): start/list/
diff --git a/tests/conftest.py b/tests/conftest.py
index 7c756f9ce5..ee9c8c7cdc 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -283,6 +283,20 @@ def _background_policy_in_tmp(tmp_path_factory, monkeypatch): # noqa: ANN001
background_policy.reset_for_tests()
[email protected](autouse=True)
+def _mission_paid_ledger_in_tmp(tmp_path_factory, monkeypatch): # noqa: ANN001
+ """Keep the missions' rolling paid-use ledger off the developer's real data
+ directory: it records real spend and gates automatic paid API use."""
+ from jarvis.missions import capacity
+
+ root = tmp_path_factory.mktemp("mission-paid-ledger")
+ monkeypatch.setattr(
+ capacity, "_default_daily_ledger_path", lambda: root / "mission_paid_ledger.json"
+ )
+ monkeypatch.setattr(capacity, "_DEFAULT_DAILY", None)
+ yield
+
+
@pytest.fixture(autouse=True)
def _app_action_state_in_tmp(tmp_path_factory, monkeypatch): # noqa: ANN001
"""Every registry-command or app-action call records its outcome for the
diff --git a/tests/fakes/fake_mission_runtime.py b/tests/fakes/fake_mission_runtime.py
index efd87c6794..195f197931 100644
--- a/tests/fakes/fake_mission_runtime.py
+++ b/tests/fakes/fake_mission_runtime.py
@@ -7,6 +7,7 @@ real fakes, never ``unittest.mock``.
from __future__ import annotations
+import asyncio
import shutil
from collections.abc import AsyncIterator, Callable
from dataclasses import dataclass
@@ -14,7 +15,13 @@ from pathlib import Path
from typing import Any
from jarvis.missions.budget import BudgetTracker
-from jarvis.missions.capacity import PaidOffer
+from jarvis.missions.capacity import (
+ CapacityPolicy,
+ DailyPaidLedger,
+ PaidCallGate,
+ PaidCallRefused,
+ PaidOffer,
+)
from jarvis.missions.critic.verdict import REQUIRED_AXES, CriticAxis, CriticVerdict
from jarvis.missions.kontrollierer.decomposer import MissionPlan, Step
from jarvis.missions.kontrollierer.orchestrator import Kontrollierer
@@ -46,7 +53,10 @@ class FakeMissionWorker:
``quota`` makes each spawn end on a spent subscription window;
``writes`` maps relative paths to content the spawn writes into its
- workspace before finishing.
+ workspace before finishing. With a ``gate`` (a paid fallback worker) each
+ spawn makes ``calls`` model calls of ``(reserve_usd, actual_usd)`` — the
+ actual ``None`` meaning "the call reported no usage" — through the gate,
+ like the real in-process API worker, and stops on a refusal.
"""
cli = "claude"
@@ -59,9 +69,16 @@ class FakeMissionWorker:
writes: dict[str, str] | None = None,
on_spawn: Callable[[str, Path], None] | None = None,
cost_usd: float = 0.0,
+ gate: PaidCallGate | None = None,
+ calls: list[tuple[float, float | None]] | None = None,
+ call_delay_s: float = 0.0,
) -> None:
self.family = family
self.cost_usd = cost_usd
+ self.gate = gate
+ self.calls = list(calls or [])
+ self.call_delay_s = call_delay_s
+ self.refused: list[str] = []
self.quota = quota
self.writes = dict(writes or {})
self.on_spawn = on_spawn
@@ -79,6 +96,25 @@ class FakeMissionWorker:
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(text, encoding="utf-8")
_write_log(log_dir)
+ if self.gate is not None and self.calls:
+ spent = 0.0
+ for reserve_usd, actual_usd in self.calls:
+ try:
+ reservation = self.gate.reserve(reserve_usd)
+ except PaidCallRefused as exc:
+ self.refused.append(exc.reason)
+ yield ResultEvent(
+ is_error=True,
+ subtype="error_during_execution",
+ result=f"[worker error: {exc}]",
+ cost_usd=spent,
+ )
+ return
+ if self.call_delay_s:
+ await asyncio.sleep(self.call_delay_s)
+ spent += self.gate.commit(reservation, actual_usd)
+ yield ResultEvent(cost_usd=spent)
+ return
if self.quota:
yield ResultEvent(
is_error=True,
@@ -148,26 +184,70 @@ class DirWorktrees:
class FakePaidOption:
- """A fixed paid offer; its workers report ``cost_per_spawn`` USD each."""
+ """A fixed paid offer. Its workers report ``cost_per_spawn`` USD each at
+ the end of a spawn — or, with ``calls``, make gated model calls like the
+ real API worker (see :class:`FakeMissionWorker`)."""
- def __init__(self, offer: PaidOffer | None, *, cost_per_spawn: float = 0.25) -> None:
+ def __init__(
+ self,
+ offer: PaidOffer | None,
+ *,
+ cost_per_spawn: float = 0.25,
+ calls: list[tuple[float, float | None]] | None = None,
+ call_delay_s: float = 0.0,
+ ) -> None:
self._offer = offer
self.cost_per_spawn = cost_per_spawn
+ self.calls = calls
+ self.call_delay_s = call_delay_s
self.offer_calls: list[dict[str, Any]] = []
self.workers: list[FakeMissionWorker] = []
+ self.gates: list[PaidCallGate] = []
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)
+ def worker(self, offer: PaidOffer, *, gate: PaidCallGate, task_text: str) -> Any:
+ self.gates.append(gate)
+ self.remaining.append(gate.remaining_usd())
+ worker = FakeMissionWorker(
+ family=offer.provider,
+ cost_usd=0.0 if self.calls else self.cost_per_spawn,
+ gate=gate,
+ calls=self.calls,
+ call_delay_s=self.call_delay_s,
+ )
self.workers.append(worker)
return worker
+class Switch:
+ """A mutable on/off value a :class:`CapacityPolicy` reads per call."""
+
+ def __init__(self, value: bool) -> None:
+ self.value = value
+
+ def __call__(self) -> bool:
+ return self.value
+
+
+def make_policy(
+ tmp_path: Path, *, pinned: bool = True, paid_fallback: bool = False
+) -> tuple[CapacityPolicy, Switch, Switch]:
+ """A real :class:`CapacityPolicy` on injected answers and a temp daily
+ ledger. Returns the policy plus its ``pinned`` and ``paid_fallback``
+ switches, which the test can flip mid-run."""
+ pinned_switch, paid_switch = Switch(pinned), Switch(paid_fallback)
+ policy = CapacityPolicy(
+ pinned=pinned_switch,
+ paid_fallback=paid_switch,
+ daily=DailyPaidLedger(tmp_path / "paid-ledger.json"),
+ )
+ return policy, pinned_switch, paid_switch
+
+
def make_kontrollierer(
manager: MissionManager,
tmp_path: Path,
@@ -175,7 +255,12 @@ def make_kontrollierer(
factory: Callable[[Step], Any],
critic: Any | None = None,
paid_option: Any | None = None,
+ capacity_policy: CapacityPolicy | None = None,
) -> Kontrollierer:
+ """A Kontrollierer on fakes. By default a subscription install (pinned)
+ with the paid-API fallback OFF and a temp daily ledger."""
+ if capacity_policy is None:
+ capacity_policy, _pinned, _paid = make_policy(tmp_path)
return Kontrollierer(
manager=manager,
decomposer=FixedPlanDecomposer(plan), # type: ignore[arg-type]
@@ -187,4 +272,5 @@ def make_kontrollierer(
job_factory=NoopJob,
isolation_root=tmp_path / "missions",
paid_option=paid_option,
+ capacity_policy=capacity_policy,
)
diff --git a/tests/missions/conftest.py b/tests/missions/conftest.py
index 761080eda2..16b117d59e 100644
--- a/tests/missions/conftest.py
+++ b/tests/missions/conftest.py
@@ -9,6 +9,18 @@ from jarvis.missions.events import EventEnvelope, MissionDispatched, now_ms
from jarvis.missions.ids import uuid7_str
[email protected](autouse=True)
+def _no_live_subscription_login(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Never read the developer's real ``claude`` / codex login to decide
+ whether this is a subscription install (jarvis/missions/capacity.py): a
+ signed-in machine would flip every mission test into the pinned path.
+ Tests that need a subscription install set the sticky marker or patch
+ ``install_is_pinned`` explicitly."""
+ from jarvis.missions import init as mission_init
+
+ monkeypatch.setattr(mission_init, "_positive_subscription_login", lambda: False)
+
+
@pytest.fixture
def tmp_missions_db(tmp_path: Path) -> Path:
"""Pfad zu einer frischen, leeren missions.db im tmp-Verzeichnis."""
diff --git a/tests/missions/test_capacity_approval.py b/tests/missions/test_capacity_approval.py
index 8a4a0d5359..5f4bd6d65a 100644
--- a/tests/missions/test_capacity_approval.py
+++ b/tests/missions/test_capacity_approval.py
@@ -1,10 +1,12 @@
"""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.
+The user's rules (2026-10-06, revised 2026-10-07): with the paid-fallback
+setting OFF, never switch to a paid API on its own; show provider, model,
+estimated cost, what the mission already spent and the reason first; options
+wait / approve for this mission / cancel; an approval covers this one mission
+run only — worker AND critic calls, up to $2 more — and is never stored or
+global; log the decision and the real cost; a declined mission stays safely
+parked.
"""
from __future__ import annotations
@@ -21,7 +23,11 @@ from jarvis.missions import init as mi
from jarvis.missions.capacity import (
PAID_MISSION_CAP_USD,
CapacityDecisionRejected,
+ DailyPaidLedger,
+ MissionPaidLedger,
+ PaidCallGate,
PaidOffer,
+ RouteDecision,
WorkerCapacityUnavailable,
estimate_paid_cost_usd,
read_checkpoint,
@@ -221,14 +227,17 @@ async def test_approved_run_uses_exactly_the_approved_offer_and_logs_real_cost(
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 == {}
+ assert usage[0].automatic is False # a manual approval, not the setting
+ # The approval and the run's ledger died with the run.
+ assert k._paid_approval == {} and k._ledgers == {}
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)
+ # Three $0.80 calls: the third would cross the $2 cap and is refused
+ # before it is made.
+ paid = FakePaidOption(OFFER, calls=[(0.8, 0.8)] * 3)
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)
@@ -238,7 +247,10 @@ async def test_cost_cap_parks_the_run_and_keeps_waiting_for_the_subscription(
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]
+ assert [p.cost_usd for p in payloads if isinstance(p, MissionPaidUsage)] == [
+ pytest.approx(1.6)
+ ]
+ assert paid.workers[0].refused == ["paid_cap_reached"]
# 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"
@@ -247,7 +259,7 @@ async def test_cost_cap_parks_the_run_and_keeps_waiting_for_the_subscription(
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)
+ paid = FakePaidOption(OFFER, calls=[(0.8, 0.8)] * 3)
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)
@@ -334,14 +346,28 @@ def test_a_spent_api_key_is_not_offered_again(monkeypatch: pytest.MonkeyPatch) -
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,
+def _manual_gate(tmp_path: Path, *, spent: float = 0.0) -> PaidCallGate:
+ """A gate on an active manual approval (consent never changes)."""
+ ledger = MissionPaidLedger(spent)
+ ledger.grant_manual()
+ return PaidCallGate(
+ mission_id="m",
+ offer=OFFER,
+ ledger=ledger,
+ daily=DailyPaidLedger(tmp_path / "ledger.json"),
+ authorize=lambda: RouteDecision("paid", automatic=False),
+ )
+
+
+def test_paid_worker_is_pinned_to_the_approved_model_and_gate(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
monkeypatch.setattr(mi, "_assemble_worker_mcp_servers", lambda **_k: ())
- worker = mi.ApiKeyPaidOption().worker(OFFER, remaining_usd=1.25, task_text="t")
+ gate = _manual_gate(tmp_path)
+ worker = mi.ApiKeyPaidOption().worker(OFFER, gate=gate, 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,
+ assert (worker.provider, worker.pinned_model, worker.paid_gate) == (
+ "claude-api", "claude-sonnet-4-6", gate,
)
@@ -349,12 +375,15 @@ def test_paid_worker_is_pinned_to_the_approved_model_and_cap(
class _UsageBrain:
- """Every turn asks for a tool and reports a fixed usage block."""
+ """Every turn asks for a tool and reports a realistic usage block: as many
+ input tokens as a quarter of the request's bytes, a full output budget."""
def __init__(self) -> None:
self.calls = 0
- async def complete(self, _req: BrainRequest) -> AsyncIterator[BrainDelta]:
+ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
+ from jarvis.missions.workers.api_agent_worker import _MAX_TOKENS, _request_bytes
+
self.calls += 1
yield BrainDelta(
tool_call={"id": f"c{self.calls}", "name": "Write",
@@ -362,7 +391,11 @@ class _UsageBrain:
)
yield BrainDelta(
finish_reason="tool_use",
- usage={"input_tokens": 200_000, "output_tokens": 10_000, "cache_hit_tokens": 0},
+ usage={
+ "input_tokens": _request_bytes(req) // 4,
+ "output_tokens": _MAX_TOKENS,
+ "cache_hit_tokens": 0,
+ },
)
@@ -373,11 +406,9 @@ async def test_api_worker_stops_at_the_cost_cap(
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
- )
+ # The approval grants $2 on top of what the mission already paid ($1).
+ gate = _manual_gate(tmp_path, spent=1.0)
+ worker = ApiAgentWorker("claude-api", pinned_model="claude-sonnet-4-6", paid_gate=gate)
events = [
ev
async for ev in worker.spawn(
@@ -388,10 +419,46 @@ async def test_api_worker_stops_at_the_cost_cap(
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
+ assert "paid_cap_reached" in result.result
+ assert gate.refusal == "paid_cap_reached"
+ # Each call reserves its maximum cost first, so a call that could cross
+ # the cap is never made: this run never spends more than the approval.
+ assert brain.calls > 1
+ assert gate.charged_usd == pytest.approx(result.cost_usd)
+ assert gate.charged_usd <= PAID_MISSION_CAP_USD + 1e-9
+
+
+async def test_api_worker_counts_a_usage_less_call_as_its_reservation(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """A stream that reports no usage is charged its whole reservation
+ (fail closed) — it can never slip under the cap."""
+
+ class _SilentBrain:
+ def __init__(self) -> None:
+ self.calls = 0
+
+ async def complete(self, _req: BrainRequest) -> AsyncIterator[BrainDelta]:
+ self.calls += 1
+ yield BrainDelta(content="done", finish_reason="end_turn")
+
+ brain = _SilentBrain()
+ monkeypatch.setattr(
+ "jarvis.missions.workers.api_agent_worker._build_brain", lambda _p, _m: brain
+ )
+ gate = _manual_gate(tmp_path)
+ worker = ApiAgentWorker("claude-api", pinned_model="claude-sonnet-4-6", paid_gate=gate)
+ events = [
+ ev
+ async for ev in worker.spawn(
+ "go", worktree=tmp_path, env={}, job=None, worker_id="w",
+ log_dir=tmp_path / "logs",
+ )
+ ]
+ assert events[-1].is_error is False and brain.calls == 1
+ assert gate.calls == 1
+ assert gate.charged_usd > 0
+ assert events[-1].cost_usd == pytest.approx(gate.charged_usd)
# --- REST -------------------------------------------------------------------------
@@ -430,6 +497,8 @@ async def test_rest_shows_the_offer_and_applies_decisions(
"cost_cap_usd": PAID_MISSION_CAP_USD,
"reason": "provider_quota",
"open_steps": 1,
+ "spent_usd": 0.0,
+ "covers_critic": True,
}
assert mismatch.status_code == 409
assert waited.status_code == 200 and waited.json()["state"] == "WAITING_CAPACITY"
diff --git a/tests/missions/test_capacity_critic.py b/tests/missions/test_capacity_critic.py
index 324d6cf735..142981a44c 100644
--- a/tests/missions/test_capacity_critic.py
+++ b/tests/missions/test_capacity_critic.py
@@ -1,8 +1,13 @@
"""A critic without capacity parks the mission; it never fails delivered work,
-re-runs a worker, or grades on another family or a paid key (2026-10-06).
-
-- The pinned critic stays on its subscription: no codex/claude cross-over,
- no per-token API critic — a worker's paid approval never covers critic calls.
+re-runs a worker, or grades on a paid key without consent (2026-10-06,
+revised 2026-10-07).
+
+- The critic of a subscription install grades on its subscription, else on
+ another connected subscription (claude <-> codex, free), else on a paid key
+ only through the mission's consent gate (setting or approval — an approval
+ covers critic calls).
+- Only a vendor's own "spent window" / "dead login" notice is a capacity
+ signal; a transient overload or rate limit is not, and arms no cooldown.
- A critic that says "no capacity" parks the mission with the review pending.
- A resume runs ONLY the missing review on the saved worker result.
"""
@@ -45,12 +50,20 @@ def _fresh_cooldowns():
clear_claude_quota_cooldown()
-def _pin(monkeypatch: pytest.MonkeyPatch) -> None:
- """A Claude-subscription install: the claude CLI is present."""
+def _pin(monkeypatch: pytest.MonkeyPatch, *, codex_login: bool = False) -> None:
+ """A Claude-subscription install: the claude CLI is present and logged in;
+ codex is logged in only when asked."""
+ monkeypatch.setattr("jarvis.missions.init.install_is_pinned", lambda: True)
monkeypatch.setattr(
"jarvis.missions.workers.claude_direct_worker._resolve_claude_binary",
lambda: "/usr/local/bin/claude",
)
+ monkeypatch.setattr("jarvis.missions.init._claude_subscription_login_state", lambda: True)
+ monkeypatch.setattr(
+ "jarvis.missions.workers.codex_direct_worker._codex_oauth_available",
+ lambda: codex_login,
+ )
+ monkeypatch.setattr("jarvis.codex_auth_state.codex_needs_reauth", lambda: False)
def _no_paid_critic(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -107,18 +120,19 @@ async def test_dead_claude_login_parks_instead_of_crossing_families(
assert (exc.value.reason, exc.value.provider) == ("provider_auth", "claude")
-async def test_codex_critic_never_falls_back_to_claude(
+async def test_spent_codex_critic_without_another_subscription_parks(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
+ _pin(monkeypatch, codex_login=True)
monkeypatch.setattr(
"jarvis.missions.critic.runner._resolve_critic_provider_model",
lambda: ("chatgpt", ""),
)
- monkeypatch.setattr("jarvis.codex_auth_state.codex_needs_reauth", lambda: False)
monkeypatch.setattr("jarvis.codex_quota_state.codex_in_quota_cooldown", lambda **_k: True)
+ monkeypatch.setattr("jarvis.missions.critic.runner._claude_cli_critic_viable", lambda: False)
async def _no_claude(self: Any, **_k: Any) -> None:
- raise AssertionError("a codex-pinned critic must not run on Claude")
+ raise AssertionError("a logged-out Claude critic must not run")
monkeypatch.setattr(CriticRunner, "_invoke_via_claude_direct", _no_claude)
_no_paid_critic(monkeypatch)
@@ -128,6 +142,167 @@ async def test_codex_critic_never_falls_back_to_claude(
assert (exc.value.reason, exc.value.provider) == ("provider_quota", "codex")
+def _approve_verdict() -> CriticVerdict:
+ return CriticVerdict(
+ verdict="approve",
+ axes={ax: CriticAxis(status="pass", evidence=["x:1"]) for ax in REQUIRED_AXES},
+ issues=[],
+ correction_instruction="",
+ summary="ok",
+ summary_de="ok",
+ confidence=0.9,
+ suggested_next_action="accept",
+ )
+
+
+async def test_spent_codex_critic_grades_on_the_claude_subscription(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """Subscription to subscription is free: the restored codex -> Claude path."""
+ _pin(monkeypatch, codex_login=True)
+ monkeypatch.setattr(
+ "jarvis.missions.critic.runner._resolve_critic_provider_model",
+ lambda: ("chatgpt", ""),
+ )
+ monkeypatch.setattr("jarvis.codex_quota_state.codex_in_quota_cooldown", lambda **_k: True)
+ monkeypatch.setattr("jarvis.missions.critic.runner._claude_cli_critic_viable", lambda: True)
+ graded: list[str] = []
+
+ async def _claude(self: Any, **_k: Any) -> CriticVerdict:
+ graded.append("claude")
+ return _approve_verdict()
+
+ monkeypatch.setattr(CriticRunner, "_invoke_via_claude_direct", _claude)
+ _no_paid_critic(monkeypatch)
+
+ verdict = await _review(tmp_path)
+ assert verdict.verdict == "approve" and graded == ["claude"]
+
+
+async def test_spent_claude_critic_grades_on_the_codex_subscription(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ _patch_direct(monkeypatch, stdout=SESSION_LIMIT, returncode=1)
+ _pin(monkeypatch, codex_login=True)
+ monkeypatch.setattr("jarvis.codex_quota_state.codex_in_quota_cooldown", lambda **_k: False)
+ _no_paid_critic(monkeypatch)
+ seen: dict[str, Any] = {}
+
+ async def _codex(self: Any, **kwargs: Any) -> CriticVerdict:
+ seen.update(kwargs)
+ return _approve_verdict()
+
+ monkeypatch.setattr(CriticRunner, "_invoke_via_codex_direct", _codex)
+
+ verdict = await _review(tmp_path)
+ assert verdict.verdict == "approve"
+ assert seen["model"] == "" # a Claude model id is never handed to codex
+ assert claude_in_quota_cooldown() # the spent window is remembered
+
+
+# --- What counts as a capacity signal ---------------------------------------------
+
+
+ "text,expected",
+ [
+ ("You've hit your session limit · resets 11:10pm", "provider_quota"),
+ ("Claude AI usage limit reached|1760000000", "provider_quota"),
+ ("You've hit your usage limit. Upgrade to Pro or try again at Jul 31st", "provider_quota"),
+ ("Error: insufficient_quota", "provider_quota"),
+ ("Your credit balance is too low to access the Anthropic API.", "provider_quota"),
+ ("Invalid API key · Please run /login", "provider_auth"),
+ ("Failed to authenticate. API Error: 401 Invalid authentication credentials",
+ "provider_auth"),
+ ("OAuth token has expired. Please obtain a new token.", "provider_auth"),
+ # Transient or unrelated — never a capacity signal:
+ ("API Error: 429 Too Many Requests (rate limit) — retry shortly", None),
+ ('API Error: 529 {"type":"overloaded_error","message":"Overloaded"}', None),
+ ("API Error: 503 Service Unavailable", None),
+ ("The patch adds a rate limit and a quota check; unknown users get 401.", None),
+ ("error: tests failed (2 of 429 passed)", None),
+ ],
+)
+def test_only_anchored_vendor_notices_are_capacity_signals(
+ text: str, expected: str | None
+) -> None:
+ from jarvis.missions.critic.runner import _capacity_signal
+
+ signal = _capacity_signal(text)
+ assert (signal[0] if signal else None) == expected
+
+
+async def test_a_transient_overload_arms_no_quota_cooldown(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ from jarvis.missions.critic.verdict import CriticSchemaInvalid
+
+ _patch_direct(
+ monkeypatch,
+ stdout='API Error: 529 {"type":"overloaded_error"} rate limit, 429',
+ returncode=1,
+ )
+ _pin(monkeypatch)
+ _no_paid_critic(monkeypatch)
+
+ with pytest.raises(CriticSchemaInvalid):
+ await _review(tmp_path)
+ assert not claude_in_quota_cooldown()
+
+
+async def test_capacity_signals_belong_to_one_call(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """Finding 3: two parallel reviews on one runner. A's spent-window notice
+ must reach A even though B (a non-capacity failure) starts in between —
+ the signal is returned per call, never kept on the shared runner."""
+ import asyncio
+
+ from jarvis.missions.critic.runner import _note_capacity_signal
+ from jarvis.missions.critic.verdict import CriticSchemaInvalid
+
+ _pin(monkeypatch)
+ _no_paid_critic(monkeypatch)
+ monkeypatch.setattr(
+ "jarvis.missions.critic.runner._resolve_critic_provider_model",
+ lambda: ("claude-api", "claude-sonnet-4-6"),
+ )
+ monkeypatch.setattr("jarvis.missions.critic.runner._claude_cli_critic_viable", lambda: True)
+ a_noted, b_started = asyncio.Event(), asyncio.Event()
+
+ async def _claude(self: Any, *, prompt: str, capacity_signals: Any = None, **_k: Any):
+ if "MISSION-A" in prompt:
+ _note_capacity_signal("claude", SESSION_LIMIT, capacity_signals)
+ a_noted.set()
+ await b_started.wait()
+ return None
+ await a_noted.wait()
+ b_started.set()
+ return None # B: garbage output, not a capacity problem
+
+ monkeypatch.setattr(CriticRunner, "_invoke_via_claude_direct", _claude)
+ monkeypatch.setattr("jarvis.claude_quota_state.claude_in_quota_cooldown", lambda **_k: False)
+ runner = CriticRunner()
+
+ async def review(tag: str) -> Any:
+ return await runner.run(
+ mission_prompt=f"Build {tag}",
+ worker_diff="diff --git a/x b/x\n+x\n",
+ worker_log="log",
+ prior_reflections="",
+ iteration=0,
+ worktree=tmp_path,
+ env={},
+ )
+
+ a, b = await asyncio.gather(
+ review("MISSION-A"), review("MISSION-B"), return_exceptions=True
+ )
+ assert isinstance(a, CriticCapacityUnavailable) and a.reason == "provider_quota"
+ assert isinstance(b, CriticSchemaInvalid)
+ assert not hasattr(runner, "_capacity_signal")
+
+
async def test_a_long_review_that_mentions_quotas_is_not_a_capacity_signal(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
@@ -259,12 +434,13 @@ async def test_capacity_waits_never_count_toward_failing_the_review(
assert factory.spawned() == 1
-async def test_paid_run_with_spent_critic_parks_without_paying_again(
+async def test_paid_run_without_critic_consent_parks_without_paying_again(
manager: MissionManager, tmp_path: Path, delivered: None
) -> None:
- """The approved paid worker runs once; its critic is spent → park. The
- approval dies with the run: the review later resumes on the subscription,
- and neither the paid worker nor a paid critic runs again."""
+ """The approved paid worker runs once; its critic cannot grade (a critic
+ that ignores the gate) → park. The approval dies with the run: the review
+ later resumes on the subscription, and neither the paid worker nor a paid
+ critic runs again."""
offer = PaidOffer(
provider="claude-api",
model="claude-sonnet-4-6",
diff --git a/tests/missions/test_capacity_no_key_escape.py b/tests/missions/test_capacity_no_key_escape.py
index 9f0a2f697e..b09dca8310 100644
--- a/tests/missions/test_capacity_no_key_escape.py
+++ b/tests/missions/test_capacity_no_key_escape.py
@@ -1,9 +1,12 @@
"""No automatic escape from the Claude subscription to a stored Anthropic key.
-User rule (2026-10-06): under NO condition may a mission whose Claude
-subscription is spent, logged out or unreadable run on a stored per-token
-Anthropic API key on its own — not on the first run, not on any resume. Only
-an explicit per-mission approval may bill a key.
+User rule (2026-10-06, revised 2026-10-07): under NO condition may a mission
+on a subscription install whose subscriptions are spent, logged out or
+unreadable run on a stored per-token Anthropic API key on its own — not on the
+first run, not on any resume. Another connected subscription is fine (free);
+a key bills only with the paid-fallback setting ON or a per-mission approval.
+An API-key-only install (never connected a subscription) is unaffected: its
+key is its primary credential (AP-22).
These tests drive the REAL worker factory and env builder from
``bootstrap_missions``. Every credential is a fake string; no secret store is
@@ -35,6 +38,7 @@ class World:
def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None:
self.login: bool | None = None # None = logged out / probe unreadable
self.cooldown = False
+ self.codex_login = False
self.live_oauth: str | None = None
self.native_subscription: object | None = None
mp = monkeypatch
@@ -53,7 +57,7 @@ class World:
mp.setattr(mi, "_api_key_family_viable", lambda _p: True)
mp.setattr(
"jarvis.missions.workers.codex_direct_worker._codex_oauth_available",
- lambda: True,
+ lambda: self.codex_login,
)
mp.setattr("jarvis.codex_auth_state.codex_needs_reauth", lambda: False)
mp.setattr("jarvis.codex_quota_state.codex_in_quota_cooldown", lambda **_k: False)
@@ -65,10 +69,18 @@ class World:
)
mp.setattr(mi, "_assemble_worker_mcp_servers", lambda **_k: ())
+ def subscription_install(self) -> None:
+ """A subscription was seen connected recently (the sticky signal)."""
+ from jarvis.brain import background_policy
+
+ background_policy.note_connected("claude-cli")
+
@pytest.fixture
def world(monkeypatch: pytest.MonkeyPatch) -> World:
- return World(monkeypatch)
+ world = World(monkeypatch)
+ world.subscription_install()
+ return world
@pytest.fixture
@@ -108,6 +120,17 @@ async def test_spent_or_unreadable_subscription_parks_instead_of_using_the_key(
assert (exc.value.reason, exc.value.provider) == (reason, "claude")
+async def test_spent_claude_moves_to_a_connected_codex_login_not_the_key(
+ stack: dict[str, Any], world: World
+) -> None:
+ from jarvis.missions.workers.codex_direct_worker import CodexDirectWorker
+
+ world.login, world.cooldown, world.codex_login = True, True, True
+ worker = stack["kontrollierer"]._worker_factory(_step())
+ assert isinstance(worker, CodexDirectWorker)
+ assert worker.backend_fallback is False
+
+
async def test_live_subscription_runs_claude_without_any_fallback(
stack: dict[str, Any], world: World
) -> None:
@@ -131,6 +154,28 @@ async def test_cli_env_never_carries_a_classic_api_key(
assert FAKE_API_KEY not in env.values()
+async def test_key_only_install_keeps_its_key(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Finding 1: Claude Code installed but never logged in, no subscription
+ ever seen — the key is this install's primary credential: not pinned, not
+ stripped, no parking (AP-22)."""
+ from jarvis.missions.workers.claude_direct_worker import ClaudeDirectWorker
+
+ World(monkeypatch) # login None, no codex login, no sticky marker
+ assert mi.install_is_pinned() is False
+ stack = await mi.bootstrap_missions(
+ db_path=tmp_path / "missions.db", isolation_root=tmp_path / "sub-agents"
+ )
+ try:
+ env = stack["kontrollierer"]._env_builder(tmp_path / "mission")
+ assert FAKE_API_KEY in env.values()
+ worker = stack["kontrollierer"]._worker_factory(_step())
+ assert isinstance(worker, ClaudeDirectWorker) # the legacy chain, unparked
+ finally:
+ await mi.shutdown_missions(stack)
+
+
async def test_cli_env_keeps_the_subscription_login(
stack: dict[str, Any], world: World, tmp_path: Path
) -> None:
@@ -140,12 +185,40 @@ async def test_cli_env_keeps_the_subscription_login(
assert FAKE_API_KEY not in env.values()
+async def test_antigravity_env_carries_no_gemini_key_on_a_subscription_install(
+ stack: dict[str, Any], world: World, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The antigravity worker crosses to the Gemini CLI on GEMINI_API_KEY when
+ agy has no login — an automatic paid switch on a subscription install."""
+ monkeypatch.setattr(mi, "_live_subagent_provider", lambda _snapshot: "antigravity")
+ env = stack["kontrollierer"]._env_builder(tmp_path / "mission")
+ assert FAKE_API_KEY not in env.values()
+
+
+async def test_antigravity_env_keeps_the_gemini_key_on_a_key_only_install(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ World(monkeypatch) # no sticky marker, no login: a key-only install
+ monkeypatch.setattr(mi, "_live_subagent_provider", lambda _snapshot: "antigravity")
+ stack = await mi.bootstrap_missions(
+ db_path=tmp_path / "missions.db", isolation_root=tmp_path / "sub-agents"
+ )
+ try:
+ env = stack["kontrollierer"]._env_builder(tmp_path / "mission")
+ assert FAKE_API_KEY in env.values()
+ finally:
+ await mi.shutdown_missions(stack)
+
+
def test_key_filter_rule() -> None:
- assert mi._anthropic_key_for_cli_env(FAKE_API_KEY, cli_present=True) is None
- assert mi._anthropic_key_for_cli_env(FAKE_OAUTH, cli_present=True) == FAKE_OAUTH
- assert mi._anthropic_key_for_cli_env(None, cli_present=True) is None
+ strip = mi._anthropic_key_for_cli_env
+ assert strip(FAKE_API_KEY, cli_present=True, pinned=True) is None
+ assert strip(FAKE_OAUTH, cli_present=True, pinned=True) == FAKE_OAUTH
+ assert strip(None, cli_present=True, pinned=True) is None
# Without the CLI there is no subscription to protect; the key is untouched.
- assert mi._anthropic_key_for_cli_env(FAKE_API_KEY, cli_present=False) == FAKE_API_KEY
+ assert strip(FAKE_API_KEY, cli_present=False, pinned=True) == FAKE_API_KEY
+ # A key-only install keeps its key even with the CLI installed (AP-22).
+ assert strip(FAKE_API_KEY, cli_present=True, pinned=False) == FAKE_API_KEY
# --- First run and every resume stay parked until approval -------------------------
diff --git a/tests/missions/test_capacity_paid_fallback.py b/tests/missions/test_capacity_paid_fallback.py
new file mode 100644
index 0000000000..3e49977685
--- /dev/null
+++ b/tests/missions/test_capacity_paid_fallback.py
@@ -0,0 +1,936 @@
+"""Paid-API fallback for missions: consent, caps and the one routing rule.
+
+The maintainer's decisions (2026-10-07, jarvis/missions/capacity.py):
+
+- subscriptions first; another connected subscription is free;
+- ``[missions] paid_api_fallback`` (default OFF): ON continues on the user's
+ key when no subscription has capacity, within $2 per mission (cumulative,
+ shared by parallel steps, worker and critic, reserved before every call)
+ and $10 per rolling 24 h of automatic use;
+- consent is checked before EVERY paid call: switching the setting off parks
+ the mission (``paid_consent_revoked``) at the next call;
+- a manual approval grants up to $2 more, covers critic calls, shows what the
+ mission already spent, and is recorded but never blocked by the daily cap;
+- the setting is written only through config_writer, read fresh, behind the
+ global web guard, flagged dangerous, and unreachable for voice/chat/agents.
+"""
+from __future__ import annotations
+
+import threading
+import time
+from collections.abc import AsyncIterator
+from pathlib import Path
+from typing import Any
+
+import httpx
+import pytest
+from fastapi import FastAPI
+
+from jarvis.missions.capacity import (
+ PAID_DAILY_CAP_USD,
+ PAID_MISSION_CAP_USD,
+ CriticCapacityUnavailable,
+ DailyPaidLedger,
+ MissionPaidLedger,
+ PaidCallGate,
+ PaidCallRefused,
+ PaidOffer,
+ RouteDecision,
+ WorkerCapacityUnavailable,
+ decide_route,
+ paid_api_fallback_enabled,
+)
+from jarvis.missions.critic.verdict import REQUIRED_AXES, CriticAxis, CriticVerdict
+from jarvis.missions.events import (
+ EventEnvelope,
+ MissionPaidUsage,
+ MissionWaitingCapacity,
+ now_ms,
+)
+from jarvis.missions.kontrollierer.decomposer import MissionPlan, Step
+from jarvis.missions.manager import MissionManager
+from jarvis.missions.state_machine import MissionState
+from tests.fakes.fake_mission_runtime import (
+ FakeMissionWorker,
+ FakePaidOption,
+ ResultEvent,
+ make_kontrollierer,
+ make_policy,
+)
+
+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 SpentSubscriptions:
+ """The worker factory of a subscription install whose subscriptions are
+ all out of capacity until ``capacity`` is set."""
+
+ 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")
+
+
+def _approve() -> CriticVerdict:
+ return CriticVerdict(
+ verdict="approve",
+ axes={ax: CriticAxis(status="pass", evidence=["x:1"]) for ax in REQUIRED_AXES},
+ issues=[],
+ correction_instruction="",
+ summary="ok",
+ summary_de="ok",
+ confidence=0.9,
+ suggested_next_action="accept",
+ )
+
+
+class GateAwareCritic:
+ """A critic whose subscription is spent: it grades only through the
+ paid gate it is handed (paying ``cost`` per review), else parks."""
+
+ def __init__(self, cost: float = 0.0) -> None:
+ self.cost = cost
+ self.calls: list[dict[str, Any]] = []
+ self.paid: list[float] = []
+
+ async def run(self, **kwargs: Any) -> CriticVerdict:
+ self.calls.append(kwargs)
+ gate: PaidCallGate | None = kwargs.get("paid_gate")
+ if gate is None:
+ raise CriticCapacityUnavailable("provider_quota", "claude")
+ try:
+ reservation = gate.reserve(self.cost)
+ except PaidCallRefused as exc:
+ raise CriticCapacityUnavailable(exc.reason, exc.provider) from None
+ self.paid.append(gate.commit(reservation, self.cost))
+ return _approve()
+
+
+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
+
+
+def _usage(payloads: list[Any]) -> list[MissionPaidUsage]:
+ return [p for p in payloads if isinstance(p, MissionPaidUsage)]
+
+
+def _waits(payloads: list[Any]) -> list[MissionWaitingCapacity]:
+ return [p for p in payloads if isinstance(p, MissionWaitingCapacity)]
+
+
+def _one_step() -> MissionPlan:
+ return MissionPlan(steps=[Step(slug="task", prompt="write it")], n_workers=1)
+
+
+# --- The routing rule ---------------------------------------------------------------
+
+
+ "kwargs,expected",
+ [
+ ({"subscription_ok": True}, RouteDecision("subscription")),
+ ({}, RouteDecision("park", "provider_quota")), # setting OFF, no approval
+ ({"paid_fallback_enabled": True}, RouteDecision("paid", automatic=True)),
+ ({"paid_fallback_enabled": True, "paid_option_available": False},
+ RouteDecision("park", "provider_quota")),
+ ({"paid_fallback_enabled": True, "mission_remaining_usd": 0.0},
+ RouteDecision("park", "paid_cap_reached")),
+ ({"paid_fallback_enabled": True, "daily_remaining_usd": 0.0},
+ RouteDecision("park", "paid_daily_cap_reached")),
+ ({"manual_approval": True}, RouteDecision("paid", automatic=False)),
+ # A manual approval is never blocked by the daily cap ...
+ ({"manual_approval": True, "daily_remaining_usd": 0.0},
+ RouteDecision("paid", automatic=False)),
+ # ... but by what it granted.
+ ({"manual_approval": True, "mission_remaining_usd": 0.0},
+ RouteDecision("park", "paid_cap_reached")),
+ ],
+)
+def test_one_routing_rule(kwargs: dict[str, Any], expected: RouteDecision) -> None:
+ base: dict[str, Any] = {
+ "subscription_ok": False,
+ "unavailable_reason": "provider_quota",
+ "manual_approval": False,
+ "paid_fallback_enabled": False,
+ "paid_option_available": True,
+ "mission_remaining_usd": 1.0,
+ "daily_remaining_usd": 5.0,
+ }
+ assert decide_route(**{**base, **kwargs}) == expected
+
+
+# --- The ledgers ------------------------------------------------------------------
+
+
+def test_concurrent_reservations_never_cross_the_mission_cap() -> None:
+ ledger = MissionPaidLedger()
+ granted: list[float] = []
+ lock = threading.Lock()
+
+ def caller() -> None:
+ for _ in range(10):
+ if ledger.try_reserve(0.3, automatic=True):
+ time.sleep(0.001)
+ ledger.settle(0.3, 0.3)
+ with lock:
+ granted.append(0.3)
+
+ threads = [threading.Thread(target=caller) for _ in range(8)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+ assert ledger.spent_usd <= PAID_MISSION_CAP_USD + 1e-9
+ assert sum(granted) == pytest.approx(ledger.spent_usd)
+ assert len(granted) == 6 # 6 x $0.30 = $1.80; a seventh would cross $2
+
+
+def test_manual_approval_grants_two_dollars_more() -> None:
+ ledger = MissionPaidLedger(spent_usd=1.75)
+ assert ledger.remaining(automatic=True) == pytest.approx(0.25)
+ assert ledger.remaining(automatic=False) == 0.0 # no approval yet
+ ledger.grant_manual()
+ assert ledger.remaining(automatic=False) == pytest.approx(PAID_MISSION_CAP_USD)
+ ledger.revoke_manual()
+ assert ledger.remaining(automatic=False) == 0.0
+
+
+def test_daily_ledger_is_rolling_and_counts_automatic_use_only(tmp_path: Path) -> None:
+ clock = [1_000_000.0]
+ ledger = DailyPaidLedger(tmp_path / "ledger.json", clock=lambda: clock[0])
+ ledger.record(4.0, automatic=True, mission_id="a")
+ ledger.record(3.0, automatic=False, mission_id="b") # manual: reported, not capped
+ assert ledger.spent_last_24h() == pytest.approx(4.0)
+ assert ledger.spent_last_24h(automatic_only=False) == pytest.approx(7.0)
+ assert ledger.remaining() == pytest.approx(PAID_DAILY_CAP_USD - 4.0)
+ assert ledger.try_reserve(6.0) and not ledger.try_reserve(0.01)
+ ledger.record(0.5, automatic=True, mission_id="a", reserved_usd=6.0)
+ # A fresh reader on the same file sees the persisted entries.
+ again = DailyPaidLedger(tmp_path / "ledger.json", clock=lambda: clock[0])
+ assert again.spent_last_24h() == pytest.approx(4.5)
+ clock[0] += 24 * 3600 + 1
+ assert again.spent_last_24h() == 0.0 # rolled out of the window
+
+
+def test_unreadable_daily_ledger_fails_closed(tmp_path: Path) -> None:
+ path = tmp_path / "ledger.json"
+ path.write_text("{not json", encoding="utf-8")
+ ledger = DailyPaidLedger(path)
+ assert ledger.remaining() == 0.0
+ assert ledger.try_reserve(0.01) is False
+
+
+# --- Setting OFF / ON -----------------------------------------------------------------
+
+
+async def test_setting_off_parks_and_never_pays(manager: MissionManager, tmp_path: Path) -> None:
+ paid = FakePaidOption(OFFER, calls=[(0.2, 0.2)])
+ k = make_kontrollierer(manager, tmp_path, _one_step(), SpentSubscriptions(), paid_option=paid)
+ mission_id = await manager.dispatch(prompt="write the report")
+
+ assert await k.run_mission(mission_id) == MissionState.WAITING_CAPACITY
+ assert paid.workers == []
+ payloads = await _payloads(manager, mission_id)
+ assert _waits(payloads)[-1].reason == "provider_quota"
+ assert _usage(payloads) == []
+
+
+async def test_setting_on_continues_on_the_key_within_the_caps(
+ manager: MissionManager, tmp_path: Path
+) -> None:
+ policy, _pinned, _paid = make_policy(tmp_path, paid_fallback=True)
+ paid = FakePaidOption(OFFER, calls=[(0.3, 0.25), (0.3, 0.2)])
+ k = make_kontrollierer(
+ manager, tmp_path, _one_step(), SpentSubscriptions(), paid_option=paid,
+ capacity_policy=policy,
+ )
+ mission_id = await manager.dispatch(prompt="write the report")
+
+ assert await k.run_mission(mission_id) == MissionState.APPROVED
+ assert [w.family for w in paid.workers] == ["claude-api"]
+ usage = _usage(await _payloads(manager, mission_id))
+ assert len(usage) == 1
+ assert (usage[0].provider, usage[0].automatic) == ("claude-api", True)
+ assert usage[0].cost_usd == pytest.approx(0.45)
+ assert policy.daily.spent_last_24h() == pytest.approx(0.45)
+
+
+async def test_a_key_only_install_ignores_the_setting(
+ manager: MissionManager, tmp_path: Path
+) -> None:
+ """The switch has no effect without a subscription: such an install never
+ parks for capacity in the first place (its factory crosses families)."""
+ policy, _pinned, _paid = make_policy(tmp_path, pinned=False, paid_fallback=True)
+ paid = FakePaidOption(OFFER, calls=[(0.3, 0.25)])
+ k = make_kontrollierer(
+ manager, tmp_path, _one_step(), lambda _s: FakeMissionWorker(family="openrouter"),
+ paid_option=paid, capacity_policy=policy,
+ )
+ mission_id = await manager.dispatch(prompt="write the report")
+ assert await k.run_mission(mission_id) == MissionState.APPROVED
+ assert paid.workers == [] and paid.offer_calls == []
+
+
+async def test_a_usage_less_call_counts_its_whole_reservation(
+ manager: MissionManager, tmp_path: Path
+) -> None:
+ policy, _pinned, _paid = make_policy(tmp_path, paid_fallback=True)
+ paid = FakePaidOption(OFFER, calls=[(0.7, None)])
+ k = make_kontrollierer(
+ manager, tmp_path, _one_step(), SpentSubscriptions(), paid_option=paid,
+ capacity_policy=policy,
+ )
+ mission_id = await manager.dispatch(prompt="write the report")
+
+ assert await k.run_mission(mission_id) == MissionState.APPROVED
+ assert _usage(await _payloads(manager, mission_id))[0].cost_usd == pytest.approx(0.7)
+ assert policy.daily.spent_last_24h() == pytest.approx(0.7)
+
+
+async def test_parallel_workers_share_one_two_dollar_ledger(
+ manager: MissionManager, tmp_path: Path
+) -> None:
+ """Finding 5: four parallel steps each want three $0.40 calls ($4.80).
+ Every call reserves first, so together they never pass $2."""
+ policy, _pinned, _paid = make_policy(tmp_path, paid_fallback=True)
+ paid = FakePaidOption(OFFER, calls=[(0.4, 0.4)] * 3, call_delay_s=0.01)
+ steps = [Step(slug=f"s{i}", prompt=f"part {i}") for i in range(4)]
+ plan = MissionPlan(steps=steps, n_workers=4)
+ k = make_kontrollierer(
+ manager, tmp_path, plan, SpentSubscriptions(), paid_option=paid,
+ capacity_policy=policy,
+ )
+ mission_id = await manager.dispatch(prompt="four parts")
+
+ assert await k.run_mission(mission_id) == MissionState.WAITING_CAPACITY
+ payloads = await _payloads(manager, mission_id)
+ spent = sum(u.cost_usd for u in _usage(payloads))
+ assert spent <= PAID_MISSION_CAP_USD + 1e-9
+ assert spent == pytest.approx(2.0) # five $0.40 calls fit, the sixth never
+ assert len(paid.workers) >= 2 # really ran in parallel on one ledger
+ assert _waits(payloads)[-1].reason == "paid_cap_reached"
+ assert "paid_cap_reached" in {r for w in paid.workers for r in w.refused}
+
+
+async def test_the_automatic_cap_is_cumulative_across_runs(
+ manager: MissionManager, tmp_path: Path
+) -> None:
+ """The worker pays $1.50; its $0.60 critic call would cross $2 and parks
+ the review. The resume starts from the recorded $1.50 — the cap never
+ resets — so the review parks again instead of paying."""
+ policy, _pinned, _paid = make_policy(tmp_path, paid_fallback=True)
+ paid = FakePaidOption(OFFER, calls=[(0.5, 0.5)] * 3)
+ critic = GateAwareCritic(cost=0.6)
+ k = make_kontrollierer(
+ manager, tmp_path, _one_step(), SpentSubscriptions(), critic=critic,
+ paid_option=paid, capacity_policy=policy,
+ )
+ k._capture_diff = lambda wt: "diff --git a/r b/r\n+r\n" # type: ignore[method-assign]
+ k._restore_task_workspace = lambda wt, art: True # type: ignore[method-assign]
+ mission_id = await manager.dispatch(prompt="write the report")
+ assert await k.run_mission(mission_id) == MissionState.WAITING_CAPACITY
+ assert await k.paid_spent_usd(mission_id) == pytest.approx(1.5)
+
+ assert await k.resume_mission(mission_id) == MissionState.WAITING_CAPACITY
+ payloads = await _payloads(manager, mission_id)
+ assert [w.reason for w in _waits(payloads)] == ["paid_cap_reached"] * 2
+ assert critic.paid == []
+ assert sum(len(w.prompts) for w in paid.workers) == 1 # the worker never re-ran
+ assert await k.paid_spent_usd(mission_id) == pytest.approx(1.5)
+
+
+# --- Daily cap ------------------------------------------------------------------------
+
+
+async def test_a_spent_daily_cap_parks_without_a_worker(
+ manager: MissionManager, tmp_path: Path
+) -> None:
+ policy, _pinned, _paid = make_policy(tmp_path, paid_fallback=True)
+ policy.daily.record(PAID_DAILY_CAP_USD, automatic=True, mission_id="earlier")
+ paid = FakePaidOption(OFFER, calls=[(0.2, 0.2)])
+ k = make_kontrollierer(
+ manager, tmp_path, _one_step(), SpentSubscriptions(), paid_option=paid,
+ capacity_policy=policy,
+ )
+ mission_id = await manager.dispatch(prompt="write the report")
+
+ assert await k.run_mission(mission_id) == MissionState.WAITING_CAPACITY
+ assert paid.workers == []
+ assert _waits(await _payloads(manager, mission_id))[-1].reason == "paid_daily_cap_reached"
+
+
+async def test_the_daily_cap_stops_a_call_that_would_cross_it(
+ manager: MissionManager, tmp_path: Path
+) -> None:
+ policy, _pinned, _paid = make_policy(tmp_path, paid_fallback=True)
+ policy.daily.record(PAID_DAILY_CAP_USD - 0.1, automatic=True, mission_id="earlier")
+ paid = FakePaidOption(OFFER, calls=[(0.4, 0.4)])
+ k = make_kontrollierer(
+ manager, tmp_path, _one_step(), SpentSubscriptions(), paid_option=paid,
+ capacity_policy=policy,
+ )
+ mission_id = await manager.dispatch(prompt="write the report")
+
+ assert await k.run_mission(mission_id) == MissionState.WAITING_CAPACITY
+ assert paid.workers[0].refused == ["paid_daily_cap_reached"]
+ assert policy.daily.spent_last_24h() == pytest.approx(PAID_DAILY_CAP_USD - 0.1)
+
+
+# --- Consent per call ------------------------------------------------------------------
+
+
+def _write_stream(log_dir: Path) -> None:
+ log_dir.mkdir(parents=True, exist_ok=True)
+ (log_dir / "stream.jsonl").write_text("{}\n", encoding="utf-8")
+
+
+def _config_text(path: Path) -> str:
+ return path.read_text(encoding="utf-8")
+
+
+class _TogglingWorker:
+ """Pays one call, then the user switches the setting off, then tries again."""
+
+ cli = "claude"
+ family = "claude-api"
+ last_pid = 1
+
+ def __init__(self, gate: PaidCallGate, switch: Any) -> None:
+ self.gate = gate
+ self.switch = switch
+
+ async def spawn(self, prompt: str, *, log_dir: Path, **_k: Any) -> AsyncIterator[Any]:
+ _write_stream(log_dir)
+ spent = self.gate.commit(self.gate.reserve(0.2), 0.2)
+ self.switch.value = False # the user turns the setting OFF mid-run
+ try:
+ self.gate.reserve(0.2)
+ except PaidCallRefused as exc:
+ yield ResultEvent(
+ is_error=True, subtype="error_during_execution", result=str(exc),
+ cost_usd=spent,
+ )
+ return
+ yield ResultEvent(cost_usd=spent)
+
+
+async def test_switching_the_setting_off_parks_at_the_next_call(
+ manager: MissionManager, tmp_path: Path
+) -> None:
+ policy, _pinned, paid_switch = make_policy(tmp_path, paid_fallback=True)
+
+ class _Option(FakePaidOption):
+ def worker(self, offer: PaidOffer, *, gate: PaidCallGate, task_text: str) -> Any:
+ self.gates.append(gate)
+ return _TogglingWorker(gate, paid_switch)
+
+ paid = _Option(OFFER)
+ k = make_kontrollierer(
+ manager, tmp_path, _one_step(), SpentSubscriptions(), paid_option=paid,
+ capacity_policy=policy,
+ )
+ mission_id = await manager.dispatch(prompt="write the report")
+
+ assert await k.run_mission(mission_id) == MissionState.WAITING_CAPACITY
+ payloads = await _payloads(manager, mission_id)
+ assert _waits(payloads)[-1].reason == "paid_consent_revoked"
+ assert [u.cost_usd for u in _usage(payloads)] == [pytest.approx(0.2)]
+ assert paid.gates[0].refusal == "paid_consent_revoked"
+
+
+# --- Resume -----------------------------------------------------------------------------
+
+
+async def test_resume_never_goes_metered_with_the_setting_off(
+ manager: MissionManager, tmp_path: Path
+) -> None:
+ policy, _pinned, paid_switch = make_policy(tmp_path)
+ paid = FakePaidOption(OFFER, calls=[(0.3, 0.3)])
+ factory = SpentSubscriptions()
+ k = make_kontrollierer(
+ manager, tmp_path, _one_step(), factory, paid_option=paid, capacity_policy=policy
+ )
+ mission_id = await manager.dispatch(prompt="write the report")
+ assert await k.run_mission(mission_id) == MissionState.WAITING_CAPACITY
+
+ for _ in range(3):
+ assert await k.resume_waiting_missions() == []
+ assert paid.workers == []
+ assert await _state(manager, mission_id) == MissionState.WAITING_CAPACITY
+
+ # The user turns the setting ON: the next tick resumes on the key.
+ paid_switch.value = True
+ assert await k.resume_waiting_missions() == [mission_id]
+ assert await _state(manager, mission_id) == MissionState.APPROVED
+ usage = _usage(await _payloads(manager, mission_id))
+ assert [(u.cost_usd, u.automatic) for u in usage] == [(pytest.approx(0.3), True)]
+
+
+# --- Manual approval: covers the critic, shows what was spent -----------------------------
+
+
+async def test_approval_covers_the_critic_and_shows_the_spend(
+ manager: MissionManager, tmp_path: Path
+) -> None:
+ critic = GateAwareCritic(cost=0.3)
+ paid = FakePaidOption(OFFER, calls=[(0.4, 0.4)])
+ k = make_kontrollierer(
+ manager, tmp_path, _one_step(), SpentSubscriptions(), critic=critic, paid_option=paid
+ )
+ mission_id = await manager.dispatch(prompt="write the report")
+ assert await k.run_mission(mission_id) == MissionState.WAITING_CAPACITY
+ # An earlier paid run of this mission already cost $0.50.
+ await manager.store.append_and_publish(
+ EventEnvelope(
+ mission_id=mission_id,
+ source_actor="kontrollierer",
+ ts_ms=now_ms(),
+ payload=MissionPaidUsage(
+ provider="claude-api", model="claude-sonnet-4-6", cost_usd=0.5,
+ cost_cap_usd=PAID_MISSION_CAP_USD, estimated_cost_usd=1.0, automatic=True,
+ ),
+ )
+ )
+
+ from jarvis.ui.web.missions_routes import router
+
+ app = FastAPI()
+ app.include_router(router)
+ app.state.mission_manager = manager
+ app.state.kontrollierer = k
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
+ shown = (await client.get(f"/api/missions/{mission_id}/paid-offer")).json()["offer"]
+ assert shown["spent_usd"] == pytest.approx(0.5)
+ assert shown["covers_critic"] is True
+
+ await k.decide_capacity(mission_id, "approve_paid", provider=OFFER.provider, model=OFFER.model)
+ for run in list(k._background_runs):
+ await run
+
+ assert await _state(manager, mission_id) == MissionState.APPROVED
+ assert critic.paid == [pytest.approx(0.3)] # the critic call ran on the approval
+ usage = _usage(await _payloads(manager, mission_id))
+ assert [(u.cost_usd, u.automatic) for u in usage[1:]] == [(pytest.approx(0.7), False)]
+ assert await k.paid_spent_usd(mission_id) == pytest.approx(1.2)
+
+
+async def test_manual_approval_is_not_blocked_by_the_daily_cap(
+ manager: MissionManager, tmp_path: Path
+) -> None:
+ policy, _pinned, _paid = make_policy(tmp_path)
+ policy.daily.record(PAID_DAILY_CAP_USD, automatic=True, mission_id="earlier")
+ paid = FakePaidOption(OFFER, calls=[(0.4, 0.4)])
+ k = make_kontrollierer(
+ manager, tmp_path, _one_step(), SpentSubscriptions(), paid_option=paid,
+ capacity_policy=policy,
+ )
+ mission_id = await manager.dispatch(prompt="write the report")
+ assert await k.run_mission(mission_id) == MissionState.WAITING_CAPACITY
+
+ await k.decide_capacity(mission_id, "approve_paid", provider=OFFER.provider, model=OFFER.model)
+ for run in list(k._background_runs):
+ await run
+
+ assert await _state(manager, mission_id) == MissionState.APPROVED
+ # Recorded for reporting, never counted against the automatic cap.
+ assert policy.daily.spent_last_24h() == pytest.approx(PAID_DAILY_CAP_USD)
+ assert policy.daily.spent_last_24h(automatic_only=False) == pytest.approx(
+ PAID_DAILY_CAP_USD + 0.4
+ )
+
+
+async def test_setting_on_lets_the_critic_pay_within_the_same_ledger(
+ manager: MissionManager, tmp_path: Path
+) -> None:
+ policy, _pinned, _paid = make_policy(tmp_path, paid_fallback=True)
+ critic = GateAwareCritic(cost=1.9) # worker $0.40 + critic $1.90 > $2
+ paid = FakePaidOption(OFFER, calls=[(0.4, 0.4)])
+ k = make_kontrollierer(
+ manager, tmp_path, _one_step(), SpentSubscriptions(), critic=critic,
+ paid_option=paid, capacity_policy=policy,
+ )
+ mission_id = await manager.dispatch(prompt="write the report")
+
+ assert await k.run_mission(mission_id) == MissionState.WAITING_CAPACITY
+ payloads = await _payloads(manager, mission_id)
+ assert _waits(payloads)[-1].reason == "paid_cap_reached"
+ assert critic.paid == [] # the critic call that would cross $2 was refused
+ assert sum(u.cost_usd for u in _usage(payloads)) == pytest.approx(0.4)
+
+
+# --- The setting itself ---------------------------------------------------------------------
+
+
+def temp_config(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ path = tmp_path / "jarvis.toml"
+ path.write_text('[ui]\ntheme = "dark"\n', encoding="utf-8")
+ monkeypatch.setenv("JARVIS_CONFIG", str(path))
+ return path
+
+
+def test_setting_defaults_off_and_is_read_fresh(temp_config: Path) -> None:
+ from jarvis.core.config import JarvisConfig, MissionsConfig
+ from jarvis.core.config_writer import set_missions_paid_api_fallback
+
+ assert MissionsConfig().paid_api_fallback is False
+ loaded = JarvisConfig(missions={"paid_api_fallback": True, "later_key": 1})
+ assert loaded.missions.paid_api_fallback is True
+ assert paid_api_fallback_enabled() is False
+ set_missions_paid_api_fallback(True)
+ assert paid_api_fallback_enabled() is True # no restart, no cache
+ text = _config_text(temp_config)
+ assert "[missions]" in text and "paid_api_fallback = true" in text
+ assert 'theme = "dark"' in text # the rest of the file is untouched
+ set_missions_paid_api_fallback(False)
+ assert paid_api_fallback_enabled() is False
+ with pytest.raises(TypeError):
+ set_missions_paid_api_fallback("yes") # type: ignore[arg-type]
+
+
+def test_an_unreadable_config_never_enables_paid_use(
+ temp_config: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ temp_config.write_text("[missions]\npaid_api_fallback = true\n", encoding="utf-8")
+ assert paid_api_fallback_enabled() is True
+
+ def _broken(*_a: Any, **_k: Any) -> Any:
+ raise OSError("config unreadable")
+
+ monkeypatch.setattr("jarvis.core.config.load_config", _broken)
+ assert paid_api_fallback_enabled() is False
+
+
+def test_no_voice_chat_or_agent_surface_can_flip_it() -> None:
+ from jarvis.app_actions.catalog import is_excluded
+ from jarvis.core.self_mod.forbidden import is_forbidden
+ from jarvis.core.self_mod.schema_introspect import introspect_mutable_specs
+
+ assert is_forbidden("missions.paid_api_fallback")
+ assert "missions.paid_api_fallback" not in {s.path for s in introspect_mutable_specs()}
+ assert is_excluded("/api/mission-billing")
+ assert is_excluded("/api/missions/{mission_id}/capacity-decision")
+
+
+# --- Routes ------------------------------------------------------------------------------------
+
+
+def _billing_app(k: Any | None = None) -> FastAPI:
+ from jarvis.ui.web.mission_billing_routes import router
+
+ app = FastAPI()
+ app.include_router(router)
+ app.state.kontrollierer = k
+ return app
+
+
+async def test_routes_read_and_persist_the_switch(
+ manager: MissionManager, tmp_path: Path, temp_config: Path
+) -> None:
+ policy, _pinned, _paid = make_policy(tmp_path)
+ policy.daily.record(1.25, automatic=True, mission_id="m")
+ k = make_kontrollierer(
+ manager, tmp_path, _one_step(), SpentSubscriptions(),
+ paid_option=FakePaidOption(OFFER), capacity_policy=policy,
+ )
+ transport = httpx.ASGITransport(app=_billing_app(k))
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
+ before = await client.get("/api/mission-billing")
+ turned_on = await client.put("/api/mission-billing", json={"paid_api_fallback": True})
+ coerced = await client.put("/api/mission-billing", json={"paid_api_fallback": "yes"})
+ extra = await client.put(
+ "/api/mission-billing", json={"paid_api_fallback": False, "daily_cap_usd": 99}
+ )
+ after = await client.get("/api/mission-billing")
+
+ assert before.status_code == 200
+ assert before.json() == {
+ "paid_api_fallback": False,
+ "subscription_mode": True,
+ "per_mission_cap_usd": PAID_MISSION_CAP_USD,
+ "daily_cap_usd": PAID_DAILY_CAP_USD,
+ "spent_last_24h_usd": 1.25,
+ "paid_provider": {
+ "provider": "claude-api", "model": "claude-sonnet-4-6", "price_known": True,
+ },
+ }
+ assert turned_on.status_code == 200 and turned_on.json()["paid_api_fallback"] is True
+ assert coerced.status_code == 422 and extra.status_code == 422
+ assert after.json()["paid_api_fallback"] is True
+ assert "paid_api_fallback = true" in _config_text(temp_config)
+ # The next decision sees it at once (the policy reads the file).
+ assert paid_api_fallback_enabled() is True
+
+
+async def test_routes_without_a_runner_show_no_priced_key(
+ temp_config: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from jarvis.missions import init as mi
+
+ monkeypatch.setattr(mi, "_api_key_family_viable", lambda _p: False)
+ transport = httpx.ASGITransport(app=_billing_app(None))
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
+ body = (await client.get("/api/mission-billing")).json()
+ assert body["paid_provider"] is None
+ assert body["subscription_mode"] is False # no subscription seen, no login
+ assert body["spent_last_24h_usd"] == 0.0
+
+
+def test_put_is_flagged_dangerous_for_the_cli() -> None:
+ schema = _billing_app().openapi()
+ put = schema["paths"]["/api/mission-billing"]["put"]
+ assert put.get("x-jarvis-dangerous") is True
+ assert put["tags"] == ["missions"]
+ assert "x-jarvis-dangerous" not in schema["paths"]["/api/mission-billing"]["get"]
+
+
[email protected]_auto_web_auth
+async def test_the_global_guard_protects_the_switch(temp_config: Path) -> None:
+ from jarvis.ui.web.surface_security import SurfaceSecurity
+
+ secured = SurfaceSecurity(
+ _billing_app(),
+ public_urls="https://jarvis.example",
+ control_key_validator=lambda token: token == "test-control", # noqa: S105 - fixture
+ session_validator=lambda token: False,
+ )
+ transport = httpx.ASGITransport(app=secured, client=("198.51.100.10", 54321))
+ body = {"paid_api_fallback": True}
+ key = {"Authorization": "Bearer test-control"}
+ async with httpx.AsyncClient(transport=transport, base_url="https://jarvis.example") as c:
+ anonymous = await c.put("/api/mission-billing", json=body)
+ foreign = await c.put(
+ "/api/mission-billing", json=body,
+ headers={**key, "Origin": "https://evil.example"},
+ )
+ assert "paid_api_fallback = true" not in _config_text(temp_config)
+ allowed = await c.put("/api/mission-billing", json=body, headers=key)
+
+ assert anonymous.status_code == 401
+ assert foreign.status_code == 403
+ assert allowed.status_code == 200
+ assert "paid_api_fallback = true" in _config_text(temp_config)
+
+
+def test_no_route_response_carries_a_secret(
+ temp_config: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The billing state names a provider and model at most — never a key."""
+ from fastapi.testclient import TestClient
+
+ from jarvis.missions import init as mi
+
+ fake_key = "sk-ant-api03-FAKE-NOT-A-SECRET"
+ monkeypatch.setattr("jarvis.core.config.get_jarvis_agent_secret", lambda _p: fake_key)
+ monkeypatch.setattr(mi, "_api_key_family_viable", lambda p: p == "claude-api")
+ client = TestClient(_billing_app(None))
+ response = client.get("/api/mission-billing")
+ assert response.status_code == 200
+ assert fake_key not in response.text
+
+
+# --- codex: a fresh login lifts the dead-login flag -----------------------------------------
+
+
+def test_a_fresh_codex_login_clears_needs_reauth(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Finding 2: a mission parked on a dead codex login resumes after
+ `codex login`, without needing a codex success first (none can happen
+ while it is parked) and without a restart."""
+ from jarvis import codex_auth_state as cas
+
+ monkeypatch.setenv("CODEX_HOME", str(tmp_path))
+ auth = tmp_path / "auth.json"
+ auth.write_text('{"tokens": {"refresh_token": "dead-FAKE"}}', encoding="utf-8")
+ cas.clear_codex_needs_reauth()
+ try:
+ cas.mark_codex_needs_reauth()
+ assert cas.codex_needs_reauth() is True # same dead login: stays flagged
+ auth.write_text('{"tokens": {"refresh_token": "fresh-FAKE"}}', encoding="utf-8")
+ assert cas.codex_needs_reauth() is False # `codex login` wrote a new one
+ assert cas.codex_needs_reauth() is False
+
+ # Without any login file the flag holds until a success clears it.
+ auth.unlink()
+ cas.mark_codex_needs_reauth()
+ assert cas.codex_needs_reauth() is True
+ assert cas.codex_auth_fingerprint() is None
+ finally:
+ cas.clear_codex_needs_reauth()
+
+
+def test_codex_fingerprint_never_contains_the_token(tmp_path: Path) -> None:
+ from jarvis.codex_auth_state import codex_auth_fingerprint
+
+ auth = tmp_path / "auth.json"
+ auth.write_text('{"tokens": {"access_token": "abc-FAKE-TOKEN"}}', encoding="utf-8")
+ fp = codex_auth_fingerprint(auth)
+ assert fp is not None and len(fp) == 16 and "FAKE" not in fp
+
+
+# --- The paid critic call itself ---------------------------------------------------------------
+
+
+class _FakeCriticBrain:
+ """An in-process API brain that answers with one approve verdict."""
+
+ usage: dict[str, int] | None = {"input_tokens": 1000, "output_tokens": 200}
+ calls = 0
+
+ def __init__(self, *_a: Any, **_k: Any) -> None:
+ pass
+
+ async def complete(self, _req: Any) -> AsyncIterator[Any]:
+ from jarvis.core.protocols import BrainDelta
+
+ type(self).calls += 1
+ yield BrainDelta(content=_approve().model_dump_json())
+ yield BrainDelta(finish_reason="end_turn", usage=type(self).usage)
+
+
+def _subscriptions_spent(monkeypatch: pytest.MonkeyPatch) -> None:
+ from jarvis.claude_quota_state import mark_claude_quota_cooldown
+
+ monkeypatch.setattr("jarvis.missions.init.install_is_pinned", lambda: True)
+ monkeypatch.setattr(
+ "jarvis.missions.critic.runner._resolve_critic_provider_model",
+ lambda: ("claude-api", "claude-sonnet-4-6"),
+ )
+ monkeypatch.setattr(
+ "jarvis.missions.workers.claude_direct_worker._resolve_claude_binary",
+ lambda: "/usr/local/bin/claude",
+ )
+ monkeypatch.setattr(
+ "jarvis.missions.workers.codex_direct_worker._codex_oauth_available", lambda: False
+ )
+ mark_claude_quota_cooldown()
+ monkeypatch.setattr(
+ "jarvis.brain.provider_registry.BrainProviderRegistry.get_class",
+ lambda self, _p: _FakeCriticBrain,
+ )
+ monkeypatch.setattr("jarvis.core.config.get_jarvis_agent_secret", lambda _p: "FAKE")
+
+
+async def _critic_review(tmp_path: Path, gate: PaidCallGate | None) -> CriticVerdict:
+ from jarvis.missions.critic.runner import CriticRunner
+
+ return await CriticRunner().run(
+ mission_prompt="Build X",
+ worker_diff="diff --git a/x b/x\n+x\n",
+ worker_log="log",
+ prior_reflections="",
+ iteration=0,
+ worktree=tmp_path,
+ env={},
+ paid_gate=gate,
+ )
+
+
+def _gate(
+ tmp_path: Path, decision: list[RouteDecision], ledger: MissionPaidLedger
+) -> PaidCallGate:
+ return PaidCallGate(
+ mission_id="m",
+ offer=OFFER,
+ ledger=ledger,
+ daily=DailyPaidLedger(tmp_path / "ledger.json"),
+ authorize=lambda: decision[0],
+ )
+
+
+async def test_the_paid_critic_reserves_and_books_each_call(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ from jarvis.claude_quota_state import clear_claude_quota_cooldown
+
+ _subscriptions_spent(monkeypatch)
+ try:
+ ledger = MissionPaidLedger()
+ gate = _gate(tmp_path, [RouteDecision("paid", automatic=True)], ledger)
+ verdict = await _critic_review(tmp_path, gate)
+ assert verdict.verdict == "approve"
+ assert gate.calls == 1
+ assert 0 < ledger.spent_usd < 0.05 # 1000 in + 200 out on Sonnet
+ assert ledger.remaining(automatic=True) == pytest.approx(
+ PAID_MISSION_CAP_USD - ledger.spent_usd
+ )
+ finally:
+ clear_claude_quota_cooldown()
+
+
+async def test_the_paid_critic_stops_when_consent_is_gone(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ from jarvis.claude_quota_state import clear_claude_quota_cooldown
+
+ _subscriptions_spent(monkeypatch)
+ _FakeCriticBrain.calls = 0
+ try:
+ ledger = MissionPaidLedger()
+ gate = _gate(tmp_path, [RouteDecision("park", "paid_consent_revoked")], ledger)
+ with pytest.raises(CriticCapacityUnavailable) as exc:
+ await _critic_review(tmp_path, gate)
+ assert exc.value.reason == "paid_consent_revoked"
+ assert _FakeCriticBrain.calls == 0 and ledger.spent_usd == 0.0
+ # No gate at all (setting OFF, no approval): the critic parks.
+ with pytest.raises(CriticCapacityUnavailable) as no_gate:
+ await _critic_review(tmp_path, None)
+ assert no_gate.value.reason == "provider_quota"
+ finally:
+ clear_claude_quota_cooldown()
+
+
+async def test_a_usage_less_paid_critic_call_counts_its_reservation(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ from jarvis.claude_quota_state import clear_claude_quota_cooldown
+
+ _subscriptions_spent(monkeypatch)
+ monkeypatch.setattr(_FakeCriticBrain, "usage", None)
+ try:
+ ledger = MissionPaidLedger()
+ gate = _gate(tmp_path, [RouteDecision("paid", automatic=True)], ledger)
+ await _critic_review(tmp_path, gate)
+ # Booked at the reservation: every prompt byte as a cache-write token
+ # plus the full 2048-token output budget.
+ assert ledger.spent_usd >= 2048 * 15 / 1_000_000
+ finally:
+ clear_claude_quota_cooldown()
+
+
+def test_no_waits_are_lost_in_the_vocabulary() -> None:
+ from typing import get_args
+
+ from jarvis.missions.capacity import CapacityWaitReason
+ from jarvis.missions.events import CAPACITY_WAIT_REASONS
+
+ assert set(get_args(CapacityWaitReason)) == set(CAPACITY_WAIT_REASONS)
+ assert {"paid_daily_cap_reached", "paid_consent_revoked"} <= set(CAPACITY_WAIT_REASONS)
diff --git a/tests/missions/test_capacity_resume.py b/tests/missions/test_capacity_resume.py
index 52dd89299f..a0789e4759 100644
--- a/tests/missions/test_capacity_resume.py
+++ b/tests/missions/test_capacity_resume.py
@@ -1,8 +1,10 @@
"""Automatic resume of a WAITING_CAPACITY mission from its checkpoint.
-The user's rules (2026-10-04): resume once the SAME subscription has capacity
-again, continue exactly from the checkpoint, never redo an approved step,
-never switch to another provider or a paid key without approval.
+The user's rules (2026-10-04, revised 2026-10-07): resume once ANY connected
+subscription has capacity again (moving between subscriptions is free), or on
+the paid-fallback setting within its caps; continue exactly from the
+checkpoint, never redo an approved step, never switch to a metered key
+without consent. A mission that keeps parking without progress backs off.
"""
from __future__ import annotations
@@ -255,11 +257,24 @@ async def test_resume_pass_never_switches_provider(
assert not any(w.prompts for w in factory.workers[1:])
-async def test_resumed_run_parks_again_if_the_worker_family_changes(
+async def test_resumed_run_may_move_to_another_subscription(
manager: MissionManager, tmp_path: Path
) -> None:
+ """Parked on Claude, resumed on the codex login: subscription to
+ subscription costs nothing extra and needs no approval."""
factory = SwitchableFactory(family="codex")
k, mission_id, _first, _second = await _park_second_step(manager, tmp_path, factory)
+ factory.built_for.clear()
+
+ assert await k.resume_waiting_missions() == [mission_id]
+ assert await _state(manager, mission_id) == MissionState.APPROVED
+
+
+async def test_resumed_run_parks_again_if_the_worker_turns_metered(
+ manager: MissionManager, tmp_path: Path
+) -> None:
+ factory = SwitchableFactory(family="openrouter")
+ k, mission_id, _first, _second = await _park_second_step(manager, tmp_path, factory)
assert await k.resume_mission(mission_id) == MissionState.WAITING_CAPACITY
wait = _waits(await _payloads(manager, mission_id))[-1]
@@ -267,6 +282,146 @@ async def test_resumed_run_parks_again_if_the_worker_family_changes(
assert not any(w.prompts for w in factory.workers[1:])
+# --- Backoff, critic probe, claim safety ----------------------------------------
+
+
+async def test_repeat_parks_without_progress_back_off(
+ manager: MissionManager, tmp_path: Path
+) -> None:
+ """Finding 4: a probe that says yes while the run keeps re-parking must
+ not churn every 5 minutes — the wait doubles from 5 to 60 minutes."""
+ from jarvis.missions.capacity import RESUME_BACKOFF_MAX_S, resume_backoff_s
+
+ factory = SwitchableFactory()
+ k, mission_id, _first, _second = await _park_second_step(manager, tmp_path, factory)
+ mission_dir = _mission_dir(tmp_path, mission_id)
+ assert read_checkpoint(mission_dir)["next_resume_ms"] == 0 # type: ignore[index]
+
+ factory.capacity = False
+ assert await k.resume_mission(mission_id) == MissionState.WAITING_CAPACITY
+ first = read_checkpoint(mission_dir)
+ assert first is not None and first["idle_parks"] == 1
+ assert first["next_resume_ms"] > first["created_ms"]
+
+ # The backoff holds even though the probe would now say yes.
+ factory.capacity = True
+ assert await k.resume_waiting_missions() == []
+ assert await _state(manager, mission_id) == MissionState.WAITING_CAPACITY
+
+ no_jitter = lambda a, b: 1.0 # noqa: E731 - fixed jitter for the arithmetic
+ assert [resume_backoff_s(n, jitter=no_jitter) for n in range(7)] == [
+ 0.0, 300.0, 600.0, 1200.0, 2400.0, RESUME_BACKOFF_MAX_S, RESUME_BACKOFF_MAX_S,
+ ]
+ assert 240.0 <= resume_backoff_s(1) <= 360.0 # jittered
+
+
+async def test_progress_resets_the_backoff(manager: MissionManager, tmp_path: Path) -> None:
+ factory = SwitchableFactory()
+ k, mission_id, _first, _second = await _park_second_step(manager, tmp_path, factory)
+ factory.capacity = False
+ await k.resume_mission(mission_id)
+ mission_dir = _mission_dir(tmp_path, mission_id)
+ checkpoint = read_checkpoint(mission_dir)
+ assert checkpoint is not None and checkpoint["idle_parks"] == 1
+ # Expire the backoff by hand: the next resume finishes the step.
+ checkpoint["next_resume_ms"] = 0
+ from jarvis.missions.capacity import write_checkpoint
+
+ write_checkpoint(mission_dir, {k_: v for k_, v in checkpoint.items() if k_ != "version"})
+ factory.capacity = True
+ assert await k.resume_waiting_missions() == [mission_id]
+ assert await _state(manager, mission_id) == MissionState.APPROVED
+ # Terminal: the checkpoint is gone, the directory may be cleaned up again.
+ assert not (mission_dir / CHECKPOINT_NAME).exists()
+
+
+async def test_resume_without_a_critic_probe_answer_stays_parked(
+ manager: MissionManager, tmp_path: Path
+) -> None:
+ """A step parked with its review pending resumes only when a critic has
+ capacity — never claim, restore and re-park on every tick."""
+ from jarvis.missions.capacity import CriticCapacityUnavailable
+ from tests.missions.test_capacity_critic import DELIVERED_DIFF, ScriptedCritic
+
+ class ProbedCritic(ScriptedCritic):
+ def __init__(self, *errors: Exception) -> None:
+ super().__init__(*errors)
+ self.available = False
+
+ def capacity_available(self) -> bool:
+ return self.available
+
+ from jarvis.missions.kontrollierer.orchestrator import Kontrollierer
+
+ critic = ProbedCritic(CriticCapacityUnavailable("provider_quota", "claude"))
+ factory = SwitchableFactory()
+ plan = MissionPlan(steps=[Step(slug="report", prompt="write it")], n_workers=1)
+ k = make_kontrollierer(manager, tmp_path, plan, factory, critic=critic)
+ k._capture_diff = lambda wt: DELIVERED_DIFF # type: ignore[method-assign]
+ k._restore_task_workspace = lambda wt, art: True # type: ignore[method-assign]
+ assert isinstance(k, Kontrollierer)
+ mission_id = await manager.dispatch(prompt="write the report")
+ assert await k.run_mission(mission_id) == MissionState.WAITING_CAPACITY
+
+ # The worker factory has capacity, but only the review is owed.
+ assert await k.resume_waiting_missions() == []
+ assert len(critic.calls) == 1
+ critic.available = True
+ assert await k.resume_waiting_missions() == [mission_id]
+ assert await _state(manager, mission_id) == MissionState.APPROVED
+ assert sum(len(w.prompts) for w in factory.workers) == 1
+
+
+async def test_a_failing_claim_parks_the_mission_again(
+ manager: MissionManager, tmp_path: Path
+) -> None:
+ factory = SwitchableFactory()
+ k, mission_id, _first, _second = await _park_second_step(manager, tmp_path, factory)
+
+ async def _broken_heartbeat(*_a: Any, **_k: Any) -> None:
+ raise RuntimeError("store hiccup")
+
+ async def _broken_finish(*_a: Any, **_k: Any) -> Any:
+ raise RuntimeError("claim bookkeeping failed")
+
+ k._finish_claim = _broken_finish # type: ignore[method-assign]
+ with pytest.raises(RuntimeError):
+ await k.resume_mission(mission_id)
+ assert await _state(manager, mission_id) == MissionState.WAITING_CAPACITY
+
+
+async def test_shutdown_reparks_a_resumed_mission_instead_of_cancelling(
+ manager: MissionManager, tmp_path: Path
+) -> None:
+ gate = asyncio.Event()
+
+ class SlowWorker(FakeMissionWorker):
+ async def spawn(self, prompt: str, **kwargs: Any): # type: ignore[override]
+ await gate.wait()
+ async for ev in super().spawn(prompt, **kwargs):
+ yield ev
+
+ factory = SwitchableFactory()
+ k, mission_id, _first, second = await _park_second_step(manager, tmp_path, factory)
+ k._worker_factory = lambda step: SlowWorker()
+
+ run = asyncio.create_task(k.resume_mission(mission_id))
+ for _ in range(200):
+ if await _state(manager, mission_id) == MissionState.RUNNING and mission_id in (
+ k.running_mission_ids()
+ ):
+ break
+ await asyncio.sleep(0.01)
+ finalized = await k.cancel_all_running(reason="app_shutdown")
+ assert finalized == [mission_id]
+ with pytest.raises(asyncio.CancelledError):
+ await run
+ assert await _state(manager, mission_id) == MissionState.WAITING_CAPACITY
+ assert (_mission_dir(tmp_path, mission_id) / CHECKPOINT_NAME).is_file()
+ waits = _waits(await _payloads(manager, mission_id))
+ assert waits[-1].repeat is True # nothing new to announce while stopping
+
+
# --- Restoring work into a git workspace --------------------------------------
diff --git a/tests/missions/test_capacity_wait.py b/tests/missions/test_capacity_wait.py
index 178e7a77aa..7e0842c458 100644
--- a/tests/missions/test_capacity_wait.py
+++ b/tests/missions/test_capacity_wait.py
@@ -1,8 +1,11 @@
-"""WAITING_CAPACITY: a mission without worker capacity is parked, never failed,
-never moved to another subscription or a paid API key (missions/capacity.py).
-
-Pins the user's rules (2026-10-04):
-- no automatic switch to another subscription or to a per-token key,
+"""WAITING_CAPACITY: a mission without worker capacity is parked, never failed
+(missions/capacity.py).
+
+Pins the user's rules (2026-10-04, revised 2026-10-07):
+- a subscription install moves between connected subscriptions for free,
+ never to a per-token key without consent,
+- a CLI that is merely installed does not make a subscription install
+ (a key-only user keeps the cross-family chain, AP-22),
- an exhausted quota parks the mission with a checkpoint and a clear message,
- a parked mission survives restarts and the age-based cleanup.
"""
@@ -37,6 +40,9 @@ from tests.fakes.fake_mission_runtime import (
make_kontrollierer,
)
+#: The real login probe — the missions conftest stubs it for every test.
+_REAL_LOGIN_PROBE = mi._positive_subscription_login
+
# --- State machine ------------------------------------------------------------
@@ -61,20 +67,21 @@ def test_parked_mission_can_resume_or_end(dst: MissionState) -> None:
# --- Pinning signal -----------------------------------------------------------
-def test_subscription_worker_is_always_pinned() -> None:
- assert pinned_to_subscription(configured_is_subscription=True) is True
+def test_positive_login_pins() -> None:
+ assert pinned_to_subscription(login_probe=lambda: True) is True
def test_key_only_install_is_not_pinned() -> None:
"""No subscription ever seen: the single-key fallback chain stays (AP-22)."""
- assert pinned_to_subscription(configured_is_subscription=False) is False
+ assert pinned_to_subscription() is False
+ assert pinned_to_subscription(login_probe=lambda: False) is False
def test_connected_subscription_pins_every_worker() -> None:
from jarvis.brain import background_policy
background_policy.note_connected("claude-cli")
- assert pinned_to_subscription(configured_is_subscription=False) is True
+ assert pinned_to_subscription(login_probe=lambda: False) is True
def test_unreadable_signal_fails_closed(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -82,7 +89,33 @@ def test_unreadable_signal_fails_closed(monkeypatch: pytest.MonkeyPatch) -> None
raise OSError("marker unreadable")
monkeypatch.setattr("jarvis.brain.background_policy.subscription_mode", _boom)
- assert pinned_to_subscription(configured_is_subscription=False) is True
+ assert pinned_to_subscription(login_probe=lambda: False) is True
+
+
+def test_a_failing_login_probe_is_not_a_login() -> None:
+ def _boom() -> bool:
+ raise OSError("probe crashed")
+
+ assert pinned_to_subscription(login_probe=_boom) is False
+
+
+def test_installed_but_logged_out_claude_cli_does_not_pin(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Finding 1: a key-only user with Claude Code installed but never logged
+ in is NOT a subscription install — never parked forever."""
+ monkeypatch.setattr(
+ "jarvis.missions.workers.claude_direct_worker._resolve_claude_binary",
+ lambda: "/usr/local/bin/claude",
+ )
+ monkeypatch.setattr(mi, "_claude_subscription_login_state", lambda: None)
+ monkeypatch.setattr(
+ "jarvis.missions.workers.codex_direct_worker._codex_oauth_available", lambda: False
+ )
+ monkeypatch.setattr(mi, "_positive_subscription_login", _REAL_LOGIN_PROBE)
+ assert mi.install_is_pinned() is False
+ monkeypatch.setattr(mi, "_claude_subscription_login_state", lambda: True)
+ assert mi.install_is_pinned() is True
# --- Worker factory: pinned resolution ----------------------------------------
@@ -134,12 +167,19 @@ def test_pinned_claude_without_cli_does_not_use_the_key(
@pytest.mark.parametrize(
- "reauth,capped,reason",
- [(True, False, "provider_auth"), (False, True, "provider_quota")],
+ "oauth,reauth,capped,reason",
+ [
+ (True, True, False, "provider_auth"),
+ (True, False, True, "provider_quota"),
+ (False, False, False, "provider_auth"), # no ChatGPT login: never on the key
+ ],
)
-def test_pinned_codex_parks_instead_of_switching_to_claude(
- monkeypatch: pytest.MonkeyPatch, reauth: bool, capped: bool, reason: str
+def test_pinned_codex_without_capacity_raises(
+ monkeypatch: pytest.MonkeyPatch, oauth: bool, reauth: bool, capped: bool, reason: str
) -> None:
+ monkeypatch.setattr(
+ "jarvis.missions.workers.codex_direct_worker._codex_oauth_available", lambda: oauth
+ )
monkeypatch.setattr("jarvis.codex_auth_state.codex_needs_reauth", lambda: reauth)
monkeypatch.setattr(
"jarvis.codex_quota_state.codex_in_quota_cooldown", lambda **_k: capped
@@ -153,6 +193,9 @@ def test_pinned_codex_parks_instead_of_switching_to_claude(
def test_pinned_codex_runs_codex_without_backend_fallback(
monkeypatch: pytest.MonkeyPatch,
) -> None:
+ monkeypatch.setattr(
+ "jarvis.missions.workers.codex_direct_worker._codex_oauth_available", lambda: True
+ )
monkeypatch.setattr("jarvis.codex_auth_state.codex_needs_reauth", lambda: False)
monkeypatch.setattr(
"jarvis.codex_quota_state.codex_in_quota_cooldown", lambda **_k: False
@@ -162,11 +205,75 @@ def test_pinned_codex_runs_codex_without_backend_fallback(
assert worker.backend_fallback is False
-def test_pinned_api_provider_without_key_does_not_cross_families(
+class _Subscriptions:
+ """Both subscription families' offline state, scripted."""
+
+ def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ self.claude_login: bool | None = True
+ self.claude_cooldown = False
+ self.codex_oauth = True
+ self.codex_cooldown = False
+ mp = monkeypatch
+ mp.setattr(
+ "jarvis.missions.workers.claude_direct_worker._resolve_claude_binary",
+ lambda: "/usr/local/bin/claude",
+ )
+ mp.setattr(mi, "_claude_subscription_login_state", lambda: self.claude_login)
+ mp.setattr(
+ "jarvis.claude_quota_state.claude_in_quota_cooldown",
+ lambda **_k: self.claude_cooldown,
+ )
+ mp.setattr(
+ "jarvis.missions.workers.codex_direct_worker._codex_oauth_available",
+ lambda: self.codex_oauth,
+ )
+ mp.setattr("jarvis.codex_auth_state.codex_needs_reauth", lambda: False)
+ mp.setattr(
+ "jarvis.codex_quota_state.codex_in_quota_cooldown",
+ lambda **_k: self.codex_cooldown,
+ )
+
+
+def test_spent_claude_moves_to_the_codex_subscription_for_free(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ subs = _Subscriptions(monkeypatch)
+ subs.claude_cooldown = True
+ worker = mi._subscription_worker("claude", None)
+ assert isinstance(worker, CodexDirectWorker)
+ assert worker.backend_fallback is False
+
+
+def test_spent_codex_moves_to_the_claude_subscription_for_free(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The old codex -> Claude Max path, restored (subscription to subscription)."""
+ subs = _Subscriptions(monkeypatch)
+ subs.codex_cooldown = True
+ worker = mi._subscription_worker("codex", None)
+ assert isinstance(worker, ClaudeDirectWorker)
+ assert worker.backend_fallback is False
+
+
+def test_no_subscription_with_capacity_raises_the_configured_reason(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ subs = _Subscriptions(monkeypatch)
+ subs.claude_cooldown = True
+ subs.codex_oauth = False
+ with pytest.raises(WorkerCapacityUnavailable) as exc:
+ mi._subscription_worker("claude", None)
+ assert (exc.value.reason, exc.value.provider) == ("provider_quota", "claude")
+
+
+def test_pinned_api_provider_without_key_does_not_cross_to_a_metered_family(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(mi, "_api_key_family_viable", lambda _p: False)
monkeypatch.setattr(mi, "_assemble_worker_mcp_servers", lambda **_k: ())
+ subs = _Subscriptions(monkeypatch)
+ subs.claude_login = None
+ subs.codex_oauth = False
def _forbidden(*_a: object, **_k: object) -> None:
raise AssertionError("a pinned mission must not cross provider families")
@@ -177,6 +284,16 @@ def test_pinned_api_provider_without_key_does_not_cross_families(
assert exc.value.provider == "openrouter"
+def test_pinned_api_provider_without_key_may_use_a_subscription(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(mi, "_api_key_family_viable", lambda _p: False)
+ monkeypatch.setattr(mi, "_assemble_worker_mcp_servers", lambda **_k: ())
+ _Subscriptions(monkeypatch)
+ worker = mi._resolve_api_agent_worker("openrouter", "task", pinned=True)
+ assert isinstance(worker, ClaudeDirectWorker)
+
+
def test_pinned_api_provider_with_key_runs_on_its_own_key(
monkeypatch: pytest.MonkeyPatch,
) -> None:
@@ -330,6 +447,25 @@ async def test_finished_steps_are_kept_and_counted(
assert [s["done"] for s in data["steps"]] == [True, False]
+async def test_key_only_install_never_parks_on_a_spent_quota(
+ manager: MissionManager, tmp_path: Path
+) -> None:
+ """Finding 4: the final-iteration provider_quota park is a subscription
+ install's rule; a key-only install fails (or crosses) as before."""
+ from tests.fakes.fake_mission_runtime import make_policy
+
+ worker = FakeMissionWorker(quota=True)
+ plan = MissionPlan(steps=[Step(slug="task", prompt="do it")], n_workers=1)
+ policy, _pinned, _paid = make_policy(tmp_path, pinned=False)
+ k = make_kontrollierer(
+ manager, tmp_path, plan, lambda _s: worker, ApprovingCritic(), capacity_policy=policy
+ )
+ mid = await manager.dispatch(prompt="write the report")
+
+ assert await k.run_mission(mid) == MissionState.FAILED
+ assert not any(isinstance(p, MissionWaitingCapacity) for p in await _events(manager, mid))
+
+
async def test_parked_mission_can_be_cancelled(
manager: MissionManager, tmp_path: Path
) -> None:
@@ -344,6 +480,11 @@ async def test_parked_mission_can_be_cancelled(
await manager.transition_state(mid, MissionState.CANCELLED, reason="ui_cancel")
view = await manager.mission(mid)
assert view is not None and view.state == MissionState.CANCELLED
+ # The cancel route then tells the runner; the checkpoint goes with it.
+ mission_dir = tmp_path / "missions" / f"mission_{mid[:13]}"
+ assert (mission_dir / CHECKPOINT_NAME).is_file()
+ k.cancel_running_mission(mid)
+ assert not (mission_dir / CHECKPOINT_NAME).exists()
# --- Restart and cleanup leave a parked mission alone -------------------------
@@ -412,3 +553,21 @@ def test_readback_keeps_the_options_under_the_length_cap() -> None:
)
assert len(text) <= MAX_VOICE_CHARS
assert text.endswith("Artefakte.") # i18n-allow: German TTS phrase under test
+
+
[email protected]("lang", ["de", "en"])
[email protected]("reason", ["paid_daily_cap_reached", "paid_consent_revoked"])
+def test_readback_names_the_new_paid_reasons(lang: str, reason: str) -> None:
+ from jarvis.missions.voice.readback import CAPACITY_WAIT_PHRASES
+
+ text = render_capacity_wait(
+ reason=reason,
+ provider="claude-api",
+ steps_done=0,
+ steps_total=1,
+ files_saved=0,
+ checkpoint_saved=True,
+ language=lang, # type: ignore[arg-type]
+ )
+ head = CAPACITY_WAIT_PHRASES[lang][reason].format(provider="Claude")
+ assert text.startswith(head)
diff --git a/tests/missions/test_capacity_wait_parity.py b/tests/missions/test_capacity_wait_parity.py
index 92e32f1bb2..59f48cc3bb 100644
--- a/tests/missions/test_capacity_wait_parity.py
+++ b/tests/missions/test_capacity_wait_parity.py
@@ -20,7 +20,7 @@ from jarvis.missions.voice.readback import CAPACITY_WAIT_PHRASES
_FRONTEND = Path(__file__).resolve().parents[2] / "jarvis" / "ui" / "web" / "frontend" / "src"
_MISSIONS_TS = (_FRONTEND / "types" / "missions.ts").read_text(encoding="utf-8")
-_LOCALES = ("de", "en", "es")
+_LOCALES = ("de", "en", "es", "zh")
def _ts_union(name: str) -> set[str]:
@@ -45,6 +45,26 @@ def test_reason_vocabulary_python_ts_parity() -> None:
assert _ts_union("CapacityWaitReason") == set(CAPACITY_WAIT_REASONS)
+def test_paid_fallback_reasons_cross_every_layer() -> None:
+ """The 2026-10-07 reasons exist in Python, TypeScript and the voice
+ tables — a reason on one side only is the BUG-008 drift class."""
+ new_reasons = {"paid_daily_cap_reached", "paid_consent_revoked"}
+ assert new_reasons <= set(CAPACITY_WAIT_REASONS)
+ assert new_reasons <= _ts_union("CapacityWaitReason")
+ for lang in ("de", "en"):
+ assert new_reasons <= set(CAPACITY_WAIT_PHRASES[lang])
+
+
+def test_paid_usage_says_whether_it_was_automatic() -> None:
+ from jarvis.missions.events import MissionPaidUsage
+
+ assert "automatic" in MissionPaidUsage.model_fields
+ m = re.search(
+ r"export interface MissionPaidUsage extends BasePayload \{([^}]+)\}", _MISSIONS_TS
+ )
+ assert m and re.search(r"^\s*automatic:\s*boolean", m.group(1), re.MULTILINE)
+
+
def test_event_type_listed_in_ts() -> None:
assert "MissionWaitingCapacity" in _ts_union("EventType")