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(computers): connect servers and local VMs over SSH

rubenluetke10-beep33fc850b7e51
diff --git a/jarvis/computers/__init__.py b/jarvis/computers/__init__.py
new file mode 100644
index 0000000000..670b178078
--- /dev/null
+++ b/jarvis/computers/__init__.py
@@ -0,0 +1,22 @@
+"""Computers: the user's own servers and virtual machines, reachable over SSH.
+
+The Settings -> Computers section registers machines Jarvis may work on — a
+rented VPS (Hostinger, Hetzner, DigitalOcean or any SSH host) or a local
+virtual machine Jarvis creates itself through Multipass. This package is the
+foundation later features build on: every machine is one :class:`Computer`
+record, reachable through :func:`jarvis.computers.service.get_service`.
+
+Layout:
+
+* :mod:`.models` — the records (Computer, facts, health).
+* :mod:`.store` — the JSON file the records live in (atomic writes).
+* :mod:`.identity` — Jarvis's own SSH key pair (private half in the keyring).
+* :mod:`.probe` — the one read-only shell script a health check runs.
+* :mod:`.ssh` — connect / run / install-key over ``asyncssh``.
+* :mod:`.cloud` — import servers from a hosting account's API.
+* :mod:`.local_vm` — create and drive local VMs through Multipass.
+* :mod:`.service` — the orchestration the REST routes call.
+
+Secrets never touch the JSON file: the private key, a kept password and the
+hosting-account tokens go through ``get_secret`` / ``set_secret`` (AP-12).
+"""
diff --git a/jarvis/computers/cloud.py b/jarvis/computers/cloud.py
new file mode 100644
index 0000000000..cde3701a82
--- /dev/null
+++ b/jarvis/computers/cloud.py
@@ -0,0 +1,401 @@
+"""Import servers from a hosting account: Hostinger, Hetzner Cloud, DigitalOcean.
+
+The user saves one API token per provider (keyring, never ``jarvis.toml``);
+Jarvis lists the account's servers so adding one is a click instead of copying
+an IP. Hostinger can also plant Jarvis's public key on an existing VM through
+its API — no password ever needed. Hetzner and DigitalOcean only accept keys
+when a server is created, so an imported server there finishes with a one-time
+password step or a pasted key.
+
+Provider error bodies never leave this module (AP-34): a failure becomes a
+sentence chosen from the HTTP status alone.
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import asdict, dataclass
+from typing import Any, Final, Literal
+
+from jarvis.core.config import delete_secret, get_secret, set_secret
+from jarvis.core.http_pool import HttpClientPool
+
+log = logging.getLogger(__name__)
+
+CloudProviderId = Literal["hostinger", "hetzner", "digitalocean"]
+
+_POOL = HttpClientPool(timeout_s=20.0)
+_MAX_PAGES = 20
+
+
+@dataclass(frozen=True)
+class CloudProvider:
+ id: CloudProviderId
+ name: str
+ keyring_slot: str
+ env_var: str
+ console_url: str
+ setup_hint: str
+ #: True when Jarvis can put its key on an EXISTING server through the API.
+ attaches_keys: bool
+ base_url: str
+
+
+PROVIDERS: Final[dict[CloudProviderId, CloudProvider]] = {
+ "hostinger": CloudProvider(
+ id="hostinger",
+ name="Hostinger",
+ keyring_slot="hostinger_api_token",
+ env_var="HOSTINGER_API_TOKEN",
+ console_url="https://hpanel.hostinger.com/profile/api",
+ setup_hint="hPanel -> Profile -> API -> New token",
+ attaches_keys=True,
+ base_url="https://developers.hostinger.com",
+ ),
+ "hetzner": CloudProvider(
+ id="hetzner",
+ name="Hetzner Cloud",
+ keyring_slot="hetzner_api_token",
+ env_var="HCLOUD_TOKEN",
+ console_url="https://console.hetzner.cloud/",
+ setup_hint="Console -> your project -> Security -> API tokens (Read is enough)",
+ attaches_keys=False,
+ base_url="https://api.hetzner.cloud",
+ ),
+ "digitalocean": CloudProvider(
+ id="digitalocean",
+ name="DigitalOcean",
+ keyring_slot="digitalocean_api_token",
+ env_var="DIGITALOCEAN_TOKEN",
+ console_url="https://cloud.digitalocean.com/account/api/tokens",
+ setup_hint="Control panel -> API -> Tokens (scope droplet:read)",
+ attaches_keys=False,
+ base_url="https://api.digitalocean.com",
+ ),
+}
+
+
+class CloudError(Exception):
+ """A provider call failed; ``message`` is safe to show the user."""
+
+ def __init__(self, message: str, *, status: int | None = None) -> None:
+ super().__init__(message)
+ self.message = message
+ self.status = status
+
+
+@dataclass(frozen=True)
+class CloudServer:
+ """One server as the provider lists it."""
+
+ id: str
+ name: str
+ host: str | None
+ status: str
+ running: bool
+ os: str | None
+ plan: str | None
+ region: str | None
+ cpus: int | None
+ memory_mb: int | None
+ disk_gb: float | None
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+# -- tokens ------------------------------------------------------------------
+
+
+def provider(provider_id: str) -> CloudProvider:
+ if provider_id not in PROVIDERS:
+ raise CloudError(f"Unknown provider: {provider_id}")
+ return PROVIDERS[provider_id] # type: ignore[index]
+
+
+def token(provider_id: str) -> str | None:
+ spec = provider(provider_id)
+ return get_secret(spec.keyring_slot, env_fallback=spec.env_var)
+
+
+def save_token(provider_id: str, value: str) -> None:
+ spec = provider(provider_id)
+ if not set_secret(spec.keyring_slot, value.strip()):
+ raise CloudError("The token could not be saved to the keyring.")
+
+
+def forget_token(provider_id: str) -> None:
+ spec = provider(provider_id)
+ if not delete_secret(spec.keyring_slot):
+ raise CloudError("The token could not be removed from the keyring.")
+
+
+# -- HTTP --------------------------------------------------------------------
+
+
+def _status_message(spec: CloudProvider, status: int) -> str:
+ if status in (401, 403):
+ return f"{spec.name} refused the API token. Create a new one and save it again."
+ if status == 404:
+ return f"{spec.name} does not know this server any more."
+ if status == 429:
+ return f"{spec.name} is rate-limiting requests. Try again in a minute."
+ if status >= 500:
+ return f"{spec.name} is having trouble right now (HTTP {status})."
+ return f"{spec.name} rejected the request (HTTP {status})."
+
+
+async def _request(
+ spec: CloudProvider,
+ api_token: str,
+ method: str,
+ path: str,
+ *,
+ params: dict[str, Any] | None = None,
+ body: dict[str, Any] | None = None,
+ client: Any | None = None,
+) -> Any:
+ import httpx
+
+ http = client if client is not None else _POOL.client()
+ url = path if path.startswith("http") else f"{spec.base_url}{path}"
+ try:
+ response = await http.request(
+ method,
+ url,
+ params=params,
+ json=body,
+ headers={"Authorization": f"Bearer {api_token}", "Accept": "application/json"},
+ )
+ except httpx.TimeoutException as exc:
+ raise CloudError(f"{spec.name} did not answer in time.") from exc
+ except httpx.HTTPError as exc:
+ raise CloudError(f"{spec.name} could not be reached.") from exc
+ if response.status_code >= 400:
+ # The body may echo the token or account details: log the status only.
+ log.info("computers: %s %s -> HTTP %s", spec.id, path, response.status_code)
+ raise CloudError(_status_message(spec, response.status_code), status=response.status_code)
+ if not response.content:
+ return None
+ try:
+ return response.json()
+ except ValueError as exc:
+ raise CloudError(f"{spec.name} sent an answer Jarvis cannot read.") from exc
+
+
+# -- parsers (pure; covered by unit tests) ------------------------------------
+
+
+def _as_int(value: Any) -> int | None:
+ try:
+ return int(value) if value is not None else None
+ except (TypeError, ValueError): # a missing number is shown as unknown
+ return None
+
+
+def parse_hostinger(vms: Any, data_centers: dict[int, str] | None = None) -> list[CloudServer]:
+ servers: list[CloudServer] = []
+ for vm in vms if isinstance(vms, list) else []:
+ if not isinstance(vm, dict) or vm.get("id") is None:
+ continue
+ ipv4 = vm.get("ipv4") or []
+ host = next(
+ (ip.get("address") for ip in ipv4 if isinstance(ip, dict) and ip.get("address")),
+ None,
+ )
+ template = vm.get("template") or {}
+ disk_mb = _as_int(vm.get("disk"))
+ dc_id = _as_int(vm.get("data_center_id"))
+ state = str(vm.get("state") or "unknown")
+ servers.append(
+ CloudServer(
+ id=str(vm["id"]),
+ name=str(vm.get("hostname") or f"vps-{vm['id']}"),
+ host=host,
+ status=state,
+ running=state == "running",
+ os=template.get("name") if isinstance(template, dict) else None,
+ plan=vm.get("plan"),
+ region=(data_centers or {}).get(dc_id) if dc_id is not None else None,
+ cpus=_as_int(vm.get("cpus")),
+ memory_mb=_as_int(vm.get("memory")),
+ disk_gb=round(disk_mb / 1024, 1) if disk_mb else None,
+ )
+ )
+ return servers
+
+
+def parse_hetzner(payload: Any) -> list[CloudServer]:
+ servers: list[CloudServer] = []
+ for row in (payload or {}).get("servers", []) if isinstance(payload, dict) else []:
+ public = (row.get("public_net") or {}).get("ipv4") or {}
+ server_type = row.get("server_type") or {}
+ location = row.get("location") or {}
+ image = row.get("image") or {}
+ memory_gb = server_type.get("memory")
+ status = str(row.get("status") or "unknown")
+ servers.append(
+ CloudServer(
+ id=str(row.get("id")),
+ name=str(row.get("name") or row.get("id")),
+ host=public.get("ip"),
+ status=status,
+ running=status == "running",
+ os=image.get("description") or image.get("name"),
+ plan=server_type.get("name"),
+ region=location.get("city") or location.get("name"),
+ cpus=_as_int(server_type.get("cores")),
+ memory_mb=int(float(memory_gb) * 1024) if memory_gb is not None else None,
+ disk_gb=float(server_type["disk"]) if server_type.get("disk") is not None else None,
+ )
+ )
+ return servers
+
+
+def parse_digitalocean(payload: Any) -> list[CloudServer]:
+ servers: list[CloudServer] = []
+ for row in (payload or {}).get("droplets", []) if isinstance(payload, dict) else []:
+ networks = ((row.get("networks") or {}).get("v4")) or []
+ host = next(
+ (
+ n.get("ip_address")
+ for n in networks
+ if isinstance(n, dict) and n.get("type") == "public"
+ ),
+ None,
+ )
+ image = row.get("image") or {}
+ region = row.get("region") or {}
+ status = str(row.get("status") or "unknown")
+ os_label = " ".join(p for p in (image.get("distribution"), image.get("name")) if p) or None
+ servers.append(
+ CloudServer(
+ id=str(row.get("id")),
+ name=str(row.get("name") or row.get("id")),
+ host=host,
+ status=status,
+ running=status == "active",
+ os=os_label,
+ plan=row.get("size_slug"),
+ region=region.get("name") or region.get("slug"),
+ cpus=_as_int(row.get("vcpus")),
+ memory_mb=_as_int(row.get("memory")),
+ disk_gb=float(row["disk"]) if row.get("disk") is not None else None,
+ )
+ )
+ return servers
+
+
+# -- listing -----------------------------------------------------------------
+
+
+async def list_servers(provider_id: str, *, client: Any | None = None) -> list[CloudServer]:
+ """Every server in the account behind the saved token."""
+ spec = provider(provider_id)
+ api_token = token(provider_id)
+ if not api_token:
+ raise CloudError(f"Save a {spec.name} API token first.")
+
+ if spec.id == "hostinger":
+ vms = await _request(spec, api_token, "GET", "/api/vps/v1/virtual-machines", client=client)
+ data_centers: dict[int, str] = {}
+ try:
+ rows = await _request(spec, api_token, "GET", "/api/vps/v1/data-centers", client=client)
+ for row in rows if isinstance(rows, list) else []:
+ if isinstance(row, dict) and row.get("id") is not None:
+ label = row.get("city") or row.get("name")
+ if label:
+ data_centers[int(row["id"])] = str(label)
+ except CloudError as exc:
+ # Region names are decoration; the server list is what matters.
+ log.info("computers: hostinger data centers unavailable: %s", exc.message)
+ return parse_hostinger(vms, data_centers)
+
+ if spec.id == "hetzner":
+ servers: list[CloudServer] = []
+ page: int | None = 1
+ while page and page <= _MAX_PAGES:
+ payload = await _request(
+ spec,
+ api_token,
+ "GET",
+ "/v1/servers",
+ params={"page": page, "per_page": 50},
+ client=client,
+ )
+ servers.extend(parse_hetzner(payload))
+ pagination = ((payload or {}).get("meta") or {}).get("pagination") or {}
+ page = _as_int(pagination.get("next_page"))
+ return servers
+
+ servers = []
+ page = 1
+ while page and page <= _MAX_PAGES:
+ payload = await _request(
+ spec,
+ api_token,
+ "GET",
+ "/v2/droplets",
+ params={"page": page, "per_page": 100},
+ client=client,
+ )
+ servers.extend(parse_digitalocean(payload))
+ links = ((payload or {}).get("links") or {}).get("pages") or {}
+ page = page + 1 if links.get("next") else None
+ return servers
+
+
+def _same_key(a: str, b: str) -> bool:
+ """Compare two OpenSSH key lines by algorithm + body, ignoring the comment."""
+ return a.split()[:2] == b.split()[:2]
+
+
+async def attach_public_key(
+ provider_id: str, server_id: str, public_key: str, *, client: Any | None = None
+) -> None:
+ """Plant ``public_key`` on an existing server (Hostinger only)."""
+ spec = provider(provider_id)
+ if not spec.attaches_keys:
+ raise CloudError(f"{spec.name} cannot add a key to an existing server.")
+ api_token = token(provider_id)
+ if not api_token:
+ raise CloudError(f"Save a {spec.name} API token first.")
+
+ key_id: int | None = None
+ for page in range(1, _MAX_PAGES + 1):
+ payload = await _request(
+ spec, api_token, "GET", "/api/vps/v1/public-keys", params={"page": page}, client=client
+ )
+ rows = (payload or {}).get("data", []) if isinstance(payload, dict) else []
+ for row in rows:
+ if isinstance(row, dict) and _same_key(str(row.get("key", "")), public_key):
+ key_id = _as_int(row.get("id"))
+ break
+ meta = (payload or {}).get("meta") or {} if isinstance(payload, dict) else {}
+ per_page = _as_int(meta.get("per_page")) or 0
+ total = _as_int(meta.get("total")) or 0
+ if key_id is not None or not rows or page * max(per_page, 1) >= total:
+ break
+ if key_id is None:
+ created = await _request(
+ spec,
+ api_token,
+ "POST",
+ "/api/vps/v1/public-keys",
+ body={"name": "Personal Jarvis", "key": public_key.strip()},
+ client=client,
+ )
+ key_id = _as_int((created or {}).get("id")) if isinstance(created, dict) else None
+ if key_id is None:
+ raise CloudError(f"{spec.name} did not confirm the new key.")
+ action = await _request(
+ spec,
+ api_token,
+ "POST",
+ f"/api/vps/v1/public-keys/attach/{server_id}",
+ body={"ids": [key_id]},
+ client=client,
+ )
+ state = (action or {}).get("state") if isinstance(action, dict) else None
+ if state == "error":
+ raise CloudError(f"{spec.name} could not add the key to this server.")
diff --git a/jarvis/computers/identity.py b/jarvis/computers/identity.py
new file mode 100644
index 0000000000..80bd8e4111
--- /dev/null
+++ b/jarvis/computers/identity.py
@@ -0,0 +1,74 @@
+"""Jarvis's own SSH key pair — the one key every connected computer trusts.
+
+Generated once on first use (Ed25519), the private half stored through
+``set_secret`` (OS keyring, or the 0600 file fallback on a headless box) and
+never written anywhere else. The public half is what the user pastes into a
+hosting panel, what cloud-init plants into a new VM, and what the
+"install key with password" step appends to ``~/.ssh/authorized_keys``.
+"""
+
+from __future__ import annotations
+
+import logging
+import platform
+import threading
+from typing import TYPE_CHECKING, Any
+
+from jarvis.core.config import get_secret, set_secret
+
+if TYPE_CHECKING:
+ import asyncssh
+
+log = logging.getLogger(__name__)
+
+#: Keyring slot of the private key (OpenSSH PEM text).
+PRIVATE_KEY_SECRET = "computers_ssh_private_key" # noqa: S105 — a slot name, not a secret
+
+_LOCK = threading.Lock()
+
+
+class IdentityError(RuntimeError):
+ """The key pair could not be created or stored."""
+
+
+def _comment() -> str:
+ host = platform.node().strip() or "desktop"
+ return f"personal-jarvis@{host}"
+
+
+def private_key() -> asyncssh.SSHKey:
+ """Return the key pair, creating and storing it on first use."""
+ import asyncssh
+
+ with _LOCK:
+ pem = get_secret(PRIVATE_KEY_SECRET, env_fallback="JARVIS_COMPUTERS_SSH_KEY")
+ if pem:
+ try:
+ return asyncssh.import_private_key(pem)
+ except (asyncssh.KeyImportError, ValueError) as exc:
+ # A damaged slot must not silently mint a new key: every
+ # computer that trusts the old one would lock us out.
+ raise IdentityError(
+ "Jarvis's SSH key in the keyring is damaged and cannot be read."
+ ) from exc
+ key = asyncssh.generate_private_key("ssh-ed25519", comment=_comment())
+ text = key.export_private_key("openssh").decode("utf-8")
+ if not set_secret(PRIVATE_KEY_SECRET, text):
+ raise IdentityError("The new SSH key could not be saved to the keyring.")
+ log.info("computers: created Jarvis's SSH key pair")
+ return key
+
+
+def public_key_line() -> str:
+ """The OpenSSH public key line (``ssh-ed25519 AAAA... comment``)."""
+ return private_key().export_public_key("openssh").decode("utf-8").strip()
+
+
+def describe() -> dict[str, Any]:
+ """Public key plus fingerprint for the UI; creates the key when missing."""
+ key = private_key()
+ return {
+ "public_key": key.export_public_key("openssh").decode("utf-8").strip(),
+ "fingerprint": key.get_fingerprint("sha256"),
+ "algorithm": key.get_algorithm(),
+ }
diff --git a/jarvis/computers/local_vm.py b/jarvis/computers/local_vm.py
new file mode 100644
index 0000000000..15b14bc63e
--- /dev/null
+++ b/jarvis/computers/local_vm.py
@@ -0,0 +1,249 @@
+"""Local virtual machines through Canonical Multipass.
+
+Multipass is open source and runs on Windows (Hyper-V or VirtualBox), macOS
+and Linux (snap) with one CLI, which makes it the one backend that keeps this
+feature identical on every desktop OS. Jarvis only drives the ``multipass``
+binary; a machine without it (a headless server, a box where the user has not
+installed it) gets ``available=False`` plus the install link for its OS and
+nothing else changes.
+
+A new VM boots Ubuntu with Jarvis's public key planted by cloud-init, so it is
+reachable over SSH as ``ubuntu@<vm ip>`` the moment it is up — the same code
+path as any rented server.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import re
+import shutil
+import sys
+import tempfile
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from typing import Any
+
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+log = logging.getLogger(__name__)
+
+DEFAULT_USER = "ubuntu"
+#: Images offered in the UI; Multipass accepts any alias it knows.
+IMAGES: tuple[str, ...] = ("24.04", "22.04")
+NAME_RE = re.compile(r"^[a-z][a-z0-9-]{0,38}[a-z0-9]$")
+LAUNCH_TIMEOUT_S = 1200
+_CLI_TIMEOUT_S = 60
+
+
+class LocalVmError(Exception):
+ """A Multipass call failed; ``message`` is safe to show the user."""
+
+ def __init__(self, message: str) -> None:
+ super().__init__(message)
+ self.message = message
+
+
+@dataclass(frozen=True)
+class LocalInstance:
+ name: str
+ state: str
+ ipv4: str | None
+ release: str | None
+ cpus: int | None = None
+ memory_total_mb: int | None = None
+ disk_total_gb: float | None = None
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+def install_url() -> str:
+ if sys.platform == "darwin":
+ return "https://canonical.com/multipass/install#macos"
+ if sys.platform.startswith("linux"):
+ return "https://canonical.com/multipass/install#linux"
+ return "https://canonical.com/multipass/install#windows"
+
+
+def install_hint() -> str:
+ if sys.platform == "darwin":
+ return "brew install --cask multipass"
+ if sys.platform.startswith("linux"):
+ return "sudo snap install multipass"
+ return "Download the Multipass installer for Windows"
+
+
+def binary() -> str | None:
+ return shutil.which("multipass")
+
+
+def valid_name(name: str) -> bool:
+ return bool(NAME_RE.match(name))
+
+
+async def _run(*args: str, timeout_s: float = _CLI_TIMEOUT_S) -> str:
+ exe = binary()
+ if exe is None:
+ raise LocalVmError("Multipass is not installed on this computer.")
+ try:
+ proc = await asyncio.create_subprocess_exec(
+ exe,
+ *args,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ except OSError as exc:
+ raise LocalVmError("Multipass could not be started.") from exc
+ try:
+ out, err = await asyncio.wait_for(proc.communicate(), timeout=timeout_s)
+ except TimeoutError as exc:
+ proc.kill()
+ await proc.wait()
+ raise LocalVmError(f"Multipass did not finish within {int(timeout_s)} s.") from exc
+ stdout = out.decode("utf-8", errors="replace")
+ if proc.returncode != 0:
+ detail = err.decode("utf-8", errors="replace").strip().splitlines()
+ # Multipass's own message is about the local VM, never a secret.
+ raise LocalVmError(detail[-1] if detail else f"Multipass failed ({proc.returncode}).")
+ return stdout
+
+
+def _num(value: Any) -> float | None:
+ try:
+ return float(value) if value is not None and value != "" else None
+ except (TypeError, ValueError): # a missing number is shown as unknown
+ return None
+
+
+def parse_list(payload: Any) -> list[LocalInstance]:
+ rows = payload.get("list", []) if isinstance(payload, dict) else []
+ instances: list[LocalInstance] = []
+ for row in rows:
+ if not isinstance(row, dict) or not row.get("name"):
+ continue
+ ips = row.get("ipv4") or []
+ instances.append(
+ LocalInstance(
+ name=str(row["name"]),
+ state=str(row.get("state") or "Unknown"),
+ ipv4=str(ips[0]) if ips else None,
+ release=row.get("release") or None,
+ )
+ )
+ return instances
+
+
+def parse_info(payload: Any, name: str) -> LocalInstance | None:
+ info = (payload.get("info") or {}).get(name) if isinstance(payload, dict) else None
+ if not isinstance(info, dict):
+ return None
+ ips = info.get("ipv4") or []
+ memory = info.get("memory") or {}
+ disk_total = 0.0
+ for disk in (info.get("disks") or {}).values():
+ disk_total += _num((disk or {}).get("total")) or 0.0
+ mem_total = _num(memory.get("total"))
+ cpus = _num(info.get("cpu_count"))
+ return LocalInstance(
+ name=name,
+ state=str(info.get("state") or "Unknown"),
+ ipv4=str(ips[0]) if ips else None,
+ release=info.get("release") or info.get("image_release") or None,
+ cpus=int(cpus) if cpus is not None else None,
+ memory_total_mb=int(mem_total // (1024 * 1024)) if mem_total else None,
+ disk_total_gb=round(disk_total / 1024**3, 1) if disk_total else None,
+ )
+
+
+async def status() -> dict[str, Any]:
+ """Is Multipass here, which version, and which instances exist."""
+ exe = binary()
+ result: dict[str, Any] = {
+ "backend": "multipass",
+ "available": exe is not None,
+ "version": None,
+ "install_url": install_url(),
+ "install_hint": install_hint(),
+ "images": list(IMAGES),
+ "instances": [],
+ "error": None,
+ }
+ if exe is None:
+ return result
+ try:
+ version = await _run("version", timeout_s=15)
+ first = version.strip().splitlines()[0] if version.strip() else ""
+ result["version"] = first.split()[-1] if first else None
+ result["instances"] = [i.to_dict() for i in await list_instances()]
+ except LocalVmError as exc:
+ # Installed but not answering (daemon stopped, missing Hyper-V):
+ # report it instead of pretending there is nothing.
+ result["error"] = exc.message
+ return result
+
+
+async def list_instances() -> list[LocalInstance]:
+ raw = await _run("list", "--format", "json")
+ try:
+ return parse_list(json.loads(raw))
+ except json.JSONDecodeError as exc:
+ raise LocalVmError("Multipass sent a list Jarvis cannot read.") from exc
+
+
+async def info(name: str) -> LocalInstance | None:
+ raw = await _run("info", name, "--format", "json")
+ try:
+ return parse_info(json.loads(raw), name)
+ except json.JSONDecodeError as exc:
+ raise LocalVmError("Multipass sent details Jarvis cannot read.") from exc
+
+
+def cloud_init(public_key: str) -> str:
+ return f"#cloud-config\nssh_authorized_keys:\n - {public_key.strip()}\n"
+
+
+async def launch(
+ name: str, *, cpus: int, memory_gb: int, disk_gb: int, image: str, public_key: str
+) -> LocalInstance:
+ """Create and boot a VM; returns once it runs and has an address."""
+ if not valid_name(name):
+ raise LocalVmError("Use 2-40 lowercase letters, digits or hyphens, starting with a letter.")
+ with tempfile.TemporaryDirectory(prefix="jarvis-vm-") as tmp:
+ seed = Path(tmp) / "cloud-init.yaml"
+ seed.write_text(cloud_init(public_key), encoding="utf-8")
+ await _run(
+ "launch",
+ image,
+ "--name",
+ name,
+ "--cpus",
+ str(cpus),
+ "--memory",
+ f"{memory_gb}G",
+ "--disk",
+ f"{disk_gb}G",
+ "--cloud-init",
+ str(seed),
+ "--timeout",
+ str(LAUNCH_TIMEOUT_S - 60),
+ timeout_s=LAUNCH_TIMEOUT_S,
+ )
+ instance = await info(name)
+ if instance is None or not instance.ipv4:
+ raise LocalVmError("The VM started but has no network address yet.")
+ return instance
+
+
+async def start(name: str) -> None:
+ await _run("start", name, timeout_s=300)
+
+
+async def stop(name: str) -> None:
+ await _run("stop", name, timeout_s=300)
+
+
+async def delete(name: str) -> None:
+ await _run("delete", "--purge", name, timeout_s=300)
diff --git a/jarvis/computers/models.py b/jarvis/computers/models.py
new file mode 100644
index 0000000000..6271f84910
--- /dev/null
+++ b/jarvis/computers/models.py
@@ -0,0 +1,94 @@
+"""Records for the Computers section.
+
+One :class:`Computer` per machine. ``facts`` is what the machine IS (OS, cores,
+memory) and changes rarely; ``health`` is how it is doing right now and is
+rewritten by every check. Both are plain data — nothing here talks to a
+network.
+"""
+
+from __future__ import annotations
+
+from typing import Literal
+
+from pydantic import BaseModel, ConfigDict, Field
+
+#: A rented or self-hosted machine reached over the network, or a VM on this box.
+ComputerKind = Literal["server", "local_vm"]
+
+#: Where the machine came from. ``generic`` is any SSH host typed in by hand.
+ProviderId = Literal["generic", "hostinger", "hetzner", "digitalocean", "multipass"]
+
+#: How Jarvis logs in. ``key`` is Jarvis's own key pair (the default and the
+#: recommended path); ``password`` keeps a password in the OS keyring.
+AuthMethod = Literal["key", "password"]
+
+#: The state a check leaves behind. ``provisioning`` belongs to a local VM that
+#: is still being created; ``stopped`` to a local VM that is powered off.
+HealthStatus = Literal[
+ "unknown",
+ "online",
+ "offline",
+ "auth_failed",
+ "host_key_changed",
+ "provisioning",
+ "stopped",
+ "error",
+]
+
+
+class ComputerFacts(BaseModel):
+ """What the machine is, read by the last successful check."""
+
+ model_config = ConfigDict(frozen=True)
+
+ hostname: str | None = None
+ os_id: str | None = None
+ os_name: str | None = None
+ kernel: str | None = None
+ arch: str | None = None
+ cpu_count: int | None = None
+ mem_total_mb: int | None = None
+ disk_total_gb: float | None = None
+
+
+class ComputerHealth(BaseModel):
+ """How the machine is doing, as of ``checked_at`` (epoch seconds)."""
+
+ model_config = ConfigDict(frozen=True)
+
+ status: HealthStatus = "unknown"
+ checked_at: float | None = None
+ latency_ms: int | None = None
+ #: A sentence for the user when the status is not ``online``.
+ message: str | None = None
+ load_1m: float | None = None
+ mem_used_pct: float | None = None
+ disk_used_pct: float | None = None
+ uptime_s: int | None = None
+
+
+class Computer(BaseModel):
+ """One machine the user connected."""
+
+ model_config = ConfigDict(frozen=True)
+
+ id: str
+ name: str
+ kind: ComputerKind = "server"
+ provider: ProviderId = "generic"
+ host: str
+ port: int = Field(default=22, ge=1, le=65535)
+ username: str = "root"
+ auth: AuthMethod = "key"
+ #: The machine's id at its provider (Hostinger VM id, droplet id, the
+ #: Multipass instance name). ``None`` for a hand-typed server.
+ provider_ref: str | None = None
+ region: str | None = None
+ plan: str | None = None
+ #: The server's own SSH host key (OpenSSH line), pinned on first contact.
+ #: A later mismatch refuses to connect instead of trusting a stranger.
+ host_key: str | None = None
+ host_fingerprint: str | None = None
+ created_at: float
+ facts: ComputerFacts | None = None
+ health: ComputerHealth = Field(default_factory=ComputerHealth)
diff --git a/jarvis/computers/probe.py b/jarvis/computers/probe.py
new file mode 100644
index 0000000000..7e070372a4
--- /dev/null
+++ b/jarvis/computers/probe.py
@@ -0,0 +1,169 @@
+"""The read-only health script and its parser.
+
+A check runs ONE command over SSH: a POSIX shell script that prints labelled
+sections (hostname, OS, cores, memory, disk, uptime, load). It only reads —
+nothing is installed or changed. Linux answers every section; macOS answers
+through its own tools; a machine whose login shell is not POSIX (a Windows
+OpenSSH server) answers little or nothing, and the check still counts as
+online with fewer facts.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from jarvis.computers.models import ComputerFacts
+
+PROBE_SCRIPT = r"""
+echo "@@hostname"; hostname 2>/dev/null
+echo "@@uname"; uname -srm 2>/dev/null
+echo "@@os"; cat /etc/os-release 2>/dev/null
+echo "@@darwin"; sw_vers 2>/dev/null
+echo "@@nproc"; nproc 2>/dev/null || getconf _NPROCESSORS_ONLN 2>/dev/null \
+ || sysctl -n hw.ncpu 2>/dev/null
+echo "@@meminfo"; head -n 3 /proc/meminfo 2>/dev/null
+echo "@@memsize"; sysctl -n hw.memsize 2>/dev/null
+echo "@@df"; df -Pk / 2>/dev/null | tail -n 1
+echo "@@uptime"; cat /proc/uptime 2>/dev/null
+echo "@@loadavg"; cat /proc/loadavg 2>/dev/null || sysctl -n vm.loadavg 2>/dev/null
+echo "@@end"
+""".strip()
+
+
+@dataclass(frozen=True)
+class ProbeReading:
+ """What one probe run found."""
+
+ facts: ComputerFacts
+ load_1m: float | None
+ mem_used_pct: float | None
+ disk_used_pct: float | None
+ uptime_s: int | None
+
+
+def _sections(output: str) -> dict[str, list[str]]:
+ sections: dict[str, list[str]] = {}
+ current: str | None = None
+ for raw in output.splitlines():
+ line = raw.rstrip("\r")
+ if line.startswith("@@"):
+ current = line[2:].strip()
+ sections.setdefault(current, [])
+ elif current is not None and line.strip():
+ sections[current].append(line.strip())
+ return sections
+
+
+def _first(lines: list[str] | None) -> str | None:
+ return lines[0] if lines else None
+
+
+def _int(value: str | None) -> int | None:
+ try:
+ return int(value) if value is not None else None
+ except ValueError: # a non-number field just means the fact is unknown
+ return None
+
+
+def _os_release(lines: list[str]) -> dict[str, str]:
+ values: dict[str, str] = {}
+ for line in lines:
+ key, sep, value = line.partition("=")
+ if sep:
+ values[key.strip()] = value.strip().strip('"').strip("'")
+ return values
+
+
+def _meminfo_kb(lines: list[str]) -> dict[str, int]:
+ values: dict[str, int] = {}
+ for line in lines:
+ key, sep, rest = line.partition(":")
+ number = _int(rest.split()[0]) if sep and rest.split() else None
+ if number is not None:
+ values[key.strip()] = number
+ return values
+
+
+def parse_probe(output: str) -> ProbeReading:
+ """Turn the script's output into facts and live numbers; never raises."""
+ s = _sections(output)
+
+ hostname = _first(s.get("hostname"))
+ kernel = arch = None
+ uname = _first(s.get("uname"))
+ if uname:
+ parts = uname.split()
+ if len(parts) >= 3:
+ kernel = f"{parts[0]} {parts[1]}"
+ arch = parts[-1]
+ else:
+ kernel = uname
+
+ os_id = os_name = None
+ release = _os_release(s.get("os", []))
+ if release:
+ os_id = release.get("ID") or None
+ os_name = release.get("PRETTY_NAME") or release.get("NAME") or None
+ darwin = _os_release([line.replace(":", "=", 1) for line in s.get("darwin", [])])
+ if not os_name and darwin.get("ProductName"):
+ os_id = "macos"
+ os_name = f"{darwin['ProductName']} {darwin.get('ProductVersion', '')}".strip()
+
+ cpu_count = _int(_first(s.get("nproc")))
+
+ mem_total_mb = None
+ mem_used_pct = None
+ meminfo = _meminfo_kb(s.get("meminfo", []))
+ if meminfo.get("MemTotal"):
+ total_kb = meminfo["MemTotal"]
+ mem_total_mb = total_kb // 1024
+ available = meminfo.get("MemAvailable", meminfo.get("MemFree"))
+ if available is not None and total_kb > 0:
+ mem_used_pct = round(100.0 * (total_kb - available) / total_kb, 1)
+ elif (memsize := _int(_first(s.get("memsize")))) is not None:
+ mem_total_mb = memsize // (1024 * 1024)
+
+ disk_total_gb = None
+ disk_used_pct = None
+ df = _first(s.get("df"))
+ if df:
+ cols = df.split()
+ if len(cols) >= 5:
+ total_k, used_k = _int(cols[1]), _int(cols[2])
+ if total_k:
+ disk_total_gb = round(total_k / (1024 * 1024), 1)
+ if used_k is not None:
+ disk_used_pct = round(100.0 * used_k / total_k, 1)
+
+ uptime_s = None
+ uptime = _first(s.get("uptime"))
+ if uptime:
+ try:
+ uptime_s = int(float(uptime.split()[0]))
+ except (ValueError, IndexError): # unknown uptime, shown as a dash
+ uptime_s = None
+
+ load_1m = None
+ load = _first(s.get("loadavg"))
+ if load:
+ try:
+ load_1m = float(load.strip("{} ").split()[0])
+ except (ValueError, IndexError): # unknown load, shown as a dash
+ load_1m = None
+
+ return ProbeReading(
+ facts=ComputerFacts(
+ hostname=hostname,
+ os_id=os_id,
+ os_name=os_name,
+ kernel=kernel,
+ arch=arch,
+ cpu_count=cpu_count,
+ mem_total_mb=mem_total_mb,
+ disk_total_gb=disk_total_gb,
+ ),
+ load_1m=load_1m,
+ mem_used_pct=mem_used_pct,
+ disk_used_pct=disk_used_pct,
+ uptime_s=uptime_s,
+ )
diff --git a/jarvis/computers/service.py b/jarvis/computers/service.py
new file mode 100644
index 0000000000..c2aca6f87d
--- /dev/null
+++ b/jarvis/computers/service.py
@@ -0,0 +1,598 @@
+"""The orchestration behind the Computers section.
+
+Every REST route is a thin call into :class:`ComputerService`. It owns the
+rules a user never has to learn:
+
+* Jarvis logs in with its OWN key by default. A password is used once to plant
+ that key and is then forgotten, unless the user explicitly keeps password
+ login (it then lives in the keyring, never in the JSON file).
+* The first contact pins the server's identity; later connections refuse a
+ changed identity until the user confirms it (:meth:`trust_new_host_key`).
+* A local VM is a record that starts in ``provisioning`` and turns into an
+ ordinary SSH computer when Multipass reports it running.
+
+Later features (deploying Jarvis to a VPS, agents working on a remote box) use
+:meth:`run` and :meth:`session` rather than opening their own connections.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import logging
+import re
+import secrets
+import time
+from collections.abc import AsyncIterator
+from typing import Any
+
+from jarvis.computers import cloud, identity, local_vm
+from jarvis.computers.models import (
+ AuthMethod,
+ Computer,
+ ComputerHealth,
+ ProviderId,
+)
+from jarvis.computers.probe import PROBE_SCRIPT, parse_probe
+from jarvis.computers.ssh import (
+ MAX_COMMAND_TIMEOUT_S,
+ CommandResult,
+ Session,
+ SshError,
+ SshTarget,
+ authorize_key_command,
+ close,
+ open_session,
+ run_command,
+)
+from jarvis.computers.store import ComputerStore
+from jarvis.core.config import delete_secret, get_secret, set_secret
+
+log = logging.getLogger(__name__)
+
+_HOST_RE = re.compile(r"^[A-Za-z0-9._:\-\[\]]{1,253}$")
+_USER_RE = re.compile(r"^[A-Za-z0-9._\-]{1,64}$")
+_PROBE_TIMEOUT_S = 25.0
+
+
+class ComputerError(Exception):
+ """A request the service refuses; ``status`` maps to the HTTP code."""
+
+ def __init__(self, message: str, *, status: int = 400, kind: str | None = None) -> None:
+ super().__init__(message)
+ self.message = message
+ self.status = status
+ self.kind = kind
+
+
+def _password_slot(computer_id: str) -> str:
+ return f"computer_password_{computer_id}"
+
+
+def _new_id() -> str:
+ return f"c_{secrets.token_hex(6)}"
+
+
+def _clean_name(name: str) -> str:
+ cleaned = " ".join(name.split())[:80]
+ if not cleaned:
+ raise ComputerError("Give the computer a name.")
+ return cleaned
+
+
+def _check_host(host: str) -> str:
+ host = host.strip()
+ if not _HOST_RE.match(host):
+ raise ComputerError("Enter an IP address or host name, for example 203.0.113.10.")
+ return host.strip("[]")
+
+
+def _check_user(username: str) -> str:
+ username = username.strip()
+ if not _USER_RE.match(username):
+ raise ComputerError("Enter the login name, for example root or ubuntu.")
+ return username
+
+
+_ERROR_STATUS = {
+ "auth": "auth_failed",
+ "host_key_changed": "host_key_changed",
+ "unreachable": "offline",
+ "timeout": "offline",
+}
+
+
+class ComputerService:
+ def __init__(self, store: ComputerStore | None = None) -> None:
+ self._store = store or ComputerStore()
+ #: Running background jobs (VM creation) per computer id.
+ self._jobs: dict[str, asyncio.Task[None]] = {}
+
+ # -- reading ------------------------------------------------------------
+
+ def all(self) -> list[Computer]:
+ return self._store.all()
+
+ def get(self, computer_id: str) -> Computer:
+ computer = self._store.get(computer_id)
+ if computer is None:
+ raise ComputerError("This computer does not exist.", status=404)
+ return computer
+
+ def is_busy(self, computer_id: str) -> bool:
+ task = self._jobs.get(computer_id)
+ return task is not None and not task.done()
+
+ # -- connecting ---------------------------------------------------------
+
+ def _target(self, computer: Computer, *, password: str | None = None) -> SshTarget:
+ if password is not None:
+ return SshTarget(
+ host=computer.host,
+ port=computer.port,
+ username=computer.username,
+ host_key=computer.host_key,
+ password=password,
+ )
+ if computer.auth == "password":
+ stored = get_secret(_password_slot(computer.id), env_fallback="")
+ if not stored:
+ raise ComputerError(
+ "The saved password is missing. Enter it again.", status=409, kind="auth"
+ )
+ return SshTarget(
+ host=computer.host,
+ port=computer.port,
+ username=computer.username,
+ host_key=computer.host_key,
+ password=stored,
+ )
+ try:
+ key = identity.private_key()
+ except identity.IdentityError as exc:
+ raise ComputerError(str(exc), status=500) from exc
+ return SshTarget(
+ host=computer.host,
+ port=computer.port,
+ username=computer.username,
+ host_key=computer.host_key,
+ client_key=key,
+ )
+
+ def _pin(self, computer_id: str, session: Session) -> None:
+ def change(row: Computer) -> Computer:
+ if row.host_key:
+ return row
+ return row.model_copy(
+ update={"host_key": session.host_key, "host_fingerprint": session.host_fingerprint}
+ )
+
+ self._store.update(computer_id, change)
+
+ @contextlib.asynccontextmanager
+ async def session(self, computer_id: str) -> AsyncIterator[Session]:
+ """An authenticated connection; pins the host key on first contact."""
+ computer = self.get(computer_id)
+ target = self._target(computer)
+ try:
+ opened = await open_session(target)
+ except SshError as exc:
+ raise ComputerError(exc.message, status=502, kind=exc.kind) from exc
+ self._pin(computer_id, opened)
+ try:
+ yield opened
+ finally:
+ close(opened)
+
+ # -- checks -------------------------------------------------------------
+
+ def _set_health(self, computer_id: str, health: ComputerHealth, **fields: Any) -> Computer:
+ updated = self._store.update(
+ computer_id, lambda row: row.model_copy(update={"health": health, **fields})
+ )
+ if updated is None:
+ raise ComputerError("This computer does not exist.", status=404)
+ return updated
+
+ async def check(self, computer_id: str) -> Computer:
+ """Connect, read the machine's facts and vitals, store both."""
+ computer = self.get(computer_id)
+ if computer.health.status == "provisioning" and self.is_busy(computer_id):
+ return computer
+ now = time.time()
+ try:
+ async with self.session(computer_id) as opened:
+ result = await run_command(opened, PROBE_SCRIPT, timeout_s=_PROBE_TIMEOUT_S)
+ latency = opened.latency_ms
+ except ComputerError as exc:
+ status = _ERROR_STATUS.get(exc.kind or "", "error")
+ if computer.kind == "local_vm" and status == "offline":
+ status = await self._local_vm_state(computer) or status
+ return self._set_health(
+ computer_id,
+ ComputerHealth(status=status, checked_at=now, message=exc.message), # type: ignore[arg-type]
+ )
+ reading = parse_probe(result.stdout)
+ return self._set_health(
+ computer_id,
+ ComputerHealth(
+ status="online",
+ checked_at=now,
+ latency_ms=latency,
+ load_1m=reading.load_1m,
+ mem_used_pct=reading.mem_used_pct,
+ disk_used_pct=reading.disk_used_pct,
+ uptime_s=reading.uptime_s,
+ ),
+ facts=reading.facts,
+ )
+
+ async def check_all(self) -> list[Computer]:
+ ids = [c.id for c in self.all()]
+ results = await asyncio.gather(*(self.check(cid) for cid in ids), return_exceptions=True)
+ for cid, outcome in zip(ids, results, strict=True):
+ if isinstance(outcome, BaseException):
+ log.warning("computers: check of %s failed: %r", cid, outcome)
+ return self.all()
+
+ async def _local_vm_state(self, computer: Computer) -> str | None:
+ if not computer.provider_ref:
+ return None
+ try:
+ instance = await local_vm.info(computer.provider_ref)
+ except local_vm.LocalVmError as exc:
+ log.info("computers: multipass state of %s unknown: %s", computer.id, exc.message)
+ return None
+ if instance is not None and instance.state.lower() == "stopped":
+ return "stopped"
+ return None
+
+ async def run(
+ self, computer_id: str, command: str, *, timeout_s: float = 60.0
+ ) -> CommandResult:
+ """Run one shell command on the computer and return its output."""
+ if not command.strip():
+ raise ComputerError("Type a command to run.")
+ timeout_s = max(1.0, min(timeout_s, MAX_COMMAND_TIMEOUT_S))
+ async with self.session(computer_id) as opened:
+ try:
+ return await run_command(opened, command, timeout_s=timeout_s)
+ except SshError as exc:
+ raise ComputerError(exc.message, status=502, kind=exc.kind) from exc
+
+ # -- adding -------------------------------------------------------------
+
+ async def _plant_key(self, target: SshTarget) -> Session:
+ """Log in with the password, add Jarvis's key, prove the key works."""
+ try:
+ opened = await open_session(target)
+ except SshError as exc:
+ raise ComputerError(exc.message, status=502, kind=exc.kind) from exc
+ try:
+ result = await run_command(
+ opened, authorize_key_command(identity.public_key_line()), timeout_s=20
+ )
+ except SshError as exc:
+ raise ComputerError(exc.message, status=502, kind=exc.kind) from exc
+ finally:
+ close(opened)
+ if result.exit_status not in (0, None):
+ raise ComputerError(
+ "The login worked, but the key could not be saved on the server "
+ "(is the home folder writable?).",
+ status=502,
+ kind="install_key",
+ )
+ verify = SshTarget(
+ host=target.host,
+ port=target.port,
+ username=target.username,
+ host_key=opened.host_key,
+ client_key=identity.private_key(),
+ )
+ try:
+ proof = await open_session(verify)
+ except SshError as exc:
+ raise ComputerError(
+ "The key was saved, but the server still refuses key logins. "
+ "Check that PubkeyAuthentication is enabled.",
+ status=502,
+ kind="install_key",
+ ) from exc
+ return proof
+
+ async def add_server(
+ self,
+ *,
+ name: str,
+ host: str,
+ port: int = 22,
+ username: str = "root",
+ auth: AuthMethod = "key",
+ password: str | None = None,
+ keep_password: bool = False,
+ provider: ProviderId = "generic",
+ provider_ref: str | None = None,
+ region: str | None = None,
+ plan: str | None = None,
+ ) -> Computer:
+ """Register a server. With a password, plant the key first (default)."""
+ computer = Computer(
+ id=_new_id(),
+ name=_clean_name(name),
+ kind="server",
+ provider=provider,
+ host=_check_host(host),
+ port=port,
+ username=_check_user(username),
+ auth="key",
+ provider_ref=provider_ref,
+ region=region,
+ plan=plan,
+ created_at=time.time(),
+ )
+ if auth == "password":
+ if not password:
+ raise ComputerError("Enter the password for this login.")
+ if keep_password:
+ if not set_secret(_password_slot(computer.id), password):
+ raise ComputerError(
+ "The password could not be saved to the keyring.", status=500
+ )
+ computer = computer.model_copy(update={"auth": "password"})
+ else:
+ proof = await self._plant_key(self._target(computer, password=password))
+ close(proof)
+ computer = computer.model_copy(
+ update={"host_key": proof.host_key, "host_fingerprint": proof.host_fingerprint}
+ )
+ self._store.add(computer)
+ return await self.check(computer.id)
+
+ async def install_key(self, computer_id: str, password: str) -> Computer:
+ """Plant Jarvis's key with a one-time password; switch to key login."""
+ computer = self.get(computer_id)
+ if not password:
+ raise ComputerError("Enter the password for this login.")
+ proof = await self._plant_key(self._target(computer, password=password))
+ close(proof)
+ delete_secret(_password_slot(computer_id))
+ self._store.update(
+ computer_id,
+ lambda row: row.model_copy(
+ update={
+ "auth": "key",
+ "host_key": row.host_key or proof.host_key,
+ "host_fingerprint": row.host_fingerprint or proof.host_fingerprint,
+ }
+ ),
+ )
+ return await self.check(computer_id)
+
+ # -- editing ------------------------------------------------------------
+
+ def update(self, computer_id: str, **fields: Any) -> Computer:
+ changes: dict[str, Any] = {}
+ if fields.get("name") is not None:
+ changes["name"] = _clean_name(fields["name"])
+ if fields.get("host") is not None:
+ changes["host"] = _check_host(fields["host"])
+ if fields.get("username") is not None:
+ changes["username"] = _check_user(fields["username"])
+ if fields.get("port") is not None:
+ changes["port"] = int(fields["port"])
+ current = self.get(computer_id)
+ if "host" in changes and changes["host"] != current.host:
+ # A different address is a different machine until proven otherwise.
+ changes.update(host_key=None, host_fingerprint=None)
+ updated = self._store.update(computer_id, lambda row: row.model_copy(update=changes))
+ if updated is None:
+ raise ComputerError("This computer does not exist.", status=404)
+ return updated
+
+ async def trust_new_host_key(self, computer_id: str) -> Computer:
+ """Forget the pinned identity and pin whatever answers next."""
+ self.get(computer_id)
+ self._store.update(
+ computer_id,
+ lambda row: row.model_copy(update={"host_key": None, "host_fingerprint": None}),
+ )
+ return await self.check(computer_id)
+
+ async def remove(self, computer_id: str, *, destroy_vm: bool = False) -> bool:
+ computer = self.get(computer_id)
+ task = self._jobs.pop(computer_id, None)
+ if task is not None and not task.done():
+ task.cancel()
+ if destroy_vm and computer.kind == "local_vm" and computer.provider_ref:
+ try:
+ await local_vm.delete(computer.provider_ref)
+ except local_vm.LocalVmError as exc:
+ raise ComputerError(exc.message, status=502) from exc
+ delete_secret(_password_slot(computer_id))
+ return self._store.remove(computer_id)
+
+ # -- cloud import ---------------------------------------------------------
+
+ async def cloud_servers(self, provider_id: str) -> list[dict[str, Any]]:
+ try:
+ servers = await cloud.list_servers(provider_id)
+ except cloud.CloudError as exc:
+ raise ComputerError(exc.message, status=502) from exc
+ added = {
+ c.provider_ref: c.id for c in self.all() if c.provider == provider_id and c.provider_ref
+ }
+ return [{**s.to_dict(), "added_as": added.get(s.id)} for s in servers]
+
+ async def import_cloud_server(
+ self,
+ provider_id: str,
+ server_id: str,
+ *,
+ name: str | None = None,
+ username: str = "root",
+ password: str | None = None,
+ ) -> Computer:
+ servers = await self.cloud_servers(provider_id)
+ match = next((s for s in servers if s["id"] == server_id), None)
+ if match is None:
+ raise ComputerError("This server is no longer in the account.", status=404)
+ if match["added_as"]:
+ raise ComputerError("This server is already connected.", status=409)
+ if not match["host"]:
+ raise ComputerError("This server has no public IPv4 address yet.")
+ spec = cloud.provider(provider_id)
+ attached = False
+ if spec.attaches_keys and not password:
+ try:
+ await cloud.attach_public_key(provider_id, server_id, identity.public_key_line())
+ attached = True
+ except cloud.CloudError as exc:
+ raise ComputerError(exc.message, status=502) from exc
+ computer = await self.add_server(
+ name=name or match["name"],
+ host=match["host"],
+ username=username,
+ auth="password" if password else "key",
+ password=password,
+ provider=provider_id, # type: ignore[arg-type]
+ provider_ref=server_id,
+ region=match.get("region"),
+ plan=match.get("plan"),
+ )
+ if attached and computer.health.status == "auth_failed":
+ # The provider applies the key asynchronously; say so instead of
+ # leaving a bare "login refused" on a key that is still on its way.
+ computer = self._set_health(
+ computer.id,
+ computer.health.model_copy(
+ update={
+ "message": f"{spec.name} is still adding the key. Check again in a minute."
+ }
+ ),
+ )
+ return computer
+
+ # -- local VMs ------------------------------------------------------------
+
+ async def create_local_vm(
+ self, *, name: str, cpus: int, memory_gb: int, disk_gb: int, image: str
+ ) -> Computer:
+ if local_vm.binary() is None:
+ raise ComputerError(
+ "Install Multipass first to create local virtual machines.", status=409
+ )
+ if not local_vm.valid_name(name):
+ raise ComputerError(
+ "Use 2-40 lowercase letters, digits or hyphens, starting with a letter."
+ )
+ if any(c.kind == "local_vm" and c.provider_ref == name for c in self.all()):
+ raise ComputerError("A virtual machine with this name already exists.", status=409)
+ try:
+ public_key = identity.public_key_line()
+ except identity.IdentityError as exc:
+ raise ComputerError(str(exc), status=500) from exc
+ computer = Computer(
+ id=_new_id(),
+ name=name,
+ kind="local_vm",
+ provider="multipass",
+ host="0.0.0.0", # noqa: S104 — placeholder until Multipass reports the VM's address
+ username=local_vm.DEFAULT_USER,
+ provider_ref=name,
+ region="This computer",
+ plan=f"{cpus} CPU · {memory_gb} GB · {disk_gb} GB",
+ created_at=time.time(),
+ health=ComputerHealth(
+ status="provisioning",
+ checked_at=time.time(),
+ message=(
+ "Creating the virtual machine. The first one downloads Ubuntu "
+ "and takes a few minutes."
+ ),
+ ),
+ )
+ self._store.add(computer)
+ self._jobs[computer.id] = asyncio.create_task(
+ self._provision(computer.id, name, cpus, memory_gb, disk_gb, image, public_key),
+ name=f"computers-provision-{name}",
+ )
+ return computer
+
+ async def _provision(
+ self,
+ computer_id: str,
+ name: str,
+ cpus: int,
+ memory_gb: int,
+ disk_gb: int,
+ image: str,
+ public_key: str,
+ ) -> None:
+ try:
+ instance = await local_vm.launch(
+ name,
+ cpus=cpus,
+ memory_gb=memory_gb,
+ disk_gb=disk_gb,
+ image=image,
+ public_key=public_key,
+ )
+ except local_vm.LocalVmError as exc:
+ log.warning("computers: creating VM %s failed: %s", name, exc.message)
+ with contextlib.suppress(ComputerError):
+ self._set_health(
+ computer_id,
+ ComputerHealth(status="error", checked_at=time.time(), message=exc.message),
+ )
+ return
+ self._store.update(
+ computer_id,
+ lambda row: row.model_copy(
+ update={
+ "host": instance.ipv4 or row.host,
+ "health": ComputerHealth(status="unknown", checked_at=time.time()),
+ }
+ ),
+ )
+ # cloud-init may still be writing the key for a few seconds after boot.
+ for attempt in range(6):
+ refreshed = await self.check(computer_id)
+ if refreshed.health.status == "online":
+ return
+ await asyncio.sleep(5 * (attempt + 1))
+
+ async def power(self, computer_id: str, action: str) -> Computer:
+ computer = self.get(computer_id)
+ if computer.kind != "local_vm" or not computer.provider_ref:
+ raise ComputerError("Only local virtual machines can be started or stopped here.")
+ try:
+ if action == "start":
+ await local_vm.start(computer.provider_ref)
+ instance = await local_vm.info(computer.provider_ref)
+ if instance is not None and instance.ipv4 and instance.ipv4 != computer.host:
+ # A restarted VM may come back on a new address; same machine.
+ self._store.update(
+ computer_id, lambda row: row.model_copy(update={"host": instance.ipv4})
+ )
+ elif action == "stop":
+ await local_vm.stop(computer.provider_ref)
+ return self._set_health(
+ computer_id, ComputerHealth(status="stopped", checked_at=time.time())
+ )
+ else:
+ raise ComputerError("Choose start or stop.")
+ except local_vm.LocalVmError as exc:
+ raise ComputerError(exc.message, status=502) from exc
+ return await self.check(computer_id)
+
+
+_SERVICE: ComputerService | None = None
+
+
+def get_service() -> ComputerService:
+ """The process-wide service (routes, CLI and later features share it)."""
+ global _SERVICE
+ if _SERVICE is None:
+ _SERVICE = ComputerService()
+ return _SERVICE
diff --git a/jarvis/computers/ssh.py b/jarvis/computers/ssh.py
new file mode 100644
index 0000000000..83c2069423
--- /dev/null
+++ b/jarvis/computers/ssh.py
@@ -0,0 +1,206 @@
+"""SSH to a computer: connect, run one command, install Jarvis's key.
+
+Built on ``asyncssh`` (pure Python), so it works the same on Windows, macOS and
+a bare Linux server with no ``ssh`` binary. Host keys are trust-on-first-use:
+the first successful contact pins the server's key on the record, and every
+later connection accepts ONLY that key — a changed key raises
+:class:`SshError` with ``kind="host_key_changed"`` before any password or
+command is sent. The user's own ``~/.ssh`` agent and config are deliberately
+NOT consulted: a computer connects with exactly the credentials shown in the
+app, on every OS.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import shlex
+import socket
+import time
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Any, Literal
+
+if TYPE_CHECKING:
+ import asyncssh
+
+log = logging.getLogger(__name__)
+
+SshErrorKind = Literal["unreachable", "timeout", "auth", "host_key_changed", "protocol"]
+
+CONNECT_TIMEOUT_S = 12.0
+#: Longest a user command may run from the UI console.
+MAX_COMMAND_TIMEOUT_S = 300.0
+#: Output beyond this is cut (per stream) so one ``cat`` cannot flood the UI.
+MAX_OUTPUT_CHARS = 200_000
+
+
+class SshError(Exception):
+ """A connection or command failed; ``kind`` picks the user-facing sentence."""
+
+ def __init__(self, kind: SshErrorKind, message: str) -> None:
+ super().__init__(message)
+ self.kind: SshErrorKind = kind
+ self.message = message
+
+
+@dataclass(frozen=True)
+class SshTarget:
+ """Everything needed to open one connection."""
+
+ host: str
+ port: int
+ username: str
+ #: Pinned OpenSSH host-key line; ``None`` on first contact (TOFU).
+ host_key: str | None = None
+ password: str | None = None
+ client_key: asyncssh.SSHKey | None = None
+
+
+@dataclass(frozen=True)
+class CommandResult:
+ exit_status: int | None
+ stdout: str
+ stderr: str
+ duration_ms: int
+ truncated: bool
+
+
+@dataclass(frozen=True)
+class Session:
+ """An open connection plus what it learned about the server."""
+
+ conn: asyncssh.SSHClientConnection
+ host_key: str
+ host_fingerprint: str
+ latency_ms: int
+
+
+def _classify(exc: BaseException) -> SshError:
+ import asyncssh
+
+ if isinstance(exc, SshError):
+ return exc
+ if isinstance(exc, asyncssh.HostKeyNotVerifiable):
+ return SshError(
+ "host_key_changed",
+ "The server's identity changed since the last connection. If you "
+ "reinstalled it, confirm the new identity; otherwise do not connect.",
+ )
+ if isinstance(exc, asyncssh.PermissionDenied):
+ return SshError("auth", "The server refused the login.")
+ if isinstance(exc, (TimeoutError, asyncio.TimeoutError)):
+ return SshError("timeout", "The server did not answer in time.")
+ if isinstance(exc, socket.gaierror):
+ return SshError("unreachable", "This address could not be found.")
+ if isinstance(exc, ConnectionRefusedError):
+ return SshError("unreachable", "The server refused the connection on this port.")
+ if isinstance(exc, OSError):
+ return SshError("unreachable", "The server could not be reached.")
+ if isinstance(exc, asyncssh.Error):
+ return SshError("protocol", f"The SSH connection failed: {exc.reason}")
+ return SshError("protocol", f"The SSH connection failed: {type(exc).__name__}")
+
+
+async def open_session(target: SshTarget, *, timeout_s: float = CONNECT_TIMEOUT_S) -> Session:
+ """Connect and authenticate; raise :class:`SshError` on any failure."""
+ import asyncssh
+
+ known_hosts: Any
+ if target.host_key:
+ try:
+ pinned = asyncssh.import_public_key(target.host_key)
+ except (asyncssh.KeyImportError, ValueError) as exc:
+ raise SshError("protocol", "The saved server identity is unreadable.") from exc
+ known_hosts = ([pinned], [], [])
+ else:
+ known_hosts = None # first contact: pin whatever key answers
+
+ options: dict[str, Any] = {
+ "port": target.port,
+ "username": target.username,
+ "known_hosts": known_hosts,
+ "agent_path": None,
+ "config": [],
+ "client_keys": [target.client_key] if target.client_key is not None else None,
+ "password": target.password,
+ "connect_timeout": timeout_s,
+ "login_timeout": timeout_s,
+ }
+ if target.client_key is None:
+ options["preferred_auth"] = "password,keyboard-interactive"
+ started = time.perf_counter()
+ try:
+ conn = await asyncssh.connect(target.host, **options)
+ except BaseException as exc:
+ if isinstance(exc, asyncio.CancelledError):
+ raise
+ error = _classify(exc)
+ log.info(
+ "computers: ssh %s@%s:%s failed (%s)",
+ target.username,
+ target.host,
+ target.port,
+ error.kind,
+ )
+ raise error from exc
+ latency_ms = int((time.perf_counter() - started) * 1000)
+ server_key = conn.get_server_host_key()
+ if server_key is None:
+ conn.close()
+ raise SshError("protocol", "The server did not present an identity.")
+ return Session(
+ conn=conn,
+ host_key=server_key.export_public_key("openssh").decode("utf-8").strip(),
+ host_fingerprint=server_key.get_fingerprint("sha256"),
+ latency_ms=latency_ms,
+ )
+
+
+def _cut(text: str) -> tuple[str, bool]:
+ if len(text) <= MAX_OUTPUT_CHARS:
+ return text, False
+ return text[:MAX_OUTPUT_CHARS], True
+
+
+async def run_command(session: Session, command: str, *, timeout_s: float) -> CommandResult:
+ """Run one command on an open session and collect its output."""
+ import asyncssh
+
+ started = time.perf_counter()
+ try:
+ result = await asyncio.wait_for(
+ session.conn.run(command, check=False, encoding="utf-8", errors="replace"),
+ timeout=timeout_s,
+ )
+ except TimeoutError as exc:
+ raise SshError("timeout", f"The command did not finish within {int(timeout_s)} s.") from exc
+ except asyncssh.Error as exc:
+ raise _classify(exc) from exc
+ stdout, cut_out = _cut(str(result.stdout or ""))
+ stderr, cut_err = _cut(str(result.stderr or ""))
+ return CommandResult(
+ exit_status=result.exit_status,
+ stdout=stdout,
+ stderr=stderr,
+ duration_ms=int((time.perf_counter() - started) * 1000),
+ truncated=cut_out or cut_err,
+ )
+
+
+def authorize_key_command(public_key: str) -> str:
+ """The idempotent shell command that adds ``public_key`` to authorized_keys."""
+ quoted = shlex.quote(public_key.strip())
+ return (
+ "umask 077 && mkdir -p ~/.ssh && touch ~/.ssh/authorized_keys && "
+ f"(grep -qxF {quoted} ~/.ssh/authorized_keys || "
+ f"printf '%s\\n' {quoted} >> ~/.ssh/authorized_keys) && "
+ "chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys"
+ )
+
+
+def close(session: Session) -> None:
+ """Close without waiting; asyncssh finishes the teardown in the background."""
+ try:
+ session.conn.close()
+ except Exception: # noqa: BLE001 — a close on a dead socket has nothing to report
+ log.debug("computers: closing an ssh session failed", exc_info=True)
diff --git a/jarvis/computers/store.py b/jarvis/computers/store.py
new file mode 100644
index 0000000000..eb699fb25f
--- /dev/null
+++ b/jarvis/computers/store.py
@@ -0,0 +1,119 @@
+"""The JSON file the computer records live in.
+
+``<user data>/computers/computers.json``, rewritten atomically (temp file +
+``os.replace``) under one process-wide lock, so a crash mid-write leaves the
+previous file intact and two requests never interleave a read-modify-write.
+No secrets are ever written here.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import tempfile
+import threading
+from collections.abc import Callable
+from pathlib import Path
+
+from pydantic import ValidationError
+
+from jarvis.computers.models import Computer
+from jarvis.core.paths import user_data_dir
+
+log = logging.getLogger(__name__)
+
+_FILE_VERSION = 1
+_LOCK = threading.RLock()
+
+
+def default_path() -> Path:
+ """Where the records live; resolved per call so a test sandbox is honoured."""
+ return user_data_dir() / "computers" / "computers.json"
+
+
+class ComputerStore:
+ """Read and write the computer list. Cheap to construct; holds no state."""
+
+ def __init__(self, path: Path | None = None) -> None:
+ self._path = path or default_path()
+
+ @property
+ def path(self) -> Path:
+ return self._path
+
+ def all(self) -> list[Computer]:
+ with _LOCK:
+ return self._read()
+
+ def get(self, computer_id: str) -> Computer | None:
+ return next((c for c in self.all() if c.id == computer_id), None)
+
+ def add(self, computer: Computer) -> Computer:
+ with _LOCK:
+ rows = self._read()
+ if any(c.id == computer.id for c in rows):
+ raise ValueError(f"A computer with id {computer.id!r} already exists.")
+ rows.append(computer)
+ self._write(rows)
+ return computer
+
+ def update(self, computer_id: str, change: Callable[[Computer], Computer]) -> Computer | None:
+ """Apply ``change`` to one record and persist it; ``None`` when unknown."""
+ with _LOCK:
+ rows = self._read()
+ for index, row in enumerate(rows):
+ if row.id == computer_id:
+ updated = change(row)
+ rows[index] = updated
+ self._write(rows)
+ return updated
+ return None
+
+ def remove(self, computer_id: str) -> bool:
+ with _LOCK:
+ rows = self._read()
+ kept = [c for c in rows if c.id != computer_id]
+ if len(kept) == len(rows):
+ return False
+ self._write(kept)
+ return True
+
+ # -- file I/O ----------------------------------------------------------
+
+ def _read(self) -> list[Computer]:
+ try:
+ raw = self._path.read_text(encoding="utf-8")
+ except FileNotFoundError: # no file yet simply means no computers yet
+ return []
+ try:
+ data = json.loads(raw)
+ except json.JSONDecodeError:
+ # Never overwrite a file we cannot read: keep a copy for the user and
+ # start from an empty list rather than refusing every request.
+ backup = self._path.with_suffix(".corrupt.json")
+ log.warning("computers: %s is not JSON; moved aside to %s", self._path, backup)
+ os.replace(self._path, backup)
+ return []
+ rows: list[Computer] = []
+ for item in data.get("computers", []) if isinstance(data, dict) else []:
+ try:
+ rows.append(Computer.model_validate(item))
+ except ValidationError as exc:
+ log.warning("computers: skipping an unreadable record: %s", exc)
+ return rows
+
+ def _write(self, rows: list[Computer]) -> None:
+ self._path.parent.mkdir(parents=True, exist_ok=True)
+ payload = {
+ "version": _FILE_VERSION,
+ "computers": [row.model_dump(mode="json") for row in rows],
+ }
+ fd, tmp = tempfile.mkstemp(prefix=".computers.", suffix=".tmp", dir=self._path.parent)
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ json.dump(payload, handle, indent=2, ensure_ascii=False)
+ os.replace(tmp, self._path)
+ except BaseException:
+ Path(tmp).unlink(missing_ok=True)
+ raise
diff --git a/jarvis/ui/web/computers_routes.py b/jarvis/ui/web/computers_routes.py
new file mode 100644
index 0000000000..0b98b159bc
--- /dev/null
+++ b/jarvis/ui/web/computers_routes.py
@@ -0,0 +1,326 @@
+"""REST API for the Computers section (Settings -> Computers).
+
+ GET /api/computers list + Jarvis's public key
+ POST /api/computers add an SSH server
+ POST /api/computers/check-all check every computer
+ GET /api/computers/identity Jarvis's public key + fingerprint
+ GET /api/computers/cloud hosting providers + token state
+ PUT /api/computers/cloud/{provider}/token save an API token (keyring)
+ DELETE /api/computers/cloud/{provider}/token forget it
+ GET /api/computers/cloud/{provider}/servers the account's servers
+ POST /api/computers/cloud/{provider}/import connect one of them
+ GET /api/computers/local Multipass state + instances
+ POST /api/computers/local create a local VM (background)
+ GET /api/computers/{id} one computer
+ PATCH /api/computers/{id} rename / edit address
+ DELETE /api/computers/{id} remove (optionally destroy the VM)
+ POST /api/computers/{id}/check connect and read vitals
+ POST /api/computers/{id}/run run one shell command
+ POST /api/computers/{id}/install-key plant Jarvis's key with a password
+ POST /api/computers/{id}/trust-host-key accept a changed server identity
+ POST /api/computers/{id}/power start / stop a local VM
+
+Static paths are registered before ``/{computer_id}`` so the dynamic route
+cannot swallow them. Store reads are plain ``def`` (threadpool); anything that
+talks to a network or a subprocess is ``async`` and awaits it. Passwords and
+tokens arrive in request bodies and go straight to the keyring or the SSH
+handshake — they are never logged or echoed back.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Literal
+
+from fastapi import APIRouter, HTTPException
+from pydantic import BaseModel, Field
+
+from jarvis.computers import cloud, identity, local_vm
+from jarvis.computers.models import Computer
+from jarvis.computers.service import ComputerError, get_service
+
+log = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/api/computers", tags=["computers"])
+
+
+def _fail(exc: ComputerError) -> HTTPException:
+ return HTTPException(status_code=exc.status, detail={"message": exc.message, "kind": exc.kind})
+
+
+def _row(computer: Computer) -> dict[str, Any]:
+ data = computer.model_dump(mode="json")
+ data["busy"] = get_service().is_busy(computer.id)
+ return data
+
+
+# -- request bodies ----------------------------------------------------------
+
+
+class AddServerBody(BaseModel):
+ name: str = Field(min_length=1, max_length=120)
+ host: str = Field(min_length=1, max_length=253)
+ port: int = Field(default=22, ge=1, le=65535)
+ username: str = Field(default="root", min_length=1, max_length=64)
+ auth: Literal["key", "password"] = "key"
+ password: str | None = Field(default=None, max_length=1024)
+ keep_password: bool = False
+
+
+class UpdateBody(BaseModel):
+ name: str | None = Field(default=None, max_length=120)
+ host: str | None = Field(default=None, max_length=253)
+ port: int | None = Field(default=None, ge=1, le=65535)
+ username: str | None = Field(default=None, max_length=64)
+
+
+class RunBody(BaseModel):
+ command: str = Field(min_length=1, max_length=20_000)
+ timeout_s: float = Field(default=60.0, ge=1, le=300)
+
+
+class PasswordBody(BaseModel):
+ password: str = Field(min_length=1, max_length=1024)
+
+
+class PowerBody(BaseModel):
+ action: Literal["start", "stop"]
+
+
+class TokenBody(BaseModel):
+ token: str = Field(min_length=8, max_length=4096)
+
+
+class ImportBody(BaseModel):
+ server_id: str = Field(min_length=1, max_length=64)
+ name: str | None = Field(default=None, max_length=120)
+ username: str = Field(default="root", max_length=64)
+ password: str | None = Field(default=None, max_length=1024)
+
+
+class LocalVmBody(BaseModel):
+ name: str = Field(min_length=2, max_length=40)
+ cpus: int = Field(default=2, ge=1, le=64)
+ memory_gb: int = Field(default=4, ge=1, le=256)
+ disk_gb: int = Field(default=20, ge=5, le=2048)
+ image: str = Field(default="24.04", max_length=40, pattern=r"^[A-Za-z0-9.:\-]+$")
+
+
+# -- collection ----------------------------------------------------------------
+
+
+def list_computers() -> dict[str, Any]:
+ return {"computers": [_row(c) for c in get_service().all()]}
+
+
[email protected]("", status_code=201)
+async def add_computer(body: AddServerBody) -> dict[str, Any]:
+ try:
+ computer = await get_service().add_server(
+ name=body.name,
+ host=body.host,
+ port=body.port,
+ username=body.username,
+ auth=body.auth,
+ password=body.password,
+ keep_password=body.keep_password,
+ )
+ except ComputerError as exc:
+ raise _fail(exc) from exc
+ return _row(computer)
+
+
[email protected]("/check-all")
+async def check_all() -> dict[str, Any]:
+ computers = await get_service().check_all()
+ return {"computers": [_row(c) for c in computers]}
+
+
[email protected]("/identity")
+def get_identity() -> dict[str, Any]:
+ try:
+ return identity.describe()
+ except identity.IdentityError as exc:
+ raise HTTPException(status_code=500, detail={"message": str(exc), "kind": None}) from exc
+
+
+# -- hosting providers ---------------------------------------------------------
+
+
+def list_cloud_providers() -> dict[str, Any]:
+ rows = []
+ for spec in cloud.PROVIDERS.values():
+ rows.append(
+ {
+ "id": spec.id,
+ "name": spec.name,
+ "connected": bool(cloud.token(spec.id)),
+ "console_url": spec.console_url,
+ "setup_hint": spec.setup_hint,
+ "attaches_keys": spec.attaches_keys,
+ }
+ )
+ return {"providers": rows}
+
+
+def _known_provider(provider_id: str) -> None:
+ if provider_id not in cloud.PROVIDERS:
+ raise HTTPException(status_code=404, detail={"message": "Unknown provider.", "kind": None})
+
+
[email protected]("/cloud/{provider_id}/token")
+async def save_cloud_token(provider_id: str, body: TokenBody) -> dict[str, Any]:
+ _known_provider(provider_id)
+ previous = cloud.token(provider_id)
+ try:
+ cloud.save_token(provider_id, body.token)
+ # Prove the token before calling it connected; a typo should say so now.
+ servers = await get_service().cloud_servers(provider_id)
+ except cloud.CloudError as exc:
+ raise HTTPException(status_code=500, detail={"message": exc.message, "kind": None}) from exc
+ except ComputerError as exc:
+ # Keep a working token rather than replace it with one that failed.
+ if previous:
+ cloud.save_token(provider_id, previous)
+ else:
+ try:
+ cloud.forget_token(provider_id)
+ except cloud.CloudError:
+ log.warning("computers: a refused %s token could not be removed", provider_id)
+ raise _fail(exc) from exc
+ return {"connected": True, "servers": servers}
+
+
[email protected]("/cloud/{provider_id}/token")
+def forget_cloud_token(provider_id: str) -> dict[str, Any]:
+ _known_provider(provider_id)
+ try:
+ cloud.forget_token(provider_id)
+ except cloud.CloudError as exc:
+ raise HTTPException(status_code=500, detail={"message": exc.message, "kind": None}) from exc
+ return {"connected": False}
+
+
[email protected]("/cloud/{provider_id}/servers")
+async def list_cloud_servers(provider_id: str) -> dict[str, Any]:
+ _known_provider(provider_id)
+ try:
+ return {"servers": await get_service().cloud_servers(provider_id)}
+ except ComputerError as exc:
+ raise _fail(exc) from exc
+
+
[email protected]("/cloud/{provider_id}/import", status_code=201)
+async def import_cloud_server(provider_id: str, body: ImportBody) -> dict[str, Any]:
+ _known_provider(provider_id)
+ try:
+ computer = await get_service().import_cloud_server(
+ provider_id,
+ body.server_id,
+ name=body.name,
+ username=body.username,
+ password=body.password,
+ )
+ except ComputerError as exc:
+ raise _fail(exc) from exc
+ return _row(computer)
+
+
+# -- local virtual machines ------------------------------------------------------
+
+
+async def local_status() -> dict[str, Any]:
+ return await local_vm.status()
+
+
[email protected]("/local", status_code=202)
+async def create_local_vm(body: LocalVmBody) -> dict[str, Any]:
+ try:
+ computer = await get_service().create_local_vm(
+ name=body.name,
+ cpus=body.cpus,
+ memory_gb=body.memory_gb,
+ disk_gb=body.disk_gb,
+ image=body.image,
+ )
+ except ComputerError as exc:
+ raise _fail(exc) from exc
+ return _row(computer)
+
+
+# -- one computer ------------------------------------------------------------------
+
+
[email protected]("/{computer_id}")
+def get_computer(computer_id: str) -> dict[str, Any]:
+ try:
+ return _row(get_service().get(computer_id))
+ except ComputerError as exc:
+ raise _fail(exc) from exc
+
+
[email protected]("/{computer_id}")
+def update_computer(computer_id: str, body: UpdateBody) -> dict[str, Any]:
+ try:
+ return _row(get_service().update(computer_id, **body.model_dump(exclude_none=True)))
+ except ComputerError as exc:
+ raise _fail(exc) from exc
+
+
[email protected]("/{computer_id}")
+async def remove_computer(computer_id: str, destroy_vm: bool = False) -> dict[str, Any]:
+ try:
+ removed = await get_service().remove(computer_id, destroy_vm=destroy_vm)
+ except ComputerError as exc:
+ raise _fail(exc) from exc
+ return {"removed": removed}
+
+
[email protected]("/{computer_id}/check")
+async def check_computer(computer_id: str) -> dict[str, Any]:
+ try:
+ return _row(await get_service().check(computer_id))
+ except ComputerError as exc:
+ raise _fail(exc) from exc
+
+
[email protected]("/{computer_id}/run")
+async def run_on_computer(computer_id: str, body: RunBody) -> dict[str, Any]:
+ try:
+ result = await get_service().run(computer_id, body.command, timeout_s=body.timeout_s)
+ except ComputerError as exc:
+ raise _fail(exc) from exc
+ return {
+ "exit_status": result.exit_status,
+ "stdout": result.stdout,
+ "stderr": result.stderr,
+ "duration_ms": result.duration_ms,
+ "truncated": result.truncated,
+ }
+
+
[email protected]("/{computer_id}/install-key")
+async def install_key(computer_id: str, body: PasswordBody) -> dict[str, Any]:
+ try:
+ return _row(await get_service().install_key(computer_id, body.password))
+ except ComputerError as exc:
+ raise _fail(exc) from exc
+
+
[email protected]("/{computer_id}/trust-host-key")
+async def trust_host_key(computer_id: str) -> dict[str, Any]:
+ try:
+ return _row(await get_service().trust_new_host_key(computer_id))
+ except ComputerError as exc:
+ raise _fail(exc) from exc
+
+
[email protected]("/{computer_id}/power")
+async def power_computer(computer_id: str, body: PowerBody) -> dict[str, Any]:
+ try:
+ return _row(await get_service().power(computer_id, body.action))
+ except ComputerError as exc:
+ raise _fail(exc) from exc
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 28cd01bd7a..d093db8c16 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -348,6 +348,7 @@ class WebServer:
from .clipboard_routes import router as clipboard_router
from .commands_routes import router as commands_router
from .computer_use_routes import router as computer_use_router
+ from .computers_routes import router as computers_router
from .contacts_routes import router as contacts_router
from .control_routes import router as control_router
from .costs_routes import router as costs_router
@@ -539,6 +540,8 @@ class WebServer:
app.include_router(chat_library_router)
# Contacts section — user-curated address book (pure file store, no Brain dep).
app.include_router(contacts_router)
+ # Settings -> Computers: the user's own servers and local VMs over SSH.
+ app.include_router(computers_router)
app.include_router(dictionary_router)
# Dictation mode — hold to speak, text lands in the focused field.
# Mounted so every action is also `jarvis api dictation <op>`, which is
diff --git a/pyproject.toml b/pyproject.toml
index 149be9adc5..6207099ef6 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -86,6 +86,10 @@ dependencies = [
"structlog>=24.4",
"loguru>=0.7",
"keyring>=25.5",
+ # SSH to the user's own servers and virtual machines (Settings -> Computers).
+ # Pure Python on top of cryptography, so it installs on every OS cell and a
+ # headless python:3.11-slim without a system ssh client.
+ "asyncssh>=2.21",
"sounddevice>=0.5", # PortAudio binding; needs system libportaudio2 on Linux
# ChatGPT-Live (Codex subscription voice) carries audio ONLY on a WebRTC
# media track — its protocol has no audio event at all. Jarvis owns that
diff --git a/requirements.in b/requirements.in
index 9c606f0153..c10e38d27c 100644
--- a/requirements.in
+++ b/requirements.in
@@ -65,6 +65,9 @@ loguru>=0.7
# Secrets (Windows Credential Manager / Linux Secret Service)
keyring>=25.5
+# SSH to the user's own servers and virtual machines (Settings -> Computers)
+asyncssh>=2.21
+
# Audio I/O
sounddevice>=0.5
# Upstream's native dependencies do not publish Windows ARM64 wheels. The
diff --git a/requirements.txt b/requirements.txt
index 7ac34fb299..98f57b098d 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -46,6 +46,14 @@ anyio==4.15.1 \
# openai
# sse-starlette
# starlette
+asyncssh==2.23.1 ; platform_machine == 'ARM64' and sys_platform == 'win32' \
+ --hash=sha256:d9dc3bc0206f3e4b5d80d1c0e6a24af2b4ad4beb556884c41fb2ad1c7ca3f44f \
+ --hash=sha256:f68e55476d41253d785bcac9a90834ae5fdea0f417bd6d7182608bda248de88e
+ # via -r requirements.in
+asyncssh==2.24.0 ; platform_machine != 'ARM64' or sys_platform != 'win32' \
+ --hash=sha256:4064c590e59ce2e8d82a2f66d35f3120d765828b4df5e3dbfb07b4a8c24686c9 \
+ --hash=sha256:9abd46300adcb6d4b73269b34c53cd0d17a138b9a22b5b38008ce7d5808734b7
+ # via -r requirements.in
attrs==26.1.0 \
--hash=sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309 \
--hash=sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32
@@ -503,6 +511,7 @@ cryptography==46.0.3 ; platform_machine == 'ARM64' and sys_platform == 'win32' \
--hash=sha256:f260d0d41e9b4da1ed1e0f1ce571f97fe370b152ab18778e9e8f67d6af432018
# via
# -r requirements.in
+ # asyncssh
# google-auth
# pyjwt
cryptography==48.0.1 ; platform_machine == 'x86_64' and sys_platform == 'darwin' \
@@ -558,6 +567,7 @@ cryptography==48.0.1 ; platform_machine == 'x86_64' and sys_platform == 'darwin'
# via
# -r requirements.in
# aiortc
+ # asyncssh
# google-auth
# pyjwt
# pyopenssl
@@ -611,6 +621,7 @@ cryptography==50.0.0 ; (platform_machine != 'x86_64' and sys_platform == 'darwin
# via
# -r requirements.in
# aiortc
+ # asyncssh
# google-auth
# pyjwt
# pyopenssl
@@ -2247,6 +2258,7 @@ typing-extensions==4.16.0 \
# via
# anthropic
# anyio
+ # asyncssh
# elevenlabs
# fastapi
# google-genai
diff --git a/tests/fakes/fake_ssh_server.py b/tests/fakes/fake_ssh_server.py
new file mode 100644
index 0000000000..faf1490e15
--- /dev/null
+++ b/tests/fakes/fake_ssh_server.py
@@ -0,0 +1,130 @@
+"""An in-process SSH server for the Computers tests.
+
+A real ``asyncssh`` server on 127.0.0.1 with a tiny scripted "shell": it
+accepts one password, trusts the public keys it has been told about (and the
+ones an ``authorized_keys`` command appends), answers the health probe with a
+canned Linux reading, and echoes every other command. Nothing on disk, no
+system ``sshd`` — the tests exercise the actual SSH handshake, host-key pinning
+and key installation end to end on every OS.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass, field
+from typing import Any
+
+import asyncssh
+
+from jarvis.computers.probe import PROBE_SCRIPT
+
+LINUX_PROBE_OUTPUT = """@@hostname
+srv-test
+@@uname
+Linux 6.8.0-45-generic x86_64
+@@os
+NAME="Ubuntu"
+ID=ubuntu
+PRETTY_NAME="Ubuntu 24.04.1 LTS"
+@@darwin
+@@nproc
+4
+@@meminfo
+MemTotal: 8000000 kB
+MemFree: 1000000 kB
+MemAvailable: 6000000 kB
+@@memsize
+@@df
+/dev/sda1 81000000 20250000 60750000 25% /
+@@uptime
+86400.52 300000.00
+@@loadavg
+0.42 0.30 0.25 1/300 12345
+@@end
+"""
+
+#: The one password the fake server accepts.
+TEST_PASSWORD = "correct horse" # noqa: S105 — a fixture, not a credential
+
+_KEY_RE = re.compile(r"'?(ssh-[a-z0-9-]+ [A-Za-z0-9+/=]+(?: [^'\s]+)?)'?")
+
+
+@dataclass
+class FakeSshState:
+ password: str = TEST_PASSWORD
+ username: str = "root"
+ authorized: set[str] = field(default_factory=set)
+ commands: list[str] = field(default_factory=list)
+
+
+def _key_body(line: str) -> str:
+ return " ".join(line.split()[:2])
+
+
+class _Server(asyncssh.SSHServer):
+ def __init__(self, state: FakeSshState) -> None:
+ self._state = state
+
+ def begin_auth(self, username: str) -> bool:
+ return True
+
+ def password_auth_supported(self) -> bool:
+ return True
+
+ def validate_password(self, username: str, password: str) -> bool:
+ return username == self._state.username and password == self._state.password
+
+ def public_key_auth_supported(self) -> bool:
+ return True
+
+ def validate_public_key(self, username: str, key: asyncssh.SSHKey) -> bool:
+ line = key.export_public_key("openssh").decode().strip()
+ return username == self._state.username and _key_body(line) in {
+ _key_body(k) for k in self._state.authorized
+ }
+
+
+class FakeSshServer:
+ """Start with :meth:`start`, stop with :meth:`stop`; ``port`` is random."""
+
+ def __init__(self, state: FakeSshState | None = None) -> None:
+ self.state = state or FakeSshState()
+ self.host_key = asyncssh.generate_private_key("ssh-ed25519")
+ self._acceptor: Any = None
+ self.port = 0
+
+ async def _process(self, process: asyncssh.SSHServerProcess) -> None:
+ command = process.command or ""
+ self.state.commands.append(command)
+ if command == PROBE_SCRIPT:
+ process.stdout.write(LINUX_PROBE_OUTPUT)
+ process.exit(0)
+ return
+ if "authorized_keys" in command:
+ match = _KEY_RE.search(command)
+ if match:
+ self.state.authorized.add(match.group(1))
+ process.exit(0)
+ return
+ if command == "fail":
+ process.stderr.write("boom\n")
+ process.exit(3)
+ return
+ process.stdout.write(f"ran: {command}\n")
+ process.exit(0)
+
+ async def start(self, port: int = 0) -> None:
+ self._acceptor = await asyncssh.listen(
+ "127.0.0.1",
+ port,
+ server_host_keys=[self.host_key],
+ server_factory=lambda: _Server(self.state),
+ process_factory=self._process,
+ )
+ self.port = self._acceptor.sockets[0].getsockname()[1]
+
+ async def stop(self) -> None:
+ if self._acceptor is not None:
+ self._acceptor.close()
+ await self._acceptor.wait_closed()
+ self._acceptor = None
diff --git a/tests/unit/computers/__init__.py b/tests/unit/computers/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/unit/computers/conftest.py b/tests/unit/computers/conftest.py
new file mode 100644
index 0000000000..3fc9b3c7f6
--- /dev/null
+++ b/tests/unit/computers/conftest.py
@@ -0,0 +1,47 @@
+"""Shared fixtures: an in-memory keyring and a sandboxed computer store."""
+
+from __future__ import annotations
+
+from collections.abc import Iterator
+
+import pytest
+
+from jarvis.computers import cloud, identity, service
+from jarvis.computers.service import ComputerService
+from jarvis.computers.store import ComputerStore
+
+
+class SecretBox:
+ """A dict standing in for the OS keyring."""
+
+ 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 secret_box(monkeypatch: pytest.MonkeyPatch) -> Iterator[SecretBox]:
+ box = SecretBox()
+ for module in (identity, service, cloud):
+ if hasattr(module, "get_secret"):
+ monkeypatch.setattr(module, "get_secret", box.get)
+ if hasattr(module, "set_secret"):
+ monkeypatch.setattr(module, "set_secret", box.set)
+ if hasattr(module, "delete_secret"):
+ monkeypatch.setattr(module, "delete_secret", box.delete)
+ yield box
+
+
+def computer_service(tmp_path, secret_box: SecretBox) -> ComputerService: # noqa: ANN001
+ return ComputerService(ComputerStore(tmp_path / "computers.json"))
diff --git a/tests/unit/computers/test_cloud_and_routes.py b/tests/unit/computers/test_cloud_and_routes.py
new file mode 100644
index 0000000000..c9dbf390c7
--- /dev/null
+++ b/tests/unit/computers/test_cloud_and_routes.py
@@ -0,0 +1,111 @@
+"""Hosting-provider calls over a mock transport, and the REST surface."""
+
+from __future__ import annotations
+
+import json
+
+import httpx
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.computers import cloud
+from jarvis.computers.service import ComputerService
+from jarvis.ui.web import computers_routes
+
+
+async def test_hostinger_attach_creates_the_key_once_and_attaches_it(secret_box) -> None: # noqa: ANN001
+ secret_box.set("hostinger_api_token", "tok-123456")
+ calls: list[tuple[str, str, object]] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ body = json.loads(request.content) if request.content else None
+ calls.append((request.method, request.url.path, body))
+ assert request.headers["Authorization"] == "Bearer tok-123456"
+ if request.url.path == "/api/vps/v1/public-keys" and request.method == "GET":
+ return httpx.Response(200, json={"data": [], "meta": {"per_page": 15, "total": 0}})
+ if request.url.path == "/api/vps/v1/public-keys":
+ return httpx.Response(200, json={"id": 325, "name": "Personal Jarvis", "key": "k"})
+ return httpx.Response(200, json={"id": 1, "state": "success"})
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ await cloud.attach_public_key("hostinger", "17923", "ssh-ed25519 AAAA me", client=client)
+
+ assert calls[-1] == ("POST", "/api/vps/v1/public-keys/attach/17923", {"ids": [325]})
+
+
+async def test_refused_token_becomes_a_sentence_without_the_body(secret_box) -> None: # noqa: ANN001
+ secret_box.set("hetzner_api_token", "bad-token")
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(401, json={"error": {"message": "secret account detail"}})
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ with pytest.raises(cloud.CloudError) as caught:
+ await cloud.list_servers("hetzner", client=client)
+
+ assert "refused the API token" in caught.value.message
+ assert "secret account detail" not in caught.value.message
+
+
+async def test_digitalocean_follows_pages(secret_box) -> None: # noqa: ANN001
+ secret_box.set("digitalocean_api_token", "do-token")
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ page = int(request.url.params["page"])
+ droplet = {"id": page, "name": f"d{page}", "status": "active", "networks": {"v4": []}}
+ links = {"pages": {"next": "x"}} if page == 1 else {"pages": {}}
+ return httpx.Response(200, json={"droplets": [droplet], "links": links})
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ servers = await cloud.list_servers("digitalocean", client=client)
+
+ assert [s.name for s in servers] == ["d1", "d2"]
+
+
+def client(computer_service: ComputerService, monkeypatch: pytest.MonkeyPatch) -> TestClient:
+ monkeypatch.setattr(computers_routes, "get_service", lambda: computer_service)
+ app = FastAPI()
+ app.include_router(computers_routes.router)
+ return TestClient(app)
+
+
+def test_routes_list_identity_and_providers(client: TestClient) -> None:
+ assert client.get("/api/computers").json() == {"computers": []}
+
+ ident = client.get("/api/computers/identity").json()
+ assert ident["public_key"].startswith("ssh-ed25519 ")
+ assert ident["fingerprint"].startswith("SHA256:")
+ # The identity is stable: the second read returns the same key.
+ assert client.get("/api/computers/identity").json()["public_key"] == ident["public_key"]
+
+ providers = {p["id"]: p for p in client.get("/api/computers/cloud").json()["providers"]}
+ assert set(providers) == {"hostinger", "hetzner", "digitalocean"}
+ assert providers["hostinger"]["attaches_keys"] is True
+ assert providers["hostinger"]["connected"] is False
+
+
+def test_routes_validate_and_404(client: TestClient) -> None:
+ bad = client.post("/api/computers", json={"name": "x", "host": "not a host!"})
+ assert bad.status_code == 400
+ assert "IP address" in bad.json()["detail"]["message"]
+
+ assert client.get("/api/computers/c_missing").status_code == 404
+ assert (
+ client.post("/api/computers/cloud/aws/import", json={"server_id": "1"}).status_code == 404
+ )
+ assert client.post("/api/computers/local", json={"name": "Bad Name"}).status_code in (400, 409)
+
+
+def test_rename_and_remove(client: TestClient, computer_service: ComputerService) -> None:
+ created = client.post(
+ "/api/computers", json={"name": "old", "host": "127.0.0.1", "port": 1}
+ ).json()
+ assert created["health"]["status"] == "offline"
+
+ renamed = client.patch(f"/api/computers/{created['id']}", json={"name": " New name "})
+ assert renamed.json()["name"] == "New name"
+
+ assert client.delete(f"/api/computers/{created['id']}").json() == {"removed": True}
+ assert computer_service.all() == []
diff --git a/tests/unit/computers/test_parsers.py b/tests/unit/computers/test_parsers.py
new file mode 100644
index 0000000000..596de647c3
--- /dev/null
+++ b/tests/unit/computers/test_parsers.py
@@ -0,0 +1,174 @@
+"""Pure parsers: the probe script, the three provider APIs, Multipass JSON."""
+
+from __future__ import annotations
+
+from jarvis.computers import cloud, local_vm
+from jarvis.computers.probe import parse_probe
+from tests.fakes.fake_ssh_server import LINUX_PROBE_OUTPUT
+
+MACOS_OUTPUT = """@@hostname
+studio.local
+@@uname
+Darwin 24.1.0 arm64
+@@os
+@@darwin
+ProductName:\t\tmacOS
+ProductVersion:\t\t15.1
+@@nproc
+10
+@@meminfo
+@@memsize
+34359738368
+@@df
+/dev/disk3s1s1 971350180 10485760 500000000 3% /
+@@uptime
+@@loadavg
+{ 1.52 1.60 1.70 }
+@@end
+"""
+
+
+def test_linux_probe() -> None:
+ reading = parse_probe(LINUX_PROBE_OUTPUT)
+
+ assert reading.facts.hostname == "srv-test"
+ assert reading.facts.os_id == "ubuntu"
+ assert reading.facts.kernel == "Linux 6.8.0-45-generic"
+ assert reading.facts.arch == "x86_64"
+ assert reading.facts.mem_total_mb == 7812
+ assert reading.mem_used_pct == 25.0
+ assert reading.uptime_s == 86400
+ assert reading.load_1m == 0.42
+
+
+def test_macos_probe() -> None:
+ reading = parse_probe(MACOS_OUTPUT)
+
+ assert reading.facts.os_name == "macOS 15.1"
+ assert reading.facts.os_id == "macos"
+ assert reading.facts.mem_total_mb == 32768
+ assert reading.facts.cpu_count == 10
+ assert reading.load_1m == 1.52
+
+
+def test_non_posix_shell_yields_empty_reading() -> None:
+ reading = parse_probe("'echo' is not recognized as an internal or external command")
+
+ assert reading.facts.os_name is None
+ assert reading.load_1m is None
+
+
+def test_hostinger_parser_maps_ip_template_and_region() -> None:
+ servers = cloud.parse_hostinger(
+ [
+ {
+ "id": 17923,
+ "hostname": "srv17923.hstgr.cloud",
+ "state": "running",
+ "plan": "KVM 4",
+ "data_center_id": 521,
+ "cpus": 4,
+ "memory": 8192,
+ "disk": 51200,
+ "ipv4": [{"id": 1, "address": "203.0.113.15"}],
+ "template": {"name": "Ubuntu 24.04 LTS"},
+ },
+ {"id": 2, "state": "stopped", "ipv4": None, "template": None},
+ ],
+ {521: "Phoenix"},
+ )
+
+ assert servers[0].host == "203.0.113.15"
+ assert servers[0].region == "Phoenix" and servers[0].disk_gb == 50.0
+ assert servers[0].running is True
+ assert servers[1].host is None and servers[1].running is False
+
+
+def test_hetzner_and_digitalocean_parsers() -> None:
+ hetzner = cloud.parse_hetzner(
+ {
+ "servers": [
+ {
+ "id": 42,
+ "name": "web",
+ "status": "running",
+ "public_net": {"ipv4": {"ip": "198.51.100.4"}},
+ "server_type": {"name": "cpx11", "cores": 2, "memory": 2.0, "disk": 40},
+ "location": {"name": "fsn1", "city": "Falkenstein"},
+ "image": {"description": "Ubuntu 24.04"},
+ }
+ ]
+ }
+ )
+ droplets = cloud.parse_digitalocean(
+ {
+ "droplets": [
+ {
+ "id": 3164444,
+ "name": "api",
+ "status": "active",
+ "memory": 1024,
+ "vcpus": 1,
+ "disk": 25,
+ "size_slug": "s-1vcpu-1gb",
+ "region": {"slug": "nyc3", "name": "New York 3"},
+ "image": {"distribution": "Ubuntu", "name": "24.04 (LTS) x64"},
+ "networks": {
+ "v4": [
+ {"ip_address": "10.0.0.2", "type": "private"},
+ {"ip_address": "192.0.2.9", "type": "public"},
+ ]
+ },
+ }
+ ]
+ }
+ )
+
+ assert hetzner[0].host == "198.51.100.4" and hetzner[0].memory_mb == 2048
+ assert hetzner[0].region == "Falkenstein"
+ assert droplets[0].host == "192.0.2.9" and droplets[0].running is True
+ assert droplets[0].os == "Ubuntu 24.04 (LTS) x64"
+
+
+def test_multipass_parsers() -> None:
+ listed = local_vm.parse_list(
+ {
+ "list": [
+ {
+ "name": "dev",
+ "state": "Running",
+ "ipv4": ["10.1.2.3"],
+ "release": "Ubuntu 24.04 LTS",
+ }
+ ]
+ }
+ )
+ info = local_vm.parse_info(
+ {
+ "errors": [],
+ "info": {
+ "dev": {
+ "state": "Running",
+ "cpu_count": "2",
+ "disks": {"sda1": {"used": "1932735283", "total": "10737418240"}},
+ "memory": {"used": 312471552, "total": 2147483648},
+ "ipv4": ["10.1.2.3"],
+ "release": "Ubuntu 24.04.1 LTS",
+ }
+ },
+ },
+ "dev",
+ )
+
+ assert listed[0].ipv4 == "10.1.2.3"
+ assert info is not None
+ assert info.cpus == 2 and info.memory_total_mb == 2048 and info.disk_total_gb == 10.0
+
+
+def test_multipass_names_and_cloud_init() -> None:
+ assert local_vm.valid_name("jarvis-vm")
+ assert not local_vm.valid_name("Jarvis VM")
+ assert not local_vm.valid_name("-x")
+ assert "ssh_authorized_keys:\n - ssh-ed25519 AAAA test" in local_vm.cloud_init(
+ "ssh-ed25519 AAAA test\n"
+ )
diff --git a/tests/unit/computers/test_ssh_end_to_end.py b/tests/unit/computers/test_ssh_end_to_end.py
new file mode 100644
index 0000000000..82d10482e3
--- /dev/null
+++ b/tests/unit/computers/test_ssh_end_to_end.py
@@ -0,0 +1,122 @@
+"""The whole SSH path against a real in-process server.
+
+Password once -> Jarvis key planted -> key login proven -> identity pinned ->
+vitals read; then a changed server identity is refused until confirmed.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from jarvis.computers import identity
+from jarvis.computers.service import ComputerError, ComputerService
+from tests.fakes.fake_ssh_server import TEST_PASSWORD, FakeSshServer
+
+
+async def ssh_server(): # noqa: ANN201
+ server = FakeSshServer()
+ await server.start()
+ try:
+ yield server
+ finally:
+ await server.stop()
+
+
+async def test_password_once_plants_the_key_and_forgets_the_password(
+ computer_service: ComputerService, ssh_server: FakeSshServer, secret_box
+) -> None: # noqa: ANN001
+ computer = await computer_service.add_server(
+ name="Hostinger VPS",
+ host="127.0.0.1",
+ port=ssh_server.port,
+ username="root",
+ auth="password",
+ password=TEST_PASSWORD,
+ )
+
+ assert computer.auth == "key"
+ assert computer.health.status == "online", computer.health.message
+ assert computer.host_key and computer.host_fingerprint.startswith("SHA256:")
+ assert computer.facts is not None
+ assert computer.facts.os_name == "Ubuntu 24.04.1 LTS"
+ assert computer.facts.cpu_count == 4
+ assert computer.health.disk_used_pct == 25.0
+ # The public key reached authorized_keys; no password was kept anywhere.
+ assert any(identity.public_key_line().split()[1] in k for k in ssh_server.state.authorized)
+ assert not any(k.startswith("computer_password_") for k in secret_box.values)
+
+
+async def test_run_returns_output_and_exit_status(
+ computer_service: ComputerService, ssh_server: FakeSshServer
+) -> None:
+ ssh_server.state.authorized.add(identity.public_key_line())
+ computer = await computer_service.add_server(name="box", host="127.0.0.1", port=ssh_server.port)
+
+ ok = await computer_service.run(computer.id, "uptime")
+ failed = await computer_service.run(computer.id, "fail")
+
+ assert ok.stdout == "ran: uptime\n" and ok.exit_status == 0
+ assert failed.exit_status == 3 and failed.stderr == "boom\n"
+
+
+async def test_key_not_installed_reports_auth_failed(
+ computer_service: ComputerService, ssh_server: FakeSshServer
+) -> None:
+ computer = await computer_service.add_server(name="box", host="127.0.0.1", port=ssh_server.port)
+
+ assert computer.health.status == "auth_failed"
+
+ fixed = await computer_service.install_key(computer.id, TEST_PASSWORD)
+ assert fixed.health.status == "online"
+
+
+async def test_wrong_password_is_refused_before_anything_is_saved(
+ computer_service: ComputerService, ssh_server: FakeSshServer
+) -> None:
+ with pytest.raises(ComputerError) as caught:
+ await computer_service.add_server(
+ name="box",
+ host="127.0.0.1",
+ port=ssh_server.port,
+ auth="password",
+ password=TEST_PASSWORD[::-1],
+ )
+
+ assert caught.value.kind == "auth"
+ assert computer_service.all() == []
+
+
+async def test_changed_server_identity_is_refused_until_trusted(
+ computer_service: ComputerService, ssh_server: FakeSshServer
+) -> None:
+ ssh_server.state.authorized.add(identity.public_key_line())
+ computer = await computer_service.add_server(name="box", host="127.0.0.1", port=ssh_server.port)
+ pinned = computer.host_fingerprint
+
+ # The "server was reinstalled": same address, new identity.
+ port = ssh_server.port
+ await ssh_server.stop()
+ impostor = FakeSshServer(ssh_server.state)
+ await impostor.start(port)
+ try:
+ refused = await computer_service.check(computer.id)
+ assert refused.health.status == "host_key_changed"
+ assert refused.host_fingerprint == pinned
+ commands_before = len(impostor.state.commands)
+ with pytest.raises(ComputerError):
+ await computer_service.run(computer.id, "whoami")
+ assert len(impostor.state.commands) == commands_before
+
+ trusted = await computer_service.trust_new_host_key(computer.id)
+ assert trusted.health.status == "online"
+ assert trusted.host_fingerprint != pinned
+ finally:
+ await impostor.stop()
+
+
+async def test_unreachable_host_is_offline(computer_service: ComputerService) -> None:
+ computer = await computer_service.add_server(name="gone", host="127.0.0.1", port=1)
+
+ assert computer.health.status == "offline"
+ assert computer.health.message
diff --git a/uv.lock b/uv.lock
index d95dd2065d..53cd19d44c 100644
--- a/uv.lock
+++ b/uv.lock
@@ -408,6 +408,58 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/fe/ba/e2081de779ca30d473f21f5b30e0e737c438205440784c7dfc81efc2b029/async_timeout-5.0.1-py3-none-any.whl", hash = "sha256:39e3809566ff85354557ec2398b55e096c8364bacac9405a7a1fa429e77fe76c", size = 6233, upload-time = "2024-11-06T16:41:37.9Z" },
]
+[[package]]
+name = "asyncssh"
+version = "2.23.1"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version >= '3.14' and platform_machine == 'ARM64' and sys_platform == 'win32'",
+ "python_full_version == '3.13.*' and platform_machine == 'ARM64' and sys_platform == 'win32'",
+ "python_full_version == '3.12.*' and platform_machine == 'ARM64' and sys_platform == 'win32'",
+ "python_full_version < '3.12' and platform_machine == 'ARM64' and sys_platform == 'win32'",
+]
+dependencies = [
+ { name = "cryptography", version = "46.0.3", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'ARM64' and sys_platform == 'win32'" },
+ { name = "typing-extensions", marker = "platform_machine == 'ARM64' and sys_platform == 'win32'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/a4/95/212d3d394f2a6ccb3f95056d3b9a7ce13c2f58503cbd6a38d037ef48cb13/asyncssh-2.23.1.tar.gz", hash = "sha256:d9dc3bc0206f3e4b5d80d1c0e6a24af2b4ad4beb556884c41fb2ad1c7ca3f44f", size = 542883, upload-time = "2026-06-07T14:15:18.832Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ef/94/9aa81bde40627af70388d634152e7c53e7533788e662b8093047501a1473/asyncssh-2.23.1-py3-none-any.whl", hash = "sha256:f68e55476d41253d785bcac9a90834ae5fdea0f417bd6d7182608bda248de88e", size = 376054, upload-time = "2026-06-07T14:15:17.375Z" },
+]
+
+[[package]]
+name = "asyncssh"
+version = "2.24.0"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version >= '3.14' and platform_machine == 'x86_64' and sys_platform == 'darwin'",
+ "(python_full_version >= '3.14' and platform_machine != 'ARM64' and sys_platform == 'win32') or (python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32')",
+ "python_full_version >= '3.14' and sys_platform == 'linux'",
+ "python_full_version >= '3.14' and platform_machine != 'x86_64' and sys_platform == 'darwin'",
+ "python_full_version == '3.13.*' and platform_machine == 'x86_64' and sys_platform == 'darwin'",
+ "python_full_version == '3.13.*' and platform_machine != 'x86_64' and sys_platform == 'darwin'",
+ "(python_full_version == '3.13.*' and platform_machine != 'ARM64' and sys_platform == 'win32') or (python_full_version == '3.13.*' and sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32')",
+ "python_full_version == '3.13.*' and sys_platform == 'linux'",
+ "python_full_version == '3.12.*' and platform_machine == 'x86_64' and sys_platform == 'darwin'",
+ "python_full_version < '3.12' and platform_machine == 'x86_64' and sys_platform == 'darwin'",
+ "python_full_version == '3.12.*' and platform_machine != 'x86_64' and sys_platform == 'darwin'",
+ "python_full_version < '3.12' and platform_machine != 'x86_64' and sys_platform == 'darwin'",
+ "(python_full_version == '3.12.*' and platform_machine != 'ARM64' and sys_platform == 'win32') or (python_full_version == '3.12.*' and sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32')",
+ "(python_full_version < '3.12' and platform_machine != 'ARM64' and sys_platform == 'win32') or (python_full_version < '3.12' and sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32')",
+ "python_full_version < '3.12' and platform_machine == 'x86_64' and sys_platform == 'linux'",
+ "python_full_version == '3.12.*' and sys_platform == 'linux'",
+ "python_full_version < '3.12' and platform_machine != 'x86_64' and sys_platform == 'linux'",
+]
+dependencies = [
+ { name = "cryptography", version = "48.0.1", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'x86_64' and sys_platform == 'darwin'" },
+ { name = "cryptography", version = "50.0.0", source = { registry = "https://pypi.org/simple" }, marker = "(platform_machine != 'x86_64' and sys_platform == 'darwin') or (platform_machine != 'ARM64' and sys_platform == 'win32') or (sys_platform != 'darwin' and sys_platform != 'win32')" },
+ { name = "typing-extensions", marker = "platform_machine != 'ARM64' or sys_platform != 'win32'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/dd/7f/2d79247bacc562104f312d27efe541673aa177feac89de291bd61bca52be/asyncssh-2.24.0.tar.gz", hash = "sha256:4064c590e59ce2e8d82a2f66d35f3120d765828b4df5e3dbfb07b4a8c24686c9", size = 550148, upload-time = "2026-06-27T20:34:44.755Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/3e/29/908ce0ca5e8cae76662e354a0f08df552d6d221844748b9e5ca06051cc44/asyncssh-2.24.0-py3-none-any.whl", hash = "sha256:9abd46300adcb6d4b73269b34c53cd0d17a138b9a22b5b38008ce7d5808734b7", size = 381237, upload-time = "2026-06-27T20:34:43.198Z" },
+]
+
[[package]]
name = "attrs"
version = "26.1.0"
@@ -2750,6 +2802,8 @@ dependencies = [
{ name = "aiosqlite" },
{ name = "anthropic" },
{ name = "anyio" },
+ { name = "asyncssh", version = "2.23.1", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'ARM64' and sys_platform == 'win32'" },
+ { name = "asyncssh", version = "2.24.0", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine != 'ARM64' or sys_platform != 'win32'" },
{ name = "audioop-lts", marker = "python_full_version >= '3.13'" },
{ name = "av", marker = "platform_machine == 'arm64' and sys_platform == 'darwin'" },
{ name = "click" },
@@ -2937,6 +2991,7 @@ requires-dist = [
{ name = "aiosqlite", specifier = ">=0.21" },
{ name = "anthropic", specifier = ">=0.96" },
{ name = "anyio", specifier = ">=4.14.2" },
+ { name = "asyncssh", specifier = ">=2.21" },
{ name = "audioop-lts", marker = "python_full_version >= '3.13'" },
{ name = "av", marker = "platform_machine == 'arm64' and sys_platform == 'darwin'", specifier = "==15.1.0" },
{ name = "av", marker = "platform_machine == 'arm64' and sys_platform == 'darwin' and extra == 'local-voice'", specifier = "==15.1.0" },