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(society): enable routine creation from subscription agents

rubenluetke10-beeped83fdbf3d28
diff --git a/jarvis/agent_chat/jarvis_harness.py b/jarvis/agent_chat/jarvis_harness.py
index 5e3cda1296..34ae2aac92 100644
--- a/jarvis/agent_chat/jarvis_harness.py
+++ b/jarvis/agent_chat/jarvis_harness.py
@@ -177,6 +177,11 @@ def codex_config_args(session_id: str | None = None) -> list[str]:
"-c",
f'mcp_servers.{_SERVER_NAME}.http_headers={{"{HEADER_NAME}"="{session_id}"}}',
]
+ if session_id.startswith("society:"):
+ # A society seat cannot carry out its role without its owned
+ # tools. Surface startup failures instead of a tools-free chat
+ # that can only promise to configure the running app.
+ args += ["-c", f"mcp_servers.{_SERVER_NAME}.required=true"]
return args
except Exception: # noqa: BLE001 — see mcp_config_json
log.warning("agent chat: could not build the Codex MCP overrides", exc_info=True)
diff --git a/jarvis/agent_chat/runner_cli.py b/jarvis/agent_chat/runner_cli.py
index 60256733b6..6b42cc2576 100644
--- a/jarvis/agent_chat/runner_cli.py
+++ b/jarvis/agent_chat/runner_cli.py
@@ -74,6 +74,7 @@ from jarvis.agent_chat.effort import normalize_effort, snap_to_ladder
from jarvis.agent_chat.events import make_event
from jarvis.agent_chat.permissions import normalize_permission
from jarvis.agent_chat.runner_api import TurnHandle
+from jarvis.agent_chat.tool_context import register_turn, unregister_turn
from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
log = logging.getLogger(__name__)
@@ -1060,7 +1061,28 @@ def _with_identity(
context for nothing. The block is fenced so the model can tell the head
from the person's words.
"""
- if identity is None or resume:
+ if identity is None:
+ return prompt
+ if resume:
+ if identity.session_id.startswith("society:"):
+ # A resumed vendor conversation may remember an old, incomplete
+ # tool catalog. Refresh the execution contract without repeating
+ # the large identity/history block on every turn.
+ return (
+ "<jarvis_turn_context>\n"
+ "You are a Society agent in the running Personal Jarvis app. "
+ "Your current tools are available through the jarvis MCP server. "
+ "For recurring-work requests, inspect society_routines, then call "
+ "society_propose_change with kind=routine, mode=apply and an exact "
+ "request_quote from the current user message. Brief confirmations "
+ "refer to the agreed task. Read back the saved routine with "
+ "society_routines before reporting it active. Do not substitute "
+ "a plan, memory note, shell command or workspace file for scheduling. "
+ "Use existing connected-account information; ask only for essential "
+ "missing information. If a tool is unavailable or fails, report the "
+ "actual blocker without claiming completion. Existing permission "
+ "rules still apply.\n</jarvis_turn_context>\n\n" + prompt
+ )
return prompt
text = identity.compact if compact else identity.text
return f"<jarvis_identity>\n{text}\n</jarvis_identity>\n\n{prompt}"
@@ -2385,6 +2407,7 @@ async def run_cli_turn(
ask=handle.request_approval,
),
)
+ tool_context = register_turn(session.session_id) if identity else None
try:
outcome = await _run_cli_once(
handle, user_text, runner, resume, identity=ident, bridge=bridge
@@ -2416,6 +2439,7 @@ async def run_cli_turn(
handle, user_text, runner, None, identity=ident, bridge=bridge
)
finally:
+ unregister_turn(session.session_id, tool_context)
ACCOUNT_OVERRIDE.reset(account_token)
if bridge is not None and identity:
bridge.disarm(ref)
diff --git a/jarvis/agent_chat/tool_context.py b/jarvis/agent_chat/tool_context.py
new file mode 100644
index 0000000000..93f6c3313e
--- /dev/null
+++ b/jarvis/agent_chat/tool_context.py
@@ -0,0 +1,50 @@
+"""Carry trusted CLI turn context across the local MCP HTTP boundary.
+
+HTTP handlers do not inherit the task that launched the CLI's ContextVars.
+Only a running, app-owned turn can register its context; tool arguments and
+HTTP headers cannot supply user text or promote a scheduled turn to a user.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterator
+from contextlib import contextmanager
+from dataclasses import dataclass
+
+from jarvis.core.protocols import ChatTurn, current_chat_turn
+from jarvis.tasks.context import client_timezone
+
+
+@dataclass(frozen=True)
+class TurnContext:
+ turn: ChatTurn
+ timezone: str | None
+
+
+_active: dict[str, TurnContext] = {}
+
+
+def register_turn(session_id: str) -> TurnContext | None:
+ turn = current_chat_turn.get()
+ if turn is None or turn.session_id != session_id:
+ return None
+ context = TurnContext(turn, client_timezone.get())
+ _active[session_id] = context
+ return context
+
+
+def unregister_turn(session_id: str, context: TurnContext | None) -> None:
+ if context is not None and _active.get(session_id) is context:
+ del _active[session_id]
+
+
+@contextmanager
+def restore_turn(session_id: str | None) -> Iterator[None]:
+ context = _active.get(session_id or "")
+ turn_token = current_chat_turn.set(context.turn if context else None)
+ zone_token = client_timezone.set(context.timezone if context else None)
+ try:
+ yield
+ finally:
+ client_timezone.reset(zone_token)
+ current_chat_turn.reset(turn_token)
diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.py
index 42fd2a67fa..8f66f7db54 100644
--- a/jarvis/brain/factory.py
+++ b/jarvis/brain/factory.py
@@ -861,9 +861,19 @@ def _register_runtime_manager(manager: Any) -> None:
return await browser_tool_for_session(session_id)
+ async def session_tools(session_id: str, tools: dict[str, Any]) -> Any:
+ from jarvis.society.surface import tools_for_cli_session
+
+ return await tools_for_cli_session(session_id, tools, manager)
+
runtime_refs.set_brain_manager(manager)
runtime_refs.set_supervisor_tool_gateway(
- BrainSupervisorToolGateway(manager, session_tool=session_tool, browser_tool=browser_tool)
+ BrainSupervisorToolGateway(
+ manager,
+ session_tool=session_tool,
+ browser_tool=browser_tool,
+ session_tools=session_tools,
+ )
)
except Exception as exc: # noqa: BLE001 - registration never blocks boot
log.debug("Runtime supervisor gateway registration failed: %s", exc)
diff --git a/jarvis/brain/tool_gateway.py b/jarvis/brain/tool_gateway.py
index 0ae7913612..3c28f620e9 100644
--- a/jarvis/brain/tool_gateway.py
+++ b/jarvis/brain/tool_gateway.py
@@ -33,10 +33,13 @@ class BrainSupervisorToolGateway:
*,
session_tool: Callable[[str], Awaitable[Tool | None]] | None = None,
browser_tool: Callable[[str], Awaitable[Tool | None]] | None = None,
+ session_tools: Callable[[str, dict[str, Any]], Awaitable[dict[str, Any] | None]]
+ | None = None,
) -> None:
self._manager = manager
self._session_tool = session_tool
self._browser_tool = browser_tool
+ self._session_tools = session_tools
self._lock = threading.Lock()
self._fingerprint: tuple[tuple[str, int], ...] = ()
self._catalog_version = 0
@@ -60,6 +63,10 @@ class BrainSupervisorToolGateway:
self._fingerprint = fingerprint
self._catalog_version += 1
+ return self._describe(tools)
+
+ @staticmethod
+ def _describe(tools: dict[str, Any]) -> tuple[SupervisorToolDescriptor, ...]:
descriptors: list[SupervisorToolDescriptor] = []
for name, tool in sorted(tools.items()):
if not callable(getattr(tool, "execute", None)):
@@ -107,8 +114,17 @@ class BrainSupervisorToolGateway:
error=f"cancelled ({request.cancel_token.reason or 'requested'})",
)
- tool = self._live_tools().get(name)
- if name in {"coding-session", "society_browser"}:
+ tools = self._live_tools()
+ ref = str(request.config_snapshot.get("approval_ref") or "")
+ scoped = None
+ if (
+ self._session_tools is not None
+ and request.origin == "agent-chat"
+ and ref.startswith("agent-chat:")
+ ):
+ scoped = await self._session_tools(ref.removeprefix("agent-chat:"), tools)
+ tool = (scoped if scoped is not None else tools).get(name)
+ if scoped is None and name in {"coding-session", "society_browser"}:
# Never install this controller in the global worker tool set.
# The authenticated chat transport supplies its canonical session reference.
ref = str(request.config_snapshot.get("approval_ref") or "")
@@ -154,6 +170,10 @@ class BrainSupervisorToolGateway:
async def session_catalog(self, session_id: str) -> tuple[SupervisorToolDescriptor, ...]:
"""Resolve the permitted session-owned tools without exposing them globally."""
+ if self._session_tools is not None:
+ tools = await self._session_tools(session_id, self._live_tools())
+ if tools is not None:
+ return self._describe(tools)
catalog = self.catalog()
scoped = []
for resolver in (self._session_tool, self._browser_tool):
diff --git a/jarvis/mcp/jarvis_tools_server.py b/jarvis/mcp/jarvis_tools_server.py
index b20f25d529..c66fa6e353 100644
--- a/jarvis/mcp/jarvis_tools_server.py
+++ b/jarvis/mcp/jarvis_tools_server.py
@@ -181,7 +181,7 @@ def build_server() -> Any:
@server.call_tool() # type: ignore[misc, no-untyped-call]
async def _call_tool(name: str, arguments: dict[str, Any] | None) -> list[Any]:
- from jarvis.core.protocols import SupervisorToolRequest
+ from jarvis.core.protocols import SupervisorToolRequest, current_chat_turn
gateway = _gateway()
if gateway is None:
@@ -196,15 +196,19 @@ def build_server() -> Any:
),
)
]
- request = SupervisorToolRequest(
- trace_id=uuid4(),
- origin=CHAT_ORIGIN,
- user_utterance="",
- rationale="agent chat tool call",
- config_snapshot=approval_snapshot(),
- )
try:
- result = await gateway.execute(name, dict(arguments or {}), request)
+ from jarvis.agent_chat.tool_context import restore_turn
+
+ with restore_turn(CHAT_SESSION_REF.get()):
+ turn = current_chat_turn.get()
+ request = SupervisorToolRequest(
+ trace_id=uuid4(),
+ origin=CHAT_ORIGIN,
+ user_utterance=turn.user_text if turn else "",
+ rationale="agent chat tool call",
+ config_snapshot=approval_snapshot(),
+ )
+ result = await gateway.execute(name, dict(arguments or {}), request)
except Exception as exc: # noqa: BLE001 — a tool failure is data for the model, not a crash
log.warning("jarvis MCP: %s raised", name, exc_info=True)
return [
diff --git a/jarvis/society/agent_tools.py b/jarvis/society/agent_tools.py
index 5f531ca9ab..5d3819465f 100644
--- a/jarvis/society/agent_tools.py
+++ b/jarvis/society/agent_tools.py
@@ -411,7 +411,8 @@ class ProposeChangeTool:
turn is None
or not turn.direct_user
or turn.session_id != caller.session_id
- or len(quote) < 4
+ or not quote
+ or (len(quote) < 4 and quote != turn.user_text.strip())
or quote not in turn.user_text
):
return _failure(
diff --git a/jarvis/society/surface.py b/jarvis/society/surface.py
index 3cc1633b97..54ecc9f9fc 100644
--- a/jarvis/society/surface.py
+++ b/jarvis/society/surface.py
@@ -144,6 +144,13 @@ request. Read the stored result before claiming success. For inferred suggestion
mode=propose. Permission changes always need confirmation. Rules support operation
add/replace/remove (old_text identifies the old rule); routines support
create/update/pause/resume/delete (task_id identifies an existing routine).
+An explicit recurring-work request is an instruction to save a routine in this turn,
+not an invitation to describe a plan or ask again whether to start. Inspect connected
+accounts for missing details before asking. Optional preferences do not block scheduling.
+Reuse the agreed task when the user confirms it briefly. After applying, call
+society_routines to verify the saved task and report its actual state and next run.
+If a prerequisite prevents execution, report that specific blocker; never claim the
+routine is active merely because you wrote its operating instructions or a memory note.
- Approvals: actions above your permission ceiling queue for the user (chat card, Jarvis bar, \
voice). A queued action is not refused — say what you are waiting for and continue with what \
you can. Secrets are never typed into a chat; credentials come from the keyring.
@@ -243,6 +250,47 @@ async def _scoped_tool_for_session(session_id: str, capability: str) -> Tool | N
return cast(Tool, _GatedTool(tool, agent, capability))
+async def tools_for_cli_session(
+ session_id: str, tools: dict[str, Any], brain: Any
+) -> dict[str, Tool] | None:
+ """Give subscription seats the same owned tools and gates as API seats.
+
+ None preserves the ordinary chat catalog; an empty mapping fails closed
+ for an unavailable society session. Resolve the roster on every call so
+ grants and retirement take effect even in an already connected CLI.
+ """
+ agent_id = agent_id_of(session_id)
+ if agent_id is None:
+ return None
+ rt = current_runtime()
+ if rt is None or await rt.store.kill_switch():
+ return {}
+ service = rt.chat_service()
+ session = service.store.get_session(session_id) if service is not None else None
+ agent = await rt.roster.get(agent_id)
+ if (
+ session is None
+ or session.surface != SURFACE
+ or agent is None
+ or str(agent.state) != "active"
+ or agent.session_id != session_id
+ ):
+ return {}
+ rt.cache_agent(agent)
+ merged = dict(tools)
+ merged.update(society_tools(getattr(brain, "_config", None), brain, session))
+ select = society_tool_filter(session)
+ selected = select(merged) if select is not None else {}
+ if session.permission_mode in ("plan", "read-only"):
+ selected = {
+ name: tool
+ for name, tool in selected.items()
+ if not getattr(tool, "is_action_tool", False)
+ and getattr(tool, "risk_tier", "monitor") == "safe"
+ }
+ return selected
+
+
def society_tools(cfg: Any, brain: Any, session: Any) -> dict[str, Tool]:
rt = current_runtime()
agent_id = agent_id_of(getattr(session, "session_id", "") or "")
diff --git a/tests/unit/society/test_cli_routines.py b/tests/unit/society/test_cli_routines.py
new file mode 100644
index 0000000000..1bd445e174
--- /dev/null
+++ b/tests/unit/society/test_cli_routines.py
@@ -0,0 +1,233 @@
+"""Subscription seats must be able to schedule and read back their own routines."""
+
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+
+import mcp.types as types
+import pytest
+
+from jarvis.agent_chat.store import AgentChatStore
+from jarvis.agent_chat.tool_context import register_turn, restore_turn, unregister_turn
+from jarvis.brain.tool_gateway import BrainSupervisorToolGateway
+from jarvis.core import runtime_refs
+from jarvis.core.protocols import ChatTurn, current_chat_turn
+from jarvis.mcp.jarvis_tools_server import CHAT_SESSION_REF, build_server
+from jarvis.society.runtime import SocietyRuntime
+from jarvis.society.surface import tools_for_cli_session
+from jarvis.tasks.context import client_timezone
+from tests.fakes.fake_agent_chat import FakeChatService
+from tests.unit.society.test_routines import FakeScheduler, FakeTaskStore
+
+
+class ExecutingFake:
+ """Record gateway routing, then exercise the actual owned tool."""
+
+ def __init__(self):
+ self.calls = []
+
+ async def execute(self, tool, arguments, **kwargs):
+ self.calls.append((tool.name, kwargs))
+ return await tool.execute(arguments, SimpleNamespace(trace_id=kwargs["trace_id"]))
+
+
+async def world(tmp_path):
+ chat_store = AgentChatStore(tmp_path / "chat.db")
+ service = FakeChatService(chat_store)
+ tasks = FakeTaskStore()
+ scheduler = FakeScheduler(tasks)
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path)))
+ rt = SocietyRuntime(
+ tmp_path,
+ seed_starter_team=False,
+ chat_service=lambda: service,
+ task_services=lambda: (tasks, scheduler),
+ cfg=lambda: cfg,
+ )
+ await rt.ensure_started()
+ agent, _ = await rt.roster.create(name="Scout")
+ chat_store.create_session(
+ session_id=agent.session_id,
+ surface="society",
+ provider="openai-codex",
+ model="test-model",
+ effort="medium",
+ cwd=str(tmp_path / "workspace"),
+ permission_mode="accept-edits",
+ )
+ executor = ExecutingFake()
+ manager = SimpleNamespace(_tools={}, _tool_executor=executor, _config=cfg)
+
+ async def scoped(session_id, tools):
+ return await tools_for_cli_session(session_id, tools, manager)
+
+ gateway = BrainSupervisorToolGateway(manager, session_tools=scoped)
+ monkey_gateway = runtime_refs.get_supervisor_tool_gateway()
+ runtime_refs.set_supervisor_tool_gateway(gateway)
+ try:
+ yield SimpleNamespace(
+ rt=rt,
+ store=chat_store,
+ tasks=tasks,
+ scheduler=scheduler,
+ gateway=gateway,
+ executor=executor,
+ server=build_server(),
+ )
+ finally:
+ runtime_refs.set_supervisor_tool_gateway(monkey_gateway)
+ await rt.close()
+ chat_store.close()
+
+
+async def call(world, name, args=None, session="society:scout"):
+ token = CHAT_SESSION_REF.set(session)
+ try:
+ result = await world.server.request_handlers[types.CallToolRequest](
+ types.CallToolRequest(
+ method="tools/call",
+ params=types.CallToolRequestParams(name=name, arguments=args or {}),
+ )
+ )
+ return result.root.content[0].text
+ finally:
+ CHAT_SESSION_REF.reset(token)
+
+
+def args(quote):
+ return {
+ "kind": "routine",
+ "mode": "apply",
+ "request_quote": quote,
+ "payload": {
+ "title": "Hourly comment replies",
+ "prompt": "Check my posts from the last five days and reply briefly to new comments.",
+ "schedule": {"kind": "every", "interval_seconds": 3600},
+ },
+ }
+
+
+async def test_cli_catalog_includes_routines_without_global_leak(world):
+ catalog = await world.gateway.session_catalog("society:scout")
+ assert {"society_routines", "society_propose_change"} <= {t.name for t in catalog}
+ assert not any(t.name.startswith("society_") for t in world.gateway.catalog())
+ assert await world.gateway.session_catalog("society:missing") == ()
+ assert await world.gateway.session_catalog("ordinary-chat") == ()
+
+
[email protected]("quote", ["Check comments every hour", "Yes", "Ja"]) # i18n-allow
+async def test_explicit_cli_request_schedules_and_reads_back(world, quote):
+ origin = ChatTurn("society:scout", "turn-1", quote, True, "trace-1")
+ token = current_chat_turn.set(origin)
+ zone = client_timezone.set("America/New_York")
+ registered = register_turn(origin.session_id)
+ current_chat_turn.reset(token)
+ client_timezone.reset(zone)
+ try:
+ result = json.loads(await call(world, "society_propose_change", args(quote)))
+ assert result["applied"] is True
+ saved = json.loads(await call(world, "society_routines"))
+ assert saved["timezone"] == "America/New_York"
+ assert len(saved["routines"]) == 1
+ assert saved["routines"][0]["trigger"]["interval_seconds"] == 3600
+ assert saved["routines"][0]["state"] == "scheduled"
+ assert world.scheduler.scheduled == ["task-1"]
+ assert world.executor.calls[0][1]["user_utterance"] == quote
+ assert current_chat_turn.get() is None
+ finally:
+ unregister_turn(origin.session_id, registered)
+ stale = await call(world, "society_propose_change", args(quote))
+ assert "exact current user request" in stale
+ assert len(world.tasks.rows) == 1
+
+
+ "direct_user,session,quote",
+ [
+ (False, "society:scout", "Check comments every hour"),
+ (True, "society:other", "Check comments every hour"),
+ (True, "society:scout", "fabricated request"),
+ (True, "society:scout", "e"),
+ ],
+)
+async def test_untrusted_or_cross_session_calls_cannot_apply(world, direct_user, session, quote):
+ origin = ChatTurn(session, "turn-1", "Check comments every hour", direct_user, "trace")
+ token = current_chat_turn.set(origin)
+ registered = register_turn(session)
+ current_chat_turn.reset(token)
+ try:
+ result = await call(world, "society_propose_change", args(quote))
+ assert "exact current user request" in result
+ assert world.tasks.rows == []
+ finally:
+ unregister_turn(session, registered)
+
+
+async def test_read_only_session_can_inspect_but_not_schedule(world):
+ world.store.update_session("society:scout", permission_mode="plan")
+ catalog = {t.name for t in await world.gateway.session_catalog("society:scout")}
+ assert "society_routines" in catalog
+ assert "society_propose_change" not in catalog
+ assert "no longer available" in await call(world, "society_propose_change", args("yes"))
+ assert world.tasks.rows == []
+
+
+async def test_grants_are_checked_again_at_call_time(world):
+ tool = SimpleNamespace(name="gmail", schema={}, description="Mail", risk_tier="ask")
+
+ async def execute(_args, _ctx):
+ raise AssertionError("A denied tool must not execute")
+
+ tool.execute = execute
+ world.gateway._manager._tools["gmail"] = tool
+ assert "gmail" in {t.name for t in await world.gateway.session_catalog("society:scout")}
+ await world.rt.roster.update("scout", {"denies": ["plugin:gmail"]})
+ assert "no longer available" in await call(world, "gmail")
+ assert world.executor.calls == []
+
+
+def test_context_cleanup_and_isolation():
+ first = ChatTurn("society:first", "one", "yes", True, "trace")
+ token = current_chat_turn.set(first)
+ registered = register_turn(first.session_id)
+ current_chat_turn.reset(token)
+ try:
+ with restore_turn("society:second"):
+ assert current_chat_turn.get() is None
+ with pytest.raises(RuntimeError), restore_turn(first.session_id):
+ assert current_chat_turn.get() == first
+ raise RuntimeError("tool failed")
+ assert current_chat_turn.get() is None
+ finally:
+ unregister_turn(first.session_id, registered)
+ with restore_turn(first.session_id):
+ assert current_chat_turn.get() is None
+
+
+def test_resumed_society_seat_refreshes_routine_contract(monkeypatch, tmp_path):
+ from jarvis.agent_chat import jarvis_harness, runner_cli
+
+ monkeypatch.setattr(runner_cli, "codex_argv_prefix", lambda: ["codex"])
+ monkeypatch.setattr(jarvis_harness, "control_key", lambda: "test-key")
+ monkeypatch.setattr(
+ jarvis_harness, "endpoint", lambda: "http://localhost:47821/api/control/mcp/"
+ )
+ identity = jarvis_harness.Identity(
+ session_id="society:scout", text="LARGE OLD IDENTITY", compact="old", path=None
+ )
+ plan = runner_cli.plan_codex(
+ prompt="Check comments every hour",
+ cwd=tmp_path,
+ model="",
+ effort="",
+ permission_mode="accept-edits",
+ resume="existing-thread",
+ identity=identity,
+ )
+ assert "mcp_servers.jarvis.required=true" in plan.argv
+ assert "society_propose_change" in plan.stdin_text
+ assert "LARGE OLD IDENTITY" not in plan.stdin_text
+ assert plan.stdin_text.endswith("Check comments every hour")
+ assert "test-key" not in " ".join(plan.argv)