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.

15.4 KB
Raw Blame
"""What a chat surface brings to a turn: the runner, the ladder, the hands.

A *surface* is one place a person types to Jarvis: the front page (``jarvis``)
and the Agentic IDE's chat mode (``agent``). They share the session store, the
WebSocket stream and the approval card; they differ in what answers and with
which tools. Before this module those differences were ``if surface == "jarvis"``
branches in four files. Now each surface is one :class:`SurfaceKit` here and
the four call sites do one lookup each — a new surface is a new kit, not four
new branches.

Import-light: the kit builders import their tool modules lazily so this file
costs nothing at boot (AP-26).
"""

from __future__ import annotations

import logging
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Final

from dodaios.core.protocols import ChatCompletion, Tool

log = logging.getLogger(__name__)

__all__ = [
    "SurfaceKit",
    "kit_for",
]

#: The ladder key of the Jarvis ladder (``permissions.JARVIS_LADDER``) —
#: spelled here so the kit table does not import the permissions module.
_JARVIS_LADDER: Final[str] = "jarvis"
_SOCIETY_LADDER: Final[str] = "society"

ToolsBuilder = Callable[[Any, Any], dict[str, Tool]]
ExtraBuilder = Callable[[Any, Any], Awaitable[str]]
#: Session-aware twins: ``(cfg, brain, session)``. A surface whose hands and
#: briefing depend on WHICH session is talking (one chat per society agent)
#: uses these; ``kit_payload`` prefers them over the session-blind builders.
SessionToolsBuilder = Callable[[Any, Any, Any], dict[str, Tool]]
SessionExtraBuilder = Callable[[Any, Any, Any], Awaitable[str]]
SessionFilterBuilder = Callable[[Any], Callable[[dict[str, Tool]], dict[str, Tool]] | None]
#: ``session -> tool names`` this session's caller works with, or ``None``
#: (see ``TurnOverride.tools_direct``).
SessionDirectTools = Callable[[Any], frozenset[str] | None]
#: ``(session, tool_name, args) -> handled``: what "Always allow" on the
#: approval card means on this surface. ``True`` = the surface remembered it
#: its own way (a society agent writes its own approval rule); ``False`` =
#: the service falls back to its default (the session flips to auto).
SessionAlwaysAllow = Callable[[Any, str, dict[str, Any]], Awaitable[bool]]
#: ``(session, user_text, assistant_name) -> system prompt`` of a plain chat.
PlainChatBuilder = Callable[[Any, str, str], Awaitable[str]]


@dataclass(frozen=True, slots=True)
class SurfaceKit:
    """One surface's turn recipe.

    ``brain_runner``
        Whether an API provider is driven by Jarvis' own brain (``brain``)
        instead of the coding agent's loop (``api``).
    ``cli_seats``
        Whether a vendor CLI may run a turn here. ``False`` means every seat
        on this surface is an API endpoint behind a key: the picker lists
        only providers with a brain plugin, and the CLI rows (Claude Code,
        Codex, Antigravity, Grok Build) are not offered at all.
    ``ladder``
        The permission ladder the composer shows, or ``None`` for the
        runner's own ladder.
    ``uses_stance``
        Whether the session's permission mode reaches the brain runner as a
        stance (it does on every brain-driven surface).
    ``tools`` / ``system_extra``
        Builders called per turn with ``(cfg, brain)``: the surface's own
        tools instead of the folder tools, and a per-turn system-prompt
        addendum (``TurnOverride.system_extra``). ``None`` = the folder
        tools / no addendum.
    ``tool_origin`` / ``credential_scope`` / ``max_turns``
        What the tool context and the override carry; ``max_turns=None``
        keeps the runner's default.
    ``workspace_dir``
        Where a new session starts when nobody picked a folder; ``None`` =
        the service's own fallback.
    """

    surface: str
    brain_runner: bool = False
    cli_seats: bool = True
    ladder: str | None = None
    uses_stance: bool = False
    tools: ToolsBuilder | None = None
    system_extra: ExtraBuilder | None = None
    tool_origin: str = "agent-chat"
    credential_scope: str = "agent"
    max_turns: int | None = None
    #: Applied to the merged tool set (the brain's own plus ``tools``): a
    #: surface that only ever needs its own hands keeps the request small
    #: and free of foreign schemas a provider may refuse. ``None`` = all.
    tool_filter: Callable[[dict[str, Tool]], dict[str, Tool]] | None = None
    #: The folder a new session of this surface starts in when the person
    #: picked none. ``None`` = the service's fallback (the home directory),
    #: which is what the IDE's chat wants: a coding agent is pointed at a
    #: project, and its composer shows the folder chip so it can be moved.
    workspace_dir: Callable[[], Path] | None = None
    #: Session-aware builders (see the type aliases above). ``None`` = use the
    #: session-blind ``tools`` / ``system_extra`` / ``tool_filter``.
    session_tools: SessionToolsBuilder | None = None
    session_system_extra: SessionExtraBuilder | None = None
    session_tool_filter: SessionFilterBuilder | None = None
    session_direct_tools: SessionDirectTools | None = None
    #: How the card's "Always allow" is remembered here (see the alias above).
    session_always_allow: SessionAlwaysAllow | None = None
    turn_completed: Callable[[Any, ChatCompletion], Awaitable[None]] | None = None
    history_start: Callable[[Any], int] | None = None
    #: End-of-turn cards for coding agents (``turn_prompts``): a ``jarvis-ask``
    #: block becomes a question card and a finished plan-mode turn a plan card,
    #: so every CLI can ask and have its plan approved, not only Claude Code.
    turn_prompts: bool = False
    #: A plain conversation: no tool on any seat. The builder writes the whole
    #: system prompt; an API seat gets it as its system prompt, a CLI seat at
    #: the head of every conversation it starts. The picker lists only the seats that can
    #: answer without tools (``catalog.rows_for``).
    plain_chat: PlainChatBuilder | None = None

    @property
    def plain(self) -> bool:
        return self.plain_chat is not None


