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.

feat(society): agents run on subscriptions - CLI seats, pinned accounts, model switching

rubenluetke10-beep516e7d1c3398
diff --git a/docs/agent-society/agent-definition.md b/docs/agent-society/agent-definition.md
index 6874b37b0b..5e1a64ab06 100644
--- a/docs/agent-society/agent-definition.md
+++ b/docs/agent-society/agent-definition.md
@@ -45,12 +45,35 @@ card; nothing hidden drives behavior.
(`lead | orchestrator | specialist`), `parent_agent_id`, `state` (`active | paused | archived`).
- `avatar` (parts + palette now; GLB/texture uri in M3), `checkpoint` (world place).
-**Brain**
-- `provider`, `model`, `effort` — from `agent_chat.catalog.rows_for("society")`: API families,
- keyless local rows (`ollama`, `local-openai`). CLI seats (Claude Code, Codex, …) are NOT
- society brains: a society agent runs on Jarvis' own harness (`brain_runner=True`,
- `cli_seats=False`, like the `jarvis` surface). CLIs are *tools* of the agent (§3.1), not its mind.
-- `fallback_policy` = the global capability-gated chain (AP-21/22); no per-agent fallback pins.
+**Brain (revised 2026-09-02 — subscriptions)**
+- `provider`, `model`, `effort` — from `agent_chat.catalog.rows_for("society")`: every API row
+ (key-based: `openai`, `gemini`, `grok`, `openrouter`, `nvidia`, `vertex`), the keyless local
+ rows (`ollama`, `local-openai`) AND the **subscription seats** — the vendor CLIs the app
+ already drives on a plan: Claude Code (Claude Max), Codex (ChatGPT), Grok Build (SuperGrok),
+ Antigravity (Google), OpenCode, Kimi, GLM, Cursor. `resolve_runner(provider, "society")`
+ decides per box: a seat's CLI when installed (`claude-api` is dual — Claude Code when
+ present, else the Anthropic API), Jarvis' brain runner for API rows.
+- **On a seat the CLI runs AS the agent**: its briefing (§3.3) is the identity the CLI is handed
+ (`jarvis_harness.identity_prompt(prompt_override=…)`, Jarvis' own layers stay out), Jarvis'
+ tools reach it over MCP (`mcp__jarvis__*`), and it brings its own hands (Claude Code's shell,
+ editor, browser). The society-only tools (`society_message_agent`, `society_wiki_note`,
+ `society_shell`, `society_browser`, `society_run_skill`) are available on the brain runner
+ today and are NOT yet offered over MCP to a seated CLI (tracked gap).
+- `account_id` — which stored subscription of that CLI the agent uses (`jarvis.agent_accounts`;
+ empty = the platform's active account). Pinned per turn through
+ `runner_cli.ACCOUNT_OVERRIDE`, so two agents can sit on two Claude Max logins.
+- **Switching later**: `POST /api/society/agents/{id}/model` (or PATCH) changes provider /
+ model / effort / account; the canonical chat is re-seated at once, transcript kept
+ (`chat_binding.ensure_session`). `GET /api/society/providers` lists every row with the
+ runner it resolves to on this box (`subscription: true|false`) and the accounts stored for
+ its CLI; models, efforts and permission ladders come from
+ `GET /api/agent-chat/catalog?surface=society`.
+- Reference check (2026-09-02): Hermes Agent switches with `hermes model` / `/model provider:name`
+ and offers Codex/ChatGPT device-code OAuth, xAI SuperGrok OAuth and Claude OAuth (Max only);
+ OpenClaw selects `agents.entries.*.model` as `provider/model`, reuses `claude -p` for the
+ Claude plan, ChatGPT OAuth for OpenAI, and keeps an ordered fallback chain. We match the
+ shape — per-agent provider/model/account, switch any time — through the seats the app
+ already runs, and keep fallbacks global (AP-21/22).
**Capabilities** (§3)
- `grant_mode`: `all` (default — everything the global tiers allow) or `allowlist`.
diff --git a/jarvis/agent_chat/jarvis_harness.py b/jarvis/agent_chat/jarvis_harness.py
index 6d23827012..750667519e 100644
--- a/jarvis/agent_chat/jarvis_harness.py
+++ b/jarvis/agent_chat/jarvis_harness.py
@@ -227,6 +227,7 @@ async def identity_prompt(
user_text: str,
history: list[dict[str, Any]],
resume: str | None,
+ prompt_override: str | None = None,
) -> str:
"""Jarvis' real prompt layers + the chat's transcript + the addendum.
@@ -242,6 +243,16 @@ async def identity_prompt(
tell the model the same story twice.
"""
parts: list[str] = []
+ if prompt_override:
+ # A society agent's seat: ITS briefing is the identity. Jarvis' own
+ # layers stay out so the CLI does not answer as Jarvis.
+ parts.append(prompt_override.strip())
+ if resume is None and history:
+ transcript = render_transcript(history)
+ if transcript:
+ parts.append("## This conversation so far\n\n" + transcript)
+ parts.append(SYSTEM_PREAMBLE)
+ return "\n\n".join(parts)
brain = _brain()
render = getattr(brain, "render_surface_prompt", None) if brain is not None else None
if callable(render):
@@ -345,9 +356,12 @@ async def build_identity(
history: list[dict[str, Any]],
resume: str | None,
with_file: bool,
+ prompt_override: str | None = None,
) -> Identity:
"""The identity for one CLI turn; ``with_file`` for a CLI that takes a file."""
- text = await identity_prompt(user_text=user_text, history=history, resume=resume)
+ text = await identity_prompt(
+ user_text=user_text, history=history, resume=resume, prompt_override=prompt_override
+ )
path = write_identity_file(text, turn_id=turn_id) if with_file else None
return Identity(session_id=session_id, text=text, compact=compact_identity(text), path=path)
diff --git a/jarvis/agent_chat/runner_cli.py b/jarvis/agent_chat/runner_cli.py
index 3d21b133c6..59b0784014 100644
--- a/jarvis/agent_chat/runner_cli.py
+++ b/jarvis/agent_chat/runner_cli.py
@@ -59,6 +59,7 @@ import shutil
import time
import uuid
from collections.abc import Callable
+from contextvars import ContextVar
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Final
@@ -208,12 +209,23 @@ def cursor_argv_prefix() -> list[str]:
return [binary]
+#: The subscription seat the CURRENT turn runs on, when its session names one
+#: (an agent-society member pinned to a specific account). Empty = the
+#: platform's active account, exactly as before the society existed.
+ACCOUNT_OVERRIDE: ContextVar[str] = ContextVar("agent_chat.account_override", default="")
+
+
def _account_env(platform: str) -> dict[str, str]:
- """The child environment for the active subscription seat of ``platform``."""
+ """The child environment for the subscription seat of ``platform`` — the
+ turn's pinned account when its session names one, else the active one."""
try:
from jarvis import agent_accounts
- account = agent_accounts.active_account(platform) # type: ignore[arg-type]
+ pinned = agent_accounts.resolve(ACCOUNT_OVERRIDE.get() or None)
+ if pinned is not None and pinned.platform == platform:
+ account = pinned
+ else:
+ account = agent_accounts.active_account(platform) # type: ignore[arg-type]
env = agent_accounts.spawn_env(platform, account.id, base=os.environ) # type: ignore[arg-type]
except Exception: # noqa: BLE001 — no account layer for this platform → plain env
env = dict(os.environ)
@@ -2231,6 +2243,26 @@ def _resume_was_lost(error: str | None) -> bool:
return any(m in low for m in _RESUME_LOST_MARKERS)
+async def _surface_identity(session: Any) -> str | None:
+ """A surface whose identity is per session (an agent-society member's
+ briefing) hands that text over; ``None`` keeps Jarvis' own layers."""
+ from jarvis.agent_chat.surface_kits import kit_for
+
+ kit = kit_for(getattr(session, "surface", "") or "")
+ if kit.session_system_extra is None:
+ return None
+ try:
+ from jarvis.agent_chat.runner_brain import brain_manager
+
+ brain = brain_manager()
+ cfg = getattr(brain, "_config", None)
+ text = await kit.session_system_extra(cfg, brain, session)
+ except Exception: # noqa: BLE001 — the CLI then runs with Jarvis' layers, never fails
+ log.warning("agent chat: surface identity unavailable this turn", exc_info=True)
+ return None
+ return text or None
+
+
async def run_cli_turn(
handle: TurnHandle,
user_text: str,
@@ -2257,6 +2289,10 @@ async def run_cli_turn(
resume = session.vendor_session
ident: jarvis_harness.Identity | None = None
ref = approval_ref(session.session_id)
+ # A society agent's seat: its own briefing is the identity (not Jarvis'
+ # layers), and its pinned subscription account is the seat's login.
+ prompt_override = await _surface_identity(session)
+ account_token = ACCOUNT_OVERRIDE.set(getattr(session, "account_id", "") or "")
if identity:
ident = await jarvis_harness.build_identity(
session_id=session.session_id,
@@ -2265,6 +2301,7 @@ async def run_cli_turn(
history=handle.history,
resume=resume,
with_file=(runner in _CLAUDE_CODE_RUNNERS),
+ prompt_override=prompt_override,
)
if bridge is not None:
from jarvis.agent_chat.approval_bridge import ChatGrant
@@ -2304,11 +2341,13 @@ async def run_cli_turn(
history=handle.history,
resume=None,
with_file=(runner in _CLAUDE_CODE_RUNNERS),
+ prompt_override=prompt_override,
)
outcome = await _run_cli_once(
handle, user_text, runner, None, identity=ident, bridge=bridge
)
finally:
+ ACCOUNT_OVERRIDE.reset(account_token)
if bridge is not None and identity:
bridge.disarm(ref)
if ident is not None:
diff --git a/jarvis/agent_chat/store.py b/jarvis/agent_chat/store.py
index b9d3977a21..362dea9f12 100644
--- a/jarvis/agent_chat/store.py
+++ b/jarvis/agent_chat/store.py
@@ -44,7 +44,8 @@ CREATE TABLE IF NOT EXISTS agent_chat_sessions (
updated_ms INTEGER NOT NULL,
message_count INTEGER NOT NULL DEFAULT 0,
preview TEXT NOT NULL DEFAULT '',
- surface TEXT NOT NULL DEFAULT 'agent'
+ surface TEXT NOT NULL DEFAULT 'agent',
+ account_id TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS agent_chat_events (
session_id TEXT NOT NULL,
@@ -96,6 +97,9 @@ class AgentChatSession:
message_count: int
preview: str
surface: str = DEFAULT_SURFACE
+ #: The subscription seat (``jarvis.agent_accounts`` id) a CLI turn runs on;
+ #: empty = the platform's active account.
+ account_id: str = ""
def to_dict(self) -> dict[str, Any]:
return asdict(self)
@@ -141,6 +145,12 @@ class AgentChatStore:
"ALTER TABLE agent_chat_sessions ADD COLUMN surface TEXT NOT NULL "
f"DEFAULT '{DEFAULT_SURFACE}'"
)
+ if "account_id" not in have:
+ # Which subscription seat a CLI turn runs on; empty = the platform's
+ # active account (the pre-column behaviour).
+ self._conn.execute(
+ "ALTER TABLE agent_chat_sessions ADD COLUMN account_id TEXT NOT NULL DEFAULT ''"
+ )
def close(self) -> None:
with self._lock:
@@ -159,6 +169,7 @@ class AgentChatStore:
title: str = "",
session_id: str | None = None,
surface: str = DEFAULT_SURFACE,
+ account_id: str = "",
) -> AgentChatSession:
if surface not in SURFACES:
raise ValueError(f"surface must be one of {SURFACES}, not {surface!r}")
@@ -171,8 +182,9 @@ class AgentChatStore:
self._conn.execute(
"INSERT INTO agent_chat_sessions (session_id, title, provider, model, effort, "
"cwd, permission_mode, vendor_session, created_ms, updated_ms, message_count, "
- "preview, surface) VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, 0, '', ?)",
- (sid, title, provider, model, effort, cwd, mode, now, now, surface),
+ "preview, surface, account_id) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, 0, '', ?, ?)",
+ (sid, title, provider, model, effort, cwd, mode, now, now, surface, account_id),
)
self._conn.commit()
session = self.get_session(sid)
@@ -217,6 +229,7 @@ class AgentChatStore:
"cwd",
"permission_mode",
"vendor_session",
+ "account_id",
}
updates = {k: v for k, v in fields.items() if k in allowed and v is not None}
if not updates:
@@ -378,4 +391,5 @@ class AgentChatStore:
message_count=int(row["message_count"]),
preview=row["preview"],
surface=str(row["surface"] or DEFAULT_SURFACE),
+ account_id=str(row["account_id"] or "") if "account_id" in row.keys() else "",
)
diff --git a/jarvis/agent_chat/surface_kits.py b/jarvis/agent_chat/surface_kits.py
index ee30bf3767..63a928190f 100644
--- a/jarvis/agent_chat/surface_kits.py
+++ b/jarvis/agent_chat/surface_kits.py
@@ -212,7 +212,13 @@ _KITS: Final[dict[str, SurfaceKit]] = {
"society": SurfaceKit(
surface="society",
brain_runner=True,
- cli_seats=False,
+ # Subscriptions (maintainer, 2026-09-02): an agent may sit on a vendor
+ # CLI seat — Claude Code (Claude Max), Codex (ChatGPT), Grok Build
+ # (SuperGrok), Antigravity (Google) — or on any API row. On a seat the
+ # CLI runs AS the agent (its briefing is the identity, runner_cli),
+ # with Jarvis' tools over MCP and its own hands; on an API row Jarvis'
+ # brain runner drives the agent's own tool set.
+ cli_seats=True,
ladder=_JARVIS_LADDER,
uses_stance=True,
tool_origin="society",
diff --git a/jarvis/society/chat_binding.py b/jarvis/society/chat_binding.py
index ff39fb4588..3de1cfcde6 100644
--- a/jarvis/society/chat_binding.py
+++ b/jarvis/society/chat_binding.py
@@ -92,10 +92,19 @@ def ensure_session(svc: Any, cfg: Any, agent: AgentRecord) -> Any:
title=agent.name,
session_id=session_id,
surface=SURFACE,
+ account_id=agent.account_id,
)
if existing.provider != provider or (model and existing.model != model):
svc.store.reseat_session(session_id, provider=provider, model=model or existing.model)
existing = svc.store.get_session(session_id)
+ updates: dict[str, str] = {}
+ if getattr(existing, "account_id", "") != agent.account_id:
+ updates["account_id"] = agent.account_id
+ if effort and existing.effort != effort:
+ updates["effort"] = effort
+ if updates:
+ svc.store.update_session(session_id, **updates)
+ existing = svc.store.get_session(session_id)
return existing
diff --git a/jarvis/society/roster.py b/jarvis/society/roster.py
index 2463cabeb1..a18ffd0ee6 100644
--- a/jarvis/society/roster.py
+++ b/jarvis/society/roster.py
@@ -95,6 +95,9 @@ class AgentRecord:
provider: str
model: str
effort: str
+ #: The subscription seat (``jarvis.agent_accounts`` id) a CLI-seated agent
+ #: runs on; empty = the platform's active account.
+ account_id: str
grant_mode: GrantMode
grants: list[str]
focus: list[str]
@@ -135,6 +138,7 @@ class AgentRecord:
"provider": self.provider,
"model": self.model,
"effort": self.effort,
+ "account_id": self.account_id,
"grant_mode": str(self.grant_mode),
"grants": list(self.grants),
"focus": list(self.focus),
@@ -178,6 +182,7 @@ class AgentRecord:
provider=str(row.get("provider") or ""),
model=str(row.get("model") or ""),
effort=str(row.get("effort") or ""),
+ account_id=str(row.get("account_id") or ""),
grant_mode=GrantMode(str(row.get("grant_mode") or "all")),
grants=list(_loads(row.get("grants_json"), [])),
focus=list(_loads(row.get("focus_json"), [])),
@@ -214,6 +219,7 @@ _EDITABLE: Final[frozenset[str]] = frozenset(
"provider",
"model",
"effort",
+ "account_id",
"grant_mode",
"grants",
"focus",
@@ -332,7 +338,14 @@ def _coerce(field_name: str, value: Any) -> Any:
if runs < 1 or runs > 10:
raise RosterError(FailureReason.BLOCKED_BY_POLICY, "max_concurrent_runs must be 1-10")
return runs
- if field_name in ("provider", "model", "effort", "workspace_dir", "wiki_namespace"):
+ if field_name in (
+ "provider",
+ "model",
+ "effort",
+ "account_id",
+ "workspace_dir",
+ "wiki_namespace",
+ ):
return str(value or "")
if field_name == "parent_agent_id":
return str(value) if value else None
diff --git a/jarvis/society/society_schema.sql b/jarvis/society/society_schema.sql
index c1e364623a..b7c51c9de4 100644
--- a/jarvis/society/society_schema.sql
+++ b/jarvis/society/society_schema.sql
@@ -22,6 +22,7 @@ CREATE TABLE IF NOT EXISTS society_agents (
provider TEXT NOT NULL DEFAULT '',
model TEXT NOT NULL DEFAULT '',
effort TEXT NOT NULL DEFAULT '',
+ account_id TEXT NOT NULL DEFAULT '', -- subscription seat (agent_accounts id)
grant_mode TEXT NOT NULL DEFAULT 'all'
CHECK (grant_mode IN ('all', 'allowlist')),
grants_json TEXT NOT NULL DEFAULT '[]',
diff --git a/jarvis/society/store.py b/jarvis/society/store.py
index bfa499ed39..0c137c0c5a 100644
--- a/jarvis/society/store.py
+++ b/jarvis/society/store.py
@@ -96,6 +96,11 @@ class SocietyStore:
existing = {str(r[1]) for r in rows}
if not existing: # pragma: no cover — schema always creates the table
raise RuntimeError("society_agents table missing after schema load")
+ if "account_id" not in existing:
+ await self.conn.execute(
+ "ALTER TABLE society_agents ADD COLUMN account_id TEXT NOT NULL DEFAULT ''"
+ )
+ log.info("society store: migration applied — added account_id")
if "browser_mode" not in existing:
await self.conn.execute(
"ALTER TABLE society_agents ADD COLUMN browser_mode TEXT NOT NULL "
diff --git a/jarvis/ui/web/frontend/src/lib/societyApi.ts b/jarvis/ui/web/frontend/src/lib/societyApi.ts
index 520a6f35be..3fa1d665b5 100644
--- a/jarvis/ui/web/frontend/src/lib/societyApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/societyApi.ts
@@ -89,6 +89,8 @@ export interface SocietyAgentRow {
provider: string;
model: string;
effort: string;
+ /** Subscription seat (agent-accounts id) for a CLI-seated agent; "" = active account. */
+ account_id: string;
grant_mode: GrantMode;
grants: string[];
focus: string[];
diff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.py
index 2168fbceb5..6395250a90 100644
--- a/jarvis/ui/web/society_routes.py
+++ b/jarvis/ui/web/society_routes.py
@@ -70,6 +70,7 @@ class CreateAgentBody(BaseModel):
provider: str = ""
model: str = ""
effort: str = ""
+ account_id: str = ""
grant_mode: str | None = None
grants: list[str] | None = None
focus: list[str] | None = None
@@ -93,6 +94,7 @@ class PatchAgentBody(BaseModel):
provider: str | None = None
model: str | None = None
effort: str | None = None
+ account_id: str | None = None
grant_mode: str | None = None
grants: list[str] | None = None
focus: list[str] | None = None
@@ -380,6 +382,102 @@ async def apply_seed_proposals(body: ApplySeedsBody, request: Request) -> dict[s
return {"agents": created, "total": len(created)}
+# --------------------------------------------------------------- providers
+
+
+class ModelBody(BaseModel):
+ provider: str = Field(min_length=1)
+ model: str = ""
+ effort: str = ""
+ account_id: str = ""
+
+
[email protected]("/providers")
+async def list_society_providers(request: Request) -> dict[str, Any]:
+ """Every provider an agent may run on, with the runner that answers on
+ this box (a vendor CLI = a subscription seat; brain = an API key) and the
+ subscription accounts stored for that CLI. Models, efforts and ladders
+ come from GET /api/agent-chat/catalog?surface=society."""
+ from jarvis.agent_chat.catalog import rows_for
+ from jarvis.agent_chat.service import resolve_runner
+
+ await _runtime(request)
+ rows = []
+ for row in rows_for("society"):
+ runner = resolve_runner(row.id, surface="society")
+ accounts: list[dict[str, Any]] = []
+ if row.agent:
+ accounts = _account_snapshots(row.agent)
+ rows.append(
+ {
+ "id": row.id,
+ "label": row.label,
+ "family": row.family,
+ "runner": runner,
+ "subscription": runner not in ("brain", "api", "unknown"),
+ "keyless": bool(getattr(row, "keyless", False)),
+ "platform": row.agent or None,
+ "accounts": accounts,
+ }
+ )
+ return {"providers": rows, "catalog": "/api/agent-chat/catalog?surface=society"}
+
+
+def _account_snapshots(platform: str) -> list[dict[str, Any]]:
+ try:
+ from jarvis import agent_accounts
+
+ if platform not in agent_accounts.platforms():
+ return []
+ return [s.to_dict() for s in agent_accounts.snapshots(platform)] # type: ignore[arg-type]
+ except Exception: # noqa: BLE001 — no account layer: the picker shows none
+ log.debug("society: account snapshots unavailable for %s", platform, exc_info=True)
+ return []
+
+
[email protected]("/agents/{agent_id}/model")
+async def switch_agent_model(agent_id: str, body: ModelBody, request: Request) -> dict[str, Any]:
+ """Move the agent onto another provider / model / effort / subscription seat.
+ Its canonical chat is re-seated at once (transcript kept)."""
+ from jarvis.agent_chat.catalog import offers
+ from jarvis.agent_chat.service import resolve_runner
+
+ rt = await _runtime(request)
+ agent = await rt.roster.resolve(agent_id)
+ if agent is None:
+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})
+ if not offers("society", body.provider):
+ raise HTTPException(
+ 422,
+ {"reason": str(FailureReason.BLOCKED_BY_POLICY), "detail": "provider not offered"},
+ )
+ fields = {
+ "provider": body.provider.strip().lower(),
+ "model": body.model.strip(),
+ "effort": body.effort.strip(),
+ "account_id": body.account_id.strip(),
+ }
+ try:
+ updated = await rt.roster.update(agent.agent_id, fields)
+ except RosterError as exc:
+ raise _typed_error(exc) from exc
+ reseated = None
+ svc = rt._get_chat() # noqa: SLF001 — the route is the runtime's operator
+ if svc is not None:
+ from jarvis.society.chat_binding import ensure_session
+
+ try:
+ session = ensure_session(svc, rt._get_cfg(), updated) # noqa: SLF001
+ reseated = session.session_id
+ except PermissionError as exc:
+ log.info("society: %s re-seat deferred: %s", agent.agent_id, exc)
+ return {
+ "agent": updated.to_dict(),
+ "runner": resolve_runner(updated.provider, surface="society"),
+ "reseated": reseated,
+ }
+
+
# ------------------------------------------------------------------ skills
diff --git a/tests/unit/society/test_subscriptions.py b/tests/unit/society/test_subscriptions.py
new file mode 100644
index 0000000000..8e6eef493e
--- /dev/null
+++ b/tests/unit/society/test_subscriptions.py
@@ -0,0 +1,189 @@
+"""Agents on subscriptions: CLI seats, per-agent accounts, model switching."""
+
+from __future__ import annotations
+
+import sqlite3
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.agent_chat import runner_cli
+from jarvis.agent_chat.catalog import offers, rows_for
+from jarvis.agent_chat.service import resolve_runner
+from jarvis.agent_chat.store import AgentChatStore
+from jarvis.agent_chat.surface_kits import kit_for
+from jarvis.society.chat_binding import ensure_session
+from jarvis.society.runtime import SocietyRuntime
+
+
+def test_society_surface_seats_clis_and_apis(monkeypatch):
+ kit = kit_for("society")
+ assert kit.cli_seats and kit.brain_runner
+ ids = {row.id for row in rows_for("society")}
+ assert {"openai", "gemini", "grok", "ollama"} <= ids
+ assert offers("society", "openai-codex") or "openai-codex" not in ids
+ # The dual Claude row: the subscription CLI when installed, else the API.
+ monkeypatch.setattr("jarvis.agent_chat.service._claude_cli_installed", lambda: True)
+ assert resolve_runner("claude-api", surface="society") == "claude-cli"
+ monkeypatch.setattr("jarvis.agent_chat.service._claude_cli_installed", lambda: False)
+ assert resolve_runner("claude-api", surface="society") == "brain"
+ assert resolve_runner("openai", surface="society") == "brain"
+ if "openai-codex" in ids:
+ assert resolve_runner("openai-codex", surface="society") == "codex-cli"
+
+
+def test_chat_store_carries_the_account(tmp_path: Path):
+ store = AgentChatStore(tmp_path / "chat.db")
+ s = store.create_session(
+ provider="claude-api", model="", effort="", cwd="", surface="society", account_id="acc-1"
+ )
+ assert s.account_id == "acc-1"
+ store.update_session(s.session_id, account_id="acc-2")
+ assert store.get_session(s.session_id).account_id == "acc-2"
+ store.close()
+ # An older database without the column migrates on open.
+ old = tmp_path / "old.db"
+ conn = sqlite3.connect(old)
+ conn.executescript(
+ "CREATE TABLE agent_chat_sessions (session_id TEXT PRIMARY KEY, title TEXT NOT NULL "
+ "DEFAULT '', provider TEXT NOT NULL DEFAULT '', model TEXT NOT NULL DEFAULT '', effort "
+ "TEXT NOT NULL DEFAULT '', cwd TEXT NOT NULL DEFAULT '', permission_mode TEXT NOT NULL "
+ "DEFAULT 'ask', vendor_session TEXT, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT "
+ "NULL, message_count INTEGER NOT NULL DEFAULT 0, preview TEXT NOT NULL DEFAULT '', "
+ "surface TEXT NOT NULL DEFAULT 'agent');"
+ "INSERT INTO agent_chat_sessions (session_id, provider, created_ms, updated_ms) "
+ "VALUES ('x', 'openai', 1, 1);"
+ )
+ conn.commit()
+ conn.close()
+ migrated = AgentChatStore(old)
+ assert migrated.get_session("x").account_id == ""
+ migrated.close()
+
+
+def test_account_env_prefers_the_pinned_seat(monkeypatch, tmp_path: Path):
+ calls: list[tuple[str, str]] = []
+
+ class FakeAccounts:
+ @staticmethod
+ def resolve(account_id):
+ if account_id == "claude-second":
+ return SimpleNamespace(id="claude-second", platform="claude")
+ if account_id == "codex-x":
+ return SimpleNamespace(id="codex-x", platform="codex")
+ return None
+
+ @staticmethod
+ def active_account(platform):
+ return SimpleNamespace(id=f"{platform}-active", platform=platform)
+
+ @staticmethod
+ def spawn_env(platform, account_id, base=None):
+ calls.append((platform, account_id))
+ return {"SEAT": account_id}
+
+ import jarvis
+
+ monkeypatch.setattr(jarvis, "agent_accounts", FakeAccounts, raising=False)
+ monkeypatch.setitem(__import__("sys").modules, "jarvis.agent_accounts", FakeAccounts)
+ token = runner_cli.ACCOUNT_OVERRIDE.set("claude-second")
+ try:
+ assert runner_cli._account_env("claude")["SEAT"] == "claude-second" # noqa: SLF001
+ # A pin for another platform never leaks: codex still uses its active seat.
+ assert runner_cli._account_env("codex")["SEAT"] == "codex-active" # noqa: SLF001
+ finally:
+ runner_cli.ACCOUNT_OVERRIDE.reset(token)
+ assert runner_cli._account_env("claude")["SEAT"] == "claude-active" # noqa: SLF001
+
+
+async def test_identity_override_replaces_jarvis_layers():
+ from jarvis.agent_chat.jarvis_harness import SYSTEM_PREAMBLE, identity_prompt
+
+ text = await identity_prompt(
+ user_text="hi",
+ history=[{"kind": "user_message", "payload": {"text": "earlier"}}],
+ resume=None,
+ prompt_override="## You are Scout — Research scout",
+ )
+ assert text.startswith("## You are Scout")
+ assert SYSTEM_PREAMBLE in text
+ assert "Jarvis" not in text.split(SYSTEM_PREAMBLE)[0] or "Scout" in text
+
+
+class FakeService:
+ def __init__(self, store: AgentChatStore) -> None:
+ self.store = store
+
+ def is_running(self, session_id: str) -> bool:
+ return False
+
+
+async def test_ensure_session_follows_account_and_effort(tmp_path: Path):
+ rt = SocietyRuntime(tmp_path, seed_starter_team=False)
+ await rt.ensure_started()
+ svc = FakeService(AgentChatStore(tmp_path / "chat.db"))
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))
+ try:
+ scout, _ = await rt.roster.create(
+ name="Scout", provider="openai", model="gpt-5", account_id="", effort="high"
+ )
+ first = ensure_session(svc, cfg, scout)
+ assert first.account_id == "" and first.effort == "high"
+ moved = await rt.roster.update(
+ "scout", {"provider": "claude-api", "model": "claude-opus-5", "account_id": "seat-2"}
+ )
+ again = ensure_session(svc, cfg, moved)
+ assert again.session_id == first.session_id
+ assert again.provider == "claude-api" and again.model == "claude-opus-5"
+ assert again.account_id == "seat-2"
+ finally:
+ await rt.close()
+
+
+def client(tmp_path: Path):
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ from jarvis.ui.web.society_routes import router
+
+ svc = FakeService(AgentChatStore(tmp_path / "chat.db"))
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))
+ runtime = SocietyRuntime(
+ tmp_path, seed_starter_team=False, chat_service=lambda: svc, cfg=lambda: cfg
+ )
+ app = FastAPI()
+ app.include_router(router)
+ app.state.society_factory = lambda: runtime
+ with TestClient(app) as c:
+ yield c, svc
+
+
+def test_providers_and_model_switch_over_rest(client, monkeypatch):
+ c, svc = client
+ providers = c.get("/api/society/providers").json()["providers"]
+ by_id = {p["id"]: p for p in providers}
+ assert "openai" in by_id and by_id["openai"]["subscription"] is False
+ assert by_id["ollama"]["keyless"] is True
+ if "openai-codex" in by_id:
+ assert by_id["openai-codex"]["subscription"] is True
+ assert by_id["openai-codex"]["platform"] == "codex"
+ assert isinstance(by_id["openai-codex"]["accounts"], list)
+
+ c.post("/api/society/agents", json={"name": "Scout", "provider": "openai", "model": "gpt-5"})
+ res = c.post(
+ "/api/society/agents/scout/model",
+ json={"provider": "gemini", "model": "gemini-3-pro", "effort": "medium", "account_id": ""},
+ )
+ assert res.status_code == 200, res.text
+ body = res.json()
+ assert body["agent"]["provider"] == "gemini" and body["agent"]["model"] == "gemini-3-pro"
+ assert body["runner"] == "brain"
+ assert body["reseated"] == "society:scout"
+ session = svc.store.get_session("society:scout")
+ assert session.provider == "gemini" and session.model == "gemini-3-pro"
+ bad = c.post("/api/society/agents/scout/model", json={"provider": "no-such-provider"})
+ assert bad.status_code == 422
+ listed = c.get("/api/society/agents/scout").json()["agent"]
+ assert listed["account_id"] == ""
diff --git a/tests/unit/society/test_surface.py b/tests/unit/society/test_surface.py
index 7e5d8a5929..d3be22068f 100644
--- a/tests/unit/society/test_surface.py
+++ b/tests/unit/society/test_surface.py
@@ -54,6 +54,7 @@ def test_agent_id_of():
def test_without_runtime_everything_is_empty():
+ runtime_mod.set_current_runtime(None) # another test's runtime may still be registered
assert runtime_mod.current_runtime() is None
session = SimpleNamespace(session_id="society:scout")
assert society_tools(None, None, session) == {}