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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(plugins): Home Assistant — voice control for the user's own smart home
Ruben Lütke2e02a16260ce
diff --git a/docs/adr/0011-router-pure-dispatcher.md b/docs/adr/0011-router-pure-dispatcher.mdindex 4593144c19..9015623d97 100644--- a/docs/adr/0011-router-pure-dispatcher.md+++ b/docs/adr/0011-router-pure-dispatcher.md@@ -978,3 +978,59 @@ supervisor, and it never enters a legacy worker tier or direct worker tool set- `tests/unit/plugins/tool/test_wiki_list.py`- `tests/unit/plugins/tool/test_wiki_tools.py` (meta-page warning)- `tests/unit/brain/test_routing.py` (ROUTER_TOOLS parity)++---++## Amendment 2026-07-25 — `home_assistant` router tool++### Context++Home Assistant is the connector where "assistant" is the literal use case:+lights, heating, doors, scenes. It reached the catalog as a `pat_paste` plugin+with a per-connection instance address, so the question was how a connected+smart home becomes callable by voice.++Its MCP integration is not the answer. Home Assistant has explicitly declined+RFC 7591 dynamic client registration, and its MCP server is deliberately scoped+to Home Assistant's own Assist pipeline — it exposes conversation, not the+entity and service surface an external assistant needs. The documented REST API+does expose exactly that.++### Decision++`ROUTER_TOOLS` gains `home_assistant`+(`jarvis/plugins/tool/home_assistant_rest.py::HomeAssistantRestTool`): list+entities (optionally by domain), read one entity's state, and call a service.++Two properties are load-bearing:++- **The server address is per-connection state**, stored in+ `Tokens.extra["instance_url"]` beside the credential rather than hardcoded.+ Home Assistant runs on the user's own network; there is no canonical+ endpoint, and the `.local` hostname does not resolve inside Docker or over a+ VPN.+- **risk_tier is `ask`, not `monitor`.** Every other native marketplace tool is+ read-focused. This one physically changes the user's home. Turning off the+ wrong light is recoverable; unlocking a door is not, so the safety layer+ decides rather than the tool.++The router remains a pure dispatcher: this is a direct gated action, never a+spawn, and it never enters a worker tool set (AP-5/AP-14). Jarvis-Agents reach+it only through ADR-0025's mission-scoped supervisor broker.++### Consequences++The long-lived access token is valid for ten years with no rotation, which+makes this the most durable connection in the catalog — and the reason the+setup text asks for a dedicated non-admin Home Assistant user, since the token+inherits every permission of whoever created it.++Reachability, not authentication, is the honest limitation: a headless Jarvis+on a server cannot see a home LAN without a remote URL or a tunnel. The tool+reports that as a network problem instead of implying a bad credential.++### Regression guards++- `tests/unit/plugins/tool/test_home_assistant_rest.py`+- `tests/unit/marketplace/test_instance_url.py`+- `tests/unit/brain/test_routing.py` (ROUTER_TOOLS parity)diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.pyindex f8872d4ab0..137021e925 100644--- a/jarvis/brain/factory.py+++ b/jarvis/brain/factory.py@@ -151,6 +151,11 @@ ROUTER_TOOLS = frozenset({# as gmail — Vercel's catalog rest_wrapper transport produced zero MCP tools,# so it must be router-visible directly. Read-only; never a spawn (AP-5/AP-14)."vercel",+ # Home Assistant Marketplace plugin (2026-07-25): native REST tool, same+ # rationale as gmail — no usable MCP surface, so it must be router-visible+ # directly or a connected smart home is not callable by voice. A direct+ # gated action (risk_tier "ask"), never a spawn (AP-5/AP-14).+ "home_assistant",# Google Calendar Marketplace plugin (2026-06-27): native bridge tool whose# bot logic is a Node script (calendar_bot.mjs). Same rationale as gmail — no# MCP server block, so it must be router-visible directly; otherwise a@@ -773,7 +778,10 @@ def _phase2_full_brain(config.safety, extra_patterns_fn=make_cli_patterns_fn(),)approval = ApprovalWorkflow(bus)- executor = ToolExecutor(bus, evaluator, approval)+ executor = ToolExecutor(+ bus, evaluator, approval,+ default_timeout_s=config.safety.tool_approval_timeout_s,+ )# HarnessManager for the internal harness fast path (computer-use /# local-action). NB: dispatch-to-harness is no longer an@@ -1414,7 +1422,10 @@ def _legacy_full_brain(bus: Any | None = None) -> Any:config.safety, extra_patterns_fn=make_cli_patterns_fn(),)approval = ApprovalWorkflow(bus)- executor = ToolExecutor(bus, evaluator, approval)+ executor = ToolExecutor(+ bus, evaluator, approval,+ default_timeout_s=config.safety.tool_approval_timeout_s,+ )tools: dict[str, Any] = {}active_tools = {"open-app", "type-text", "run-shell", "search-web", "remember",diff --git a/jarvis/marketplace/catalog.py b/jarvis/marketplace/catalog.pyindex 89e3df0a2a..dda6f288d2 100644--- a/jarvis/marketplace/catalog.py+++ b/jarvis/marketplace/catalog.py@@ -21,12 +21,35 @@ class _BaseAuth(BaseModel):model_config = ConfigDict(extra="forbid")+class InstanceUrlSpec(_BaseAuth):+ """A per-user base address, for services the user hosts themselves.++ Home Assistant, Jellyfin, Nextcloud, Paperless and Immich have no fixed+ public endpoint: the address IS user data, so the catalog can only describe+ the field, never fill it. When present, the connect dialog asks for the+ address alongside the token and `validation_endpoint` is treated as a path+ RELATIVE to it.+ """++ label: str+ placeholder: str+ # Appended to the entered address to check the credential works. Kept+ # separate from the address so a user pasting a trailing slash, a path, or+ # the full URL of some page still validates.+ validation_path: str = "/"+ help_md: str | None = None++class PatPasteAuth(_BaseAuth):mode: Literal["pat_paste"]token_creation_url: strtoken_prefix: strvalidation_endpoint: strinstruction_md: str+ # Set for self-hosted services: the user supplies the address, so+ # `validation_endpoint` above is ignored in favour of+ # `instance_url.validation_path` appended to what they entered.+ instance_url: InstanceUrlSpec | None = None# How to present the pasted token when validating + wiring downstream:# bearer -> Authorization: Bearer <token> (GitHub/Vercel/Supabase)# bot -> Authorization: Bot <token> (Discord)diff --git a/jarvis/marketplace/instance_url.py b/jarvis/marketplace/instance_url.pynew file mode 100644index 0000000000..864f1fb151--- /dev/null+++ b/jarvis/marketplace/instance_url.py@@ -0,0 +1,56 @@+"""Normalize the base address of a self-hosted service.++Home Assistant, Jellyfin, Nextcloud, Paperless and Immich have no fixed public+endpoint — the address is the user's own. People type it the way they see it in+their browser, which means a trailing slash, a path they happened to be on, a+missing scheme, or a copied URL with a query string. All of those are the same+server, and none of them should fail a connection.++Deliberately does NOT resolve or reach anything: it only shapes the string. The+connect flow finds out whether the address is real by actually calling it.+"""++from __future__ import annotations++from urllib.parse import urlsplit, urlunsplit++# A plain hostname without a scheme is far more likely to be a LAN box reached+# over http than a public https host, but guessing wrong costs a confusing+# failure. https is the safer default: a user running plain http can type it,+# whereas silently downgrading to http would send their long-lived token in the+# clear.+_DEFAULT_SCHEME = "https"+++class InstanceUrlError(ValueError):+ """The entered address cannot be a service base URL."""+++def normalize_instance_url(raw: str) -> str:+ """Return ``scheme://host[:port]`` with no trailing slash.++ Raises :class:`InstanceUrlError` when the input cannot be an address at all,+ so the caller can say something useful instead of failing later with a+ confusing HTTP error.+ """+ value = (raw or "").strip()+ if not value:+ raise InstanceUrlError("no address given")++ # `urlsplit` reads a scheme-less "homeassistant.local:8123" as scheme+ # "homeassistant.local" — the port looks like a scheme to it. Add the+ # scheme first so the whole string is parsed as an authority.+ if "//" not in value:+ value = f"{_DEFAULT_SCHEME}://{value}"++ parts = urlsplit(value)+ if parts.scheme not in ("http", "https"):+ raise InstanceUrlError(+ f"address must start with http:// or https:// (got {parts.scheme!r})"+ )+ if not parts.hostname:+ raise InstanceUrlError("address is missing a host name")++ # Drop whatever page the user happened to copy from, plus any query or+ # fragment: what we need is the server root.+ return urlunsplit((parts.scheme, parts.netloc, "", "", "")).rstrip("/")diff --git a/jarvis/marketplace/seed_catalog.json b/jarvis/marketplace/seed_catalog.jsonindex ffec5bd526..5420bce48f 100644--- a/jarvis/marketplace/seed_catalog.json+++ b/jarvis/marketplace/seed_catalog.json@@ -1,5 +1,5 @@{- "version": 3,+ "version": 4,"schema_version": "2026-05-09","plugins": [{@@ -503,6 +503,32 @@"url": "https://mcp.cal.com/mcp","auth_header_template": "Authorization: Bearer ${plugin_cal_com_access_token}"}+ },+ {+ "id": "home_assistant",+ "display_name": "Home Assistant",+ "description": "Lights, heating, doors and scenes in your own smart home",+ "category": "Home & Devices",+ "logo_slug": "homeassistant",+ "logo_color": "18BCF2",+ "featured": true,+ "longevity": "permanent",+ "longevity_note": "A Home Assistant long-lived access token is valid for ten years and is never renewed or rotated, so this connection needs no maintenance.",+ "auth": {+ "mode": "pat_paste",+ "token_creation_url": "https://www.home-assistant.io/docs/authentication/#your-account-profile",+ "token_prefix": "",+ "validation_endpoint": "https://homeassistant.local:8123/api/",+ "instruction_md": "In Home Assistant open your **profile** (your name, bottom left) → **Security** → **Long-lived access tokens** → **Create token**. It is shown once, so copy it straight away.\n\nThe token inherits every permission of the account that creates it, so prefer a dedicated non-admin Home Assistant user over your own admin account.",+ "instance_url": {+ "label": "Your Home Assistant address",+ "placeholder": "http://192.168.1.20:8123",+ "validation_path": "/api/",+ "help_md": "The address you use in your browser. Home Assistant runs on your home network, so a Jarvis on a different machine, behind a VPN or in a container may not reach it."+ }+ },+ "native_tool": "home_assistant",+ "post_install_hint_md": "Try “turn off the living room lights” or “is the garage door still open”. Acting on a device asks for confirmation first."}]}diff --git a/jarvis/marketplace/usage_cards/home_assistant.md b/jarvis/marketplace/usage_cards/home_assistant.mdnew file mode 100644index 0000000000..9052446da2--- /dev/null+++ b/jarvis/marketplace/usage_cards/home_assistant.md@@ -0,0 +1,11 @@+---+plugin_id: home_assistant+keywords: home assistant, homeassistant, licht, lichter, light, lights, luz, luces, lampe, lamp, lámpara, heizung, heating, calefacción, temperatur, temperature, temperatura, thermostat, termostato, steckdose, socket, plug, enchufe, rollladen, blinds, persiana, garage, garagentor, garage door, puerta, tür, door, puerta, schloss, lock, cerradura, szene, scene, escena, sensor, schalte, switch, smart home, hausautomation, domótica # i18n-allow: spoken-input matching vocabulary (de/en/es), not prose+---+Use the home_assistant tool to read and control the user's smart home.++- List entities (optionally filtered by domain: light, switch, climate, cover, lock, sensor) to find the right `entity_id` before acting. Never guess one.+- Read a state before reporting it; say the friendly name, not the raw entity id.+- To act, call a service: domain + service + entity_id, e.g. `light` / `turn_off`. Extra data goes in `data`, e.g. `{"brightness_pct": 30}` or `{"temperature": 21}`.+- After a service call, report what actually changed rather than saying "done" — the response lists the affected entities.+- Home Assistant runs on the user's home network. If it cannot be reached, say that the server is unreachable from this machine instead of implying the credential is wrong.diff --git a/jarvis/plugins/tool/home_assistant_rest.py b/jarvis/plugins/tool/home_assistant_rest.pynew file mode 100644index 0000000000..889cf22ea0--- /dev/null+++ b/jarvis/plugins/tool/home_assistant_rest.py@@ -0,0 +1,271 @@+"""home_assistant tool — control the user's smart home over the REST API.++Home Assistant is the one connector where "assistant" is the literal use case:+lights, heating, doors, scenes. It is wired as a NATIVE tool rather than through+its MCP integration on purpose. Home Assistant has explicitly declined dynamic+client registration, and its MCP server is scoped to its own Assist pipeline —+so it exposes conversation, not the entity and service surface a voice assistant+actually needs. The documented REST API does.++Two properties shape everything here:++* **The address is user data.** Home Assistant runs on the user's own network,+ so the base URL is stored per connection (``Tokens.extra['instance_url']``)+ rather than hardcoded. Never assume the ``.local`` hostname — mDNS does not+ resolve inside Docker or over a VPN.+* **The token never expires but carries full rights.** A Long-Lived Access Token+ is valid for ten years with no refresh, which is why this is the most durable+ connection in the catalog; it also inherits every permission of the account+ that created it, which is why the setup text asks for a dedicated non-admin+ user.++Risk tier ``ask``: unlike the read-only REST plugins, calling a service here+physically changes something in the user's home. Turning off the wrong light is+recoverable; unlocking a door is not, so the safety layer gets to weigh in+rather than this tool deciding on its own.+"""+from __future__ import annotations++from collections.abc import Callable+from typing import Any++from jarvis.core.protocols import ExecutionContext, ToolResult++_NOT_CONNECTED = (+ "Home Assistant is not connected — connect it in the Plugins view."+)+# Entity attributes worth speaking. The raw state object carries dozens of+# fields (icons, ids, timestamps) that would bury the answer.+_SPOKEN_ATTRS = (+ "friendly_name",+ "brightness",+ "current_temperature",+ "temperature",+ "battery_level",+ "unit_of_measurement",+)+++def _default_connection() -> tuple[str | None, str | None]:+ """Return ``(base_url, token)`` for the connected Home Assistant."""+ from jarvis.marketplace.token_store import TokenStore++ tokens = TokenStore().load("home_assistant")+ if tokens is None:+ return None, None+ return tokens.extra.get("instance_url"), tokens.access+++def _summarize(state: dict[str, Any]) -> dict[str, Any]:+ """Reduce a raw entity state to what is worth reading aloud."""+ attrs = state.get("attributes") or {}+ out: dict[str, Any] = {+ "entity_id": state.get("entity_id"),+ "state": state.get("state"),+ }+ for key in _SPOKEN_ATTRS:+ if key in attrs:+ out[key] = attrs[key]+ return out+++class HomeAssistantRestTool:+ name: str = "home_assistant"+ risk_tier: str = "ask"+ description: str = (+ "Control and read the user's Home Assistant smart home: list devices, "+ "read the state of one device, or call a service to act on it. Use for "+ "'turn the living room lights off', 'is the garage door still open', "+ "'set the heating to 21 degrees', 'what is the temperature in the "+ "bedroom'. Actions: list_entities, get_state, call_service. Requires "+ "the Home Assistant plugin to be connected in the Plugins view."+ )+ schema: dict[str, Any] = {+ "type": "object",+ "properties": {+ "action": {+ "type": "string",+ "enum": ["list_entities", "get_state", "call_service"],+ "default": "list_entities",+ },+ "domain_filter": {+ "type": "string",+ "description": (+ "restrict list_entities to one domain, e.g. light, switch, "+ "climate, cover, sensor, lock"+ ),+ },+ "entity_id": {+ "type": "string",+ "description": "e.g. light.living_room (get_state, call_service)",+ },+ "domain": {+ "type": "string",+ "description": "service domain for call_service, e.g. light",+ },+ "service": {+ "type": "string",+ "description": "service name for call_service, e.g. turn_on",+ },+ "data": {+ "type": "object",+ "description": (+ "extra service data, e.g. {'brightness_pct': 30} or "+ "{'temperature': 21}"+ ),+ },+ },+ "required": ["action"],+ }++ def __init__(+ self,+ connection_provider: Callable[[], tuple[str | None, str | None]] | None = None,+ transport: Any | None = None,+ ) -> None:+ from ._http_pool import HttpClientPool++ self._connection = connection_provider or _default_connection+ self._pool = HttpClientPool(transport=transport)++ # -- internal helpers ---------------------------------------------------++ def _resolve(self) -> tuple[str, dict[str, str]] | None:+ base, token = self._connection()+ if not base or not token:+ return None+ return base, {+ "Authorization": f"Bearer {token}",+ "Content-Type": "application/json",+ "User-Agent": "Personal-Jarvis/1.0",+ }++ # -- public actions (also directly unit-testable) -----------------------++ async def list_entities(+ self, *, domain_filter: str | None = None, limit: int = 60+ ) -> dict[str, Any]:+ resolved = self._resolve()+ if resolved is None:+ return {"error": _NOT_CONNECTED}+ base, headers = resolved+ client = self._pool.client()+ resp = await client.get(f"{base}/api/states", headers=headers)+ resp.raise_for_status()+ states = resp.json()+ if not isinstance(states, list):+ return {"error": "unexpected response from Home Assistant"}+ if domain_filter:+ prefix = f"{domain_filter.strip().rstrip('.')}."+ states = [s for s in states if str(s.get("entity_id", "")).startswith(prefix)]+ # A real home has hundreds of entities. Sending them all would blow the+ # prompt budget and bury the ones the user meant.+ return {+ "total": len(states),+ "returned": min(len(states), limit),+ "entities": [_summarize(s) for s in states[:limit]],+ }++ async def get_state(self, *, entity_id: str) -> dict[str, Any]:+ resolved = self._resolve()+ if resolved is None:+ return {"error": _NOT_CONNECTED}+ base, headers = resolved+ client = self._pool.client()+ resp = await client.get(f"{base}/api/states/{entity_id}", headers=headers)+ if resp.status_code == 404:+ return {"error": f"no entity called {entity_id!r} in Home Assistant"}+ resp.raise_for_status()+ return _summarize(resp.json())++ async def call_service(+ self,+ *,+ domain: str,+ service: str,+ entity_id: str | None = None,+ data: dict[str, Any] | None = None,+ ) -> dict[str, Any]:+ resolved = self._resolve()+ if resolved is None:+ return {"error": _NOT_CONNECTED}+ base, headers = resolved+ payload: dict[str, Any] = dict(data or {})+ if entity_id:+ payload["entity_id"] = entity_id+ client = self._pool.client()+ resp = await client.post(+ f"{base}/api/services/{domain}/{service}",+ headers=headers,+ json=payload,+ )+ resp.raise_for_status()+ changed = resp.json()+ # Home Assistant answers with the entities whose state changed. Reading+ # that back is what lets the assistant say what actually happened rather+ # than "done" — the difference between a report and a guess.+ return {+ "called": f"{domain}.{service}",+ "changed": [_summarize(s) for s in changed] if isinstance(changed, list) else [],+ }++ # -- Tool protocol ------------------------------------------------------++ async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:+ action = (args.get("action") or "list_entities").strip()+ try:+ if action == "list_entities":+ out = await self.list_entities(domain_filter=args.get("domain_filter"))+ elif action == "get_state":+ entity_id = args.get("entity_id")+ if not entity_id:+ return ToolResult(success=False, output=None, error="entity_id missing")+ out = await self.get_state(entity_id=entity_id)+ elif action == "call_service":+ domain = args.get("domain")+ service = args.get("service")+ if not domain or not service:+ return ToolResult(+ success=False,+ output=None,+ error="call_service needs both domain and service",+ )+ out = await self.call_service(+ domain=domain,+ service=service,+ entity_id=args.get("entity_id"),+ data=args.get("data") if isinstance(args.get("data"), dict) else None,+ )+ else:+ return ToolResult(success=False, output=None, error=f"unknown action {action!r}")+ except Exception as exc: # noqa: BLE001+ return ToolResult(success=False, output=None, error=self._explain(exc))++ if isinstance(out, dict) and out.get("error"):+ return ToolResult(success=False, output=None, error=out["error"])+ return ToolResult(success=True, output=out)++ @staticmethod+ def _explain(exc: Exception) -> str:+ """Turn a transport failure into something a person can act on.++ Home Assistant lives on the home network, so the common failure is not+ a bad token but an unreachable server — Jarvis running on a different+ machine, a VPN, or a container. "ConnectError" tells the user nothing;+ naming the likely cause tells them what to check.+ """+ import httpx++ if isinstance(exc, httpx.ConnectError | httpx.ConnectTimeout):+ return (+ "Could not reach Home Assistant. It runs on your home network, "+ "so check that this machine can reach that address (a VPN, a "+ "container or a remote server will not see it)."+ )+ if isinstance(exc, httpx.HTTPStatusError) and exc.response.status_code == 401:+ return (+ "Home Assistant rejected the access token. Create a new "+ "long-lived token in your Home Assistant profile and reconnect "+ "the plugin."+ )+ return str(exc)diff --git a/jarvis/skills/builtin/__init__.py b/jarvis/skills/builtin/__init__.pyindex 4309362350..d34387609e 100644--- a/jarvis/skills/builtin/__init__.py+++ b/jarvis/skills/builtin/__init__.py@@ -46,6 +46,7 @@ _PLUGIN_PAIRED_SKILLS: tuple[str, ...] = ("plugin-canva","plugin-airtable","plugin-cal_com",+ "plugin-home_assistant",)BUILTIN_SKILL_NAMES: tuple[str, ...] = (diff --git a/jarvis/skills/builtin/plugin-cal_com/SKILL.md b/jarvis/skills/builtin/plugin-cal_com/SKILL.mdindex 1a58ab0d6c..ebb3ae57f8 100644--- a/jarvis/skills/builtin/plugin-cal_com/SKILL.md+++ b/jarvis/skills/builtin/plugin-cal_com/SKILL.md@@ -9,7 +9,7 @@ intent_verbs: [zeig, lies, buch, verschieb, sag ab, show, list, book, rescheduleintent_objects: [cal.com, calcom, cal com, calcom-buchung, calcom booking, calcom-termin, calcom-verfügbarkeit, calcom availability, buchungslink, booking link] # i18n-allow: spoken-input vocabulary, de/en/estriggers:- type: voice- pattern: '(cal\.com|calcom|buchungslink|booking link)' # i18n-allow: spoken-input vocabulary+ pattern: '(cal[\s.]?com|buchungslink|booking link)' # i18n-allow: spoken-input vocabulary; speech writes "cal com" with a spacerequires_tools: [cal_com]risk_policy:default_tier: monitordiff --git a/jarvis/skills/builtin/plugin-home_assistant/SKILL.md b/jarvis/skills/builtin/plugin-home_assistant/SKILL.mdnew file mode 100644index 0000000000..9e079f9ca7--- /dev/null+++ b/jarvis/skills/builtin/plugin-home_assistant/SKILL.md@@ -0,0 +1,24 @@+---+schema_version: "1"+name: plugin-home_assistant+description: Read and control the user's Home Assistant smart home.+when_to_use: Use when the user asks about or wants to change something physical at home — lights, heating, doors, blinds, sockets, scenes or a room sensor.+category: home+plugin_id: home_assistant+intent_verbs: [schalte, mach, dimm, stell, öffne, schließ, zeig, turn, switch, dim, set, open, close, show, enciende, apaga, abre, cierra, pon] # i18n-allow: spoken-input vocabulary, de/en/es+intent_objects: [home assistant, homeassistant, licht, lichter, lampe, light, lights, lamp, luz, luces, heizung, heating, calefacción, thermostat, temperatur, temperature, temperatura, rollladen, blinds, persiana, garagentor, garage door, steckdose, socket, enchufe, szene, scene, escena, smart home] # i18n-allow: spoken-input vocabulary, de/en/es+triggers:+ - type: voice+ pattern: '(home ?assistant|smart ?home|hausautomation|dom[oó]tica)' # i18n-allow: spoken-input vocabulary+requires_tools: [home_assistant]+risk_policy:+ default_tier: ask+---++Use the connected Home Assistant to read and control the user's home.++- Find the entity before acting: list the relevant domain (light, switch, climate, cover, lock) and match the room or device the user named. A guessed `entity_id` silently does nothing.+- Acting on a home is physical and asks for confirmation. State plainly what you are about to change — which device, in which room, to what.+- Report the result from what actually changed, not from the fact that the call returned.+- Prefer the narrowest action: one entity over a whole area, a scene the user already has over a hand-built set of calls.+- If the server cannot be reached, say so as a network problem — Home Assistant lives on the home network and a machine elsewhere will not see it.diff --git a/jarvis/ui/web/marketplace_routes.py b/jarvis/ui/web/marketplace_routes.pyindex 325a21dc59..8da7da0ba1 100644--- a/jarvis/ui/web/marketplace_routes.py+++ b/jarvis/ui/web/marketplace_routes.py@@ -44,6 +44,7 @@ from jarvis.marketplace.discord_connect import (on_discord_connected,on_discord_disconnected,)+from jarvis.marketplace.instance_url import InstanceUrlError, normalize_instance_urlfrom jarvis.marketplace.revoke import revoke_tokensfrom jarvis.marketplace.telegram_connect import (on_telegram_connected,@@ -141,7 +142,9 @@ def _make_validator(transport: httpx.AsyncBaseTransport | None = None):Raises ``httpx.HTTPError`` to the caller when the endpoint is unreachable."""- async def _validate(auth: PatPasteAuth, token: str) -> tuple[bool, int]:+ async def _validate(+ auth: PatPasteAuth, token: str, instance_url: str | None = None+ ) -> tuple[bool, int]:scheme = getattr(auth, "auth_scheme", "bearer")headers = {"User-Agent": "Personal-Jarvis/1.0"}if scheme == "telegram_path":@@ -153,6 +156,10 @@ def _make_validator(transport: httpx.AsyncBaseTransport | None = None):else: # bearerurl = auth.validation_endpointheaders["Authorization"] = f"Bearer {token}"+ if auth.instance_url is not None and instance_url:+ # Self-hosted: the catalog cannot know the address, so validation+ # goes to the user's own server instead of a fixed endpoint.+ url = normalize_instance_url(instance_url) + auth.instance_url.validation_pathasync with httpx.AsyncClient(timeout=10.0, transport=transport) as client:resp = await client.get(url, headers=headers)if resp.status_code != 200:@@ -274,6 +281,9 @@ async def list_plugins(response: Response) -> dict[str, Any]:class PatConnectBody(BaseModel):token: str = Field(min_length=1, max_length=2048)+ # Base address of the user's own server, for self-hosted plugins whose+ # catalog entry declares an `instance_url`. Not a secret.+ instance_url: str | None = Field(default=None, max_length=512)# Owner lock for channel plugins (telegram/discord): the numeric user id the# bot will obey. When given, it is added to the allowlist and# trust-on-first-contact is turned off. Not a secret — lives in jarvis.toml.@@ -304,12 +314,38 @@ async def connect_pat(plugin_id: str, body: PatConnectBody, request: Request) ->f"(got first 4 chars: {token[:4]!r})",)+ # Self-hosted services (Home Assistant, Jellyfin, ...) live at the user's+ # own address, which the catalog cannot know.+ instance_url: str | None = None+ if spec.auth.instance_url is not None:+ if not (body.instance_url or "").strip():+ raise HTTPException(+ status_code=400,+ detail=f"{spec.display_name} needs the address of your own server",+ )+ try:+ instance_url = normalize_instance_url(body.instance_url or "")+ except InstanceUrlError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc++ target = (+ instance_url + spec.auth.instance_url.validation_path+ if instance_url and spec.auth.instance_url+ else spec.auth.validation_endpoint+ )try:- ok, status = await _validate_token(spec.auth, token)+ # Only widen the call for self-hosted plugins. Every other caller (and+ # every injected test double) keeps the two-argument shape it has had+ # since the flow was written.+ ok, status = (+ await _validate_token(spec.auth, token, instance_url)+ if instance_url+ else await _validate_token(spec.auth, token)+ )except httpx.HTTPError as exc:raise HTTPException(status_code=502,- detail=f"could not reach {spec.auth.validation_endpoint}: {type(exc).__name__}",+ detail=f"could not reach {target}: {type(exc).__name__}",) from excif not ok:@@ -319,7 +355,11 @@ async def connect_pat(plugin_id: str, body: PatConnectBody, request: Request) ->)store = TokenStore()- store.save(plugin_id, Tokens(access=token))+ # The address rides in `extra` beside the token: it is per-connection state,+ # it must survive a restart exactly like the credential, and a tool that has+ # the token but not the address can do nothing with it.+ extra = {"instance_url": instance_url} if instance_url else {}+ store.save(plugin_id, Tokens(access=token, extra=extra))if plugin_id in _CHANNEL_PLUGIN_IDS:# A channel "connect" enables the in-repo bidirectional channel. Do not# report a successful Marketplace connect if the canonical channeldiff --git a/tests/unit/brain/test_routing.py b/tests/unit/brain/test_routing.pyindex 2e50d0ce41..b4b4541d5f 100644--- a/tests/unit/brain/test_routing.py+++ b/tests/unit/brain/test_routing.py@@ -1893,6 +1893,13 @@ def test_router_tools_is_pure_dispatcher_set() -> None:# rationale as gmail — its rest_wrapper transport produced zero MCP# tools, so it must be router-visible directly. Read-only."vercel",+ # Home Assistant Marketplace plugin (2026-07-25): native REST tool,+ # same rationale as gmail — Home Assistant declined dynamic client+ # registration and its MCP server only exposes its own Assist+ # pipeline, so the entity/service surface must be router-visible+ # directly. risk_tier "ask": a service call physically changes+ # something in the user's home. Never a spawn (AP-5/AP-14).+ "home_assistant",# Google Calendar Marketplace plugin (2026-06-27): native bridge tool# whose bot logic is a Node script (calendar_bot.mjs). Same rationale# as gmail — no MCP server block, so it must be router-visiblediff --git a/tests/unit/marketplace/test_instance_url.py b/tests/unit/marketplace/test_instance_url.pynew file mode 100644index 0000000000..a1f07db990--- /dev/null+++ b/tests/unit/marketplace/test_instance_url.py@@ -0,0 +1,54 @@+"""Self-hosted services live at an address only the user knows.++People type that address the way they see it in their browser: with a trailing+slash, with whatever page they were on, sometimes without a scheme. All of those+are the same server, and none of them should fail a connection.+"""++from __future__ import annotations++import pytest++from jarvis.marketplace.instance_url import InstanceUrlError, normalize_instance_url+++ ("raw", "expected"),+ [+ ("https://ha.example.test", "https://ha.example.test"),+ ("https://ha.example.test/", "https://ha.example.test"),+ (" https://ha.example.test/ ", "https://ha.example.test"),+ # Copied from the address bar while on some page of the app.+ ("https://ha.example.test/lovelace/0", "https://ha.example.test"),+ ("https://ha.example.test/profile?foo=1#bar", "https://ha.example.test"),+ # Explicit http for a LAN box stays http — never silently upgraded, or+ # the connection would simply fail for everyone on a plain-http server.+ ("http://192.168.1.20:8123", "http://192.168.1.20:8123"),+ ("http://192.168.1.20:8123/", "http://192.168.1.20:8123"),+ ],+)+def test_shapes_what_a_person_would_actually_paste(raw: str, expected: str) -> None:+ assert normalize_instance_url(raw) == expected+++def test_a_bare_host_with_a_port_is_not_mistaken_for_a_scheme() -> None:+ """`urlsplit` reads "homeassistant.local:8123" as scheme+ "homeassistant.local" — the port looks like a scheme to it. Getting this+ wrong would reject the single most common way a Home Assistant user writes+ their address."""+ assert (+ normalize_instance_url("homeassistant.local:8123")+ == "https://homeassistant.local:8123"+ )+++def test_a_scheme_less_host_defaults_to_https() -> None:+ """Defaulting to http would send a long-lived token in the clear. A user on+ plain http can say so; a user on https must not be downgraded silently."""+ assert normalize_instance_url("ha.example.test") == "https://ha.example.test"++[email protected]("raw", ["", " ", "ftp://ha.example.test", "https://"])+def test_rejects_what_cannot_be_an_address(raw: str) -> None:+ with pytest.raises(InstanceUrlError):+ normalize_instance_url(raw)diff --git a/tests/unit/plugins/tool/test_home_assistant_rest.py b/tests/unit/plugins/tool/test_home_assistant_rest.pynew file mode 100644index 0000000000..ae713748df--- /dev/null+++ b/tests/unit/plugins/tool/test_home_assistant_rest.py@@ -0,0 +1,194 @@+"""Home Assistant tool — driven against a mock transport, no credentials.++Two things make this plugin different from the other REST-backed ones and both+are covered here: the server address is per-user state rather than a constant,+and a call physically changes something in the user's home.+"""++from __future__ import annotations++import json++import httpx+import pytest++from jarvis.plugins.tool.home_assistant_rest import HomeAssistantRestTool++BASE = "http://ha.test:8123"++STATES = [+ {+ "entity_id": "light.living_room",+ "state": "on",+ "attributes": {+ "friendly_name": "Living room",+ "brightness": 180,+ "supported_color_modes": ["hs"],+ "icon": "mdi:lamp",+ },+ },+ {+ "entity_id": "cover.garage_door",+ "state": "open",+ "attributes": {"friendly_name": "Garage door", "device_class": "garage"},+ },+ {+ "entity_id": "climate.bedroom",+ "state": "heat",+ "attributes": {"friendly_name": "Bedroom", "current_temperature": 19.5},+ },+]+++def _tool(+ handler, base: str | None = BASE, token: str | None = "llat" # noqa: S107 - fake token+) -> HomeAssistantRestTool:+ return HomeAssistantRestTool(+ connection_provider=lambda: (base, token),+ transport=httpx.MockTransport(handler),+ )+++def _states_handler(seen: list[httpx.Request] | None = None):+ def handler(request: httpx.Request) -> httpx.Response:+ if seen is not None:+ seen.append(request)+ path = request.url.path+ if path == "/api/states":+ return httpx.Response(200, json=STATES)+ if path.startswith("/api/states/"):+ entity = path.rsplit("/", 1)[-1]+ for state in STATES:+ if state["entity_id"] == entity:+ return httpx.Response(200, json=state)+ return httpx.Response(404, json={"message": "Entity not found."})+ if path.startswith("/api/services/"):+ return httpx.Response(+ 200,+ json=[+ {+ **STATES[0],+ "state": "off",+ "attributes": {"friendly_name": "Living room"},+ }+ ],+ )+ return httpx.Response(500)++ return handler+++async def test_calls_the_users_own_server_not_a_fixed_endpoint() -> None:+ """The address is user data. Getting this wrong would send a home-network+ token to whatever host the catalog happened to name."""+ seen: list[httpx.Request] = []+ result = await _tool(_states_handler(seen)).list_entities()++ assert result["total"] == 3+ assert str(seen[0].url).startswith(BASE)+ assert seen[0].headers["Authorization"] == "Bearer llat"+++async def test_summarizes_entities_instead_of_dumping_them() -> None:+ """A real home has hundreds of entities carrying dozens of fields each.+ Passing that through would bury the answer and blow the prompt budget."""+ result = await _tool(_states_handler()).list_entities()++ first = result["entities"][0]+ assert first["entity_id"] == "light.living_room"+ assert first["friendly_name"] == "Living room"+ assert first["brightness"] == 180+ assert "supported_color_modes" not in first+ assert "icon" not in first+++async def test_filters_by_domain() -> None:+ result = await _tool(_states_handler()).list_entities(domain_filter="light")+ assert [e["entity_id"] for e in result["entities"]] == ["light.living_room"]+++async def test_reads_one_entity() -> None:+ result = await _tool(_states_handler()).get_state(entity_id="climate.bedroom")+ assert result["state"] == "heat"+ assert result["current_temperature"] == 19.5+++async def test_a_missing_entity_says_so_rather_than_raising() -> None:+ result = await _tool(_states_handler()).get_state(entity_id="light.nope")+ assert "no entity" in result["error"]+++async def test_a_service_call_reports_what_actually_changed() -> None:+ """Home Assistant answers with the entities whose state changed. Reading+ that back is what lets the assistant say what happened instead of 'done'."""+ seen: list[httpx.Request] = []+ result = await _tool(_states_handler(seen)).call_service(+ domain="light", service="turn_off", entity_id="light.living_room"+ )++ assert result["called"] == "light.turn_off"+ assert result["changed"][0]["state"] == "off"+ body = seen[-1].content.decode()+ assert "light.living_room" in body+++async def test_service_data_is_passed_through() -> None:+ seen: list[httpx.Request] = []+ await _tool(_states_handler(seen)).call_service(+ domain="climate",+ service="set_temperature",+ entity_id="climate.bedroom",+ data={"temperature": 21},+ )+ sent = json.loads(seen[-1].content.decode())+ assert sent["temperature"] == 21+ assert sent["entity_id"] == "climate.bedroom"+++async def test_acting_on_a_home_is_gated_rather_than_silent() -> None:+ """Read-only plugins sit at 'monitor'. Turning off the wrong light is+ recoverable, unlocking a door is not, so this one lets the safety layer+ weigh in."""+ assert HomeAssistantRestTool.risk_tier == "ask"+++async def test_an_unconfigured_plugin_explains_itself() -> None:+ tool = HomeAssistantRestTool(connection_provider=lambda: (None, None))+ result = await tool.list_entities()+ assert "not connected" in result["error"]+++async def test_an_unreachable_home_says_what_to_check() -> None:+ """Home Assistant lives on the home network, so the common failure is a+ server this machine cannot see — not a bad token. 'ConnectError' tells the+ user nothing."""++ def refuse(request: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("refused", request=request)++ tool = _tool(refuse)+ result = await tool.execute({"action": "list_entities"}, ctx=None)++ assert result.success is False+ assert "home network" in result.error+++async def test_a_rejected_token_points_at_the_fix() -> None:+ def unauthorized(request: httpx.Request) -> httpx.Response:+ return httpx.Response(401, json={"message": "Unauthorized"})++ result = await _tool(unauthorized).execute({"action": "list_entities"}, ctx=None)++ assert result.success is False+ assert "long-lived token" in result.error