def _chat_workspace() -> Path:
    """The Jarvis chat's own working folder — imported lazily (AP-26)."""
    from dodaios.core.paths import chat_workspace_dir

    return chat_workspace_dir()


def _local_models_tools(cfg: Any, _brain: Any) -> dict[str, Tool]:
    """The setup assistant's hands — the ``lm_*`` tools (lazy, AP-26)."""
    from dodaios.local_models.assistant_tools import build_tools
    from dodaios.local_models.health_monitor import server_root

    return build_tools(cfg, root=server_root(cfg))


async def _local_models_extra(cfg: Any, _brain: Any) -> str:
    """What the assistant can already see: machine, inventory, roles, catalogue.

    Read per turn rather than once per session, because the whole point of the
    assistant is that things change while it works — a model finishes pulling,
    the server comes up, a role gets filled.
    """
    from dodaios.local_models.assistant_prompt import build_system_extra
    from dodaios.local_models.health_monitor import server_root

    return await build_system_extra(cfg, root=server_root(cfg))


def _society_tools(cfg: Any, brain: Any, session: Any) -> dict[str, Tool]:
    """The agent's own hands - teammate messaging and its wiki namespace (lazy)."""
    from dodaios.society.surface import society_tools

    return society_tools(cfg, brain, session)


def _jarvis_tools(_cfg: Any, _brain: Any, session: Any) -> dict[str, Tool]:
    from dodaios.agent_chat.folder_tools import folder_tools
    from dodaios.society.browser.tool import lead_browser_tools

    stance = "plan" if getattr(session, "permission_mode", "") == "plan" else "ask"
    tools = folder_tools(Path(getattr(session, "cwd", "") or _chat_workspace()), stance=stance)
    tools.update(lead_browser_tools(session))
    return tools


async def _society_extra(cfg: Any, brain: Any, session: Any) -> str:
    """Who the agent is, what it reaches for, how the ecosystem works (lazy)."""
    from dodaios.society.surface import society_system_extra

    return await society_system_extra(cfg, brain, session)


def _society_filter(session: Any) -> Callable[[dict[str, Tool]], dict[str, Tool]] | None:
    """Grant / focus / deny over the merged tool set (lazy)."""
    from dodaios.society.surface import society_tool_filter

    return society_tool_filter(session)


def _society_direct(session: Any) -> frozenset[str] | None:
    """The tools the agent's role points at (lazy)."""
    from dodaios.society.surface import society_direct_tools

    return society_direct_tools(session)


async def _society_always_allow(session: Any, tool_name: str, args: dict[str, Any]) -> bool:
    """ "Always allow" writes the agent's own approval rule (lazy)."""
    from dodaios.society.surface import remember_always_allow

    return await remember_always_allow(session, tool_name, args)


async def _society_completed(session: Any, completion: ChatCompletion) -> None:
    from dodaios.self_build.app import chat_turn_completed as self_build_observe
    from dodaios.society.runtime import current_runtime

    runtime = current_runtime()
    if runtime is not None:
        await runtime.turn_completed(session, completion)
    await self_build_observe(session, completion, surface="society")


async def _jarvis_completed(session: Any, completion: ChatCompletion) -> None:
    """Feed Jarvis' own learning loop and the self-building loop (lazy, no-ops when off)."""
    from dodaios.memory.learning.loop import current_loop
    from dodaios.self_build.app import chat_turn_completed as self_build_observe

    loop = current_loop()
    if loop is not None:
        await loop.chat_turn_completed(session, completion)
    await self_build_observe(session, completion, surface="jarvis")


