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(ultrawiki): connect a service nobody here has ever heard of
Ruben Lütke2686716af8a0
diff --git a/UltraWiki/08-universal-ingestion.md b/UltraWiki/08-universal-ingestion.mdindex 2b487e159c..24048b912c 100644--- a/UltraWiki/08-universal-ingestion.md+++ b/UltraWiki/08-universal-ingestion.md@@ -168,6 +168,41 @@ size and item counts are bounded like every other connector.---+---++## What shipped, and what is honestly still open (2026-07-26)++**Shipped and tested:** the extractor coverage (A1), every reader routed+through it (A2), the frugal enrichment lane (A3), the platform guide (B) and+the generic custom source (C). Two defects surfaced on the way and were fixed:+`_decode` tried UTF-16 without a byte order mark, turning ordinary+Windows-encoded notes into CJK-looking noise; and an office archive missing its+manifest part was discarded whole though every slide was present.++One finding was larger than a defect: **connector metadata never reached the+store.** There was no column for it, so the source format, a file's+modification time and a chat's participants were dropped on every import since+the store was written. Added additively; existing databases migrate in place.++**Open, deliberately:**++* **Local speech recognition cannot transcribe an imported file.** Only the+ cloud providers gained `transcribe_container`; `faster-whisper` did not,+ because the always-on wake loop holds a native inference engine and sharing+ one is the AP-24 hang. A second instance would need its own lifecycle work.+* **The Gemini and OpenRouter speech plugins** send audio as inline base64+ rather than multipart, so they need their own small `transcribe_container`.+* **No UI yet** for the platform guide or the custom source. Both are complete+ as REST routes, which makes them CLI commands automatically (charter §5).+* **A photo inside a `.tar` cannot be described.** A tar entry cannot be+ reopened without decompressing the whole stream again, so those items say so+ rather than waiting in a queue forever. Importing the same export as a `.zip`+ removes the limitation.+* **`.enex` (Evernote) and `.pst` (Outlook)** are named in the guide as+ unreadable rather than silently failing.+* **Watched-folder mode** for the custom source was dropped as redundant: the+ local-folder source already watches a folder and now reads every format.+## Definition of done (charter §3, all four paths)1. **One arbitrary key** — a user whose only credential is for some otherdiff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 3f04277b79..87ae325715 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -2956,6 +2956,7 @@"connector_conversations": "Unterhaltungen mit {name}","connector_normal_wiki": "Eingebautes Wiki","connector_export_import": "Exportdatei",+ "connector_custom_source": "Eigene Quelle","connector_plugin_bridge": "Verbundene Integration (Plugins / MCP)","approve_import": "Freigeben & alles importieren","import_started": "Import gestartet – alles, was diese Quelle enthält, wird kopiert.",@@ -3165,7 +3166,8 @@"airtable": "Datensätze aus deinen Bases und Tabellen.","discord": "Nachrichten aus den Servern und Kanälen, denen du folgst.","telegram": "Nachrichten aus deinen Chats und Kanälen.",- "export_import": "Jeder Export, den du schon hast – Takeout, WhatsApp-Chats, Mail-Archive, PDFs."+ "export_import": "Jeder Export, den du schon hast – Takeout, WhatsApp-Chats, Mail-Archive, PDFs.",+ "custom_source": "Jeder Dienst mit einer eigenen Adresse – eine Web-Schnittstelle oder ein RSS-Feed, auf den du das hier richtest."},"export": {"path_label": "Exportdatei oder -ordner",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 3be119c7d2..46765c37f2 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -2942,6 +2942,7 @@"connector_conversations": "Conversations with {name}","connector_normal_wiki": "Built-in wiki","connector_export_import": "Export file",+ "connector_custom_source": "Custom source","connector_plugin_bridge": "Connected integration (plugins / MCP)","approve_import": "Approve & import everything","import_started": "Import started - everything this source holds is being copied in.",@@ -3151,7 +3152,8 @@"airtable": "Records from your bases and tables.","discord": "Messages from the servers and channels you follow.","telegram": "Messages from your chats and channels.",- "export_import": "Any export you already have - Takeout, WhatsApp chats, mail archives, PDFs."+ "export_import": "Any export you already have - Takeout, WhatsApp chats, mail archives, PDFs.",+ "custom_source": "Any service with an address of its own - a web API or an RSS feed you point this at."},"export": {"path_label": "Export file or folder",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 86e90cb477..35b6631724 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -2941,6 +2941,7 @@"connector_conversations": "Conversaciones con {name}","connector_normal_wiki": "Wiki integrado","connector_export_import": "Archivo de exportación",+ "connector_custom_source": "Fuente propia","connector_plugin_bridge": "Integración conectada (plugins / MCP)","approve_import": "Aprobar e importar todo","import_started": "Importación iniciada: se está copiando todo lo que contiene esta fuente.",@@ -3150,7 +3151,8 @@"airtable": "Registros de tus bases y tablas.","discord": "Mensajes de los servidores y canales que sigues.","telegram": "Mensajes de tus chats y canales.",- "export_import": "Cualquier exportación que ya tengas: Takeout, chats de WhatsApp, archivos de correo, PDF."+ "export_import": "Cualquier exportación que ya tengas: Takeout, chats de WhatsApp, archivos de correo, PDF.",+ "custom_source": "Cualquier servicio con dirección propia: una API web o un feed RSS al que apuntes esto."},"export": {"path_label": "Archivo o carpeta de exportación",diff --git a/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts b/jarvis/ui/web/frontend/src/lib/ultrawikiApi.tsindex fce8b605fb..648203ab71 100644--- a/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts+++ b/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts@@ -83,6 +83,7 @@ export const ULTRAWIKI_NEUTRAL_BRANDS = ["chat","wiki","archive",+ "link",] as const;export type UltraWikiNeutralBrand =(typeof ULTRAWIKI_NEUTRAL_BRANDS)[number];diff --git a/jarvis/ultrawiki/connector_catalog.py b/jarvis/ultrawiki/connector_catalog.pyindex 6f2c90edbe..e514af2a33 100644--- a/jarvis/ultrawiki/connector_catalog.py+++ b/jarvis/ultrawiki/connector_catalog.py@@ -89,7 +89,9 @@ CONNECTOR_STATUSES: tuple[ConnectorStatus, ...] = ("available", "adapter_pending#: connector has no vendor and must never borrow one; the frontend maps these#: to its own icons. Kept as a closed set so a typo cannot silently become a#: missing logo.-NEUTRAL_BRANDS: tuple[str, ...] = ("vault", "folder", "chat", "wiki", "archive")+NEUTRAL_BRANDS: tuple[str, ...] = (+ "vault", "folder", "chat", "wiki", "archive", "link"+)@dataclass(frozen=True, slots=True)@@ -183,6 +185,18 @@ BUILTIN_CONNECTORS: tuple[UltraWikiConnectorSpec, ...] = (label_key="ultrawiki.sources.connector_export_import",description_key="ultrawiki.connectors.export_import",),+ # The escape hatch: everything the roster will never name. A service with+ # no adapter and no export button had no route at all, and there will+ # always be one — a niche app, a regional network, a company's own tool.+ UltraWikiConnectorSpec(+ id="custom-source",+ kind="builtin",+ label="Custom source",+ brand="link",+ status="available",+ label_key="ultrawiki.sources.connector_custom_source",+ description_key="ultrawiki.connectors.custom_source",+ ),)diff --git a/jarvis/ultrawiki/connectors/__init__.py b/jarvis/ultrawiki/connectors/__init__.pyindex 5968949697..667fe1b8ce 100644--- a/jarvis/ultrawiki/connectors/__init__.py+++ b/jarvis/ultrawiki/connectors/__init__.py@@ -72,14 +72,21 @@ def _make_export_import() -> UWConnector:return ExportImportConnector()+def _make_custom_source() -> UWConnector:+ from jarvis.ultrawiki.connectors.custom_source import CustomSourceConnector++ return CustomSourceConnector()++def builtin_connectors() -> dict[str, ConnectorFactory]:- """The six built-in connectors, keyed by connector id."""+ """The seven built-in connectors, keyed by connector id."""return {"obsidian-vault": _make_obsidian_vault,"local-folder": _make_local_folder,"jarvis-conversations": _make_jarvis_conversations,"normal-wiki": _make_normal_wiki,"export-import": _make_export_import,+ "custom-source": _make_custom_source,"plugin-bridge": _make_plugin_bridge,}diff --git a/jarvis/ultrawiki/connectors/custom_source.py b/jarvis/ultrawiki/connectors/custom_source.pynew file mode 100644index 0000000000..6354e72da2--- /dev/null+++ b/jarvis/ultrawiki/connectors/custom_source.py@@ -0,0 +1,607 @@+"""Connect a service nobody here has ever heard of.++The last gap in "import everything from every platform". A service with no+adapter and no export button had no route at all — and there will always be+one: a niche journalling app, a regional social network, a company's internal+tool, something released next month.++Two modes, both configured entirely in the app:++* **``http``** — a URL that returns JSON, an optional credential, a path to+ the list of records, and a mapping saying which field is the id, the title,+ the text, the timestamp and the link. Paging by cursor or page number;+ freshness by passing a since-parameter.+* **``feed``** — RSS or Atom, which a surprising share of services still emit+ and which needs no configuration beyond the address.++Why a mapping rather than a schema guess: every API names things differently+(``id`` / ``uuid`` / ``pk``, ``created_at`` / ``published`` / ``date``), and a+guess that is right nine times out of ten produces a silently wrong tenth.+Naming the fields takes a minute and never lies.++**Safety.** This connector fetches a URL the user typed, which makes it the+one place in UltraWiki where a misconfiguration could reach somewhere it+should not. Refused by default: any scheme other than http/https, and any+address that resolves into a private, loopback, link-local or reserved range.+The second is the SSRF guard — a URL like ``http://169.254.169.254/`` is a+cloud metadata endpoint, and ``http://localhost:8080/`` is whatever else runs+on this machine. A user who genuinely means their own network ticks+``allow_private_network`` and says so explicitly.++Everything it yields is a plain :class:`RawItem`; it touches no store, no+model and no embedding (design doc 02, hard rule 1).+"""++from __future__ import annotations++import ipaddress+import logging+import re+import socket+from collections.abc import AsyncIterator, Iterator+from datetime import UTC, datetime+from typing import Any+from urllib.parse import urlparse++from jarvis.ultrawiki.types import (+ AuthKind,+ ConnectorCapabilities,+ ConnectorContext,+ IncrementalMode,+ RawItem,+)++log = logging.getLogger(__name__)++__all__ = [+ "CustomSourceConnector",+ "CustomSourceError",+ "MODES",+ "check_url",+ "map_record",+ "walk_path",+]++#: The two shapes a user can configure.+MODES: tuple[str, ...] = ("http", "feed")++#: Bytes accepted from one response. A knowledge source that answers with more+#: than this per page is misconfigured, and reading it would be a memory+#: exhaustion the user never asked for.+MAX_RESPONSE_BYTES = 32 * 1024 * 1024++#: Pages walked in one run. Bounds a paging loop whose cursor never advances —+#: which is a normal API bug, not an attack, and would otherwise run forever.+MAX_PAGES = 200++#: Items accepted from one run, as the same kind of backstop.+MAX_ITEMS = 50_000++#: Seconds for one request.+REQUEST_TIMEOUT_S = 30.0++#: Characters kept from one record's text.+MAX_BODY_CHARS = 200_000++#: Field names tried when the user maps nothing, in order. A convenience for+#: the common case — NOT a schema guess: an unmapped field that matches none+#: of these stays empty and the item says so, rather than silently taking+#: whatever field happened to be first.+_DEFAULT_FIELDS: dict[str, tuple[str, ...]] = {+ "id": ("id", "uuid", "guid", "key", "pk", "identifier", "_id"),+ "title": ("title", "name", "subject", "headline", "summary"),+ "body": ("body", "text", "content", "description", "message", "note"),+ "timestamp": (+ "timestamp", "created_at", "createdAt", "published", "published_at",+ "date", "updated_at", "updatedAt", "time",+ ),+ "permalink": ("permalink", "url", "link", "html_url", "href"),+}+++class CustomSourceError(RuntimeError):+ """The source cannot be read. Raised so the reason reaches the source card.++ Deliberately raised rather than returning nothing: a run that yields zero+ items and reports success is the failure mode that leaves a user staring+ at an empty knowledge base with nothing anywhere explaining why.+ """+++# ---------------------------------------------------------------------------+# URL safety+# ---------------------------------------------------------------------------+++def check_url(url: str, *, allow_private: bool = False) -> str:+ """Return the URL if it is safe to fetch; raise otherwise.++ Resolution happens here rather than being left to the HTTP client so the+ decision is made on the ADDRESS, not on the hostname: ``internal.example``+ resolving to 10.0.0.5 has to be refused for the same reason the literal+ address would be.+ """+ text = str(url or "").strip()+ if not text:+ raise CustomSourceError("This source has no address configured.")+ parsed = urlparse(text)+ if parsed.scheme not in ("http", "https"):+ raise CustomSourceError(+ f"{parsed.scheme or 'that'!r} is not an address this can fetch — "+ "use http:// or https://."+ )+ host = parsed.hostname or ""+ if not host:+ raise CustomSourceError(f"{text!r} has no host in it.")+ if allow_private:+ return text+ for address in _resolve(host):+ if not address.is_global:+ raise CustomSourceError(+ f"{host} resolves to {address}, which is on a private or "+ "reserved network. If that is deliberate — your own server, "+ "something on this machine — tick 'this is on my own network' "+ "on the source."+ )+ return text+++def _resolve(host: str) -> list[Any]:+ """Every IP a hostname resolves to. A literal address resolves to itself."""+ try:+ return [ipaddress.ip_address(host)]+ except ValueError:+ pass+ try:+ infos = socket.getaddrinfo(host, None)+ except OSError as exc:+ raise CustomSourceError(f"{host} could not be looked up ({exc}).") from exc+ found: list[Any] = []+ for info in infos:+ try:+ found.append(ipaddress.ip_address(info[4][0]))+ except (ValueError, IndexError):+ continue+ if not found:+ raise CustomSourceError(f"{host} resolves to no usable address.")+ return found+++# ---------------------------------------------------------------------------+# Reading a record out of arbitrary JSON+# ---------------------------------------------------------------------------+++def walk_path(payload: Any, path: str) -> Any:+ """Follow a dotted path into parsed JSON. ``None`` when it does not exist.++ ``data.items`` walks two keys; ``data.0.items`` indexes a list. An empty+ path returns the payload itself, which is what an API answering a bare+ array needs.+ """+ current = payload+ for part in str(path or "").split("."):+ if not part:+ continue+ if isinstance(current, dict):+ current = current.get(part)+ elif isinstance(current, list):+ try:+ current = current[int(part)]+ except (ValueError, IndexError):+ return None+ else:+ return None+ if current is None:+ return None+ return current+++def _field(record: dict[str, Any], mapped: str, role: str) -> str:+ """One mapped field of a record as text.++ An explicit mapping wins and is followed exactly — including into nested+ paths. Without one, the conventional names for that role are tried, and+ anything else yields ``""``.+ """+ if mapped:+ value = walk_path(record, mapped)+ return "" if value is None else _stringify(value)+ for candidate in _DEFAULT_FIELDS.get(role, ()):+ if candidate in record and record[candidate] is not None:+ return _stringify(record[candidate])+ return ""+++def _stringify(value: Any) -> str:+ if isinstance(value, str):+ return value+ if isinstance(value, (int, float, bool)):+ return str(value)+ if isinstance(value, (list, dict)):+ import json # noqa: PLC0415 — only for the unusual shape++ try:+ return json.dumps(value, ensure_ascii=False, indent=2)+ except (TypeError, ValueError):+ return str(value)+ return str(value)+++_ISO_LIKE = re.compile(r"^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2}))?")+++def _timestamp(raw: str) -> str:+ """A record's time as ISO-8601 UTC, or ``""`` when it is unreadable.++ Handles the three shapes that actually occur: ISO-8601, a Unix epoch (in+ seconds or milliseconds), and an RFC-2822 date from a feed. Anything else+ yields empty rather than a guess — a wrong timestamp puts a memory in the+ wrong year, which is worse than none.+ """+ text = str(raw or "").strip()+ if not text:+ return ""+ if text.replace(".", "", 1).isdigit():+ try:+ number = float(text)+ except ValueError:+ return ""+ # Milliseconds if it is far past a plausible second-based date.+ if number > 3_000_000_000:+ number /= 1000+ try:+ return datetime.fromtimestamp(number, tz=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ except (OverflowError, OSError, ValueError):+ return ""+ match = _ISO_LIKE.match(text)+ if match:+ year, month, day, hour, minute, second = match.groups()+ try:+ moment = datetime(+ int(year), int(month), int(day), int(hour), int(minute),+ int(second or 0), tzinfo=UTC,+ )+ except ValueError:+ return ""+ return moment.strftime("%Y-%m-%dT%H:%M:%SZ")+ try:+ from email.utils import parsedate_to_datetime # noqa: PLC0415 — feeds only++ moment = parsedate_to_datetime(text)+ except (TypeError, ValueError, IndexError):+ return ""+ if moment.tzinfo is None:+ moment = moment.replace(tzinfo=UTC)+ return moment.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+++def map_record(+ record: Any, mapping: dict[str, str], *, source_url: str, index: int+) -> RawItem | None:+ """One API record as a :class:`RawItem`, or ``None`` when it holds nothing.++ A record with no text at all is dropped rather than stored empty: an item+ with an empty body ranks in search and says nothing, which is worse than+ not existing.+ """+ if not isinstance(record, dict):+ # A bare list of strings is a legitimate, if unusual, answer.+ text = _stringify(record).strip()+ if not text:+ return None+ return RawItem(+ external_id=f"{index:08d}",+ body=text[:MAX_BODY_CHARS],+ permalink=source_url,+ timestamp_utc="",+ title=text.splitlines()[0][:200],+ )++ body = _field(record, mapping.get("body", ""), "body")+ title = _field(record, mapping.get("title", ""), "title")+ if not body.strip() and not title.strip():+ return None+ external_id = _field(record, mapping.get("id", ""), "id") or f"{index:08d}"+ return RawItem(+ external_id=external_id[:400],+ body=(body or title)[:MAX_BODY_CHARS],+ permalink=_field(record, mapping.get("permalink", ""), "permalink") or source_url,+ timestamp_utc=_timestamp(_field(record, mapping.get("timestamp", ""), "timestamp")),+ title=title[:400],+ author_raw=_field(record, mapping.get("author", ""), "author"),+ metadata={"custom_source": True},+ )+++# ---------------------------------------------------------------------------+# Feeds+# ---------------------------------------------------------------------------++_ENTRY_RE = re.compile(r"<(item|entry)\b.*?</\1>", re.DOTALL | re.IGNORECASE)+_TAG_RE = re.compile(r"<[^>]+>")+++def _feed_field(entry: str, *names: str) -> str:+ """One element's text out of a feed entry, tags stripped."""+ for name in names:+ match = re.search(+ rf"<{name}\b[^>]*>(.*?)</{name}>", entry, re.DOTALL | re.IGNORECASE+ )+ if match:+ return _unescape(_TAG_RE.sub("", match.group(1))).strip()+ # Atom's <link href="..."/> carries its value in an attribute.+ attr = re.search(rf'<{name}\b[^>]*href="([^"]+)"', entry, re.IGNORECASE)+ if attr:+ return _unescape(attr.group(1)).strip()+ return ""+++def _unescape(text: str) -> str:+ from html import unescape # noqa: PLC0415 — tiny, local++ return unescape(text.replace("<![CDATA[", "").replace("]]>", ""))+++def _feed_items(markup: str, source_url: str) -> Iterator[RawItem]:+ """Parse an RSS or Atom document with the stdlib only.++ Regex rather than an XML parser on purpose: real feeds in the wild are+ frequently not well-formed (unescaped ampersands, stray tags), and a+ strict parser rejects the whole document over one bad character in one+ entry. This reads the entries it can and skips the rest.+ """+ for index, match in enumerate(_ENTRY_RE.finditer(markup)):+ entry = match.group(0)+ title = _feed_field(entry, "title")+ body = _feed_field(entry, "content:encoded", "content", "description", "summary")+ if not title and not body:+ continue+ yield RawItem(+ external_id=(+ _feed_field(entry, "guid", "id")+ or _feed_field(entry, "link")+ or f"{index:08d}"+ )[:400],+ body=(body or title)[:MAX_BODY_CHARS],+ permalink=_feed_field(entry, "link") or source_url,+ timestamp_utc=_timestamp(+ _feed_field(entry, "pubDate", "published", "updated", "dc:date")+ ),+ title=title[:400],+ author_raw=_feed_field(entry, "author", "dc:creator"),+ metadata={"custom_source": True, "feed": True},+ )+++# ---------------------------------------------------------------------------+# The connector+# ---------------------------------------------------------------------------+++class CustomSourceConnector:+ """Read a user-configured HTTP endpoint or feed as raw items.++ Config keys:++ - ``mode``: ``"http"`` (default) or ``"feed"``.+ - ``url``: the address to fetch. Required.+ - ``secret_slot``: name of a stored credential, resolved through the Jarvis+ secret chain. Never a literal key in the config (AP-12).+ - ``auth_style``: ``"bearer"`` (default), ``"header"`` or ``"query"``.+ - ``auth_name``: header or query-parameter name for the two latter styles.+ - ``items_path``: dotted path to the record list (``""`` = the whole body).+ - ``fields``: mapping of ``id`` / ``title`` / ``body`` / ``timestamp`` /+ ``permalink`` / ``author`` onto the record's own field names.+ - ``page_param`` + ``page_start``: page-number paging.+ - ``cursor_path`` + ``cursor_param``: cursor paging.+ - ``since_param``: parameter carrying the incremental cursor.+ - ``allow_private_network``: fetch an address on a private range.+ """++ id = "custom-source"+ label = "Custom source"+ auth = AuthKind.APIKEY+ capabilities = ConnectorCapabilities(+ backfill=True,+ # Cursor rather than NONE even without a since-parameter: a re-read is+ # idempotent, so the worst case is repeated work, never duplicates.+ incremental=IncrementalMode.CURSOR,+ deletes=False,+ )++ async def backfill(+ self, ctx: ConnectorContext, checkpoint: str | None = None+ ) -> AsyncIterator[RawItem]:+ async for item in self._read(ctx, since=""):+ yield item++ async def incremental(+ self, ctx: ConnectorContext, cursor: str | None = None+ ) -> AsyncIterator[RawItem]:+ async for item in self._read(ctx, since=str(cursor or "")):+ yield item++ # -- internals ---------------------------------------------------------++ async def _read(self, ctx: ConnectorContext, *, since: str) -> AsyncIterator[RawItem]:+ config = ctx.config or {}+ mode = str(config.get("mode") or "http").strip().lower()+ if mode not in MODES:+ raise CustomSourceError(+ f"{mode!r} is not a mode this understands — use "+ f"{' or '.join(MODES)}."+ )+ url = check_url(+ str(config.get("url") or ""),+ allow_private=bool(config.get("allow_private_network")),+ )+ client = await self._client()+ try:+ if mode == "feed":+ markup = await self._fetch_text(client, url, config, ctx, params={})+ for item in _feed_items(markup, url):+ yield item+ return+ async for item in self._read_http(client, url, config, ctx, since):+ yield item+ finally:+ await client.aclose()++ async def _read_http(+ self,+ client: Any,+ url: str,+ config: dict[str, Any],+ ctx: ConnectorContext,+ since: str,+ ) -> AsyncIterator[RawItem]:+ import json # noqa: PLC0415 — lazy++ mapping = {+ str(key): str(value)+ for key, value in (config.get("fields") or {}).items()+ }+ items_path = str(config.get("items_path") or "")+ page_param = str(config.get("page_param") or "")+ cursor_param = str(config.get("cursor_param") or "")+ cursor_path = str(config.get("cursor_path") or "")+ since_param = str(config.get("since_param") or "")++ params: dict[str, str] = {}+ if since_param and since:+ params[since_param] = since+ page = int(config.get("page_start") or 1)+ cursor = ""+ seen_cursors: set[str] = set()+ seen = 0++ for _round in range(MAX_PAGES):+ call_params = dict(params)+ if page_param:+ call_params[page_param] = str(page)+ if cursor_param and cursor:+ call_params[cursor_param] = cursor++ raw = await self._fetch_text(client, url, config, ctx, params=call_params)+ try:+ payload = json.loads(raw)+ except ValueError as exc:+ raise CustomSourceError(+ f"{url} did not answer with JSON ({exc}). If it is an RSS "+ "or Atom feed, set this source's mode to 'feed'."+ ) from exc++ records = walk_path(payload, items_path)+ if records is None and not items_path:+ records = payload+ if isinstance(records, dict):+ records = [records]+ if not isinstance(records, list):+ raise CustomSourceError(+ f"{url} answered with no list of records at "+ f"{items_path or 'the top level'}. Point 'items_path' at "+ "the field holding the list."+ )+ if not records:+ return++ for record in records:+ item = map_record(record, mapping, source_url=url, index=seen)+ seen += 1+ if item is not None:+ yield item+ if seen >= MAX_ITEMS:+ log.info(+ "custom source %s: stopped at the %d-item ceiling",+ ctx.source_id,+ MAX_ITEMS,+ )+ return++ if cursor_path:+ next_cursor = walk_path(payload, cursor_path)+ next_cursor = "" if next_cursor is None else str(next_cursor)+ # Any cursor already used ends the walk, not just a repeat of+ # the previous one: an API that alternates A→B→A→B is an+ # ordinary bug, and comparing only against the last value+ # would follow it until the page ceiling.+ if not next_cursor or next_cursor in seen_cursors:+ return+ seen_cursors.add(next_cursor)+ cursor = next_cursor+ continue+ if page_param:+ page += 1+ continue+ return++ async def _client(self) -> Any:+ import httpx # noqa: PLC0415 — lazy (AP-26)++ return httpx.AsyncClient(+ timeout=REQUEST_TIMEOUT_S,+ follow_redirects=False, # a redirect could aim anywhere; see check_url+ )++ async def _fetch_text(+ self,+ client: Any,+ url: str,+ config: dict[str, Any],+ ctx: ConnectorContext,+ *,+ params: dict[str, str],+ ) -> str:+ import httpx # noqa: PLC0415 — lazy++ headers = {"Accept": "application/json, application/xml, text/xml, */*"}+ call_params = dict(params)+ secret = self._secret(ctx, config)+ if secret:+ style = str(config.get("auth_style") or "bearer").strip().lower()+ name = str(config.get("auth_name") or "").strip()+ if style == "header":+ headers[name or "Authorization"] = secret+ elif style == "query":+ call_params[name or "token"] = secret+ else:+ headers["Authorization"] = f"Bearer {secret}"++ try:+ response = await client.get(url, headers=headers, params=call_params)+ except httpx.HTTPError as exc:+ raise CustomSourceError(f"{url} could not be reached ({exc}).") from exc+ if response.status_code >= 400:+ raise CustomSourceError(+ f"{url} answered {response.status_code}. "+ + (+ "Check the credential on this source."+ if response.status_code in (401, 403)+ else "Check the address and any parameters."+ )+ )+ body = response.content+ if len(body) > MAX_RESPONSE_BYTES:+ raise CustomSourceError(+ f"{url} answered with more than "+ f"{MAX_RESPONSE_BYTES // (1024 * 1024)} MB in one response; "+ "use paging so it arrives in parts."+ )+ return body.decode(response.encoding or "utf-8", errors="replace")++ def _secret(self, ctx: ConnectorContext, config: dict[str, Any]) -> str:+ """The configured credential, resolved through the Jarvis secret chain.++ A literal key in the config is deliberately NOT supported (AP-12): it+ would end up in `jarvis.toml`, which is exactly where credentials must+ never live.+ """+ slot = str(config.get("secret_slot") or "").strip()+ if not slot or ctx.secret_get is None:+ return ""+ try:+ return str(ctx.secret_get(slot) or "")+ except Exception: # noqa: BLE001 — a missing credential is not a crash+ log.debug("custom source: credential %s unavailable", slot, exc_info=True)+ return ""diff --git a/tests/unit/ultrawiki/test_connectors.py b/tests/unit/ultrawiki/test_connectors.pyindex e38d951d37..0c23fbe854 100644--- a/tests/unit/ultrawiki/test_connectors.py+++ b/tests/unit/ultrawiki/test_connectors.py@@ -64,7 +64,7 @@ def _ctx(config: dict) -> ConnectorContext:class TestRegistry:- def test_builtin_connectors_expose_six_fresh_factories(self):+ def test_builtin_connectors_expose_seven_fresh_factories(self):registry = builtin_connectors()assert set(registry) == {"obsidian-vault",@@ -72,6 +72,7 @@ class TestRegistry:"jarvis-conversations","normal-wiki","export-import",+ "custom-source","plugin-bridge",}for name, factory in registry.items():diff --git a/tests/unit/ultrawiki/test_custom_source.py b/tests/unit/ultrawiki/test_custom_source.pynew file mode 100644index 0000000000..127fe65bba--- /dev/null+++ b/tests/unit/ultrawiki/test_custom_source.py@@ -0,0 +1,461 @@+"""The custom source — connect a service nobody here has ever heard of.++The security half is the important half. This is the one connector that+fetches an address the user typed, so it is the only place in UltraWiki where+a misconfiguration could reach somewhere it should not: a cloud metadata+endpoint, or whatever else happens to be listening on this machine.++The rest guards the promise that a wrong field mapping fails visibly. A+connector that quietly yields nothing and reports success is what leaves+someone staring at an empty knowledge base with nothing anywhere explaining+why.++Offline throughout: every fetch is a fake.+"""++from __future__ import annotations++import json+from typing import Any++import pytest++from jarvis.ultrawiki.connectors.custom_source import (+ CustomSourceConnector,+ CustomSourceError,+ check_url,+ map_record,+ walk_path,+)+from jarvis.ultrawiki.types import ConnectorContext, RawItem, UWConnector+++class _Response:+ def __init__(self, payload: Any, status: int = 200, *, text: str = "") -> None:+ self.status_code = status+ self.encoding = "utf-8"+ self.content = (+ text.encode("utf-8")+ if text+ else json.dumps(payload).encode("utf-8")+ )+++class _FakeClient:+ """Records every call and answers from a queued list of responses."""++ def __init__(self, responses: list[Any]) -> None:+ self._responses = list(responses)+ self.calls: list[dict[str, Any]] = []+ self.closed = False++ async def get(self, url: str, *, headers: dict, params: dict) -> Any:+ self.calls.append({"url": url, "headers": dict(headers), "params": dict(params)})+ if not self._responses:+ raise AssertionError("more requests than the test queued")+ return self._responses.pop(0)++ async def aclose(self) -> None:+ self.closed = True+++def connector_with(client: _FakeClient) -> CustomSourceConnector:+ connector = CustomSourceConnector()++ async def _client() -> Any:+ return client++ connector._client = _client # type: ignore[method-assign]+ return connector+++def ctx(**config: Any) -> ConnectorContext:+ config.setdefault("url", "https://example.com/api/items")+ config.setdefault("allow_private_network", True) # example.com is fine, but+ return ConnectorContext(source_id="custom-1", config=config)+++async def collect(connector: CustomSourceConnector, context: ConnectorContext) -> list[RawItem]:+ return [item async for item in connector.backfill(context)]+++# ---------------------------------------------------------------------------+# URL safety — the half that matters+# ---------------------------------------------------------------------------+++class TestUrlSafety:+ @pytest.mark.parametrize(+ "url",+ [+ "http://127.0.0.1:8080/api",+ "http://localhost/api",+ "http://169.254.169.254/latest/meta-data/", # cloud metadata+ "http://10.0.0.5/internal",+ "http://192.168.1.10/api",+ "http://172.16.4.4/api",+ "http://[::1]/api",+ ],+ )+ def test_private_and_reserved_addresses_are_refused(self, url: str):+ """169.254.169.254 is the one that matters: it is the cloud metadata+ endpoint, and reaching it can hand out credentials."""+ with pytest.raises(CustomSourceError) as excinfo:+ check_url(url)+ assert "private" in str(excinfo.value) or "reserved" in str(excinfo.value)++ def test_a_deliberate_private_address_is_allowed_when_asked_for(self):+ assert check_url("http://192.168.1.10/api", allow_private=True)++ @pytest.mark.parametrize(+ "url",+ ["file:///etc/passwd", "ftp://example.com/x", "gopher://example.com"],+ )+ def test_only_http_and_https_are_fetched(self, url: str):+ with pytest.raises(CustomSourceError):+ check_url(url)++ def test_an_empty_or_hostless_address_is_refused(self):+ with pytest.raises(CustomSourceError):+ check_url("")+ with pytest.raises(CustomSourceError):+ check_url("https://")++ def test_a_public_address_passes(self):+ assert check_url("https://8.8.8.8/api") == "https://8.8.8.8/api"++ async def test_redirects_are_not_followed(self):+ """A redirect could aim anywhere, including back at a private range —+ which would walk straight around the check above."""+ import httpx++ connector = CustomSourceConnector()+ client = await connector._client()+ try:+ assert isinstance(client, httpx.AsyncClient)+ assert client.follow_redirects is False+ finally:+ await client.aclose()+++# ---------------------------------------------------------------------------+# Reading records+# ---------------------------------------------------------------------------+++class TestPaths:+ def test_a_dotted_path_walks_dicts_and_lists(self):+ payload = {"data": {"items": [{"id": 1}, {"id": 2}]}}+ assert walk_path(payload, "data.items")[1]["id"] == 2+ assert walk_path(payload, "data.items.0.id") == 1++ def test_a_missing_path_is_none_rather_than_an_error(self):+ assert walk_path({"a": 1}, "b.c.d") is None++ def test_an_empty_path_is_the_payload_itself(self):+ """An API answering a bare array needs this."""+ payload = [{"id": 1}]+ assert walk_path(payload, "") is payload+++class TestMapping:+ def test_an_explicit_mapping_is_followed_exactly(self):+ record = {"pk": "x1", "headline": "Title", "note": "Body text"}+ item = map_record(+ record,+ {"id": "pk", "title": "headline", "body": "note"},+ source_url="https://example.com",+ index=0,+ )+ assert item.external_id == "x1"+ assert item.title == "Title"+ assert item.body == "Body text"++ def test_conventional_names_are_tried_when_nothing_is_mapped(self):+ item = map_record(+ {"id": "a", "title": "T", "content": "C", "created_at": "2024-03-01T10:00:00Z"},+ {},+ source_url="https://example.com",+ index=0,+ )+ assert item.external_id == "a"+ assert item.timestamp_utc == "2024-03-01T10:00:00Z"++ def test_an_unmapped_unconventional_field_stays_empty_rather_than_guessed(self):+ """A guess that is right nine times in ten produces a silently wrong+ tenth — an item filed under the wrong year, say."""+ item = map_record(+ {"xyzzy": "some text", "plugh": "2024-03-01"},+ {"body": "xyzzy"},+ source_url="https://example.com",+ index=0,+ )+ assert item.timestamp_utc == ""++ def test_a_record_with_no_text_is_dropped(self):+ """An empty item ranks in search and says nothing."""+ assert map_record({"id": "x"}, {}, source_url="https://e.com", index=0) is None++ def test_a_nested_field_can_be_mapped(self):+ item = map_record(+ {"id": "1", "author": {"name": "Ada"}, "text": "hi"},+ {"author": "author.name"},+ source_url="https://e.com",+ index=0,+ )+ assert item.author_raw == "Ada"++ @pytest.mark.parametrize(+ ("raw", "expected"),+ [+ ("2024-03-01T10:00:00Z", "2024-03-01T10:00:00Z"),+ ("2024-03-01 10:00", "2024-03-01T10:00:00Z"),+ ("1709287200", "2024-03-01T10:00:00Z"),+ ("1709287200000", "2024-03-01T10:00:00Z"), # milliseconds+ ("Fri, 01 Mar 2024 10:00:00 +0000", "2024-03-01T10:00:00Z"),+ ],+ )+ def test_the_time_shapes_that_actually_occur_are_read(self, raw, expected):+ item = map_record(+ {"text": "x", "timestamp": raw}, {}, source_url="https://e.com", index=0+ )+ assert item.timestamp_utc == expected++ def test_an_unreadable_time_is_empty_rather_than_wrong(self):+ """A wrong timestamp files a memory in the wrong year."""+ item = map_record(+ {"text": "x", "timestamp": "last Tuesday"},+ {},+ source_url="https://e.com",+ index=0,+ )+ assert item.timestamp_utc == ""+++# ---------------------------------------------------------------------------+# The HTTP mode end to end+# ---------------------------------------------------------------------------+++class TestHttpMode:+ async def test_a_simple_endpoint_is_read(self):+ client = _FakeClient([_Response([{"id": "1", "text": "hello"}])])+ items = await collect(connector_with(client), ctx())+ assert [item.body for item in items] == ["hello"]+ assert client.closed, "the client must always be closed"++ async def test_a_credential_is_sent_as_configured_and_never_stored_inline(self):+ client = _FakeClient([_Response([{"id": "1", "text": "x"}])])+ context = ctx(+ secret_slot="my-api-key", # noqa: S106 — a slot NAME; the value is not here+ auth_style="header",+ auth_name="X-Token",+ )+ context.secret_get = lambda slot: "s3cret" if slot == "my-api-key" else ""+ await collect(connector_with(client), context)+ assert client.calls[0]["headers"]["X-Token"] == "s3cret"+ # The config itself carries only the SLOT name, never the value.+ assert "s3cret" not in json.dumps(context.config)++ async def test_bearer_is_the_default_style(self):+ client = _FakeClient([_Response([{"id": "1", "text": "x"}])])+ context = ctx(secret_slot="k") # noqa: S106 — a slot name, not a secret+ context.secret_get = lambda slot: "abc"+ await collect(connector_with(client), context)+ assert client.calls[0]["headers"]["Authorization"] == "Bearer abc"++ async def test_cursor_paging_walks_until_the_cursor_stops_moving(self):+ client = _FakeClient(+ [+ _Response({"items": [{"id": "1", "text": "a"}], "next": "c2"}),+ _Response({"items": [{"id": "2", "text": "b"}], "next": "c3"}),+ _Response({"items": [{"id": "3", "text": "c"}], "next": ""}),+ ]+ )+ items = await collect(+ connector_with(client),+ ctx(items_path="items", cursor_path="next", cursor_param="cursor"),+ )+ assert [item.body for item in items] == ["a", "b", "c"]+ assert client.calls[1]["params"]["cursor"] == "c2"++ async def test_a_cursor_that_never_advances_does_not_loop_forever(self):+ """A stuck cursor is an ordinary API bug, not an attack.++ Two requests: the first cursor is legitimately new, the second repeats+ it and ends the walk. Without the guard this would run to the page+ ceiling and re-import the same page two hundred times.+ """+ client = _FakeClient(+ [_Response({"items": [{"id": "1", "text": "a"}], "next": "same"})] * 5+ )+ items = await collect(+ connector_with(client),+ ctx(items_path="items", cursor_path="next", cursor_param="cursor"),+ )+ assert len(client.calls) == 2+ assert len(items) == 2++ async def test_a_cursor_that_alternates_between_two_values_also_stops(self):+ """A→B→A→B would run to the ceiling if only the LAST value were+ compared; every cursor already used ends the walk."""+ client = _FakeClient(+ [+ _Response({"items": [{"id": "1", "text": "a"}], "next": "B"}),+ _Response({"items": [{"id": "2", "text": "b"}], "next": "A"}),+ _Response({"items": [{"id": "3", "text": "c"}], "next": "B"}),+ _Response({"items": [{"id": "4", "text": "d"}], "next": "A"}),+ ]+ )+ await collect(+ connector_with(client),+ ctx(items_path="items", cursor_path="next", cursor_param="cursor"),+ )+ assert len(client.calls) == 3, "the repeat of B must end it"++ async def test_page_paging_stops_at_the_first_empty_page(self):+ client = _FakeClient(+ [+ _Response({"items": [{"id": "1", "text": "a"}]}),+ _Response({"items": []}),+ ]+ )+ items = await collect(+ connector_with(client), ctx(items_path="items", page_param="page")+ )+ assert len(items) == 1+ assert client.calls[1]["params"]["page"] == "2"++ async def test_the_incremental_cursor_is_passed_as_the_since_parameter(self):+ client = _FakeClient([_Response([])])+ connector = connector_with(client)+ context = ctx(since_param="updated_since")+ [item async for item in connector.incremental(context, "2024-01-01T00:00:00Z")]+ assert client.calls[0]["params"]["updated_since"] == "2024-01-01T00:00:00Z"+++# ---------------------------------------------------------------------------+# Failing visibly+# ---------------------------------------------------------------------------+++class TestHonestFailure:+ async def test_a_wrong_items_path_says_so_instead_of_yielding_nothing(self):+ """Silence here is what leaves someone staring at an empty database."""+ client = _FakeClient([_Response({"results": [{"id": "1", "text": "a"}]})])+ with pytest.raises(CustomSourceError) as excinfo:+ await collect(connector_with(client), ctx(items_path="items"))+ assert "items_path" in str(excinfo.value)++ async def test_html_where_json_was_expected_suggests_the_feed_mode(self):+ client = _FakeClient([_Response(None, text="<rss><channel></channel></rss>")])+ with pytest.raises(CustomSourceError) as excinfo:+ await collect(connector_with(client), ctx())+ assert "feed" in str(excinfo.value)++ async def test_an_auth_failure_points_at_the_credential(self):+ client = _FakeClient([_Response({}, status=401)])+ with pytest.raises(CustomSourceError) as excinfo:+ await collect(connector_with(client), ctx())+ assert "credential" in str(excinfo.value)++ async def test_an_unknown_mode_is_refused_by_name(self):+ with pytest.raises(CustomSourceError) as excinfo:+ await collect(connector_with(_FakeClient([])), ctx(mode="graphql"))+ assert "graphql" in str(excinfo.value)++ async def test_an_oversized_response_is_refused_with_advice(self):+ import jarvis.ultrawiki.connectors.custom_source as module++ big = _Response(None, text="x" * 200)+ client = _FakeClient([big])+ original = module.MAX_RESPONSE_BYTES+ module.MAX_RESPONSE_BYTES = 100+ try:+ with pytest.raises(CustomSourceError) as excinfo:+ await collect(connector_with(client), ctx())+ assert "paging" in str(excinfo.value)+ finally:+ module.MAX_RESPONSE_BYTES = original+++# ---------------------------------------------------------------------------+# Feeds+# ---------------------------------------------------------------------------+++RSS = """<?xml version="1.0"?>+<rss version="2.0"><channel>+ <title>A blog</title>+ <item>+ <title>First post</title>+ <link>https://example.com/1</link>+ <guid>post-1</guid>+ <pubDate>Fri, 01 Mar 2024 10:00:00 +0000</pubDate>+ <description>Some & content</description>+ </item>+ <item>+ <title>Second post</title>+ <link>https://example.com/2</link>+ <description><![CDATA[<p>Rich <b>text</b></p>]]></description>+ </item>+</channel></rss>"""++ATOM = """<?xml version="1.0"?>+<feed xmlns="http://www.w3.org/2005/Atom">+ <entry>+ <title>Atom entry</title>+ <id>urn:uuid:1</id>+ <link href="https://example.com/a"/>+ <updated>2024-03-01T10:00:00Z</updated>+ <content>Body here</content>+ </entry>+</feed>"""+++class TestFeedMode:+ async def test_an_rss_feed_is_read(self):+ client = _FakeClient([_Response(None, text=RSS)])+ items = await collect(connector_with(client), ctx(mode="feed"))+ assert [item.title for item in items] == ["First post", "Second post"]+ assert items[0].external_id == "post-1"+ assert items[0].timestamp_utc == "2024-03-01T10:00:00Z"+ assert "Some & content" in items[0].body++ async def test_html_inside_an_entry_becomes_readable_text(self):+ client = _FakeClient([_Response(None, text=RSS)])+ items = await collect(connector_with(client), ctx(mode="feed"))+ assert "Rich text" in items[1].body.replace(" ", " ")+ assert "<b>" not in items[1].body++ async def test_an_atom_feed_is_read_including_its_link_attribute(self):+ client = _FakeClient([_Response(None, text=ATOM)])+ items = await collect(connector_with(client), ctx(mode="feed"))+ assert items[0].permalink == "https://example.com/a"+ assert items[0].body == "Body here"++ async def test_a_malformed_feed_yields_what_it_can(self):+ """Real feeds are frequently not well-formed; a strict parser would+ reject the whole document over one bad character in one entry."""+ broken = RSS.replace("</channel>", "")+ client = _FakeClient([_Response(None, text=broken)])+ items = await collect(connector_with(client), ctx(mode="feed"))+ assert len(items) == 2+++# ---------------------------------------------------------------------------+# The contract+# ---------------------------------------------------------------------------+++def test_it_satisfies_the_connector_protocol():+ assert isinstance(CustomSourceConnector(), UWConnector)+++def test_it_is_offered_as_a_built_in_source():+ from jarvis.ultrawiki.connector_catalog import get_connector+ from jarvis.ultrawiki.connectors import builtin_connectors++ assert "custom-source" in builtin_connectors()+ entry = get_connector("custom-source")+ assert entry is not None and entry.status == "available"