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): choose which computer a Jarvis agent runs on

rubenluetke10-beep4e95cf9bc6f7
diff --git a/jarvis/agent_chat/remote_cli.py b/jarvis/agent_chat/remote_cli.py
new file mode 100644
index 0000000000..40abd27a68
--- /dev/null
+++ b/jarvis/agent_chat/remote_cli.py
@@ -0,0 +1,246 @@
+"""Run a coding-agent CLI turn on another computer over SSH.
+
+A society agent placed on a connected computer (``computer_id``) runs its CLI
+there: the turn is planned exactly as a local one (``runner_cli`` planners),
+the argv is rewritten for the remote machine, and the process is started over
+the computer's pinned SSH connection. :class:`RemoteCliProcess` looks like the
+``asyncio.subprocess.Process`` the local path uses — ``stdin`` / ``stdout`` /
+``stderr`` / ``wait`` / ``kill`` / ``returncode`` — so the stream translation,
+approval control protocol and error handling in ``runner_cli`` stay one code
+path for both.
+
+What does NOT travel:
+
+* Local paths and secrets. The environment is an allow-list of a few
+ prompt-suppressing variables; the CLI uses the login it has on the remote
+ machine (``claude login`` / ``codex login`` there), never this box's.
+* Jarvis' own MCP tools. That endpoint listens on this computer's localhost
+ and a remote CLI cannot reach it, so ``--mcp-config`` / the Codex
+ ``mcp_servers`` overrides are dropped for remote turns.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import logging
+import shlex
+from collections.abc import Sequence
+from typing import Any, Final
+
+log = logging.getLogger(__name__)
+
+#: Environment variables a remote CLI turn carries: prompt- and colour-free
+#: output only. Everything else in the local env (config dirs, account homes,
+#: API keys) describes THIS machine and must not leak to the remote one.
+REMOTE_ENV_ALLOW: Final[frozenset[str]] = frozenset({"NO_COLOR", "TERM", "LANG", "LC_ALL"})
+
+#: Leading argv parts that are how THIS box launches a CLI (interpreters,
+#: shell wrappers) rather than the CLI's own arguments.
+_LAUNCHER_PARTS: Final[frozenset[str]] = frozenset(
+ {
+ "node",
+ "node.exe",
+ "cmd",
+ "cmd.exe",
+ "/c",
+ "/d",
+ "/s",
+ "powershell",
+ "powershell.exe",
+ "pwsh",
+ "pwsh.exe",
+ "-file",
+ "-noprofile",
+ "-executionpolicy",
+ "bypass",
+ "-noninteractive",
+ }
+)
+
+_LOCAL_ONLY_FLAGS_WITH_VALUE: Final[frozenset[str]] = frozenset({"--mcp-config"})
+
+
+class RemoteCliUnavailable(RuntimeError):
+ """The remote machine cannot run this CLI; ``str(exc)`` is user-facing."""
+
+
+def _looks_like_launcher(part: str) -> bool:
+ low = part.lower()
+ if low in _LAUNCHER_PARTS:
+ return True
+ if "/" in part or "\\" in part:
+ return True # a local absolute path to a binary, shim or cli.js
+ return low.endswith((".exe", ".cmd", ".bat", ".ps1", ".js", ".mjs"))
+
+
+def remote_argv(
+ argv: Sequence[str],
+ *,
+ binary: str,
+ local_cwd: str,
+ remote_cwd: str,
+ system_prompt_files: dict[str, str] | None = None,
+) -> list[str]:
+ """Rewrite a locally planned argv for the remote machine.
+
+ The local launcher prefix becomes the bare ``binary`` (found on the
+ remote PATH); the local working folder becomes the remote one; Jarvis'
+ localhost MCP wiring is dropped; an ``--append-system-prompt-file`` (a
+ local file) is inlined as ``--append-system-prompt``.
+ """
+ parts = list(argv)
+ start = 0
+ while start < len(parts) and _looks_like_launcher(parts[start]):
+ start += 1
+ rest = parts[start:]
+ out: list[str] = [binary]
+ skip = False
+ files = system_prompt_files or {}
+ for index, part in enumerate(rest):
+ if skip:
+ skip = False
+ continue
+ if part in _LOCAL_ONLY_FLAGS_WITH_VALUE:
+ skip = True
+ continue
+ if part == "-c" and index + 1 < len(rest) and "mcp_servers" in rest[index + 1]:
+ skip = True
+ continue
+ if part == "--append-system-prompt-file" and index + 1 < len(rest):
+ text = files.get(rest[index + 1])
+ skip = True
+ if text:
+ out += ["--append-system-prompt", text]
+ continue
+ out.append(remote_cwd if part == local_cwd else part)
+ return out
+
+
+def remote_env(env: dict[str, str]) -> dict[str, str]:
+ """The allow-listed variables plus ``CI=1`` (never a secret, never a path)."""
+ kept = {k: v for k, v in env.items() if k in REMOTE_ENV_ALLOW}
+ kept["CI"] = "1"
+ kept.setdefault("NO_COLOR", "1")
+ return kept
+
+
+class _Stdin:
+ """``proc.stdin`` for a remote process: ``close`` ends input, not the channel."""
+
+ def __init__(self, writer: Any) -> None:
+ self._writer = writer
+ self._eof = False
+
+ def write(self, data: bytes) -> None:
+ if not self._eof:
+ self._writer.write(data)
+
+ async def drain(self) -> None:
+ await self._writer.drain()
+
+ def is_closing(self) -> bool:
+ return self._eof or bool(self._writer.is_closing())
+
+ def close(self) -> None:
+ if self._eof:
+ return
+ self._eof = True
+ with contextlib.suppress(OSError, BrokenPipeError):
+ self._writer.write_eof()
+
+
+class RemoteCliProcess:
+ """An SSH-backed process with the ``asyncio.subprocess.Process`` surface."""
+
+ pid: int | None = None
+
+ def __init__(self, process: Any, stack: contextlib.AsyncExitStack) -> None:
+ self._process = process
+ self._stack = stack
+ self.stdin = _Stdin(process.stdin)
+ self.stdout = process.stdout
+ self.stderr = process.stderr
+ self._closed = False
+
+ @property
+ def returncode(self) -> int | None:
+ code = self._process.returncode
+ return None if code is None else int(code)
+
+ async def wait(self) -> int | None:
+ with contextlib.suppress(Exception): # a torn-down channel reports no status
+ await self._process.wait_closed()
+ await self._release()
+ return self.returncode
+
+ def kill(self) -> None:
+ # Many sshd builds ignore signal requests; closing the channel hangs
+ # up the remote command's terminal-less session instead.
+ with contextlib.suppress(Exception):
+ self._process.kill()
+ with contextlib.suppress(Exception):
+ self._process.close()
+
+ async def _release(self) -> None:
+ if self._closed:
+ return
+ self._closed = True
+ await self._stack.aclose()
+
+
+async def spawn(
+ computer_id: str,
+ *,
+ agent_id: str,
+ runner: str,
+ binary: str,
+ argv: Sequence[str],
+ local_cwd: str,
+ env: dict[str, str],
+ system_prompt_files: dict[str, str] | None = None,
+) -> RemoteCliProcess:
+ """Start the CLI on ``computer_id`` inside the agent's remote workspace."""
+ from jarvis.computers.service import ComputerError, get_service
+ from jarvis.computers.ssh import SshError, run_command
+ from jarvis.society.remote import remote_workspace_expr
+
+ stack = contextlib.AsyncExitStack()
+ try:
+ opened = await stack.enter_async_context(get_service().session(computer_id))
+ folder = remote_workspace_expr(agent_id)
+ probe = await run_command(
+ opened,
+ f"mkdir -p {folder} && cd {folder} && pwd && "
+ f"(command -v {shlex.quote(binary)} >/dev/null 2>&1 && echo found || echo missing)",
+ timeout_s=20,
+ )
+ lines = [line.strip() for line in probe.stdout.splitlines() if line.strip()]
+ if len(lines) < 2:
+ raise RemoteCliUnavailable("The agent's computer did not answer the setup check.")
+ remote_cwd, presence = lines[-2], lines[-1]
+ computer = get_service().get(computer_id)
+ if presence != "found":
+ raise RemoteCliUnavailable(
+ f"Install {binary} on {computer.name} (and log in there once), "
+ "or set the agent to run on this computer."
+ )
+ command_argv = remote_argv(
+ argv,
+ binary=binary,
+ local_cwd=local_cwd,
+ remote_cwd=remote_cwd,
+ system_prompt_files=system_prompt_files,
+ )
+ assignments = " ".join(f"{k}={shlex.quote(v)}" for k, v in remote_env(env).items())
+ command = (
+ f"cd {shlex.quote(remote_cwd)} && exec env {assignments} {shlex.join(command_argv)}"
+ )
+ log.info("agent chat: %s turn for %s runs on %s", runner, agent_id, computer.name)
+ process = await opened.conn.create_process(command, encoding=None)
+ except (ComputerError, SshError) as exc:
+ await stack.aclose()
+ raise RemoteCliUnavailable(f"Could not reach the agent's computer: {exc.message}") from exc
+ except BaseException:
+ await stack.aclose()
+ raise
+ return RemoteCliProcess(process, stack)
diff --git a/jarvis/agent_chat/runner_cli.py b/jarvis/agent_chat/runner_cli.py
index 5e6852ae16..6f49269f02 100644
--- a/jarvis/agent_chat/runner_cli.py
+++ b/jarvis/agent_chat/runner_cli.py
@@ -122,6 +122,8 @@ CLI_BINARIES: Final[dict[str, tuple[str, ...]]] = {
def _which(*names: str) -> str | None:
+ if _REMOTE_PLANNING.get():
+ return names[0] if names else None
# The well-known install dirs a GUI-launched process does not inherit
# (``~/.local/bin``, ``~/.grok/bin``, npm's prefix) — best-effort, and the
# same augmentation a pane runs before it resolves its CLI.
@@ -230,6 +232,10 @@ ACCOUNT_OVERRIDE: ContextVar[str] = ContextVar("agent_chat.account_override", de
_CATALOG_IGNORE_CONFIG: ContextVar[bool] = ContextVar("cli_catalog.ignore_config", default=False)
+#: Set while a turn is planned for ANOTHER computer (a society agent placed on
+#: a VPS): binary lookups answer the bare name, since the CLI is found on the
+#: remote PATH, not this one (``jarvis.agent_chat.remote_cli``).
+_REMOTE_PLANNING: ContextVar[bool] = ContextVar("agent_chat.remote_planning", default=False)
_CATALOG_CWD: ContextVar[Path | None] = ContextVar("cli_catalog.cwd", default=None)
_ACCOUNT_ENVS: ContextVar[dict[str, dict[str, str]] | None] = ContextVar(
"cli_catalog.envs", default=None
@@ -2729,13 +2735,18 @@ async def _run_cli_once(
usage: dict[str, int] = {}
cost_usd: float | None = None
vendor_session: str | None = None
+ from jarvis.society.remote import placement_for_session
+
+ # A society agent placed on another computer runs its CLI there over SSH.
+ placement = await placement_for_session(session)
+ remote_token = _REMOTE_PLANNING.set(placement is not None)
try:
with cli_catalog_scope(
cwd=cwd,
ignore_user_config=identity is not None or bool(getattr(handle, "gateway_only", False)),
):
- if runner == "codex-cli":
+ if runner == "codex-cli" and placement is None:
models = await asyncio.to_thread(read_codex_models, required_model=session.model)
if session.model and (
models is None or not any(row["id"] == session.model for row in models)
@@ -2750,7 +2761,7 @@ async def _run_cli_once(
if row["id"] == session.model:
effort = snap_to_ladder(session.effort, list(row.get("efforts", [])))
break
- if runner == "agy-cli":
+ if runner == "agy-cli" and placement is None:
# A chat can start before the model picker has loaded its catalog.
# Resolve the installed CLI's effort ladder off the event loop so
# newly available models keep the required model/effort pairing.
@@ -2792,6 +2803,8 @@ async def _run_cli_once(
raise CliUnavailable("The selected runner cannot isolate task tools.")
except CliUnavailable as exc:
return _Outcome("error", str(exc), {}, None, None)
+ finally:
+ _REMOTE_PLANNING.reset(remote_token)
vendor_session = plan.vendor_session
if (
@@ -2805,32 +2818,59 @@ async def _run_cli_once(
log.info("agent chat %s: %s argv=%s", handle.turn_id, runner, plan.argv[:6])
started_at = time.time()
tree = None
- if getattr(handle, "goal_turn", False) or (
- session.surface == "society" and session.permission_mode == "plan"
+ if placement is None and (
+ getattr(handle, "goal_turn", False)
+ or (session.surface == "society" and session.permission_mode == "plan")
):
from jarvis.core.process_tree import make_process_tree
tree = make_process_tree("chat-controlled-cli")
- try:
- proc = await asyncio.create_subprocess_exec(
- *plan.argv,
- cwd=str(cwd),
- env=plan.env,
- stdin=asyncio.subprocess.PIPE
- if plan.stdin_text is not None
- else asyncio.subprocess.DEVNULL,
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.PIPE,
- creationflags=NO_WINDOW_CREATIONFLAGS,
- start_new_session=tree is not None and os.name != "nt",
- limit=_READLINE_LIMIT,
- )
- if tree is not None:
- tree.assign(proc.pid)
- except (OSError, ValueError) as exc:
- if tree is not None:
- tree.close()
- return _Outcome("error", f"Could not start {runner}: {exc}", {}, None, None)
+ proc: Any
+ if placement is not None:
+ from jarvis.agent_chat.remote_cli import RemoteCliUnavailable, spawn
+
+ prompt_files: dict[str, str] = {}
+ if identity is not None and identity.path is not None:
+ try:
+ prompt_files[str(identity.path)] = await asyncio.to_thread(
+ Path(identity.path).read_text, encoding="utf-8"
+ )
+ except OSError:
+ log.warning("agent chat: identity file unreadable for a remote turn")
+ try:
+ proc = await spawn(
+ placement[0],
+ agent_id=placement[1],
+ runner=runner,
+ binary=CLI_BINARIES[runner][0],
+ argv=plan.argv,
+ local_cwd=str(cwd),
+ env=plan.env,
+ system_prompt_files=prompt_files,
+ )
+ except RemoteCliUnavailable as exc:
+ return _Outcome("error", str(exc), {}, None, None)
+ else:
+ try:
+ proc = await asyncio.create_subprocess_exec(
+ *plan.argv,
+ cwd=str(cwd),
+ env=plan.env,
+ stdin=asyncio.subprocess.PIPE
+ if plan.stdin_text is not None
+ else asyncio.subprocess.DEVNULL,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ start_new_session=tree is not None and os.name != "nt",
+ limit=_READLINE_LIMIT,
+ )
+ if tree is not None:
+ tree.assign(proc.pid)
+ except (OSError, ValueError) as exc:
+ if tree is not None:
+ tree.close()
+ return _Outcome("error", f"Could not start {runner}: {exc}", {}, None, None)
make_state, translate = _SHAPES[plan.shape]
state: Any = make_state(handle.turn_id, vendor_session)
@@ -3044,7 +3084,12 @@ async def _run_cli_once(
usage = dict(state.usage)
cost_usd = getattr(state, "cost_usd", None)
vendor_session = state.vendor_session or vendor_session
- if vendor_session is None and plan.discover is not None and status == "done":
+ if (
+ vendor_session is None
+ and plan.discover is not None
+ and status == "done"
+ and placement is None # the CLI's store lives on the remote machine
+ ):
# A CLI that never said which conversation it opened: ask its store.
vendor_session = await asyncio.to_thread(plan.discover, cwd, started_at)
result_text = str(getattr(state, "result_text", "") or "")
diff --git a/jarvis/society/agent_tools.py b/jarvis/society/agent_tools.py
index ba3aa56d58..5a37e97b33 100644
--- a/jarvis/society/agent_tools.py
+++ b/jarvis/society/agent_tools.py
@@ -593,12 +593,13 @@ class ShellTool:
def __init__(
self, runtime: Any, agent_id: str, *, workspace: Path, backend: Any = None
) -> None:
- from .shell import default_backend
-
self._runtime = runtime
self._agent_id = agent_id
self._workspace = Path(workspace)
- self._backend = backend or default_backend()
+ #: An explicit backend (tests, a future container) wins; otherwise the
+ #: agent's placement picks one per call — a move to another computer
+ #: applies from the very next command.
+ self._backend = backend
@staticmethod
def _level(command: str) -> str:
@@ -666,13 +667,16 @@ class ShellTool:
timeout = float(args.get("timeout_s") or DEFAULT_TIMEOUT_S)
except (TypeError, ValueError):
timeout = DEFAULT_TIMEOUT_S
- result = await self._backend.run(command, cwd=cwd, timeout_s=timeout)
+ from .remote import backend_for
+
+ backend = self._backend or backend_for(caller, self._workspace)
+ result = await backend.run(command, cwd=cwd, timeout_s=timeout)
body = {
"output": result.output,
"exit_code": result.exit_code,
"seconds": round(result.seconds, 2),
"folder": str(cwd),
- "backend": getattr(self._backend, "name", "local"),
+ "backend": getattr(backend, "name", "local"),
}
if result.timed_out:
return ToolResult(success=False, output=body, error="command timed out")
diff --git a/jarvis/society/remote.py b/jarvis/society/remote.py
new file mode 100644
index 0000000000..65f38207b3
--- /dev/null
+++ b/jarvis/society/remote.py
@@ -0,0 +1,143 @@
+"""Run a society agent's work on another computer (a VPS, a local VM) over SSH.
+
+An agent with ``computer_id`` set keeps its chat, memory and approvals here;
+only the parts that touch a machine move: its shell commands
+(:class:`SshShellBackend`) and, for CLI-seated agents, the coding CLI itself
+(``jarvis.agent_chat.runner_cli``). Both reach the machine through
+``jarvis.computers.service.get_service()`` — the same pinned-host-key SSH
+every other feature uses, never a second connection layer.
+
+The agent's remote workspace is ``~/jarvis-agents/<agent_id>`` on that
+machine, created on demand. Local containment (``resolve_contained``) still
+decides WHICH subfolder a command may use; this module only maps that
+subfolder onto the remote workspace.
+"""
+
+from __future__ import annotations
+
+import logging
+import shlex
+import time
+from pathlib import Path, PurePosixPath
+from typing import Any, Final
+
+from .shell import (
+ DEFAULT_TIMEOUT_S,
+ MAX_TIMEOUT_S,
+ OUTPUT_CAP_CHARS,
+ ShellBackend,
+ ShellResult,
+ _cap,
+ default_backend,
+)
+
+log = logging.getLogger(__name__)
+
+#: The parent folder of every agent workspace on a remote computer.
+REMOTE_ROOT: Final[str] = "jarvis-agents"
+
+
+def remote_workspace_expr(agent_id: str, relative: str = "") -> str:
+ """A shell expression for the agent's remote folder, ``$HOME``-anchored.
+
+ ``$HOME`` stays outside the quotes so the remote shell expands it; the
+ agent id and subfolder are quoted, so nothing the agent names is ever
+ interpreted by that shell.
+ """
+ rel = (
+ PurePosixPath(REMOTE_ROOT, agent_id, relative)
+ if relative
+ else PurePosixPath(REMOTE_ROOT, agent_id)
+ )
+ return '"$HOME"/' + shlex.quote(str(rel))
+
+
+def wrap_in_workspace(agent_id: str, command: str, *, relative: str = "") -> str:
+ """``mkdir -p <ws> && cd <ws> && <command>`` with prompt-free defaults."""
+ folder = remote_workspace_expr(agent_id, relative)
+ return f"mkdir -p {folder} && cd {folder} && export CI=1 NO_COLOR=1 && {command}"
+
+
+class SshShellBackend:
+ """Runs an agent's shell commands inside its workspace on another computer."""
+
+ name: str = "ssh"
+
+ def __init__(self, computer_id: str, agent_id: str, *, workspace: Path) -> None:
+ self._computer_id = computer_id
+ self._agent_id = agent_id
+ self._workspace = Path(workspace)
+
+ def _relative(self, cwd: Path) -> str:
+ try:
+ rel = Path(cwd).resolve().relative_to(self._workspace.resolve())
+ except ValueError:
+ return ""
+ text = rel.as_posix()
+ return "" if text == "." else text
+
+ async def run(self, command: str, *, cwd: Path, timeout_s: float) -> ShellResult:
+ from jarvis.computers.service import ComputerError, get_service
+
+ timeout = max(1.0, min(float(timeout_s or DEFAULT_TIMEOUT_S), MAX_TIMEOUT_S))
+ wrapped = wrap_in_workspace(self._agent_id, command, relative=self._relative(cwd))
+ started = time.perf_counter()
+ try:
+ async with get_service().session(self._computer_id) as opened:
+ from jarvis.computers.ssh import SshError, run_command
+
+ try:
+ result = await run_command(opened, wrapped, timeout_s=timeout)
+ except SshError as exc:
+ if exc.kind == "timeout":
+ return ShellResult(
+ output=f"Command timed out after {int(timeout)} s",
+ exit_code=None,
+ seconds=time.perf_counter() - started,
+ timed_out=True,
+ )
+ raise ComputerError(exc.message, status=502, kind=exc.kind) from exc
+ except ComputerError as exc:
+ log.info("society: remote shell for %s failed: %s", self._agent_id, exc.message)
+ return ShellResult(
+ output=f"Could not reach the agent's computer: {exc.message}",
+ exit_code=None,
+ seconds=time.perf_counter() - started,
+ failed_to_start=True,
+ )
+ text = (result.stdout + (("\n" + result.stderr) if result.stderr else "")).rstrip()
+ return ShellResult(
+ output=_cap(text, OUTPUT_CAP_CHARS),
+ exit_code=result.exit_status,
+ seconds=time.perf_counter() - started,
+ )
+
+
+def backend_for(agent: Any, workspace: Path) -> ShellBackend:
+ """The shell an agent's commands run in: remote when it is placed on a computer."""
+ computer_id = getattr(agent, "computer_id", None)
+ if computer_id:
+ return SshShellBackend(str(computer_id), str(agent.agent_id), workspace=workspace)
+ return default_backend()
+
+
+async def placement_for_session(session: Any) -> tuple[str, str] | None:
+ """``(computer_id, agent_id)`` when a society chat's agent runs elsewhere.
+
+ Society chats are ``society:<agent_id>``; any other surface, an unknown
+ agent or an agent on this computer answers ``None`` (run locally).
+ """
+ if getattr(session, "surface", "") != "society":
+ return None
+ session_id = str(getattr(session, "session_id", "") or "")
+ if not session_id.startswith("society:"):
+ return None
+ agent_id = session_id.split(":", 1)[1]
+ from .runtime import current_runtime
+
+ runtime = current_runtime()
+ if runtime is None:
+ return None
+ agent = await runtime.roster.get(agent_id)
+ computer_id = getattr(agent, "computer_id", None) if agent is not None else None
+ return (str(computer_id), agent_id) if computer_id else None
diff --git a/jarvis/society/roster.py b/jarvis/society/roster.py
index 68b56d42bf..657824dd0c 100644
--- a/jarvis/society/roster.py
+++ b/jarvis/society/roster.py
@@ -119,6 +119,9 @@ class AgentRecord:
created_ms: int
updated_ms: int
stats: dict[str, Any] = field(default_factory=dict)
+ #: Where the agent's work executes: ``None`` = this computer, else the id
+ #: of a connected machine (``jarvis.computers``) reached over SSH.
+ computer_id: str | None = None
@property
def session_id(self) -> str:
@@ -160,6 +163,7 @@ class AgentRecord:
"max_concurrent_runs": self.max_concurrent_runs,
"browser_mode": str(self.browser_mode),
"browser_allowed_domains": list(self.browser_allowed_domains),
+ "computer_id": self.computer_id,
"session_id": self.session_id,
"created_ms": self.created_ms,
"updated_ms": self.updated_ms,
@@ -207,6 +211,7 @@ class AgentRecord:
str(x) for x in _loads(row.get("browser_allowed_domains_json"), [])
],
created_ms=int(row.get("created_ms") or 0),
+ computer_id=str(row["computer_id"]) if row.get("computer_id") else None,
updated_ms=int(row.get("updated_ms") or 0),
)
@@ -239,6 +244,7 @@ _EDITABLE: Final[frozenset[str]] = frozenset(
"max_concurrent_runs",
"browser_mode",
"browser_allowed_domains",
+ "computer_id",
}
)
@@ -289,6 +295,20 @@ def _enum(kind: Any, value: Any, field_name: str) -> str:
) from exc
+def _validate_computer(value: Any) -> str | None:
+ """``None``/empty = this computer; otherwise a connected computer's id."""
+ if value is None or str(value).strip() == "":
+ return None
+ computer_id = str(value).strip()
+ from jarvis.computers.store import ComputerStore
+
+ if ComputerStore().get(computer_id) is None:
+ raise RosterError(
+ FailureReason.TARGET_UNKNOWN, f"computer {computer_id!r} is not connected"
+ )
+ return computer_id
+
+
def _coerce(field_name: str, value: Any) -> Any:
"""Validate one editable field and return its column value."""
if field_name == "name":
@@ -372,6 +392,8 @@ def _coerce(field_name: str, value: Any) -> Any:
return str(value or "")
if field_name == "parent_agent_id":
return str(value) if value else None
+ if field_name == "computer_id":
+ return _validate_computer(value)
raise RosterError(FailureReason.BLOCKED_BY_POLICY, f"unknown field {field_name}")
@@ -423,6 +445,10 @@ class Roster:
return await self._hydrate(existing), False
tier_value = Tier(_enum(Tier, tier, "tier"))
agent_id = slugify(clean_name)
+ if tier_value is Tier.LEAD and fields.get("computer_id"):
+ raise RosterError(
+ FailureReason.TIER_NOT_ALLOWED, "the lead always runs on this computer"
+ )
if tier_value is Tier.LEAD and agent_id != LEAD_AGENT_ID:
raise RosterError(
FailureReason.TIER_NOT_ALLOWED, "exactly one lead exists and it is Jarvis"
@@ -496,6 +522,10 @@ class Roster:
raise RosterError(FailureReason.BLOCKED_BY_POLICY, f"field {key!r} is not editable")
if key == "tier" and agent_id == LEAD_AGENT_ID and str(value) != str(Tier.LEAD):
raise RosterError(FailureReason.TIER_NOT_ALLOWED, "Jarvis stays the lead")
+ if key == "computer_id" and agent_id == LEAD_AGENT_ID and value:
+ raise RosterError(
+ FailureReason.TIER_NOT_ALLOWED, "the lead always runs on this computer"
+ )
if key == "tier" and str(value) == str(Tier.LEAD) and agent_id != LEAD_AGENT_ID:
raise RosterError(FailureReason.TIER_NOT_ALLOWED, "only Jarvis is the lead")
if key == "parent_agent_id" and value:
diff --git a/jarvis/society/society_schema.sql b/jarvis/society/society_schema.sql
index 8b84b21ea1..90e5b9db7e 100644
--- a/jarvis/society/society_schema.sql
+++ b/jarvis/society/society_schema.sql
@@ -44,6 +44,9 @@ CREATE TABLE IF NOT EXISTS society_agents (
CHECK (browser_mode IN ('own', 'attach')),
browser_allowed_domains_json TEXT NOT NULL DEFAULT '[]',
max_concurrent_runs INTEGER NOT NULL DEFAULT 1,
+ -- Where the agent's work executes: NULL = this computer, else the id of a
+ -- connected machine in jarvis/computers (a VPS or a local VM, over SSH).
+ computer_id TEXT DEFAULT NULL,
created_ms INTEGER NOT NULL,
updated_ms INTEGER NOT NULL
);
diff --git a/jarvis/society/store.py b/jarvis/society/store.py
index ade2581973..2e52844fc1 100644
--- a/jarvis/society/store.py
+++ b/jarvis/society/store.py
@@ -135,6 +135,12 @@ class SocietyStore:
"TEXT NOT NULL DEFAULT '[]'"
)
log.info("society store: migration applied — added browser_allowed_domains")
+ if "computer_id" not in existing:
+ # NULL = this computer; every existing agent keeps running here.
+ await self.conn.execute(
+ "ALTER TABLE society_agents ADD COLUMN computer_id TEXT DEFAULT NULL"
+ )
+ log.info("society store: migration applied — added computer_id")
await self._migrate_checkpoint_vocabulary()
async def _migrate_checkpoint_vocabulary(self) -> None:
diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentSpecSheet.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentSpecSheet.tsx
index 5b76f9141b..fc32fb5689 100644
--- a/jarvis/ui/web/frontend/src/components/society/card/AgentSpecSheet.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentSpecSheet.tsx
@@ -31,12 +31,13 @@
* Every string goes through the locale files.
*/
import { useMemo, useState } from "react";
-import { MessageSquare, Pause, Play } from "lucide-react";
+import { MessageSquare, Pause, Play, Server } from "lucide-react";
import { ProviderLogo } from "@/components/providers/ProviderLogo";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Switch } from "@/components/ui/switch";
import { useT } from "@/i18n";
+import { useComputers } from "@/hooks/useComputers";
import { societyDisplayName } from "@/lib/societyDisplayName";
import { cn } from "@/lib/utils";
import { useEventStore } from "@/store/events";
@@ -48,6 +49,7 @@ import { useAgentActivity, useAgentSkills, type AgentActivity } from "../cardDat
import { PERMISSION_CEILINGS } from "@/lib/societyApi";
import {
+ useSetAgentComputer,
useSetAgentPaused,
useSocietyCapabilities,
useUpdateAgentDescription,
@@ -58,6 +60,7 @@ import {
type SocietyAgent,
} from "../data";
import { CapabilityTile } from "./CapabilityTile";
+import { ComputerPicker } from "../create/ComputerPicker";
import { LeadBrain, LeadInstructions } from "./LeadSections";
import "./agentCard.css";
@@ -218,6 +221,10 @@ export function AgentSpecSheet({ agent, onOpenChat, onRetired }: AgentSpecSheetP
const activity = useAgentActivity(agent.agentId);
const skills = useAgentSkills(agent.agentId);
const setPaused = useSetAgentPaused();
+ const computers = useComputers();
+ const remoteComputer = agent.computerId
+ ? (computers.data ?? []).find((c) => c.id === agent.computerId) ?? null
+ : null;
const [busy, setBusy] = useState(false);
const byId = useMemo(() => {
const map = new Map<string, Capability>();
@@ -277,6 +284,16 @@ export function AgentSpecSheet({ agent, onOpenChat, onRetired }: AgentSpecSheetP
.join(" · ")}
</span>
</span>
+ {remoteComputer ? (
+ <span
+ data-testid="agent-remote-badge"
+ title={t("society.card.runs_on_badge").replace("{computer}", remoteComputer.name)}
+ className="inline-flex max-w-[40%] shrink-0 items-center gap-1 rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground"
+ >
+ <Server className="h-3 w-3 shrink-0" aria-hidden />
+ <span className="truncate">{remoteComputer.name}</span>
+ </span>
+ ) : null}
<span className={cn("ac-dot", STATE_FILL[agent.state])} data-state={agent.state} aria-hidden />
<span className="shrink-0 text-xs text-muted-foreground">
{activeRuns > 0
@@ -349,6 +366,8 @@ export function AgentSpecSheet({ agent, onOpenChat, onRetired }: AgentSpecSheetP
</section>
) : null}
+ {agent.tier !== "lead" && <RunsOnSection agent={agent} />}
+
<LimitsSection
agent={agent}
reachFilled={reachFilled}
@@ -769,3 +788,34 @@ function RuleRow({ label, ids, byId }: { label: string; ids: string[]; byId: Map
</div>
);
}
+
+/**
+ * Where the agent's work executes — this computer or a connected one. The
+ * change applies from the agent's next turn; a turn already running finishes
+ * where it started.
+ */
+function RunsOnSection({ agent }: { agent: SocietyAgent }) {
+ const t = useT();
+ const setComputer = useSetAgentComputer();
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState("");
+ return (
+ <section className="flex flex-col gap-2" data-testid="agent-runs-on">
+ <ComputerPicker
+ value={agent.computerId ?? ""}
+ labelClass="ac-head mb-1 block"
+ testId="agent-runs-on-picker"
+ onChange={(id) => {
+ if (saving || id === (agent.computerId ?? "")) return;
+ setSaving(true);
+ setError("");
+ setComputer(agent, id)
+ .catch((err: unknown) => setError(err instanceof Error ? err.message : String(err)))
+ .finally(() => setSaving(false));
+ }}
+ />
+ {error ? <p role="alert" className="text-xs text-destructive">{error}</p> : null}
+ {saving ? <p className="text-xs text-muted-foreground">{t("society.card.runs_on_saving")}</p> : null}
+ </section>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/create/ComputerPicker.tsx b/jarvis/ui/web/frontend/src/components/society/create/ComputerPicker.tsx
new file mode 100644
index 0000000000..a4e241f5aa
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/create/ComputerPicker.tsx
@@ -0,0 +1,91 @@
+/**
+ * "Runs on" — where an agent's work executes: this computer, or one of the
+ * machines connected in the Computers section (a VPS, a local VM). The value
+ * is a computer id; "" means this computer. Shared by the create dialog and
+ * the agent's spec sheet so the two can never offer different choices.
+ */
+import { Monitor, Server } from "lucide-react";
+import { Combobox } from "@/components/ui/combobox";
+import { useComputers } from "@/hooks/useComputers";
+import { useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import { useEventStore } from "@/store/events";
+import type { Computer } from "@/lib/computersApi";
+
+function Dot({ computer }: { computer: Computer }) {
+ const status = computer.health.status;
+ return (
+ <span className="relative inline-flex h-4 w-4 items-center justify-center" aria-hidden>
+ <Server className="h-3.5 w-3.5 text-muted-foreground" />
+ <span
+ className={cn(
+ "absolute -bottom-0.5 -right-0.5 h-1.5 w-1.5 rounded-full",
+ status === "online" ? "bg-success" : status === "unknown" ? "bg-foreground-faint" : "bg-warning",
+ )}
+ />
+ </span>
+ );
+}
+
+export function ComputerPicker({
+ value,
+ onChange,
+ labelClass,
+ testId = "society-computer-picker",
+}: {
+ value: string;
+ onChange: (computerId: string) => void;
+ labelClass?: string;
+ testId?: string;
+}) {
+ const t = useT();
+ const computers = useComputers();
+ const setActiveSection = useEventStore((s) => s.setActiveSection);
+ const rows = computers.data ?? [];
+ const chosen = rows.find((c) => c.id === value);
+
+ return (
+ <div data-testid={testId}>
+ <span className={labelClass}>{t("society.create.runs_on")}</span>
+ <Combobox
+ value={value}
+ groups={[
+ {
+ id: "computers",
+ options: [
+ {
+ value: "",
+ label: t("society.create.runs_on_here"),
+ icon: <Monitor className="h-3.5 w-3.5 text-muted-foreground" />,
+ },
+ ...rows.map((c) => ({
+ value: c.id,
+ label: c.name,
+ hint: `${c.username}@${c.host}`,
+ icon: <Dot computer={c} />,
+ })),
+ ],
+ },
+ ]}
+ onChange={onChange}
+ ariaLabel={t("society.create.runs_on")}
+ />
+ <p className="mt-1 text-xs text-muted-foreground">
+ {chosen
+ ? chosen.health.status === "online"
+ ? t("society.create.runs_on_remote_hint")
+ : t("society.create.runs_on_offline_hint")
+ : t("society.create.runs_on_here_hint")}{" "}
+ {rows.length === 0 && (
+ <button
+ type="button"
+ onClick={() => setActiveSection("computers")}
+ className="text-accent underline-offset-4 hover:underline"
+ >
+ {t("society.create.runs_on_connect")}
+ </button>
+ )}
+ </p>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx b/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx
index 57e26d0470..37539bfbb3 100644
--- a/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx
@@ -37,6 +37,7 @@ import { Switch } from "@/components/ui/switch";
import { Combobox, isComboboxPanelEvent, type ComboboxGroup } from "@/components/ui/combobox";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useT } from "@/i18n";
+import { ComputerPicker } from "./ComputerPicker";
import {
fetchAgentChatCatalog,
fetchAgentConnections,
@@ -128,6 +129,8 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialo
const [model, setModel] = useState("");
const [effort, setEffort] = useState("");
const [accountId, setAccountId] = useState("");
+ // "" = this computer; otherwise a connected computer (VPS / local VM) id.
+ const [computerId, setComputerId] = useState("");
const [ceiling, setCeiling] = useState<PermissionCeiling>("monitor");
const [budget, setBudget] = useState("2");
// A cap is the default because an agent that can spend without one is the
@@ -366,6 +369,7 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialo
model,
effort,
accountId,
+ computerId,
// Every tool Jarvis has connected; what the agent reaches for first
// is settled in its own chat afterwards (maintainer, 2026-09-02).
grantMode: "all",
@@ -569,6 +573,8 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialo
<p className="mt-1 text-xs text-muted-foreground">{t("society.create.brain_hint")}</p>
</div>
+ <ComputerPicker value={computerId} onChange={setComputerId} labelClass={labelClass} />
+
<Collapsible.Root open={advanced} onOpenChange={setAdvanced}>
<Collapsible.Trigger asChild>
<button
diff --git a/jarvis/ui/web/frontend/src/components/society/data.ts b/jarvis/ui/web/frontend/src/components/society/data.ts
index 153fe6907f..4938e0eaa7 100644
--- a/jarvis/ui/web/frontend/src/components/society/data.ts
+++ b/jarvis/ui/web/frontend/src/components/society/data.ts
@@ -100,6 +100,8 @@ export interface SocietyAgent {
effort: string;
/** Stored subscription login; empty means the platform's active account. */
accountId?: string;
+ /** Where the agent runs: null/absent = this computer, else a connected computer id. */
+ computerId?: string | null;
/** The character: archetype, base, parts, palette. null = the palette tile. */
figure: FigureRecipe | null;
palette: AgentPalette;
@@ -144,6 +146,8 @@ export interface NewAgentInput {
effort: string;
/** The stored subscription login of a CLI seat; "" = that platform's active account. */
accountId: string;
+ /** "" = this computer; otherwise the connected computer the agent runs on. */
+ computerId: string;
grantMode: GrantMode;
toolGrants: string[];
focus: string[];
@@ -220,6 +224,7 @@ export function rowToAgent(row: SocietyAgentRow): SocietyAgent {
providerLabel: row.provider ? (PROVIDER_LABELS[row.provider] ?? row.provider) : "",
model: row.model,
accountId: row.account_id,
+ computerId: row.computer_id ?? null,
effort: row.effort,
figure,
palette: paletteFor(figure),
@@ -374,6 +379,7 @@ export function useCreateAgent() {
model: input.model || undefined,
effort: input.effort || undefined,
account_id: input.accountId || undefined,
+ computer_id: input.computerId || undefined,
avatar: input.figure,
grant_mode: input.grantMode,
grants: input.grantMode === "allowlist" ? input.toolGrants : undefined,
@@ -561,6 +567,33 @@ export function useUpdateAgentLimits() {
);
}
+/** Move an agent to another computer (`PATCH computer_id`); "" = this computer. */
+export function useSetAgentComputer() {
+ const client = useQueryClient();
+ return useCallback(
+ async (agent: SocietyAgent, computerId: string): Promise<void> => {
+ const sample = SAMPLE_ROSTER.includes(agent) || LOCAL_ROSTER.includes(agent);
+ if (sample) {
+ agent.computerId = computerId || null;
+ } else {
+ const res = await fetch(`/api/society/agents/${encodeURIComponent(agent.agentId)}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ computer_id: computerId }),
+ });
+ if (!res.ok) {
+ const detail = (await res.json().catch(() => null)) as { detail?: unknown } | null;
+ const inner = detail?.detail as { detail?: unknown } | string | undefined;
+ const message = typeof inner === "string" ? inner : typeof inner?.detail === "string" ? inner.detail : "";
+ throw new Error(message || `computer ${res.status}`);
+ }
+ }
+ await client.invalidateQueries({ queryKey: ROSTER_QUERY_KEY });
+ },
+ [client],
+ );
+}
+
/** Pause or resume an agent (`PATCH /api/society/agents/{id}`); sample rows flip locally. */
export function useSetAgentPaused() {
const client = useQueryClient();
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index f6e78b683f..89047f74df 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -5410,6 +5410,8 @@
"hub:models": "Kesselhaus"
},
"card": {
+ "runs_on_saving": "Wird verschoben…",
+ "runs_on_badge": "Läuft auf {computer}",
"brain_shared_hint": "Das Gehirn des getippten Chats, gewählt an der Modell-Pille im Chat. Sprache läuft über das Realtime-Gehirn aus den Sprach-Einstellungen.",
"instructions_file": "Ständige Anweisungen ({0})",
"instructions_empty": "Noch keine ständigen Anweisungen — die Vorlage ist einen Klick entfernt.",
@@ -5563,6 +5565,12 @@
"shoes": "Schuhe"
},
"create": {
+ "runs_on": "Läuft auf",
+ "runs_on_here": "Dieser Computer",
+ "runs_on_here_hint": "Der Agent arbeitet auf diesem Computer.",
+ "runs_on_remote_hint": "Befehle und Coding-CLI des Agenten laufen per SSH auf diesem Computer; {name} behält den Chat hier.",
+ "runs_on_offline_hint": "Dieser Computer ist gerade nicht erreichbar; Läufe des Agenten scheitern, bis er wieder online ist.",
+ "runs_on_connect": "Computer verbinden",
"import": ".glb importieren",
"importing": "Wird geprüft…",
"import_hint": "Bring deine eigene Figur mit — ein binäres glTF, das den Figurenvertrag einhält (docs/agent-society/character-pipeline.md).",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 048612f4a9..e9be9b255a 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -5443,6 +5443,8 @@
"hub:models": "Boiler House"
},
"card": {
+ "runs_on_saving": "Moving…",
+ "runs_on_badge": "Runs on {computer}",
"brain_shared_hint": "The brain of the typed chat, picked in the chat's model pill. Voice runs on the realtime brain from the voice settings.",
"instructions_file": "Standing instructions ({0})",
"instructions_empty": "No standing instructions yet — the template is a click away.",
@@ -5596,6 +5598,12 @@
"shoes": "Shoes"
},
"create": {
+ "runs_on": "Runs on",
+ "runs_on_here": "This computer",
+ "runs_on_here_hint": "The agent works on this computer.",
+ "runs_on_remote_hint": "The agent’s commands and coding CLI run on that computer over SSH; {name} keeps the chat here.",
+ "runs_on_offline_hint": "That computer is not reachable right now; the agent’s runs fail until it is back online.",
+ "runs_on_connect": "Connect a computer",
"import": "Import .glb",
"importing": "Checking…",
"import_hint": "Bring your own figure — a binary glTF that honours the character contract (docs/agent-society/character-pipeline.md).",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index ccb381401c..3fa50bb844 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -5410,6 +5410,8 @@
"hub:models": "Sala de Calderas"
},
"card": {
+ "runs_on_saving": "Moviendo…",
+ "runs_on_badge": "Se ejecuta en {computer}",
"brain_shared_hint": "El cerebro del chat escrito, elegido en la píldora de modelo del chat. La voz usa el cerebro en tiempo real de los ajustes de voz.",
"instructions_file": "Instrucciones permanentes ({0})",
"instructions_empty": "Aún no hay instrucciones permanentes; la plantilla está a un clic.",
@@ -5563,6 +5565,12 @@
"shoes": "Zapatos"
},
"create": {
+ "runs_on": "Se ejecuta en",
+ "runs_on_here": "Este ordenador",
+ "runs_on_here_hint": "El agente trabaja en este ordenador.",
+ "runs_on_remote_hint": "Los comandos y la CLI de programación del agente se ejecutan en ese ordenador por SSH; {name} mantiene el chat aquí.",
+ "runs_on_offline_hint": "Ese ordenador no está accesible ahora; las ejecuciones del agente fallarán hasta que vuelva a estar en línea.",
+ "runs_on_connect": "Conectar un ordenador",
"import": "Importar .glb",
"importing": "Comprobando…",
"import_hint": "Trae tu propia figura: un glTF binario que cumpla el contrato de personajes (docs/agent-society/character-pipeline.md).",
diff --git a/jarvis/ui/web/frontend/src/lib/societyApi.ts b/jarvis/ui/web/frontend/src/lib/societyApi.ts
index af7dff9919..122995c6db 100644
--- a/jarvis/ui/web/frontend/src/lib/societyApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/societyApi.ts
@@ -160,6 +160,8 @@ export interface SocietyAgentRow {
max_concurrent_runs: number;
browser_mode: BrowserMode;
browser_allowed_domains: string[];
+ /** Where the agent runs: null = this computer, else a connected computer id. */
+ computer_id: string | null;
session_id: string;
created_ms: number;
updated_ms: number;
diff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.py
index 5792f8ba22..f22043798b 100644
--- a/jarvis/ui/web/society_routes.py
+++ b/jarvis/ui/web/society_routes.py
@@ -93,6 +93,8 @@ class CreateAgentBody(BaseModel):
avatar: dict[str, Any] | None = None
browser_mode: str | None = None
browser_allowed_domains: list[str] | None = None
+ #: Where the agent runs: "" = this computer, else a connected computer id.
+ computer_id: str | None = None
class PatchAgentBody(BaseModel):
@@ -120,6 +122,8 @@ class PatchAgentBody(BaseModel):
checkpoint: str | None = None
browser_mode: str | None = None
browser_allowed_domains: list[str] | None = None
+ #: Where the agent runs: "" = this computer, else a connected computer id.
+ computer_id: str | None = None
class MessageBody(BaseModel):
diff --git a/tests/fakes/fake_ssh_server.py b/tests/fakes/fake_ssh_server.py
index faf1490e15..52cfbcd4b5 100644
--- a/tests/fakes/fake_ssh_server.py
+++ b/tests/fakes/fake_ssh_server.py
@@ -11,6 +11,7 @@ and key installation end to end on every OS.
from __future__ import annotations
import re
+from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
from typing import Any
@@ -55,6 +56,10 @@ class FakeSshState:
username: str = "root"
authorized: set[str] = field(default_factory=set)
commands: list[str] = field(default_factory=list)
+ #: Optional scripted command handler: return True when it answered the
+ #: process (wrote output and called ``exit``); False falls through to the
+ #: built-in behaviour. Lets a test play a remote CLI or a shell.
+ handler: Callable[[str, Any], Awaitable[bool]] | None = None
def _key_body(line: str) -> str:
@@ -96,6 +101,8 @@ class FakeSshServer:
async def _process(self, process: asyncssh.SSHServerProcess) -> None:
command = process.command or ""
self.state.commands.append(command)
+ if self.state.handler is not None and await self.state.handler(command, process):
+ return
if command == PROBE_SCRIPT:
process.stdout.write(LINUX_PROBE_OUTPUT)
process.exit(0)
diff --git a/tests/unit/society/test_remote_placement.py b/tests/unit/society/test_remote_placement.py
new file mode 100644
index 0000000000..2b424ff33b
--- /dev/null
+++ b/tests/unit/society/test_remote_placement.py
@@ -0,0 +1,316 @@
+"""A society agent placed on another computer: data, shell and CLI over SSH.
+
+Runs against the real in-process SSH server (``tests/fakes/fake_ssh_server``):
+the roster stores and validates ``computer_id``, the agent's shell commands
+run inside ``~/jarvis-agents/<agent>`` on that machine, and a CLI turn is
+started there with a rewritten argv and read back line by line.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.agent_chat import remote_cli
+from jarvis.computers import identity, service
+from jarvis.computers.service import ComputerService
+from jarvis.computers.store import ComputerStore
+from jarvis.society import remote
+from jarvis.society.failure_reasons import FailureReason
+from jarvis.society.roster import Roster, RosterError
+from jarvis.society.runtime import SocietyRuntime
+from jarvis.society.store import SocietyStore
+from jarvis.ui.web.society_routes import router
+from tests.fakes.fake_ssh_server import TEST_PASSWORD, FakeSshServer
+
+
+class _SecretBox:
+ def __init__(self) -> None:
+ self.values: dict[str, str] = {}
+
+ def get(self, key: str, env_fallback: str | None = None) -> str | None:
+ return self.values.get(key)
+
+ def set(self, key: str, value: str) -> bool:
+ self.values[key] = value
+ return True
+
+ def delete(self, key: str) -> bool:
+ self.values.pop(key, None)
+ return True
+
+
+def computers(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> ComputerService:
+ """A sandboxed Computers service shared by the roster check and the SSH path."""
+ box = _SecretBox()
+ for module in (identity, service):
+ monkeypatch.setattr(module, "get_secret", box.get)
+ monkeypatch.setattr(module, "set_secret", box.set)
+ if hasattr(module, "delete_secret"):
+ monkeypatch.setattr(module, "delete_secret", box.delete)
+ path = tmp_path / "computers.json"
+ monkeypatch.setattr("jarvis.computers.store.default_path", lambda: path)
+ svc = ComputerService(ComputerStore(path))
+ monkeypatch.setattr(service, "_SERVICE", svc)
+ return svc
+
+
+async def ssh_server(): # noqa: ANN201
+ server = FakeSshServer()
+ await server.start()
+ try:
+ yield server
+ finally:
+ await server.stop()
+
+
+async def vps(computers: ComputerService, ssh_server: FakeSshServer): # noqa: ANN201
+ return await computers.add_server(
+ name="VPS", host="127.0.0.1", port=ssh_server.port, auth="password", password=TEST_PASSWORD
+ )
+
+
+async def roster(tmp_path: Path): # noqa: ANN201
+ store = SocietyStore(tmp_path / "society.db")
+ await store.open()
+ try:
+ yield Roster(store)
+ finally:
+ await store.close()
+
+
+# -- data -----------------------------------------------------------------------
+
+
+async def test_computer_id_round_trips_and_clears(roster: Roster, vps) -> None: # noqa: ANN001
+ scout, _ = await roster.create(name="Scout", computer_id=vps.id)
+ assert scout.computer_id == vps.id
+ assert scout.to_dict()["computer_id"] == vps.id
+
+ again = await roster.get("scout")
+ assert again is not None and again.computer_id == vps.id
+
+ moved = await roster.update("scout", {"computer_id": ""})
+ assert moved.computer_id is None
+
+
+async def test_unknown_computer_is_refused(roster: Roster, computers) -> None: # noqa: ANN001
+ with pytest.raises(RosterError) as caught:
+ await roster.create(name="Scout", computer_id="c_nope")
+ assert caught.value.reason is FailureReason.TARGET_UNKNOWN
+
+
+async def test_the_lead_always_stays_here(roster: Roster, vps) -> None: # noqa: ANN001
+ await roster.list() # seeds nothing, but the lead can be created explicitly
+ lead, _ = await roster.create(name="Jarvis", tier="lead")
+ with pytest.raises(RosterError):
+ await roster.update(lead.agent_id, {"computer_id": vps.id})
+
+
+def test_create_route_validates_the_computer(tmp_path: Path, computers) -> None: # noqa: ANN001
+ runtime = SocietyRuntime(
+ tmp_path,
+ seed_starter_team=False,
+ mission_manager=lambda: None,
+ mission_bus=lambda: SimpleNamespace(subscribe_all=lambda h: lambda: None),
+ brain_tools=dict,
+ )
+ app = FastAPI()
+ app.include_router(router)
+ app.state.society = None
+ app.state.society_factory = lambda: runtime
+ with TestClient(app) as client:
+ try:
+ refused = client.post(
+ "/api/society/agents", json={"name": "Scout", "computer_id": "c_x"}
+ )
+ assert refused.status_code == 404
+ local = client.post("/api/society/agents", json={"name": "Scout"})
+ assert local.json()["agent"]["computer_id"] is None
+ finally:
+ assert client.portal is not None
+ client.portal.call(runtime.close)
+
+
+# -- shell ------------------------------------------------------------------------
+
+
+async def test_shell_runs_inside_the_remote_workspace(
+ tmp_path: Path, vps, ssh_server: FakeSshServer
+) -> None: # noqa: ANN001
+ async def handler(command: str, process: Any) -> bool:
+ if command.startswith("mkdir -p"):
+ process.stdout.write("hello from the vps\n")
+ process.stderr.write("a warning\n")
+ process.exit(0)
+ return True
+ return False
+
+ ssh_server.state.handler = handler
+ workspace = tmp_path / "ws"
+ (workspace / "sub").mkdir(parents=True)
+ agent = SimpleNamespace(agent_id="scout", computer_id=vps.id)
+ backend = remote.backend_for(agent, workspace)
+ assert backend.name == "ssh"
+
+ result = await backend.run("ls -la", cwd=workspace / "sub", timeout_s=30)
+
+ assert result.ok
+ assert "hello from the vps" in result.output and "a warning" in result.output
+ sent = ssh_server.state.commands[-1]
+ assert '"$HOME"/jarvis-agents/scout/sub' in sent
+ assert sent.endswith("&& ls -la")
+
+
+async def test_shell_reports_an_unreachable_computer(tmp_path: Path, computers) -> None: # noqa: ANN001
+ gone = await computers.add_server(name="Gone", host="127.0.0.1", port=1)
+ backend = remote.SshShellBackend(gone.id, "scout", workspace=tmp_path)
+
+ result = await backend.run("true", cwd=tmp_path, timeout_s=10)
+
+ assert result.failed_to_start and "Could not reach" in result.output
+
+
+def test_local_agents_keep_the_local_shell(tmp_path: Path) -> None:
+ agent = SimpleNamespace(agent_id="scout", computer_id=None)
+ assert remote.backend_for(agent, tmp_path).name == "local"
+
+
+# -- CLI ----------------------------------------------------------------------------
+
+
+def test_argv_is_rewritten_for_the_remote_machine() -> None:
+ argv = [
+ "node",
+ r"C:\npm\node_modules\@anthropic-ai\claude-code\cli.js",
+ "--print",
+ "--mcp-config",
+ '{"mcpServers": {}}',
+ "--append-system-prompt-file",
+ r"C:\tmp\identity.md",
+ "exec",
+ "--cd",
+ r"C:\data\society\scout\workspace",
+ "-c",
+ 'mcp_servers.jarvis.url="http://127.0.0.1:47821"',
+ "-c",
+ 'sandbox_mode="workspace-write"',
+ ]
+ out = remote_cli.remote_argv(
+ argv,
+ binary="claude",
+ local_cwd=r"C:\data\society\scout\workspace",
+ remote_cwd="/root/jarvis-agents/scout",
+ system_prompt_files={r"C:\tmp\identity.md": "You are Scout."},
+ )
+ assert out == [
+ "claude",
+ "--print",
+ "--append-system-prompt",
+ "You are Scout.",
+ "exec",
+ "--cd",
+ "/root/jarvis-agents/scout",
+ "-c",
+ 'sandbox_mode="workspace-write"',
+ ]
+
+
+def test_remote_env_carries_no_local_secrets() -> None:
+ env = remote_cli.remote_env(
+ {"ANTHROPIC_API_KEY": "sk-x", "CLAUDE_CONFIG_DIR": r"C:\x", "NO_COLOR": "1"}
+ )
+ assert env == {"NO_COLOR": "1", "CI": "1"}
+
+
+async def test_cli_turn_streams_from_the_remote_process(vps, ssh_server: FakeSshServer) -> None: # noqa: ANN001
+ async def handler(command: str, process: Any) -> bool:
+ if "command -v" in command:
+ process.stdout.write("/root/jarvis-agents/scout\nfound\n")
+ process.exit(0)
+ return True
+ if "exec env" in command:
+ prompt = await process.stdin.readline()
+ process.stdout.write(json.dumps({"type": "echo", "got": prompt.strip()}) + "\n")
+ process.stdout.write(json.dumps({"type": "result", "result": "done"}) + "\n")
+ process.exit(0)
+ return True
+ return False
+
+ ssh_server.state.handler = handler
+ proc = await remote_cli.spawn(
+ vps.id,
+ agent_id="scout",
+ runner="claude-cli",
+ binary="claude",
+ argv=[r"C:\bin\claude.exe", "--print", "--output-format", "stream-json"],
+ local_cwd=r"C:\ws",
+ env={"PATH": r"C:\secret-path"},
+ )
+ proc.stdin.write(b"hello there\n")
+ await proc.stdin.drain()
+ first = json.loads(await proc.stdout.readline())
+ second = json.loads(await proc.stdout.readline())
+ proc.stdin.close()
+ code = await proc.wait()
+
+ assert first == {"type": "echo", "got": "hello there"}
+ assert second["type"] == "result"
+ assert code == 0
+ launched = ssh_server.state.commands[-1]
+ assert "cd /root/jarvis-agents/scout && exec env CI=1 NO_COLOR=1 claude --print" in launched
+ assert "secret-path" not in launched
+
+
+async def test_missing_cli_on_the_remote_is_a_clear_sentence(
+ vps, ssh_server: FakeSshServer
+) -> None: # noqa: ANN001
+ async def handler(command: str, process: Any) -> bool:
+ if "command -v" in command:
+ process.stdout.write("/root/jarvis-agents/scout\nmissing\n")
+ process.exit(0)
+ return True
+ return False
+
+ ssh_server.state.handler = handler
+ with pytest.raises(remote_cli.RemoteCliUnavailable) as caught:
+ await remote_cli.spawn(
+ vps.id,
+ agent_id="scout",
+ runner="codex-cli",
+ binary="codex",
+ argv=["codex", "exec"],
+ local_cwd="/work",
+ env={},
+ )
+ assert "Install codex on VPS" in str(caught.value)
+
+
+async def test_placement_follows_the_society_roster(monkeypatch: pytest.MonkeyPatch) -> None:
+ agents = {
+ "scout": SimpleNamespace(computer_id="c_1"),
+ "here": SimpleNamespace(computer_id=None),
+ }
+
+ async def get(agent_id: str) -> Any:
+ return agents.get(agent_id)
+
+ fake_runtime = SimpleNamespace(roster=SimpleNamespace(get=get))
+ monkeypatch.setattr("jarvis.society.runtime.current_runtime", lambda: fake_runtime)
+
+ def chat(surface: str, sid: str) -> SimpleNamespace:
+ return SimpleNamespace(surface=surface, session_id=sid)
+
+ assert await remote.placement_for_session(chat("society", "society:scout")) == ("c_1", "scout")
+ assert await remote.placement_for_session(chat("society", "society:here")) is None
+ assert await remote.placement_for_session(chat("jarvis", "society:scout")) is None