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(marketplace): community index source with TTL cache and honest degradation

rubenluetke10-beepc7831b6ce819
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index ef89d08473..cc5ed534c8 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -3237,6 +3237,13 @@ class MarketplaceConfig(BaseModel):
"""
public_callback_base_url: str = ""
+ # Where the community marketplace index lives. The default is the public
+ # registry's GitHub Pages deployment; forks and air-gapped mirrors point
+ # this at their own compiled index. Empty string disables the community
+ # section entirely (browse shows only the shipped seed catalog).
+ community_index_url: str = (
+ "https://personaljarvis.github.io/marketplace/index.json"
+ )
model_config = ConfigDict(extra="allow")
diff --git a/jarvis/marketplace/community_source.py b/jarvis/marketplace/community_source.py
new file mode 100644
index 0000000000..b27c82c2d5
--- /dev/null
+++ b/jarvis/marketplace/community_source.py
@@ -0,0 +1,182 @@
+"""Fetch and cache the community marketplace index.
+
+The registry repo (PersonalJarvis/marketplace) compiles every published
+plugin and skill into one static ``index.json`` served from GitHub Pages.
+This module is the app's only reader of that feed: fetch with short
+timeouts, validate into typed models, and persist the result under
+``data/marketplace_index.json`` so browsing keeps working offline and on a
+headless box (same doctrine as the seed catalogs).
+
+Never called on the boot critical path (contract §7) — the Plugins view
+triggers a TTL-gated refresh when it opens, plus an explicit refresh button.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import time
+from pathlib import Path
+from typing import Any
+
+import httpx
+from pydantic import BaseModel, ConfigDict, Field, ValidationError
+
+logger = logging.getLogger(__name__)
+
+# Repo-root data/ — same resolution as jarvis/marketplace/catalog_data.py.
+_CACHE_PATH = (
+ Path(__file__).resolve().parent.parent.parent / "data" / "marketplace_index.json"
+)
+
+_FETCH_TIMEOUT = httpx.Timeout(connect=3.0, read=10.0, write=10.0, pool=10.0)
+# How long a fetched index stays fresh before a view-open refetches it. The
+# refresh endpoint bypasses this; publishing latency is CI-bound (~minutes),
+# so a quarter hour keeps browsing snappy without hammering the host.
+_CACHE_TTL_SECONDS = 900.0
+
+# One in-process fetch at a time — a double view-open must not race two
+# downloads into the same cache file.
+_fetch_lock = asyncio.Lock()
+
+
+class _Tolerant(BaseModel):
+ """``extra="allow"``: the index is produced by a NEWER registry than this
+ client may be — unknown fields must never break browsing (BUG-016 class
+ is catalog files rejected wholesale over one new field)."""
+
+ model_config = ConfigDict(extra="allow")
+
+
+class CommunityPluginEntry(_Tolerant):
+ name: str
+ publisher: str | None = None
+ version: str | None = None
+ published_at: str | None = None
+ source_url: str | None = None
+ # The raw Agent Plugins v1.0.0 manifests, embedded verbatim. Conversion
+ # to a PluginSpec happens at INSTALL time (agent_plugins_loader), so a
+ # malformed community entry degrades to one uninstallable card instead of
+ # taking the whole index down.
+ plugin_json: dict[str, Any]
+ mcp_json: dict[str, Any] | None = None
+ usage_card: str | None = None
+
+
+class CommunitySkillEntry(_Tolerant):
+ name: str
+ title: str | None = None
+ description: str = ""
+ publisher: str | None = None
+ version: str | None = None
+ published_at: str | None = None
+ categories: list[str] = Field(default_factory=list)
+ source_url: str | None = None
+ # Direct download of the SKILL.md — consumed by the existing
+ # /api/skills/catalog/install route.
+ raw_url: str | None = None
+
+
+class CommunityIndex(_Tolerant):
+ revision: int = 0
+ generated_at: str | None = None
+ plugins: list[CommunityPluginEntry] = Field(default_factory=list)
+ skills: list[CommunitySkillEntry] = Field(default_factory=list)
+
+
+def index_url() -> str:
+ """The configured index URL (empty string = community section disabled)."""
+ from jarvis.core.config import load_config
+
+ try:
+ return str(load_config().marketplace.community_index_url).strip()
+ except Exception: # noqa: BLE001 - config trouble must not kill browsing
+ logger.warning("community index: could not read config, using default")
+ from jarvis.core.config import MarketplaceConfig
+
+ return MarketplaceConfig().community_index_url
+
+
+def _read_cache() -> tuple[float, CommunityIndex] | None:
+ try:
+ raw = json.loads(_CACHE_PATH.read_text(encoding="utf-8-sig"))
+ return float(raw["fetched_at"]), CommunityIndex.model_validate(raw["index"])
+ except FileNotFoundError:
+ return None
+ except (OSError, ValueError, KeyError, ValidationError) as exc:
+ logger.warning("community index: unreadable cache (%s) — refetching", exc)
+ return None
+
+
+def _write_cache(index: CommunityIndex) -> None:
+ """Atomic tmp+replace, like every other data/ writer in this repo."""
+ try:
+ _CACHE_PATH.parent.mkdir(parents=True, exist_ok=True)
+ tmp = _CACHE_PATH.with_suffix(".json.tmp")
+ tmp.write_text(
+ json.dumps(
+ {"fetched_at": time.time(), "index": index.model_dump(mode="json")},
+ ensure_ascii=False,
+ ),
+ encoding="utf-8",
+ )
+ tmp.replace(_CACHE_PATH)
+ except OSError as exc:
+ # A read-only disk costs persistence, not the current browse.
+ logger.warning("community index: cache write failed: %s", exc)
+
+
+def cached_index() -> CommunityIndex | None:
+ """The last fetched index regardless of age, or None if never fetched."""
+ hit = _read_cache()
+ return hit[1] if hit else None
+
+
+async def get_index(
+ *,
+ force: bool = False,
+ transport: httpx.AsyncBaseTransport | None = None,
+) -> tuple[CommunityIndex | None, str]:
+ """Return ``(index, status)`` with status one of:
+
+ - ``"disabled"`` — no index URL configured
+ - ``"fresh"`` — served straight from a within-TTL cache
+ - ``"fetched"`` — downloaded and cached just now
+ - ``"stale"`` — network failed; serving the outdated cache honestly
+ - ``"unavailable"`` — network failed and there is no cache at all
+ """
+ url = index_url()
+ if not url:
+ return None, "disabled"
+
+ async with _fetch_lock:
+ hit = _read_cache()
+ if hit and not force and (time.time() - hit[0]) < _CACHE_TTL_SECONDS:
+ return hit[1], "fresh"
+
+ try:
+ async with httpx.AsyncClient(
+ timeout=_FETCH_TIMEOUT, follow_redirects=True, transport=transport
+ ) as client:
+ response = await client.get(url)
+ response.raise_for_status()
+ index = CommunityIndex.model_validate(response.json())
+ except (httpx.HTTPError, ValueError, ValidationError) as exc:
+ logger.warning("community index: fetch failed (%s)", exc)
+ if hit:
+ return hit[1], "stale"
+ return None, "unavailable"
+
+ _write_cache(index)
+ return index, "fetched"
+
+
+__all__ = [
+ "CommunityIndex",
+ "CommunityPluginEntry",
+ "CommunitySkillEntry",
+ "cached_index",
+ "get_index",
+ "index_url",
+]
diff --git a/tests/unit/marketplace/test_community_source.py b/tests/unit/marketplace/test_community_source.py
new file mode 100644
index 0000000000..e6be939c82
--- /dev/null
+++ b/tests/unit/marketplace/test_community_source.py
@@ -0,0 +1,155 @@
+"""Community index fetch + cache: fresh/fetched/stale/unavailable/disabled."""
+
+from __future__ import annotations
+
+import json
+import time
+from pathlib import Path
+from typing import Any
+
+import httpx
+import pytest
+
+from jarvis.marketplace import community_source
+
+
+def _index_payload(revision: int = 1) -> dict[str, Any]:
+ return {
+ "revision": revision,
+ "generated_at": "2026-08-12T12:00:00Z",
+ "plugins": [
+ {
+ "name": "todo-fox",
+ "publisher": "octocat",
+ "version": "1.0.0",
+ "plugin_json": {"name": "todo-fox", "description": "d"},
+ "mcp_json": None,
+ "usage_card": "---\nkeywords: todo\n---\nbody",
+ "brand_new_field_from_future": True,
+ }
+ ],
+ "skills": [
+ {
+ "name": "three-point-check",
+ "description": "Three bullets",
+ "publisher": "octocat",
+ "raw_url": "https://raw.example/skills/three-point-check/SKILL.md",
+ }
+ ],
+ }
+
+
+def cache_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ path = tmp_path / "marketplace_index.json"
+ monkeypatch.setattr(community_source, "_CACHE_PATH", path)
+ monkeypatch.setattr(community_source, "index_url", lambda: "https://reg.example/index.json")
+ return path
+
+
+def _transport(handler: Any) -> httpx.MockTransport:
+ return httpx.MockTransport(handler)
+
+
+def _seed_cache(path: Path, payload: dict[str, Any], fetched_at: float) -> None:
+ path.write_text(
+ json.dumps({"fetched_at": fetched_at, "index": payload}), encoding="utf-8"
+ )
+
+
+def _cache_exists(path: Path) -> bool:
+ return path.exists()
+
+
+def _seed_corrupt_cache(path: Path) -> None:
+ path.write_text("{not json", encoding="utf-8")
+
+
+async def test_fetch_validates_and_caches(cache_path: Path) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json=_index_payload())
+
+ index, status = await community_source.get_index(transport=_transport(handler))
+ assert status == "fetched"
+ assert index is not None
+ assert index.plugins[0].name == "todo-fox"
+ assert index.skills[0].raw_url is not None
+ assert _cache_exists(cache_path)
+
+
+async def test_within_ttl_serves_cache_without_network(cache_path: Path) -> None:
+ _seed_cache(cache_path, _index_payload(revision=7), time.time())
+
+ def handler(request: httpx.Request) -> httpx.Response: # pragma: no cover
+ raise AssertionError("must not fetch inside the TTL")
+
+ index, status = await community_source.get_index(transport=_transport(handler))
+ assert status == "fresh"
+ assert index is not None and index.revision == 7
+
+
+async def test_force_refetches_inside_ttl(cache_path: Path) -> None:
+ _seed_cache(cache_path, _index_payload(revision=1), time.time())
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json=_index_payload(revision=2))
+
+ index, status = await community_source.get_index(
+ force=True, transport=_transport(handler)
+ )
+ assert status == "fetched"
+ assert index is not None and index.revision == 2
+
+
+async def test_network_failure_serves_stale_cache(cache_path: Path) -> None:
+ _seed_cache(cache_path, _index_payload(revision=3), 0.0)
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ raise httpx.ConnectError("offline")
+
+ index, status = await community_source.get_index(transport=_transport(handler))
+ assert status == "stale"
+ assert index is not None and index.revision == 3
+
+
+async def test_network_failure_without_cache_is_honest(cache_path: Path) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ raise httpx.ConnectError("offline")
+
+ index, status = await community_source.get_index(transport=_transport(handler))
+ assert status == "unavailable"
+ assert index is None
+
+
+async def test_empty_url_disables(cache_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(community_source, "index_url", lambda: "")
+ index, status = await community_source.get_index()
+ assert status == "disabled"
+ assert index is None
+
+
+async def test_corrupt_cache_refetches(cache_path: Path) -> None:
+ _seed_corrupt_cache(cache_path)
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json=_index_payload(revision=9))
+
+ index, status = await community_source.get_index(transport=_transport(handler))
+ assert status == "fetched"
+ assert index is not None and index.revision == 9
+
+
+async def test_malformed_index_body_rejected(cache_path: Path) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json={"plugins": [{"no_name": True}]})
+
+ index, status = await community_source.get_index(transport=_transport(handler))
+ assert status == "unavailable"
+ assert index is None
+
+
+def test_config_default_points_at_registry_pages() -> None:
+ from jarvis.core.config import MarketplaceConfig
+
+ assert MarketplaceConfig().community_index_url.startswith("https://")
+ assert MarketplaceConfig().community_index_url.endswith("/index.json")