async def _person_chat_completed(session: Any, completion: ChatCompletion) -> None:
    """The IDE's agent chat and side chat: the person's typed turns feed the
    self-building loop (lazy, a no-op when off)."""
    from dodaios.self_build.app import chat_turn_completed as self_build_observe

    await self_build_observe(session, completion, surface=str(getattr(session, "surface", "")))


def _society_history_start(session: Any) -> int:
    from dodaios.agent_chat.service import session_runner
    from dodaios.society.runtime import current_runtime

    if session_runner(session) != "brain":
        return 0  # Subscription seats retain their vendor's history/compaction contract.
    runtime = current_runtime()
    return runtime.conversations.checkpoint(session.session_id)[0] if runtime is not None else 0


async def _side_chat(session: Any, user_text: str, assistant_name: str) -> str:
    """The IDE side chat's system prompt (lazy, AP-26)."""
    from dodaios.agentic_ide.side_chat import system_prompt

    return await system_prompt(session, user_text, assistant_name)


def _only_local_models(tools: dict[str, Tool]) -> dict[str, Tool]:
    """Its own hands and nothing else.

    The assistant sets up local models; the wiki, the calendar and the folder
    tools are foreign schemas that only make the request bigger and give a
    provider more to refuse.
    """
    from dodaios.local_models.assistant_tools import TOOL_PREFIX

    return {name: tool for name, tool in tools.items() if name.startswith(TOOL_PREFIX)}


# ── the table ─────────────────────────────────────────────────────────────

_KITS: Final[dict[str, SurfaceKit]] = {
    "agent": SurfaceKit(surface="agent", turn_prompts=True, turn_completed=_person_chat_completed),
    "jarvis": SurfaceKit(
        surface="jarvis",
        brain_runner=True,
        # Subscription seats may answer here too: the CLI then runs inside the
        # Jarvis harness (``dodaios_harness``) with Jarvis' tools over MCP, so a
        # plan bills the subscription instead of a key.
        cli_seats=True,
        ladder=_JARVIS_LADDER,
        uses_stance=True,
        session_tools=_jarvis_tools,
        # Typed turns teach Jarvis the same way spoken ones do.
        turn_completed=_jarvis_completed,
        # Not the home directory: this surface hands out the folder tools, and
        # the read-only four are tier ``safe`` — they run without a card. The
        # composer hides the chip here (a person talks to Jarvis, they do not
        # point it at a checkout), so the default is also the only folder most
        # of these chats ever see. It has to be a small one.
        workspace_dir=_chat_workspace,
    ),
    # The Local models section's setup assistant. It runs on Jarvis' own
    # harness over the Agents tier (an API key, never a vendor CLI and never
    # the voice brain) so that a person whose voice runs on Ollama still gets
    # a capable model to set Ollama UP. Session policy — one chat per install,
    # re-created when the tier moves — lives in
    # ``dodaios/local_models/assistant_session.py``.
    "local-models": SurfaceKit(
        surface="local-models",
        brain_runner=True,
        cli_seats=False,
        ladder=_JARVIS_LADDER,
        uses_stance=True,
        tools=_local_models_tools,
        system_extra=_local_models_extra,
        tool_origin="local-models-assistant",
        tool_filter=_only_local_models,
        # No folder: this surface never touches a checkout. Its hands talk to
        # the local server and the config, and the composer shows no chip.
        workspace_dir=_chat_workspace,
    ),
    # An agent-society member's canonical chat (dodaios/society). Jarvis' own
    # harness on an API provider (the roster row's pick, else the Agents
    # tier), the Jarvis ladder as stances, and per-session hands: the agent's
    # grant/focus/deny over the brain's tool set plus its two society tools.
    # The briefing is assembled per session from the roster row and the
    # capability catalog (agent-definition section 3.3).
    "society": SurfaceKit(
        surface="society",
        brain_runner=True,
        # 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=_SOCIETY_LADDER,
        uses_stance=True,
        tool_origin="society",
        session_tools=_society_tools,
        session_system_extra=_society_extra,
        session_tool_filter=_society_filter,
        session_direct_tools=_society_direct,
        session_always_allow=_society_always_allow,
        turn_completed=_society_completed,
        history_start=_society_history_start,
        workspace_dir=_chat_workspace,
    ),
    # The Agentic IDE's side chat: a plain AI chat beside the terminals. No
    # tools, no approvals, no workspace - the model answers from the
    # conversation alone. Subscription CLIs may answer too, run tool-free, so a
    # person without an API key still has a chat.
    "side": SurfaceKit(
        surface="side",
        cli_seats=True,
        plain_chat=_side_chat,
        workspace_dir=_chat_workspace,
        turn_completed=_person_chat_completed,
    ),
}


def kit_for(surface: str) -> SurfaceKit:
    """The kit of ``surface``; an unknown name behaves like the agent surface."""
    return _KITS.get(surface or "", _KITS["agent"])