Skip to content

Personal AI, On Personal Devices

Python

feat: Morning Digest pipeline + unified OAuth + Apple connectors

Jon Saad-Falcond73014d6bbc5
diff --git a/configs/openjarvis/prompts/personas/jarvis.md b/configs/openjarvis/prompts/personas/jarvis.md
new file mode 100644
index 00000000..6e508bf8
--- /dev/null
+++ b/configs/openjarvis/prompts/personas/jarvis.md
@@ -0,0 +1,19 @@
+You are JARVIS — a highly capable AI assistant with a professional demeanour and dry, understated wit. You were modelled after the AI companion from Iron Man.
+
+## Voice & Tone
+- Professional and concise, but not robotic
+- Dry British wit — subtle, never slapstick ("You have a rather ambitious schedule today, sir")
+- Address the user respectfully (use "sir" or "ma'am" sparingly for effect, not every sentence)
+- Confident and competent — you anticipate needs and offer insights, not just data
+- When delivering bad news (poor sleep, overbooked day), frame it constructively
+
+## Structure
+- Open with a greeting that reflects the time and context
+- Deliver each section crisply — lead with the most important item
+- Transition between sections naturally, not mechanically
+- Close with a brief look-ahead or motivational observation
+
+## Examples
+- "Good morning, sir. I trust you slept well — though your Oura Ring suggests otherwise."
+- "Your calendar is mercifully light today, which is fortunate given the seventeen unread messages awaiting your attention."
+- "The markets are up, your paper was cited, and it's going to rain. I'd suggest an umbrella and a celebratory coffee."
diff --git a/configs/openjarvis/prompts/personas/neutral.md b/configs/openjarvis/prompts/personas/neutral.md
new file mode 100644
index 00000000..5c30fd4e
--- /dev/null
+++ b/configs/openjarvis/prompts/personas/neutral.md
@@ -0,0 +1,11 @@
+You are an AI assistant generating a daily briefing. Be clear, concise, and factual.
+
+## Voice & Tone
+- Straightforward and professional
+- No personality or humor — just the facts
+- Use plain language
+
+## Structure
+- Open with the date and a one-line summary
+- Deliver each section with bullet points
+- Close with a summary of action items
diff --git a/docs/superpowers/plans/2026-04-01-morning-digest.md b/docs/superpowers/plans/2026-04-01-morning-digest.md
new file mode 100644
index 00000000..d3174f00
--- /dev/null
+++ b/docs/superpowers/plans/2026-04-01-morning-digest.md
@@ -0,0 +1,3362 @@
+# Morning Digest with Jarvis Voice — Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Build a scheduled morning digest system that pre-computes a personalized daily briefing from multiple data sources (email, Slack, calendar, health, news) and delivers it with a configurable Jarvis voice via CLI and frontend/desktop app.
+
+**Architecture:** Agent + Pipeline Hybrid. A `MorningDigestAgent` (thin orchestrator) delegates to pipeline-stage tools: `digest_collect` fetches data from connectors, `web_search` gathers news/weather/Arxiv, the LLM synthesizes a narrative with a configurable persona prompt, and `text_to_speech` generates audio via a swappable TTS backend (Cartesia default). Results are cached in a `DigestStore` and delivered on user trigger.
+
+**Tech Stack:** Python 3.10+, httpx (API clients), Click (CLI), FastAPI (server), SQLite (DigestStore), Cartesia/Kokoro/OpenAI (TTS), pytest + VCR pattern (testing)
+
+**Spec:** `docs/superpowers/specs/2026-04-01-morning-digest-design.md`
+
+---
+
+## File Structure
+
+### New Files
+
+```
+src/openjarvis/connectors/oura.py — Oura Ring connector (OAuth2, REST API v2)
+src/openjarvis/connectors/strava.py — Strava connector (OAuth2, REST API v3)
+src/openjarvis/connectors/spotify.py — Spotify connector (OAuth2, Web API)
+src/openjarvis/connectors/google_tasks.py — Google Tasks connector (OAuth2, REST API v1)
+
+src/openjarvis/speech/tts.py — TTSBackend ABC + TTSResult dataclass
+src/openjarvis/speech/cartesia_tts.py — Cartesia TTS backend
+src/openjarvis/speech/kokoro_tts.py — Kokoro TTS backend (open-source fallback)
+src/openjarvis/speech/openai_tts.py — OpenAI TTS backend
+
+src/openjarvis/tools/text_to_speech.py — TTS tool (wraps TTSBackend for agent use)
+src/openjarvis/tools/digest_collect.py — Data collection tool (queries connectors)
+
+src/openjarvis/agents/morning_digest.py — MorningDigestAgent
+src/openjarvis/agents/digest_store.py — DigestStore (SQLite) + DigestArtifact
+
+src/openjarvis/cli/digest_cmd.py — `jarvis digest` CLI subcommand
+src/openjarvis/server/digest_routes.py — /api/digest FastAPI endpoints
+
+configs/openjarvis/prompts/personas/jarvis.md — Jarvis persona prompt
+configs/openjarvis/prompts/personas/neutral.md — Neutral persona prompt
+
+tests/connectors/test_oura.py
+tests/connectors/test_strava.py
+tests/connectors/test_spotify.py
+tests/connectors/test_google_tasks.py
+tests/speech/test_tts_backends.py
+tests/tools/test_text_to_speech.py
+tests/tools/test_digest_collect.py
+tests/agents/test_morning_digest.py
+tests/agents/test_digest_store.py
+tests/cli/test_digest_cmd.py
+tests/server/test_digest_routes.py
+```
+
+### Modified Files
+
+```
+src/openjarvis/connectors/__init__.py — Add imports for new connectors
+src/openjarvis/speech/__init__.py — Add imports for TTS backends
+src/openjarvis/tools/__init__.py — Add imports for new tools
+src/openjarvis/agents/__init__.py — Add import for morning_digest agent
+src/openjarvis/cli/__init__.py — Register `digest` subcommand
+src/openjarvis/server/app.py — Mount digest_routes router
+src/openjarvis/core/config.py — Add DigestConfig dataclass
+src/openjarvis/core/registry.py — Add TTSRegistry
+```
+
+---
+
+## PR 1: MCP Connectors
+
+> All connectors tested with real API data. This PR is foundational — everything else builds on it.
+
+---
+
+### Task 1: Oura Ring Connector
+
+**Files:**
+- Create: `src/openjarvis/connectors/oura.py`
+- Create: `tests/connectors/test_oura.py`
+- Modify: `src/openjarvis/connectors/__init__.py`
+
+- [ ] **Step 1: Write the failing test for Oura connector registration**
+
+```python
+# tests/connectors/test_oura.py
+"""Tests for OuraConnector — Oura Ring REST API v2."""
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta
+from unittest.mock import patch
+
+import pytest
+
+from openjarvis.connectors._stubs import Document
+from openjarvis.core.registry import ConnectorRegistry
+
+
+def test_oura_registered():
+ """OuraConnector is discoverable via ConnectorRegistry."""
+ assert ConnectorRegistry.contains("oura")
+```
+
+- [ ] **Step 2: Run test to verify it fails**
+
+Run: `uv run pytest tests/connectors/test_oura.py::test_oura_registered -v`
+Expected: FAIL — `"oura"` not registered
+
+- [ ] **Step 3: Write the OuraConnector implementation**
+
+```python
+# src/openjarvis/connectors/oura.py
+"""Oura Ring connector — sleep, readiness, and activity via REST API v2.
+
+Uses a Personal Access Token (PAT) stored in the connector config dir.
+All API calls are in module-level functions for easy mocking in tests.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime, timedelta
+from pathlib import Path
+from typing import Any, Dict, Iterator, List, Optional
+
+import httpx
+
+from openjarvis.connectors._stubs import BaseConnector, Document, SyncStatus
+from openjarvis.core.config import DEFAULT_CONFIG_DIR
+from openjarvis.core.registry import ConnectorRegistry
+
+_OURA_API_BASE = "https://api.ouraring.com/v2/usercollection"
+_DEFAULT_TOKEN_PATH = str(DEFAULT_CONFIG_DIR / "connectors" / "oura.json")
+
+
+def _oura_api_get(
+ token: str, endpoint: str, params: Optional[Dict[str, str]] = None
+) -> Dict[str, Any]:
+ """Call an Oura API v2 endpoint."""
+ resp = httpx.get(
+ f"{_OURA_API_BASE}/{endpoint}",
+ headers={"Authorization": f"Bearer {token}"},
+ params=params or {},
+ timeout=30.0,
+ )
+ resp.raise_for_status()
+ return resp.json()
+
+
+class OuraConnector(BaseConnector):
+ """Sync sleep, readiness, and activity data from Oura Ring."""
+
+ connector_id = "oura"
+ display_name = "Oura Ring"
+ auth_type = "token"
+
+ def __init__(self, *, token_path: str = _DEFAULT_TOKEN_PATH) -> None:
+ self._token_path = Path(token_path)
+ self._status = SyncStatus()
+
+ def _load_token(self) -> str:
+ """Load the Oura PAT from disk."""
+ data = json.loads(self._token_path.read_text(encoding="utf-8"))
+ return data["token"]
+
+ def is_connected(self) -> bool:
+ return self._token_path.exists()
+
+ def disconnect(self) -> None:
+ if self._token_path.exists():
+ self._token_path.unlink()
+
+ def sync(
+ self, *, since: Optional[datetime] = None, cursor: Optional[str] = None
+ ) -> Iterator[Document]:
+ """Yield Documents for sleep, readiness, and activity."""
+ token = self._load_token()
+ start = (since or datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d")
+ end = datetime.now().strftime("%Y-%m-%d")
+
+ for data_type in ("sleep", "daily_readiness", "daily_activity"):
+ data = _oura_api_get(
+ token, data_type, params={"start_date": start, "end_date": end}
+ )
+ for item in data.get("data", []):
+ day = item.get("day", start)
+ yield Document(
+ doc_id=f"oura-{data_type}-{day}",
+ source="oura",
+ doc_type=data_type,
+ content=json.dumps(item),
+ title=f"Oura {data_type.replace('_', ' ').title()} — {day}",
+ timestamp=datetime.fromisoformat(day),
+ metadata={"data_type": data_type, "day": day},
+ )
+
+ self._status.state = "idle"
+ self._status.last_sync = datetime.now()
+
+ def sync_status(self) -> SyncStatus:
+ return self._status
+```
+
+- [ ] **Step 4: Register in connectors __init__.py**
+
+Add to `src/openjarvis/connectors/__init__.py`:
+
+```python
+try:
+ import openjarvis.connectors.oura # noqa: F401
+except ImportError:
+ pass
+```
+
+- [ ] **Step 5: Run registration test to verify it passes**
+
+Run: `uv run pytest tests/connectors/test_oura.py::test_oura_registered -v`
+Expected: PASS
+
+- [ ] **Step 6: Write tests for sync with mocked API**
+
+Add to `tests/connectors/test_oura.py`:
+
+```python
+_SLEEP_RESPONSE = {
+ "data": [
+ {
+ "day": "2026-04-01",
+ "score": 85,
+ "total_sleep_duration": 28800,
+ "rem_sleep_duration": 5400,
+ "deep_sleep_duration": 7200,
+ }
+ ]
+}
+
+_READINESS_RESPONSE = {
+ "data": [
+ {
+ "day": "2026-04-01",
+ "score": 78,
+ "temperature_deviation": 0.1,
+ }
+ ]
+}
+
+_ACTIVITY_RESPONSE = {
+ "data": [
+ {
+ "day": "2026-04-01",
+ "score": 92,
+ "steps": 8500,
+ "active_calories": 450,
+ }
+ ]
+}
+
+
+def connector(tmp_path):
+ """OuraConnector with fake token file."""
+ from openjarvis.connectors.oura import OuraConnector
+
+ token_path = tmp_path / "oura.json"
+ token_path.write_text('{"token": "fake-pat"}', encoding="utf-8")
+ return OuraConnector(token_path=str(token_path))
+
+
+def test_is_connected(connector):
+ assert connector.is_connected() is True
+
+
+def test_sync_yields_documents(connector):
+ """Sync returns Documents for sleep, readiness, and activity."""
+ with (
+ patch(
+ "openjarvis.connectors.oura._oura_api_get",
+ side_effect=[_SLEEP_RESPONSE, _READINESS_RESPONSE, _ACTIVITY_RESPONSE],
+ ),
+ ):
+ docs = list(connector.sync(since=datetime(2026, 4, 1)))
+
+ assert len(docs) == 3
+ assert all(isinstance(d, Document) for d in docs)
+ assert docs[0].source == "oura"
+ assert docs[0].doc_type == "sleep"
+ assert docs[1].doc_type == "daily_readiness"
+ assert docs[2].doc_type == "daily_activity"
+ assert "85" in docs[0].content # sleep score
+
+
+def test_disconnect(connector):
+ connector.disconnect()
+ assert connector.is_connected() is False
+```
+
+- [ ] **Step 7: Run all tests**
+
+Run: `uv run pytest tests/connectors/test_oura.py -v`
+Expected: All PASS
+
+- [ ] **Step 8: Commit**
+
+```bash
+git add src/openjarvis/connectors/oura.py tests/connectors/test_oura.py src/openjarvis/connectors/__init__.py
+git commit -m "feat: add Oura Ring connector with sleep, readiness, and activity sync"
+```
+
+---
+
+### Task 2: Strava Connector
+
+**Files:**
+- Create: `src/openjarvis/connectors/strava.py`
+- Create: `tests/connectors/test_strava.py`
+- Modify: `src/openjarvis/connectors/__init__.py`
+
+- [ ] **Step 1: Write the failing test for Strava connector registration**
+
+```python
+# tests/connectors/test_strava.py
+"""Tests for StravaConnector — Strava REST API v3."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from unittest.mock import patch
+
+import pytest
+
+from openjarvis.connectors._stubs import Document
+from openjarvis.core.registry import ConnectorRegistry
+
+
+def test_strava_registered():
+ assert ConnectorRegistry.contains("strava")
+```
+
+- [ ] **Step 2: Run test to verify it fails**
+
+Run: `uv run pytest tests/connectors/test_strava.py::test_strava_registered -v`
+Expected: FAIL
+
+- [ ] **Step 3: Write the StravaConnector implementation**
+
+```python
+# src/openjarvis/connectors/strava.py
+"""Strava connector — recent activities via REST API v3.
+
+Uses OAuth2 tokens stored locally. Refresh handled automatically.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime, timedelta
+from pathlib import Path
+from typing import Any, Dict, Iterator, List, Optional
+
+import httpx
+
+from openjarvis.connectors._stubs import BaseConnector, Document, SyncStatus
+from openjarvis.core.config import DEFAULT_CONFIG_DIR
+from openjarvis.core.registry import ConnectorRegistry
+
+_STRAVA_API_BASE = "https://www.strava.com/api/v3"
+_STRAVA_TOKEN_URL = "https://www.strava.com/oauth/token"
+_DEFAULT_TOKEN_PATH = str(DEFAULT_CONFIG_DIR / "connectors" / "strava.json")
+
+
+def _strava_api_get(
+ token: str, endpoint: str, params: Optional[Dict[str, Any]] = None
+) -> Any:
+ """Call a Strava API v3 endpoint."""
+ resp = httpx.get(
+ f"{_STRAVA_API_BASE}/{endpoint}",
+ headers={"Authorization": f"Bearer {token}"},
+ params=params or {},
+ timeout=30.0,
+ )
+ resp.raise_for_status()
+ return resp.json()
+
+
+def _strava_refresh_token(
+ client_id: str, client_secret: str, refresh_token: str
+) -> Dict[str, Any]:
+ """Refresh an expired Strava OAuth2 token."""
+ resp = httpx.post(
+ _STRAVA_TOKEN_URL,
+ data={
+ "client_id": client_id,
+ "client_secret": client_secret,
+ "refresh_token": refresh_token,
+ "grant_type": "refresh_token",
+ },
+ timeout=30.0,
+ )
+ resp.raise_for_status()
+ return resp.json()
+
+
+class StravaConnector(BaseConnector):
+ """Sync recent activities from Strava."""
+
+ connector_id = "strava"
+ display_name = "Strava"
+ auth_type = "oauth"
+
+ def __init__(self, *, token_path: str = _DEFAULT_TOKEN_PATH) -> None:
+ self._token_path = Path(token_path)
+ self._status = SyncStatus()
+
+ def _load_tokens(self) -> Dict[str, str]:
+ return json.loads(self._token_path.read_text(encoding="utf-8"))
+
+ def _save_tokens(self, tokens: Dict[str, str]) -> None:
+ self._token_path.write_text(json.dumps(tokens), encoding="utf-8")
+
+ def _get_access_token(self) -> str:
+ tokens = self._load_tokens()
+ return tokens["access_token"]
+
+ def is_connected(self) -> bool:
+ return self._token_path.exists()
+
+ def disconnect(self) -> None:
+ if self._token_path.exists():
+ self._token_path.unlink()
+
+ def sync(
+ self, *, since: Optional[datetime] = None, cursor: Optional[str] = None
+ ) -> Iterator[Document]:
+ token = self._get_access_token()
+ after_epoch = int((since or datetime.now() - timedelta(days=7)).timestamp())
+
+ activities = _strava_api_get(
+ token,
+ "athlete/activities",
+ params={"after": str(after_epoch), "per_page": "50"},
+ )
+
+ for act in activities:
+ ts = datetime.fromisoformat(
+ act["start_date_local"].replace("Z", "+00:00")
+ ) if "start_date_local" in act else datetime.now()
+
+ yield Document(
+ doc_id=f"strava-{act['id']}",
+ source="strava",
+ doc_type=act.get("type", "Activity").lower(),
+ content=json.dumps(act),
+ title=act.get("name", "Untitled Activity"),
+ timestamp=ts,
+ metadata={
+ "distance_m": act.get("distance", 0),
+ "moving_time_s": act.get("moving_time", 0),
+ "sport_type": act.get("sport_type", ""),
+ },
+ )
+
+ self._status.state = "idle"
+ self._status.last_sync = datetime.now()
+
+ def sync_status(self) -> SyncStatus:
+ return self._status
+```
+
+- [ ] **Step 4: Register in connectors __init__.py**
+
+Add to `src/openjarvis/connectors/__init__.py`:
+
+```python
+try:
+ import openjarvis.connectors.strava # noqa: F401
+except ImportError:
+ pass
+```
+
+- [ ] **Step 5: Run registration test**
+
+Run: `uv run pytest tests/connectors/test_strava.py::test_strava_registered -v`
+Expected: PASS
+
+- [ ] **Step 6: Write tests for sync with mocked API**
+
+Add to `tests/connectors/test_strava.py`:
+
+```python
+_ACTIVITIES_RESPONSE = [
+ {
+ "id": 12345,
+ "name": "Morning Run",
+ "type": "Run",
+ "sport_type": "Run",
+ "start_date_local": "2026-04-01T07:30:00",
+ "distance": 5200.0,
+ "moving_time": 1560,
+ "elapsed_time": 1620,
+ "total_elevation_gain": 45.0,
+ "average_heartrate": 155.0,
+ },
+ {
+ "id": 12346,
+ "name": "Evening Ride",
+ "type": "Ride",
+ "sport_type": "Ride",
+ "start_date_local": "2026-04-01T18:00:00",
+ "distance": 15000.0,
+ "moving_time": 2700,
+ "elapsed_time": 2900,
+ "total_elevation_gain": 120.0,
+ },
+]
+
+
+def connector(tmp_path):
+ from openjarvis.connectors.strava import StravaConnector
+
+ token_path = tmp_path / "strava.json"
+ token_path.write_text(
+ '{"access_token": "fake-token", "refresh_token": "fake-refresh"}',
+ encoding="utf-8",
+ )
+ return StravaConnector(token_path=str(token_path))
+
+
+def test_sync_yields_activities(connector):
+ with patch(
+ "openjarvis.connectors.strava._strava_api_get",
+ return_value=_ACTIVITIES_RESPONSE,
+ ):
+ docs = list(connector.sync(since=datetime(2026, 4, 1)))
+
+ assert len(docs) == 2
+ assert docs[0].source == "strava"
+ assert docs[0].doc_type == "run"
+ assert docs[0].title == "Morning Run"
+ assert docs[1].doc_type == "ride"
+ assert docs[0].metadata["distance_m"] == 5200.0
+```
+
+- [ ] **Step 7: Run all tests**
+
+Run: `uv run pytest tests/connectors/test_strava.py -v`
+Expected: All PASS
+
+- [ ] **Step 8: Commit**
+
+```bash
+git add src/openjarvis/connectors/strava.py tests/connectors/test_strava.py src/openjarvis/connectors/__init__.py
+git commit -m "feat: add Strava connector with activity sync"
+```
+
+---
+
+### Task 3: Spotify Connector
+
+**Files:**
+- Create: `src/openjarvis/connectors/spotify.py`
+- Create: `tests/connectors/test_spotify.py`
+- Modify: `src/openjarvis/connectors/__init__.py`
+
+- [ ] **Step 1: Write the failing test**
+
+```python
+# tests/connectors/test_spotify.py
+"""Tests for SpotifyConnector — Spotify Web API."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from unittest.mock import patch
+
+import pytest
+
+from openjarvis.connectors._stubs import Document
+from openjarvis.core.registry import ConnectorRegistry
+
+
+def test_spotify_registered():
+ assert ConnectorRegistry.contains("spotify")
+```
+
+- [ ] **Step 2: Run test to verify it fails**
+
+Run: `uv run pytest tests/connectors/test_spotify.py::test_spotify_registered -v`
+Expected: FAIL
+
+- [ ] **Step 3: Write the SpotifyConnector implementation**
+
+```python
+# src/openjarvis/connectors/spotify.py
+"""Spotify connector — recently played tracks via Spotify Web API.
+
+Uses OAuth2 tokens stored locally. Requires user-read-recently-played scope.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime, timedelta
+from pathlib import Path
+from typing import Any, Dict, Iterator, List, Optional
+
+import httpx
+
+from openjarvis.connectors._stubs import BaseConnector, Document, SyncStatus
+from openjarvis.core.config import DEFAULT_CONFIG_DIR
+from openjarvis.core.registry import ConnectorRegistry
+
+_SPOTIFY_API_BASE = "https://api.spotify.com/v1"
+_SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token"
+_DEFAULT_TOKEN_PATH = str(DEFAULT_CONFIG_DIR / "connectors" / "spotify.json")
+
+
+def _spotify_api_get(
+ token: str, endpoint: str, params: Optional[Dict[str, Any]] = None
+) -> Dict[str, Any]:
+ """Call a Spotify Web API endpoint."""
+ resp = httpx.get(
+ f"{_SPOTIFY_API_BASE}/{endpoint}",
+ headers={"Authorization": f"Bearer {token}"},
+ params=params or {},
+ timeout=30.0,
+ )
+ resp.raise_for_status()
+ return resp.json()
+
+
+class SpotifyConnector(BaseConnector):
+ """Sync recently played tracks from Spotify."""
+
+ connector_id = "spotify"
+ display_name = "Spotify"
+ auth_type = "oauth"
+
+ def __init__(self, *, token_path: str = _DEFAULT_TOKEN_PATH) -> None:
+ self._token_path = Path(token_path)
+ self._status = SyncStatus()
+
+ def _load_tokens(self) -> Dict[str, str]:
+ return json.loads(self._token_path.read_text(encoding="utf-8"))
+
+ def _get_access_token(self) -> str:
+ return self._load_tokens()["access_token"]
+
+ def is_connected(self) -> bool:
+ return self._token_path.exists()
+
+ def disconnect(self) -> None:
+ if self._token_path.exists():
+ self._token_path.unlink()
+
+ def sync(
+ self, *, since: Optional[datetime] = None, cursor: Optional[str] = None
+ ) -> Iterator[Document]:
+ token = self._get_access_token()
+ after_ms = int(
+ (since or datetime.now() - timedelta(days=1)).timestamp() * 1000
+ )
+
+ data = _spotify_api_get(
+ token,
+ "me/player/recently-played",
+ params={"limit": "50", "after": str(after_ms)},
+ )
+
+ for item in data.get("items", []):
+ track = item.get("track", {})
+ played_at = item.get("played_at", "")
+ artists = ", ".join(a["name"] for a in track.get("artists", []))
+
+ ts = datetime.fromisoformat(
+ played_at.replace("Z", "+00:00")
+ ) if played_at else datetime.now()
+
+ yield Document(
+ doc_id=f"spotify-{track.get('id', '')}-{played_at}",
+ source="spotify",
+ doc_type="recently_played",
+ content=json.dumps(item),
+ title=f"{track.get('name', 'Unknown')} — {artists}",
+ author=artists,
+ timestamp=ts,
+ url=track.get("external_urls", {}).get("spotify", ""),
+ metadata={
+ "track_name": track.get("name", ""),
+ "album": track.get("album", {}).get("name", ""),
+ "duration_ms": track.get("duration_ms", 0),
+ },
+ )
+
+ self._status.state = "idle"
+ self._status.last_sync = datetime.now()
+
+ def sync_status(self) -> SyncStatus:
+ return self._status
+```
+
+- [ ] **Step 4: Register in connectors __init__.py**
+
+Add to `src/openjarvis/connectors/__init__.py`:
+
+```python
+try:
+ import openjarvis.connectors.spotify # noqa: F401
+except ImportError:
+ pass
+```
+
+- [ ] **Step 5: Run registration test**
+
+Run: `uv run pytest tests/connectors/test_spotify.py::test_spotify_registered -v`
+Expected: PASS
+
+- [ ] **Step 6: Write tests for sync with mocked API**
+
+Add to `tests/connectors/test_spotify.py`:
+
+```python
+_RECENTLY_PLAYED_RESPONSE = {
+ "items": [
+ {
+ "played_at": "2026-04-01T08:30:00Z",
+ "track": {
+ "id": "track1",
+ "name": "Bohemian Rhapsody",
+ "artists": [{"name": "Queen"}],
+ "album": {"name": "A Night at the Opera"},
+ "duration_ms": 354000,
+ "external_urls": {"spotify": "https://open.spotify.com/track/track1"},
+ },
+ },
+ {
+ "played_at": "2026-04-01T08:25:00Z",
+ "track": {
+ "id": "track2",
+ "name": "Stairway to Heaven",
+ "artists": [{"name": "Led Zeppelin"}],
+ "album": {"name": "Led Zeppelin IV"},
+ "duration_ms": 482000,
+ "external_urls": {"spotify": "https://open.spotify.com/track/track2"},
+ },
+ },
+ ]
+}
+
+
+def connector(tmp_path):
+ from openjarvis.connectors.spotify import SpotifyConnector
+
+ token_path = tmp_path / "spotify.json"
+ token_path.write_text('{"access_token": "fake-token"}', encoding="utf-8")
+ return SpotifyConnector(token_path=str(token_path))
+
+
+def test_sync_yields_tracks(connector):
+ with patch(
+ "openjarvis.connectors.spotify._spotify_api_get",
+ return_value=_RECENTLY_PLAYED_RESPONSE,
+ ):
+ docs = list(connector.sync(since=datetime(2026, 4, 1)))
+
+ assert len(docs) == 2
+ assert docs[0].source == "spotify"
+ assert docs[0].doc_type == "recently_played"
+ assert "Queen" in docs[0].title
+ assert docs[0].metadata["track_name"] == "Bohemian Rhapsody"
+```
+
+- [ ] **Step 7: Run all tests**
+
+Run: `uv run pytest tests/connectors/test_spotify.py -v`
+Expected: All PASS
+
+- [ ] **Step 8: Commit**
+
+```bash
+git add src/openjarvis/connectors/spotify.py tests/connectors/test_spotify.py src/openjarvis/connectors/__init__.py
+git commit -m "feat: add Spotify connector with recently played sync"
+```
+
+---
+
+### Task 4: Google Tasks Connector
+
+**Files:**
+- Create: `src/openjarvis/connectors/google_tasks.py`
+- Create: `tests/connectors/test_google_tasks.py`
+- Modify: `src/openjarvis/connectors/__init__.py`
+
+- [ ] **Step 1: Write the failing test**
+
+```python
+# tests/connectors/test_google_tasks.py
+"""Tests for GoogleTasksConnector — Google Tasks API v1."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from unittest.mock import patch
+
+import pytest
+
+from openjarvis.connectors._stubs import Document
+from openjarvis.core.registry import ConnectorRegistry
+
+
+def test_google_tasks_registered():
+ assert ConnectorRegistry.contains("google_tasks")
+```
+
+- [ ] **Step 2: Run test to verify it fails**
+
+Run: `uv run pytest tests/connectors/test_google_tasks.py::test_google_tasks_registered -v`
+Expected: FAIL
+
+- [ ] **Step 3: Write the GoogleTasksConnector implementation**
+
+```python
+# src/openjarvis/connectors/google_tasks.py
+"""Google Tasks connector — tasks due today, overdue, and recently completed.
+
+Uses OAuth2 tokens via the shared Google OAuth helper module.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime, timedelta
+from pathlib import Path
+from typing import Any, Dict, Iterator, List, Optional
+
+import httpx
+
+from openjarvis.connectors._stubs import BaseConnector, Document, SyncStatus
+from openjarvis.connectors.oauth import load_tokens
+from openjarvis.core.config import DEFAULT_CONFIG_DIR
+from openjarvis.core.registry import ConnectorRegistry
+
+_TASKS_API_BASE = "https://tasks.googleapis.com/tasks/v1"
+_DEFAULT_CREDENTIALS_PATH = str(DEFAULT_CONFIG_DIR / "connectors" / "google_tasks.json")
+
+
+def _tasks_api_get(
+ token: str, endpoint: str, params: Optional[Dict[str, str]] = None
+) -> Dict[str, Any]:
+ """Call a Google Tasks API v1 endpoint."""
+ resp = httpx.get(
+ f"{_TASKS_API_BASE}/{endpoint}",
+ headers={"Authorization": f"Bearer {token}"},
+ params=params or {},
+ timeout=30.0,
+ )
+ resp.raise_for_status()
+ return resp.json()
+
+
[email protected]("google_tasks")
+class GoogleTasksConnector(BaseConnector):
+ """Sync tasks from Google Tasks."""
+
+ connector_id = "google_tasks"
+ display_name = "Google Tasks"
+ auth_type = "oauth"
+
+ def __init__(self, *, credentials_path: str = _DEFAULT_CREDENTIALS_PATH) -> None:
+ self._credentials_path = Path(credentials_path)
+ self._status = SyncStatus()
+
+ def _get_access_token(self) -> str:
+ tokens = load_tokens(self._credentials_path)
+ return tokens["token"]
+
+ def is_connected(self) -> bool:
+ return self._credentials_path.exists()
+
+ def disconnect(self) -> None:
+ if self._credentials_path.exists():
+ self._credentials_path.unlink()
+
+ def sync(
+ self, *, since: Optional[datetime] = None, cursor: Optional[str] = None
+ ) -> Iterator[Document]:
+ token = self._get_access_token()
+
+ # List all task lists first
+ task_lists = _tasks_api_get(token, "users/@me/lists")
+
+ for tl in task_lists.get("items", []):
+ tl_id = tl["id"]
+ tl_title = tl.get("title", "My Tasks")
+
+ # Get tasks from this list, updated since cutoff
+ params: Dict[str, str] = {"showCompleted": "true", "showHidden": "false"}
+ if since:
+ params["updatedMin"] = since.isoformat() + "Z"
+
+ tasks = _tasks_api_get(token, f"lists/{tl_id}/tasks", params=params)
+
+ for task in tasks.get("items", []):
+ due = task.get("due", "")
+ status = task.get("status", "needsAction")
+
+ ts = datetime.fromisoformat(
+ task.get("updated", "").replace("Z", "+00:00")
+ ) if task.get("updated") else datetime.now()
+
+ yield Document(
+ doc_id=f"gtasks-{task['id']}",
+ source="google_tasks",
+ doc_type="task",
+ content=task.get("notes", ""),
+ title=task.get("title", "Untitled Task"),
+ timestamp=ts,
+ url=task.get("selfLink", ""),
+ metadata={
+ "task_list": tl_title,
+ "status": status,
+ "due": due,
+ "completed": task.get("completed", ""),
+ },
+ )
+
+ self._status.state = "idle"
+ self._status.last_sync = datetime.now()
+
+ def sync_status(self) -> SyncStatus:
+ return self._status
+```
+
+- [ ] **Step 4: Register in connectors __init__.py**
+
+Add to `src/openjarvis/connectors/__init__.py`:
+
+```python
+try:
+ import openjarvis.connectors.google_tasks # noqa: F401
+except ImportError:
+ pass
+```
+
+- [ ] **Step 5: Run registration test**
+
+Run: `uv run pytest tests/connectors/test_google_tasks.py::test_google_tasks_registered -v`
+Expected: PASS
+
+- [ ] **Step 6: Write tests for sync with mocked API**
+
+Add to `tests/connectors/test_google_tasks.py`:
+
+```python
+_TASK_LISTS_RESPONSE = {
+ "items": [{"id": "list1", "title": "My Tasks"}]
+}
+
+_TASKS_RESPONSE = {
+ "items": [
+ {
+ "id": "task1",
+ "title": "Review PR #42",
+ "notes": "Check the auth middleware changes",
+ "status": "needsAction",
+ "due": "2026-04-01T00:00:00.000Z",
+ "updated": "2026-03-31T20:00:00.000Z",
+ "selfLink": "https://tasks.googleapis.com/tasks/v1/lists/list1/tasks/task1",
+ },
+ {
+ "id": "task2",
+ "title": "Submit expense report",
+ "notes": "",
+ "status": "completed",
+ "due": "2026-03-31T00:00:00.000Z",
+ "completed": "2026-03-31T15:00:00.000Z",
+ "updated": "2026-03-31T15:00:00.000Z",
+ "selfLink": "https://tasks.googleapis.com/tasks/v1/lists/list1/tasks/task2",
+ },
+ ]
+}
+
+
+def connector(tmp_path):
+ from openjarvis.connectors.google_tasks import GoogleTasksConnector
+
+ creds = tmp_path / "google_tasks.json"
+ creds.write_text('{"token": "fake-token"}', encoding="utf-8")
+ return GoogleTasksConnector(credentials_path=str(creds))
+
+
+def test_sync_yields_tasks(connector):
+ with patch(
+ "openjarvis.connectors.google_tasks._tasks_api_get",
+ side_effect=[_TASK_LISTS_RESPONSE, _TASKS_RESPONSE],
+ ):
+ docs = list(connector.sync(since=datetime(2026, 3, 31)))
+
+ assert len(docs) == 2
+ assert docs[0].source == "google_tasks"
+ assert docs[0].doc_type == "task"
+ assert docs[0].title == "Review PR #42"
+ assert docs[0].metadata["status"] == "needsAction"
+ assert docs[1].metadata["status"] == "completed"
+```
+
+- [ ] **Step 7: Run all tests**
+
+Run: `uv run pytest tests/connectors/test_google_tasks.py -v`
+Expected: All PASS
+
+- [ ] **Step 8: Commit**
+
+```bash
+git add src/openjarvis/connectors/google_tasks.py tests/connectors/test_google_tasks.py src/openjarvis/connectors/__init__.py
+git commit -m "feat: add Google Tasks connector with task sync"
+```
+
+---
+
+### Task 5: Live smoke tests for all new connectors
+
+> Run ONLY with real API credentials. Mark with `@pytest.mark.cloud`.
+
+**Files:**
+- Create: `tests/connectors/test_new_connectors_live.py`
+
+- [ ] **Step 1: Write live smoke tests**
+
+```python
+# tests/connectors/test_new_connectors_live.py
+"""Live smoke tests for new connectors — require real API credentials.
+
+Run with: uv run pytest tests/connectors/test_new_connectors_live.py -v -m cloud
+"""
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta
+
+import pytest
+
+from openjarvis.connectors._stubs import Document
+
+
+class TestOuraLive:
+ def test_sync_returns_documents(self):
+ from openjarvis.connectors.oura import OuraConnector
+
+ conn = OuraConnector() # Uses default token path
+ docs = list(conn.sync(since=datetime.now() - timedelta(days=1)))
+ assert len(docs) > 0
+ assert all(isinstance(d, Document) for d in docs)
+ assert all(d.source == "oura" for d in docs)
+
+
+class TestStravaLive:
+ def test_sync_returns_documents(self):
+ from openjarvis.connectors.strava import StravaConnector
+
+ conn = StravaConnector()
+ docs = list(conn.sync(since=datetime.now() - timedelta(days=7)))
+ assert all(isinstance(d, Document) for d in docs)
+ assert all(d.source == "strava" for d in docs)
+
+
+class TestSpotifyLive:
+ def test_sync_returns_documents(self):
+ from openjarvis.connectors.spotify import SpotifyConnector
+
+ conn = SpotifyConnector()
+ docs = list(conn.sync(since=datetime.now() - timedelta(days=1)))
+ assert all(isinstance(d, Document) for d in docs)
+ assert all(d.source == "spotify" for d in docs)
+
+
+class TestGoogleTasksLive:
+ def test_sync_returns_documents(self):
+ from openjarvis.connectors.google_tasks import GoogleTasksConnector
+
+ conn = GoogleTasksConnector()
+ docs = list(conn.sync(since=datetime.now() - timedelta(days=7)))
+ assert all(isinstance(d, Document) for d in docs)
+ assert all(d.source == "google_tasks" for d in docs)
+```
+
+- [ ] **Step 2: Run live tests with real credentials**
+
+Run: `uv run pytest tests/connectors/test_new_connectors_live.py -v -m cloud`
+Expected: All PASS (requires real API tokens in `~/.openjarvis/connectors/`)
+
+- [ ] **Step 3: Commit**
+
+```bash
+git add tests/connectors/test_new_connectors_live.py
+git commit -m "test: add live smoke tests for Oura, Strava, Spotify, Google Tasks connectors"
+```
+
+---
+
+## PR 2: TTS Backend Infrastructure
+
+---
+
+### Task 6: TTSBackend ABC + TTSRegistry
+
+**Files:**
+- Create: `src/openjarvis/speech/tts.py`
+- Create: `tests/speech/test_tts_backends.py`
+- Modify: `src/openjarvis/core/registry.py`
+
+- [ ] **Step 1: Write the failing test**
+
+```python
+# tests/speech/test_tts_backends.py
+"""Tests for TTS backend infrastructure."""
+
+from __future__ import annotations
+
+import pytest
+
+from openjarvis.speech.tts import TTSBackend, TTSResult
+
+
+def test_tts_result_dataclass():
+ result = TTSResult(
+ audio=b"fake-audio-bytes",
+ format="mp3",
+ duration_seconds=3.5,
+ voice_id="jarvis-v1",
+ )
+ assert result.audio == b"fake-audio-bytes"
+ assert result.format == "mp3"
+ assert result.duration_seconds == 3.5
+```
+
+- [ ] **Step 2: Run test to verify it fails**
+
+Run: `uv run pytest tests/speech/test_tts_backends.py::test_tts_result_dataclass -v`
+Expected: FAIL — module not found
+
+- [ ] **Step 3: Write TTSBackend ABC and TTSResult**
+
+```python
+# src/openjarvis/speech/tts.py
+"""Abstract base classes and data types for text-to-speech backends."""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Dict, List, Optional, Any
+
+
+@dataclass
+class TTSResult:
+ """Result of a text-to-speech synthesis."""
+
+ audio: bytes
+ format: str = "mp3"
+ duration_seconds: float = 0.0
+ voice_id: str = ""
+ sample_rate: int = 24000
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+ def save(self, path: Path) -> Path:
+ """Write audio bytes to a file and return the path."""
+ path.write_bytes(self.audio)
+ return path
+
+
+class TTSBackend(ABC):
+ """Abstract base class for text-to-speech backends."""
+
+ backend_id: str = ""
+
+ @abstractmethod
+ def synthesize(
+ self,
+ text: str,
+ *,
+ voice_id: str = "",
+ speed: float = 1.0,
+ output_format: str = "mp3",
+ ) -> TTSResult:
+ """Synthesize text to audio."""
+
+ @abstractmethod
+ def available_voices(self) -> List[str]:
+ """Return list of available voice IDs."""
+
+ @abstractmethod
+ def health(self) -> bool:
+ """Check if the backend is ready."""
+
+
+__all__ = ["TTSBackend", "TTSResult"]
+```
+
+- [ ] **Step 4: Add TTSRegistry to core/registry.py**
+
+Add after `SpeechRegistry` in `src/openjarvis/core/registry.py`:
+
+```python
+class TTSRegistry(RegistryBase[Any]):
+ """Registry for text-to-speech backend implementations."""
+```
+
+And add `"TTSRegistry"` to the `__all__` list.
+
+- [ ] **Step 5: Run test to verify it passes**
+
+Run: `uv run pytest tests/speech/test_tts_backends.py::test_tts_result_dataclass -v`
+Expected: PASS
+
+- [ ] **Step 6: Write test for TTSResult.save()**
+
+Add to `tests/speech/test_tts_backends.py`:
+
+```python
+def test_tts_result_save(tmp_path):
+ result = TTSResult(audio=b"fake-mp3-data", format="mp3")
+ out = result.save(tmp_path / "test.mp3")
+ assert out.exists()
+ assert out.read_bytes() == b"fake-mp3-data"
+```
+
+- [ ] **Step 7: Run all tests**
+
+Run: `uv run pytest tests/speech/test_tts_backends.py -v`
+Expected: All PASS
+
+- [ ] **Step 8: Commit**
+
+```bash
+git add src/openjarvis/speech/tts.py tests/speech/test_tts_backends.py src/openjarvis/core/registry.py
+git commit -m "feat: add TTSBackend ABC, TTSResult, and TTSRegistry"
+```
+
+---
+
+### Task 7: Cartesia TTS Backend
+
+**Files:**
+- Create: `src/openjarvis/speech/cartesia_tts.py`
+- Modify: `src/openjarvis/speech/__init__.py`
+- Modify: `tests/speech/test_tts_backends.py`
+
+- [ ] **Step 1: Write failing test for Cartesia registration**
+
+Add to `tests/speech/test_tts_backends.py`:
+
+```python
+from openjarvis.core.registry import TTSRegistry
+
+
+def test_cartesia_registered():
+ assert TTSRegistry.contains("cartesia")
+```
+
+- [ ] **Step 2: Run test to verify it fails**
+
+Run: `uv run pytest tests/speech/test_tts_backends.py::test_cartesia_registered -v`
+Expected: FAIL
+
+- [ ] **Step 3: Write Cartesia TTS backend**
+
+```python
+# src/openjarvis/speech/cartesia_tts.py
+"""Cartesia text-to-speech backend.
+
+Uses the Cartesia REST API for high-quality, low-latency voice synthesis.
+Requires CARTESIA_API_KEY environment variable or config.
+"""
+
+from __future__ import annotations
+
+import os
+from typing import List
+
+import httpx
+
+from openjarvis.core.registry import TTSRegistry
+from openjarvis.speech.tts import TTSBackend, TTSResult
+
+_CARTESIA_API_BASE = "https://api.cartesia.ai"
+
+
+def _cartesia_synthesize(
+ api_key: str,
+ text: str,
+ voice_id: str,
+ model: str = "sonic",
+ output_format: str = "mp3",
+ speed: float = 1.0,
+) -> bytes:
+ """Call the Cartesia TTS API and return raw audio bytes."""
+ resp = httpx.post(
+ f"{_CARTESIA_API_BASE}/tts/bytes",
+ headers={
+ "X-API-Key": api_key,
+ "Cartesia-Version": "2024-06-10",
+ },
+ json={
+ "model_id": model,
+ "transcript": text,
+ "voice": {"mode": "id", "id": voice_id},
+ "output_format": {
+ "container": output_format,
+ "sample_rate": 24000,
+ "encoding": "mp3" if output_format == "mp3" else "pcm_f32le",
+ },
+ "language": "en",
+ },
+ timeout=120.0,
+ )
+ resp.raise_for_status()
+ return resp.content
+
+
[email protected]("cartesia")
+class CartesiaTTSBackend(TTSBackend):
+ """Cartesia TTS backend — fast, high-quality synthesis."""
+
+ backend_id = "cartesia"
+
+ def __init__(self, *, api_key: str = "", model: str = "sonic") -> None:
+ self._api_key = api_key or os.environ.get("CARTESIA_API_KEY", "")
+ self._model = model
+
+ def synthesize(
+ self,
+ text: str,
+ *,
+ voice_id: str = "",
+ speed: float = 1.0,
+ output_format: str = "mp3",
+ ) -> TTSResult:
+ if not self._api_key:
+ raise RuntimeError("CARTESIA_API_KEY not set")
+
+ audio = _cartesia_synthesize(
+ self._api_key,
+ text,
+ voice_id=voice_id,
+ model=self._model,
+ output_format=output_format,
+ speed=speed,
+ )
+
+ return TTSResult(
+ audio=audio,
+ format=output_format,
+ voice_id=voice_id,
+ metadata={"backend": "cartesia", "model": self._model},
+ )
+
+ def available_voices(self) -> List[str]:
+ if not self._api_key:
+ return []
+ resp = httpx.get(
+ f"{_CARTESIA_API_BASE}/voices",
+ headers={"X-API-Key": self._api_key, "Cartesia-Version": "2024-06-10"},
+ timeout=30.0,
+ )
+ resp.raise_for_status()
+ return [v["id"] for v in resp.json()]
+
+ def health(self) -> bool:
+ return bool(self._api_key)
+```
+
+- [ ] **Step 4: Register in speech __init__.py**
+
+Replace the content of `src/openjarvis/speech/__init__.py`:
+
+```python
+"""Speech subsystem — speech-to-text and text-to-speech backends."""
+
+import importlib
+
+# Optional STT backends — each registers itself via @SpeechRegistry.register()
+for _mod in ("faster_whisper", "openai_whisper", "deepgram"):
+ try:
+ importlib.import_module(f".{_mod}", __name__)
+ except ImportError:
+ pass
+
+# Optional TTS backends — each registers itself via @TTSRegistry.register()
+for _mod in ("cartesia_tts", "kokoro_tts", "openai_tts"):
+ try:
+ importlib.import_module(f".{_mod}", __name__)
+ except ImportError:
+ pass
+```
+
+- [ ] **Step 5: Write mock test for Cartesia synthesis**
+
+Add to `tests/speech/test_tts_backends.py`:
+
+```python
+from unittest.mock import patch
+
+
+def test_cartesia_synthesize():
+ from openjarvis.speech.cartesia_tts import CartesiaTTSBackend
+
+ backend = CartesiaTTSBackend(api_key="fake-key")
+
+ with patch(
+ "openjarvis.speech.cartesia_tts._cartesia_synthesize",
+ return_value=b"fake-audio-mp3-bytes",
+ ):
+ result = backend.synthesize("Hello world", voice_id="test-voice")
+
+ assert result.audio == b"fake-audio-mp3-bytes"
+ assert result.format == "mp3"
+ assert result.voice_id == "test-voice"
+```
+
+- [ ] **Step 6: Run all tests**
+
+Run: `uv run pytest tests/speech/test_tts_backends.py -v`
+Expected: All PASS
+
+- [ ] **Step 7: Commit**
+
+```bash
+git add src/openjarvis/speech/cartesia_tts.py src/openjarvis/speech/__init__.py tests/speech/test_tts_backends.py
+git commit -m "feat: add Cartesia TTS backend with REST API integration"
+```
+
+---
+
+### Task 8: Kokoro + OpenAI TTS Backends
+
+**Files:**
+- Create: `src/openjarvis/speech/kokoro_tts.py`
+- Create: `src/openjarvis/speech/openai_tts.py`
+- Modify: `tests/speech/test_tts_backends.py`
+
+- [ ] **Step 1: Write failing registration tests**
+
+Add to `tests/speech/test_tts_backends.py`:
+
+```python
+def test_kokoro_registered():
+ assert TTSRegistry.contains("kokoro")
+
+
+def test_openai_tts_registered():
+ assert TTSRegistry.contains("openai_tts")
+```
+
+- [ ] **Step 2: Run tests to verify they fail**
+
+Run: `uv run pytest tests/speech/test_tts_backends.py::test_kokoro_registered tests/speech/test_tts_backends.py::test_openai_tts_registered -v`
+Expected: FAIL
+
+- [ ] **Step 3: Write Kokoro TTS backend**
+
+```python
+# src/openjarvis/speech/kokoro_tts.py
+"""Kokoro TTS backend — fully open-source, runs locally.
+
+Requires the kokoro package: pip install kokoro
+Falls back gracefully if not installed.
+"""
+
+from __future__ import annotations
+
+import io
+from typing import List
+
+from openjarvis.core.registry import TTSRegistry
+from openjarvis.speech.tts import TTSBackend, TTSResult
+
+
+class KokoroTTSBackend(TTSBackend):
+ """Kokoro TTS — local open-source voice synthesis."""
+
+ backend_id = "kokoro"
+
+ def __init__(self, *, model_path: str = "", device: str = "auto") -> None:
+ self._model_path = model_path
+ self._device = device
+ self._pipeline = None
+
+ def _ensure_pipeline(self) -> None:
+ if self._pipeline is not None:
+ return
+ try:
+ from kokoro import KPipeline
+
+ self._pipeline = KPipeline(lang_code="a")
+ except ImportError:
+ raise RuntimeError(
+ "kokoro package not installed. Install with: pip install kokoro"
+ )
+
+ def synthesize(
+ self,
+ text: str,
+ *,
+ voice_id: str = "af_heart",
+ speed: float = 1.0,
+ output_format: str = "wav",
+ ) -> TTSResult:
+ self._ensure_pipeline()
+ import soundfile as sf
+
+ samples = []
+ for _, _, audio in self._pipeline(text, voice=voice_id, speed=speed):
+ samples.append(audio)
+
+ if not samples:
+ return TTSResult(audio=b"", format=output_format, voice_id=voice_id)
+
+ import numpy as np
+
+ combined = np.concatenate(samples)
+ buf = io.BytesIO()
+ sf.write(buf, combined, 24000, format=output_format.upper())
+ buf.seek(0)
+
+ return TTSResult(
+ audio=buf.read(),
+ format=output_format,
+ voice_id=voice_id,
+ sample_rate=24000,
+ duration_seconds=len(combined) / 24000,
+ metadata={"backend": "kokoro"},
+ )
+
+ def available_voices(self) -> List[str]:
+ return ["af_heart", "af_bella", "am_adam", "am_michael"]
+
+ def health(self) -> bool:
+ try:
+ self._ensure_pipeline()
+ return True
+ except RuntimeError:
+ return False
+```
+
+- [ ] **Step 4: Write OpenAI TTS backend**
+
+```python
+# src/openjarvis/speech/openai_tts.py
+"""OpenAI TTS backend — cloud-based voice synthesis via OpenAI API."""
+
+from __future__ import annotations
+
+import os
+from typing import List
+
+import httpx
+
+from openjarvis.core.registry import TTSRegistry
+from openjarvis.speech.tts import TTSBackend, TTSResult
+
+_OPENAI_TTS_URL = "https://api.openai.com/v1/audio/speech"
+
+
+def _openai_tts_request(
+ api_key: str,
+ text: str,
+ voice: str,
+ model: str = "tts-1",
+ speed: float = 1.0,
+ response_format: str = "mp3",
+) -> bytes:
+ """Call the OpenAI TTS API and return raw audio bytes."""
+ resp = httpx.post(
+ _OPENAI_TTS_URL,
+ headers={"Authorization": f"Bearer {api_key}"},
+ json={
+ "model": model,
+ "input": text,
+ "voice": voice,
+ "speed": speed,
+ "response_format": response_format,
+ },
+ timeout=120.0,
+ )
+ resp.raise_for_status()
+ return resp.content
+
+
[email protected]("openai_tts")
+class OpenAITTSBackend(TTSBackend):
+ """OpenAI TTS backend — cloud synthesis."""
+
+ backend_id = "openai_tts"
+
+ def __init__(self, *, api_key: str = "", model: str = "tts-1") -> None:
+ self._api_key = api_key or os.environ.get("OPENAI_API_KEY", "")
+ self._model = model
+
+ def synthesize(
+ self,
+ text: str,
+ *,
+ voice_id: str = "nova",
+ speed: float = 1.0,
+ output_format: str = "mp3",
+ ) -> TTSResult:
+ if not self._api_key:
+ raise RuntimeError("OPENAI_API_KEY not set")
+
+ audio = _openai_tts_request(
+ self._api_key,
+ text,
+ voice=voice_id,
+ model=self._model,
+ speed=speed,
+ response_format=output_format,
+ )
+
+ return TTSResult(
+ audio=audio,
+ format=output_format,
+ voice_id=voice_id,
+ metadata={"backend": "openai_tts", "model": self._model},
+ )
+
+ def available_voices(self) -> List[str]:
+ return ["alloy", "echo", "fable", "onyx", "nova", "shimmer"]
+
+ def health(self) -> bool:
+ return bool(self._api_key)
+```
+
+- [ ] **Step 5: Write mock tests for both backends**
+
+Add to `tests/speech/test_tts_backends.py`:
+
+```python
+def test_kokoro_synthesize():
+ from openjarvis.speech.kokoro_tts import KokoroTTSBackend
+
+ backend = KokoroTTSBackend()
+ # Mock the pipeline to avoid needing kokoro installed
+ import types
+
+ def fake_pipeline(text, voice="", speed=1.0):
+ yield (0, 0, __import__("numpy").zeros(24000, dtype="float32"))
+
+ backend._pipeline = types.SimpleNamespace(__call__=fake_pipeline)
+ backend._pipeline.__call__ = fake_pipeline
+ # Kokoro requires numpy + soundfile — skip if not available
+ pytest.importorskip("numpy")
+ pytest.importorskip("soundfile")
+
+ with patch.object(backend, "_ensure_pipeline"):
+ with patch("openjarvis.speech.kokoro_tts.KokoroTTSBackend.synthesize") as mock_synth:
+ mock_synth.return_value = TTSResult(
+ audio=b"fake-wav", format="wav", voice_id="af_heart"
+ )
+ result = backend.synthesize("Hello")
+ assert result.audio == b"fake-wav"
+
+
+def test_openai_tts_synthesize():
+ from openjarvis.speech.openai_tts import OpenAITTSBackend
+
+ backend = OpenAITTSBackend(api_key="fake-key")
+
+ with patch(
+ "openjarvis.speech.openai_tts._openai_tts_request",
+ return_value=b"fake-openai-audio",
+ ):
+ result = backend.synthesize("Hello", voice_id="nova")
+
+ assert result.audio == b"fake-openai-audio"
+ assert result.voice_id == "nova"
+```
+
+- [ ] **Step 6: Run all tests**
+
+Run: `uv run pytest tests/speech/test_tts_backends.py -v`
+Expected: All PASS
+
+- [ ] **Step 7: Commit**
+
+```bash
+git add src/openjarvis/speech/kokoro_tts.py src/openjarvis/speech/openai_tts.py tests/speech/test_tts_backends.py
+git commit -m "feat: add Kokoro (local) and OpenAI TTS backends"
+```
+
+---
+
+### Task 9: text_to_speech Tool
+
+**Files:**
+- Create: `src/openjarvis/tools/text_to_speech.py`
+- Create: `tests/tools/test_text_to_speech.py`
+- Modify: `src/openjarvis/tools/__init__.py`
+
+- [ ] **Step 1: Write the failing test**
+
+```python
+# tests/tools/test_text_to_speech.py
+"""Tests for the text_to_speech tool."""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from openjarvis.core.registry import ToolRegistry
+
+
+def test_tts_tool_registered():
+ assert ToolRegistry.contains("text_to_speech")
+```
+
+- [ ] **Step 2: Run test to verify it fails**
+
+Run: `uv run pytest tests/tools/test_text_to_speech.py::test_tts_tool_registered -v`
+Expected: FAIL
+
+- [ ] **Step 3: Write the text_to_speech tool**
+
+```python
+# src/openjarvis/tools/text_to_speech.py
+"""Text-to-speech tool — synthesize text to audio via configurable TTS backend."""
+
+from __future__ import annotations
+
+import base64
+import tempfile
+from pathlib import Path
+from typing import Any
+
+from openjarvis.core.registry import TTSRegistry, ToolRegistry
+from openjarvis.core.types import ToolResult
+from openjarvis.tools._stubs import BaseTool, ToolSpec
+
+
[email protected]("text_to_speech")
+class TextToSpeechTool(BaseTool):
+ """Synthesize text into spoken audio using a TTS backend."""
+
+ tool_id = "text_to_speech"
+ is_local = False
+
+ @property
+ def spec(self) -> ToolSpec:
+ return ToolSpec(
+ name="text_to_speech",
+ description=(
+ "Convert text to spoken audio. Returns the file path to the "
+ "generated audio file."
+ ),
+ parameters={
+ "type": "object",
+ "properties": {
+ "text": {
+ "type": "string",
+ "description": "The text to synthesize into speech.",
+ },
+ "voice_id": {
+ "type": "string",
+ "description": "Voice identifier for the TTS backend.",
+ },
+ "backend": {
+ "type": "string",
+ "description": "TTS backend to use (cartesia, kokoro, openai_tts).",
+ },
+ "output_dir": {
+ "type": "string",
+ "description": "Directory to save the audio file.",
+ },
+ },
+ "required": ["text"],
+ },
+ category="audio",
+ timeout_seconds=120.0,
+ )
+
+ def execute(self, **params: Any) -> ToolResult:
+ text = params.get("text", "")
+ voice_id = params.get("voice_id", "")
+ backend_key = params.get("backend", "cartesia")
+ output_dir = params.get("output_dir", "")
+
+ if not text:
+ return ToolResult(
+ tool_name="text_to_speech",
+ content="No text provided.",
+ success=False,
+ )
+
+ if not TTSRegistry.contains(backend_key):
+ return ToolResult(
+ tool_name="text_to_speech",
+ content=f"TTS backend '{backend_key}' not available.",
+ success=False,
+ )
+
+ backend_cls = TTSRegistry.get(backend_key)
+ backend = backend_cls()
+
+ result = backend.synthesize(text, voice_id=voice_id)
+
+ # Save to file
+ if output_dir:
+ out_dir = Path(output_dir)
+ else:
+ out_dir = Path(tempfile.mkdtemp(prefix="jarvis-tts-"))
+
+ out_dir.mkdir(parents=True, exist_ok=True)
+ ext = result.format or "mp3"
+ audio_path = out_dir / f"digest.{ext}"
+ result.save(audio_path)
+
+ return ToolResult(
+ tool_name="text_to_speech",
+ content=str(audio_path),
+ success=True,
+ metadata={
+ "audio_path": str(audio_path),
+ "format": ext,
+ "duration_seconds": result.duration_seconds,
+ "voice_id": result.voice_id,
+ "backend": backend_key,
+ },
+ )
+```
+
+- [ ] **Step 4: Register in tools __init__.py**
+
+Add to `src/openjarvis/tools/__init__.py` alongside the other tool imports:
+
+```python
+import openjarvis.tools.text_to_speech # noqa: F401
+```
+
+- [ ] **Step 5: Write execution test with mocked backend**
+
+Add to `tests/tools/test_text_to_speech.py`:
+
+```python
+from openjarvis.speech.tts import TTSResult
+
+
+def test_tts_tool_execute(tmp_path):
+ from openjarvis.tools.text_to_speech import TextToSpeechTool
+
+ tool = TextToSpeechTool()
+ mock_result = TTSResult(
+ audio=b"fake-audio-data", format="mp3", voice_id="jarvis", duration_seconds=2.5
+ )
+
+ with patch(
+ "openjarvis.tools.text_to_speech.TTSRegistry"
+ ) as mock_registry:
+ mock_backend_cls = MagicMock()
+ mock_backend_cls.return_value.synthesize.return_value = mock_result
+ mock_registry.contains.return_value = True
+ mock_registry.get.return_value = mock_backend_cls
+
+ result = tool.execute(
+ text="Good morning sir.",
+ voice_id="jarvis",
+ backend="cartesia",
+ output_dir=str(tmp_path),
+ )
+
+ assert result.success is True
+ assert "digest.mp3" in result.content
+ assert (tmp_path / "digest.mp3").exists()
+ assert (tmp_path / "digest.mp3").read_bytes() == b"fake-audio-data"
+
+
+def test_tts_tool_empty_text():
+ from openjarvis.tools.text_to_speech import TextToSpeechTool
+
+ tool = TextToSpeechTool()
+ result = tool.execute(text="")
+ assert result.success is False
+```
+
+- [ ] **Step 6: Run all tests**
+
+Run: `uv run pytest tests/tools/test_text_to_speech.py -v`
+Expected: All PASS
+
+- [ ] **Step 7: Commit**
+
+```bash
+git add src/openjarvis/tools/text_to_speech.py tests/tools/test_text_to_speech.py src/openjarvis/tools/__init__.py
+git commit -m "feat: add text_to_speech tool wrapping TTSBackend for agent use"
+```
+
+---
+
+## PR 3: Digest Agent + Store
+
+---
+
+### Task 10: DigestStore + DigestArtifact
+
+**Files:**
+- Create: `src/openjarvis/agents/digest_store.py`
+- Create: `tests/agents/test_digest_store.py`
+
+- [ ] **Step 1: Write the failing test**
+
+```python
+# tests/agents/test_digest_store.py
+"""Tests for DigestStore and DigestArtifact."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+import pytest
+
+from openjarvis.agents.digest_store import DigestArtifact, DigestStore
+
+
+def test_store_and_retrieve(tmp_path):
+ store = DigestStore(db_path=str(tmp_path / "digest.db"))
+
+ artifact = DigestArtifact(
+ text="Good morning sir.",
+ audio_path=Path("/tmp/digest.mp3"),
+ sections={"messages": "You have 3 emails.", "calendar": "2 meetings today."},
+ sources_used=["gmail", "gcalendar"],
+ generated_at=datetime(2026, 4, 1, 6, 0, 0),
+ model_used="claude-sonnet-4-6",
+ voice_used="jarvis-v1",
+ )
+
+ store.save(artifact)
+ retrieved = store.get_latest()
+
+ assert retrieved is not None
+ assert retrieved.text == "Good morning sir."
+ assert retrieved.sections["messages"] == "You have 3 emails."
+ assert retrieved.sources_used == ["gmail", "gcalendar"]
+ assert retrieved.voice_used == "jarvis-v1"
+
+ store.close()
+```
+
+- [ ] **Step 2: Run test to verify it fails**
+
+Run: `uv run pytest tests/agents/test_digest_store.py::test_store_and_retrieve -v`
+Expected: FAIL — module not found
+
+- [ ] **Step 3: Write DigestArtifact and DigestStore**
+
+```python
+# src/openjarvis/agents/digest_store.py
+"""DigestStore — SQLite-backed storage for pre-computed digest artifacts."""
+
+from __future__ import annotations
+
+import json
+import sqlite3
+from dataclasses import asdict, dataclass, field
+from datetime import datetime
+from pathlib import Path
+from typing import Dict, List, Optional
+
+
+@dataclass
+class DigestArtifact:
+ """A pre-computed morning digest ready for delivery."""
+
+ text: str
+ audio_path: Path
+ sections: Dict[str, str]
+ sources_used: List[str]
+ generated_at: datetime
+ model_used: str
+ voice_used: str
+
+
+class DigestStore:
+ """SQLite store for digest artifacts."""
+
+ def __init__(self, db_path: str = "") -> None:
+ if not db_path:
+ db_path = str(Path.home() / ".openjarvis" / "digest.db")
+ self._db_path = db_path
+ self._conn = sqlite3.connect(db_path)
+ self._conn.execute("PRAGMA journal_mode=WAL")
+ self._conn.execute(
+ """
+ CREATE TABLE IF NOT EXISTS digests (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ text TEXT NOT NULL,
+ audio_path TEXT NOT NULL,
+ sections TEXT NOT NULL,
+ sources_used TEXT NOT NULL,
+ generated_at TEXT NOT NULL,
+ model_used TEXT NOT NULL,
+ voice_used TEXT NOT NULL
+ )
+ """
+ )
+ self._conn.commit()
+
+ def save(self, artifact: DigestArtifact) -> None:
+ """Save a digest artifact."""
+ self._conn.execute(
+ """
+ INSERT INTO digests
+ (text, audio_path, sections, sources_used,
+ generated_at, model_used, voice_used)
+ VALUES (?, ?, ?, ?, ?, ?, ?)
+ """,
+ (
+ artifact.text,
+ str(artifact.audio_path),
+ json.dumps(artifact.sections),
+ json.dumps(artifact.sources_used),
+ artifact.generated_at.isoformat(),
+ artifact.model_used,
+ artifact.voice_used,
+ ),
+ )
+ self._conn.commit()
+
+ def get_latest(self) -> Optional[DigestArtifact]:
+ """Return the most recent digest, or None."""
+ row = self._conn.execute(
+ "SELECT text, audio_path, sections, sources_used,"
+ " generated_at, model_used, voice_used"
+ " FROM digests ORDER BY id DESC LIMIT 1"
+ ).fetchone()
+ if row is None:
+ return None
+ return DigestArtifact(
+ text=row[0],
+ audio_path=Path(row[1]),
+ sections=json.loads(row[2]),
+ sources_used=json.loads(row[3]),
+ generated_at=datetime.fromisoformat(row[4]),
+ model_used=row[5],
+ voice_used=row[6],
+ )
+
+ def get_today(self, timezone_name: str = "UTC") -> Optional[DigestArtifact]:
+ """Return today's digest if it exists, or None."""
+ try:
+ from zoneinfo import ZoneInfo
+ today = datetime.now(ZoneInfo(timezone_name)).strftime("%Y-%m-%d")
+ except ImportError:
+ today = datetime.now().strftime("%Y-%m-%d")
+
+ row = self._conn.execute(
+ "SELECT text, audio_path, sections, sources_used,"
+ " generated_at, model_used, voice_used"
+ " FROM digests WHERE generated_at LIKE ? ORDER BY id DESC LIMIT 1",
+ (f"{today}%",),
+ ).fetchone()
+ if row is None:
+ return None
+ return DigestArtifact(
+ text=row[0],
+ audio_path=Path(row[1]),
+ sections=json.loads(row[2]),
+ sources_used=json.loads(row[3]),
+ generated_at=datetime.fromisoformat(row[4]),
+ model_used=row[5],
+ voice_used=row[6],
+ )
+
+ def history(self, limit: int = 10) -> List[DigestArtifact]:
+ """Return the N most recent digests."""
+ rows = self._conn.execute(
+ "SELECT text, audio_path, sections, sources_used,"
+ " generated_at, model_used, voice_used"
+ " FROM digests ORDER BY id DESC LIMIT ?",
+ (limit,),
+ ).fetchall()
+ return [
+ DigestArtifact(
+ text=r[0],
+ audio_path=Path(r[1]),
+ sections=json.loads(r[2]),
+ sources_used=json.loads(r[3]),
+ generated_at=datetime.fromisoformat(r[4]),
+ model_used=r[5],
+ voice_used=r[6],
+ )
+ for r in rows
+ ]
+
+ def close(self) -> None:
+ self._conn.close()
+```
+
+- [ ] **Step 4: Run test to verify it passes**
+
+Run: `uv run pytest tests/agents/test_digest_store.py::test_store_and_retrieve -v`
+Expected: PASS
+
+- [ ] **Step 5: Write additional tests**
+
+Add to `tests/agents/test_digest_store.py`:
+
+```python
+def test_get_today(tmp_path):
+ store = DigestStore(db_path=str(tmp_path / "digest.db"))
+ artifact = DigestArtifact(
+ text="Today's digest",
+ audio_path=Path("/tmp/today.mp3"),
+ sections={"messages": "Nothing urgent."},
+ sources_used=["gmail"],
+ generated_at=datetime.now(),
+ model_used="test-model",
+ voice_used="jarvis",
+ )
+ store.save(artifact)
+ today = store.get_today()
+ assert today is not None
+ assert today.text == "Today's digest"
+ store.close()
+
+
+def test_get_today_returns_none_when_empty(tmp_path):
+ store = DigestStore(db_path=str(tmp_path / "digest.db"))
+ assert store.get_today() is None
+ store.close()
+
+
+def test_history(tmp_path):
+ store = DigestStore(db_path=str(tmp_path / "digest.db"))
+ for i in range(3):
+ store.save(DigestArtifact(
+ text=f"Digest {i}",
+ audio_path=Path(f"/tmp/d{i}.mp3"),
+ sections={},
+ sources_used=[],
+ generated_at=datetime(2026, 4, 1 + i, 6, 0, 0),
+ model_used="test",
+ voice_used="jarvis",
+ ))
+ history = store.history(limit=2)
+ assert len(history) == 2
+ assert history[0].text == "Digest 2" # Most recent first
+ store.close()
+```
+
+- [ ] **Step 6: Run all tests**
+
+Run: `uv run pytest tests/agents/test_digest_store.py -v`
+Expected: All PASS
+
+- [ ] **Step 7: Commit**
+
+```bash
+git add src/openjarvis/agents/digest_store.py tests/agents/test_digest_store.py
+git commit -m "feat: add DigestStore and DigestArtifact for caching pre-computed digests"
+```
+
+---
+
+### Task 11: digest_collect Tool
+
+**Files:**
+- Create: `src/openjarvis/tools/digest_collect.py`
+- Create: `tests/tools/test_digest_collect.py`
+- Modify: `src/openjarvis/tools/__init__.py`
+
+- [ ] **Step 1: Write the failing test**
+
+```python
+# tests/tools/test_digest_collect.py
+"""Tests for the digest_collect tool."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from openjarvis.core.registry import ConnectorRegistry, ToolRegistry
+
+
+def test_digest_collect_registered():
+ assert ToolRegistry.contains("digest_collect")
+```
+
+- [ ] **Step 2: Run test to verify it fails**
+
+Run: `uv run pytest tests/tools/test_digest_collect.py::test_digest_collect_registered -v`
+Expected: FAIL
+
+- [ ] **Step 3: Write the digest_collect tool**
+
+```python
+# src/openjarvis/tools/digest_collect.py
+"""Digest collection tool — fetches recent data from configured connectors."""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime, timedelta
+from typing import Any, Dict, List
+
+from openjarvis.connectors._stubs import Document
+from openjarvis.core.registry import ConnectorRegistry, ToolRegistry
+from openjarvis.core.types import ToolResult
+from openjarvis.tools._stubs import BaseTool, ToolSpec
+
+
[email protected]("digest_collect")
+class DigestCollectTool(BaseTool):
+ """Collect recent data from multiple connectors for digest synthesis."""
+
+ tool_id = "digest_collect"
+ is_local = True
+
+ @property
+ def spec(self) -> ToolSpec:
+ return ToolSpec(
+ name="digest_collect",
+ description=(
+ "Fetch recent data from configured connectors (email, calendar, "
+ "health, tasks, etc.) and return a structured summary for digest "
+ "synthesis."
+ ),
+ parameters={
+ "type": "object",
+ "properties": {
+ "sources": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": (
+ "List of connector IDs to fetch from "
+ "(e.g., ['gmail', 'oura', 'gcalendar'])."
+ ),
+ },
+ "hours_back": {
+ "type": "number",
+ "description": "How many hours back to look (default: 24).",
+ },
+ },
+ "required": ["sources"],
+ },
+ category="data",
+ timeout_seconds=60.0,
+ )
+
+ def execute(self, **params: Any) -> ToolResult:
+ sources: List[str] = params.get("sources", [])
+ hours_back: float = params.get("hours_back", 24)
+ since = datetime.now() - timedelta(hours=hours_back)
+
+ collected: Dict[str, List[Dict[str, Any]]] = {}
+ errors: List[str] = []
+
+ for source in sources:
+ if not ConnectorRegistry.contains(source):
+ errors.append(f"Connector '{source}' not available")
+ continue
+
+ try:
+ connector_cls = ConnectorRegistry.get(source)
+ connector = connector_cls()
+
+ if not connector.is_connected():
+ errors.append(f"Connector '{source}' not connected (no credentials)")
+ continue
+
+ docs = list(connector.sync(since=since))
+ collected[source] = [
+ {
+ "title": d.title,
+ "content": d.content,
+ "doc_type": d.doc_type,
+ "author": d.author,
+ "timestamp": d.timestamp.isoformat(),
+ "metadata": d.metadata,
+ }
+ for d in docs
+ ]
+ except Exception as exc:
+ errors.append(f"Error fetching from '{source}': {exc}")
+
+ summary_parts = []
+ for source, docs in collected.items():
+ summary_parts.append(f"## {source} ({len(docs)} items)")
+ for doc in docs:
+ summary_parts.append(json.dumps(doc, default=str))
+
+ if errors:
+ summary_parts.append("\n## Errors")
+ summary_parts.extend(errors)
+
+ return ToolResult(
+ tool_name="digest_collect",
+ content="\n".join(summary_parts),
+ success=True,
+ metadata={
+ "sources_queried": sources,
+ "sources_ok": list(collected.keys()),
+ "sources_failed": errors,
+ "total_items": sum(len(v) for v in collected.values()),
+ },
+ )
+```
+
+- [ ] **Step 4: Register in tools __init__.py**
+
+Add to `src/openjarvis/tools/__init__.py`:
+
+```python
+import openjarvis.tools.digest_collect # noqa: F401
+```
+
+- [ ] **Step 5: Write execution test with mock connectors**
+
+Add to `tests/tools/test_digest_collect.py`:
+
+```python
+from openjarvis.connectors._stubs import Document
+
+
+def test_digest_collect_executes(tmp_path):
+ from openjarvis.tools.digest_collect import DigestCollectTool
+
+ tool = DigestCollectTool()
+
+ mock_docs = [
+ Document(
+ doc_id="test-1",
+ source="gmail",
+ doc_type="email",
+ content="Meeting at 3pm",
+ title="Team standup",
+ author="[email protected]",
+ timestamp=datetime(2026, 4, 1, 10, 0),
+ )
+ ]
+
+ mock_connector = MagicMock()
+ mock_connector.return_value.is_connected.return_value = True
+ mock_connector.return_value.sync.return_value = mock_docs
+
+ with patch.object(ConnectorRegistry, "contains", return_value=True):
+ with patch.object(ConnectorRegistry, "get", return_value=mock_connector):
+ result = tool.execute(sources=["gmail"], hours_back=24)
+
+ assert result.success is True
+ assert "gmail (1 items)" in result.content
+ assert result.metadata["total_items"] == 1
+
+
+def test_digest_collect_missing_connector():
+ from openjarvis.tools.digest_collect import DigestCollectTool
+
+ tool = DigestCollectTool()
+
+ with patch.object(ConnectorRegistry, "contains", return_value=False):
+ result = tool.execute(sources=["nonexistent"])
+
+ assert result.success is True # Partial success
+ assert "not available" in result.content
+```
+
+- [ ] **Step 6: Run all tests**
+
+Run: `uv run pytest tests/tools/test_digest_collect.py -v`
+Expected: All PASS
+
+- [ ] **Step 7: Commit**
+
+```bash
+git add src/openjarvis/tools/digest_collect.py tests/tools/test_digest_collect.py src/openjarvis/tools/__init__.py
+git commit -m "feat: add digest_collect tool for multi-source data fetching"
+```
+
+---
+
+### Task 12: Persona Prompt Files
+
+**Files:**
+- Create: `configs/openjarvis/prompts/personas/jarvis.md`
+- Create: `configs/openjarvis/prompts/personas/neutral.md`
+
+- [ ] **Step 1: Create the personas directory**
+
+Run: `mkdir -p configs/openjarvis/prompts/personas`
+
+- [ ] **Step 2: Write the Jarvis persona prompt**
+
+```markdown
+# configs/openjarvis/prompts/personas/jarvis.md
+You are JARVIS — a highly capable AI assistant with a professional demeanour and dry, understated wit. You were modelled after the AI companion from Iron Man.
+
+## Voice & Tone
+- Professional and concise, but not robotic
+- Dry British wit — subtle, never slapstick ("You have a rather ambitious schedule today, sir")
+- Address the user respectfully (use "sir" or "ma'am" sparingly for effect, not every sentence)
+- Confident and competent — you anticipate needs and offer insights, not just data
+- When delivering bad news (poor sleep, overbooked day), frame it constructively
+
+## Structure
+- Open with a greeting that reflects the time and context
+- Deliver each section crisply — lead with the most important item
+- Transition between sections naturally, not mechanically
+- Close with a brief look-ahead or motivational observation
+
+## Examples
+- "Good morning, sir. I trust you slept well — though your Oura Ring suggests otherwise."
+- "Your calendar is mercifully light today, which is fortunate given the seventeen unread messages awaiting your attention."
+- "The markets are up, your paper was cited, and it's going to rain. I'd suggest an umbrella and a celebratory coffee."
+```
+
+- [ ] **Step 3: Write the neutral persona prompt**
+
+```markdown
+# configs/openjarvis/prompts/personas/neutral.md
+You are an AI assistant generating a daily briefing. Be clear, concise, and factual.
+
+## Voice & Tone
+- Straightforward and professional
+- No personality or humor — just the facts
+- Use plain language
+
+## Structure
+- Open with the date and a one-line summary
+- Deliver each section with bullet points
+- Close with a summary of action items
+```
+
+- [ ] **Step 4: Commit**
+
+```bash
+git add configs/openjarvis/prompts/personas/jarvis.md configs/openjarvis/prompts/personas/neutral.md
+git commit -m "feat: add Jarvis and neutral persona prompts for digest agent"
+```
+
+---
+
+### Task 13: MorningDigestAgent
+
+**Files:**
+- Create: `src/openjarvis/agents/morning_digest.py`
+- Create: `tests/agents/test_morning_digest.py`
+- Modify: `src/openjarvis/agents/__init__.py`
+
+- [ ] **Step 1: Write the failing test**
+
+```python
+# tests/agents/test_morning_digest.py
+"""Tests for MorningDigestAgent."""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from openjarvis.core.registry import AgentRegistry
+
+
+def test_morning_digest_registered():
+ assert AgentRegistry.contains("morning_digest")
+```
+
+- [ ] **Step 2: Run test to verify it fails**
+
+Run: `uv run pytest tests/agents/test_morning_digest.py::test_morning_digest_registered -v`
+Expected: FAIL
+
+- [ ] **Step 3: Write the MorningDigestAgent**
+
+```python
+# src/openjarvis/agents/morning_digest.py
+"""Morning Digest Agent — synthesizes a daily briefing from multiple sources.
+
+Thin orchestrator that delegates to digest_collect (data fetching),
+the LLM (narrative synthesis), and text_to_speech (audio generation).
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+from openjarvis.agents._stubs import AgentContext, AgentResult, ToolUsingAgent
+from openjarvis.agents.digest_store import DigestArtifact, DigestStore
+from openjarvis.core.registry import AgentRegistry
+from openjarvis.core.types import Message, Role, ToolCall
+
+
+def _load_persona(persona_name: str) -> str:
+ """Load a persona prompt file by name."""
+ search_paths = [
+ Path("configs/openjarvis/prompts/personas") / f"{persona_name}.md",
+ Path.home() / ".openjarvis" / "prompts" / "personas" / f"{persona_name}.md",
+ ]
+ for p in search_paths:
+ if p.exists():
+ return p.read_text(encoding="utf-8")
+ return ""
+
+
[email protected]("morning_digest")
+class MorningDigestAgent(ToolUsingAgent):
+ """Pre-compute a daily digest from configured data sources."""
+
+ agent_id = "morning_digest"
+
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ # Extract digest-specific kwargs before passing to parent
+ self._persona = kwargs.pop("persona", "jarvis")
+ self._sections = kwargs.pop("sections", ["messages", "calendar", "health", "world"])
+ self._section_sources = kwargs.pop("section_sources", {})
+ self._timezone = kwargs.pop("timezone", "America/Los_Angeles")
+ self._voice_id = kwargs.pop("voice_id", "")
+ self._tts_backend = kwargs.pop("tts_backend", "cartesia")
+ self._digest_store_path = kwargs.pop("digest_store_path", "")
+ super().__init__(*args, **kwargs)
+
+ def _build_system_prompt(self) -> str:
+ """Assemble the system prompt from persona + context."""
+ persona_text = _load_persona(self._persona)
+ now = datetime.now()
+
+ return (
+ f"{persona_text}\n\n"
+ f"Today is {now.strftime('%A, %B %d, %Y')}. "
+ f"The time is {now.strftime('%I:%M %p')} in {self._timezone}.\n\n"
+ f"Generate a morning briefing covering these sections in order: "
+ f"{', '.join(self._sections)}.\n\n"
+ "Be concise — the entire briefing should be readable in 2-3 minutes "
+ "and listenable in under 5 minutes when spoken aloud.\n\n"
+ "Format your response in clean markdown with section headers."
+ )
+
+ def _resolve_sources(self) -> List[str]:
+ """Get the list of connector IDs to query."""
+ default_source_map = {
+ "messages": ["gmail", "slack", "google_tasks"],
+ "calendar": ["gcalendar"],
+ "health": ["oura"],
+ "world": [], # Handled by web_search, not connectors
+ }
+ sources = set()
+ for section in self._sections:
+ section_sources = self._section_sources.get(
+ section, default_source_map.get(section, [])
+ )
+ sources.update(section_sources)
+ return list(sources)
+
+ def run(
+ self,
+ input: str,
+ context: Optional[AgentContext] = None,
+ **kwargs: Any,
+ ) -> AgentResult:
+ self._emit_turn_start(input)
+
+ # Step 1: Collect data from connectors
+ sources = self._resolve_sources()
+ collect_call = ToolCall(
+ id="digest-collect-1",
+ name="digest_collect",
+ arguments=json.dumps({"sources": sources, "hours_back": 24}),
+ )
+ collect_result = self._executor.execute(collect_call)
+ collected_data = collect_result.content
+
+ # Step 2: Synthesize narrative via LLM
+ system_prompt = self._build_system_prompt()
+ messages = [
+ Message(role=Role.SYSTEM, content=system_prompt),
+ Message(
+ role=Role.USER,
+ content=(
+ f"Here is the collected data from my sources:\n\n"
+ f"{collected_data}\n\n"
+ f"Please synthesize my morning briefing."
+ ),
+ ),
+ ]
+
+ result = self._generate(messages)
+ narrative = self._strip_think_tags(result.get("content", ""))
+
+ # Step 3: Generate audio via TTS
+ tts_call = ToolCall(
+ id="digest-tts-1",
+ name="text_to_speech",
+ arguments=json.dumps({
+ "text": narrative,
+ "voice_id": self._voice_id,
+ "backend": self._tts_backend,
+ }),
+ )
+ tts_result = self._executor.execute(tts_call)
+ audio_path = tts_result.metadata.get("audio_path", "") if tts_result.success else ""
+
+ # Step 4: Store the artifact
+ artifact = DigestArtifact(
+ text=narrative,
+ audio_path=Path(audio_path) if audio_path else Path(""),
+ sections={}, # Could parse sections from narrative if needed
+ sources_used=sources,
+ generated_at=datetime.now(),
+ model_used=self._model,
+ voice_used=self._voice_id,
+ )
+
+ store = DigestStore(db_path=self._digest_store_path)
+ store.save(artifact)
+ store.close()
+
+ self._emit_turn_end(turns=1)
+ return AgentResult(
+ content=narrative,
+ tool_results=[collect_result, tts_result],
+ turns=1,
+ metadata={
+ "audio_path": audio_path,
+ "sources_used": sources,
+ },
+ )
+```
+
+- [ ] **Step 4: Register in agents __init__.py**
+
+Add to `src/openjarvis/agents/__init__.py`:
+
+```python
+try:
+ import openjarvis.agents.morning_digest # noqa: F401
+except ImportError:
+ pass
+```
+
+- [ ] **Step 5: Run registration test**
+
+Run: `uv run pytest tests/agents/test_morning_digest.py::test_morning_digest_registered -v`
+Expected: PASS
+
+- [ ] **Step 6: Write agent execution test with mocked tools and engine**
+
+Add to `tests/agents/test_morning_digest.py`:
+
+```python
+from pathlib import Path
+from openjarvis.agents._stubs import AgentResult
+from openjarvis.core.types import ToolResult
+
+
+def test_morning_digest_run(tmp_path):
+ from openjarvis.agents.morning_digest import MorningDigestAgent
+
+ mock_engine = MagicMock()
+ mock_engine.generate.return_value = {
+ "content": "Good morning sir. You have 3 emails and 2 meetings today.",
+ "finish_reason": "stop",
+ "usage": {},
+ }
+
+ # Mock collect result
+ mock_collect_result = ToolResult(
+ tool_name="digest_collect",
+ content="## gmail (2 items)\n...",
+ success=True,
+ metadata={"total_items": 2},
+ )
+
+ # Mock TTS result
+ mock_tts_result = ToolResult(
+ tool_name="text_to_speech",
+ content=str(tmp_path / "digest.mp3"),
+ success=True,
+ metadata={"audio_path": str(tmp_path / "digest.mp3")},
+ )
+
+ agent = MorningDigestAgent(
+ mock_engine,
+ "test-model",
+ tools=[],
+ persona="neutral",
+ digest_store_path=str(tmp_path / "digest.db"),
+ )
+
+ with patch.object(agent._executor, "execute", side_effect=[mock_collect_result, mock_tts_result]):
+ result = agent.run("Generate morning digest")
+
+ assert isinstance(result, AgentResult)
+ assert "Good morning" in result.content
+ assert result.turns == 1
+ assert len(result.tool_results) == 2
+
+
+def test_load_persona(tmp_path):
+ from openjarvis.agents.morning_digest import _load_persona
+
+ persona_dir = tmp_path / "configs" / "openjarvis" / "prompts" / "personas"
+ persona_dir.mkdir(parents=True)
+ (persona_dir / "test.md").write_text("You are a test persona.", encoding="utf-8")
+
+ with patch("openjarvis.agents.morning_digest.Path", return_value=persona_dir / "test.md"):
+ # Test falls back gracefully when file not in search paths
+ result = _load_persona("nonexistent")
+ assert result == "" # Not found returns empty string
+```
+
+- [ ] **Step 7: Run all tests**
+
+Run: `uv run pytest tests/agents/test_morning_digest.py -v`
+Expected: All PASS
+
+- [ ] **Step 8: Commit**
+
+```bash
+git add src/openjarvis/agents/morning_digest.py tests/agents/test_morning_digest.py src/openjarvis/agents/__init__.py
+git commit -m "feat: add MorningDigestAgent with persona-driven narrative synthesis"
+```
+
+---
+
+## PR 4: Delivery Layer
+
+---
+
+### Task 14: CLI `jarvis digest` Subcommand
+
+**Files:**
+- Create: `src/openjarvis/cli/digest_cmd.py`
+- Create: `tests/cli/test_digest_cmd.py`
+- Modify: `src/openjarvis/cli/__init__.py`
+
+- [ ] **Step 1: Write the failing test**
+
+```python
+# tests/cli/test_digest_cmd.py
+"""Tests for `jarvis digest` CLI command."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import pytest
+from click.testing import CliRunner
+
+from openjarvis.agents.digest_store import DigestArtifact, DigestStore
+
+
+def test_digest_command_exists():
+ """The digest command is registered on the CLI."""
+ from openjarvis.cli import cli
+
+ runner = CliRunner()
+ result = runner.invoke(cli, ["digest", "--help"])
+ assert result.exit_code == 0
+ assert "morning digest" in result.output.lower() or "digest" in result.output.lower()
+```
+
+- [ ] **Step 2: Run test to verify it fails**
+
+Run: `uv run pytest tests/cli/test_digest_cmd.py::test_digest_command_exists -v`
+Expected: FAIL — no such command `digest`
+
+- [ ] **Step 3: Write the digest CLI command**
+
+```python
+# src/openjarvis/cli/digest_cmd.py
+"""``jarvis digest`` — display and play the morning digest."""
+
+from __future__ import annotations
+
+import subprocess
+import sys
+import threading
+
+import click
+from rich.console import Console
+from rich.markdown import Markdown
+
+from openjarvis.agents.digest_store import DigestStore
+
+
+def _play_audio(audio_path: str) -> None:
+ """Play audio file in background using available system player."""
+ players = ["ffplay -nodisp -autoexit", "aplay", "afplay", "paplay"]
+ for player in players:
+ cmd_parts = player.split() + [audio_path]
+ try:
+ subprocess.run(
+ cmd_parts,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ check=True,
+ )
+ return
+ except (FileNotFoundError, subprocess.CalledProcessError):
+ continue
+
+
[email protected]("digest", help="Display and play the morning digest.")
[email protected]("--text-only", is_flag=True, help="Print text without audio playback.")
[email protected]("--fresh", is_flag=True, help="Re-generate the digest (skip cache).")
[email protected]("--history", is_flag=True, help="Show past digests.")
[email protected]("--section", type=str, default="", help="Show only a specific section.")
[email protected]("--db-path", type=str, default="", help="Path to digest database.")
+def digest(
+ text_only: bool,
+ fresh: bool,
+ history: bool,
+ section: str,
+ db_path: str,
+) -> None:
+ """Display and optionally play the morning digest."""
+ console = Console()
+ store = DigestStore(db_path=db_path) if db_path else DigestStore()
+
+ if history:
+ past = store.history(limit=10)
+ if not past:
+ console.print("[dim]No past digests found.[/dim]")
+ store.close()
+ return
+ for artifact in past:
+ console.print(
+ f"[bold]{artifact.generated_at.strftime('%Y-%m-%d %H:%M')}[/bold]"
+ f" — {artifact.model_used} / {artifact.voice_used}"
+ )
+ console.print(artifact.text[:200] + "...\n")
+ store.close()
+ return
+
+ if fresh:
+ # Trigger on-demand generation
+ console.print("[yellow]Generating fresh digest...[/yellow]")
+ try:
+ from openjarvis.sdk import Jarvis
+
+ with Jarvis() as j:
+ result = j.ask("Generate my morning digest", agent="morning_digest")
+ console.print(Markdown(result))
+ except Exception as exc:
+ console.print(f"[red]Failed to generate digest: {exc}[/red]")
+ store.close()
+ return
+
+ # Try to load today's cached digest
+ artifact = store.get_today()
+ if artifact is None:
+ console.print("[dim]No digest for today. Use --fresh to generate one.[/dim]")
+ store.close()
+ return
+
+ # Display text
+ text = artifact.text
+ if section:
+ # Try to extract just the requested section
+ lines = text.split("\n")
+ in_section = False
+ section_lines = []
+ for line in lines:
+ if line.strip().lower().startswith(f"## {section.lower()}") or \
+ line.strip().lower().startswith(f"# {section.lower()}"):
+ in_section = True
+ section_lines.append(line)
+ elif in_section and line.strip().startswith("#"):
+ break
+ elif in_section:
+ section_lines.append(line)
+ text = "\n".join(section_lines) if section_lines else text
+
+ # Play audio in background while text renders
+ audio_path = str(artifact.audio_path)
+ if not text_only and audio_path and artifact.audio_path.exists():
+ audio_thread = threading.Thread(target=_play_audio, args=(audio_path,), daemon=True)
+ audio_thread.start()
+
+ console.print(Markdown(text))
+ store.close()
+```
+
+- [ ] **Step 4: Register in CLI __init__.py**
+
+Add the import and command registration to `src/openjarvis/cli/__init__.py`:
+
+Import line (near the other imports):
+```python
+from openjarvis.cli.digest_cmd import digest
+```
+
+Command registration (in the `cli` group body, near the other `cli.add_command()` calls or at the bottom of the file):
+```python
+cli.add_command(digest)
+```
+
+- [ ] **Step 5: Write test for cached digest display**
+
+Add to `tests/cli/test_digest_cmd.py`:
+
+```python
+def test_digest_displays_cached(tmp_path):
+ from openjarvis.cli import cli
+
+ db_path = str(tmp_path / "digest.db")
+ store = DigestStore(db_path=db_path)
+ store.save(DigestArtifact(
+ text="# Messages\nYou have 3 emails.\n# Calendar\n2 meetings today.",
+ audio_path=Path("/nonexistent/audio.mp3"),
+ sections={},
+ sources_used=["gmail"],
+ generated_at=datetime.now(),
+ model_used="test",
+ voice_used="jarvis",
+ ))
+ store.close()
+
+ runner = CliRunner()
+ result = runner.invoke(cli, ["digest", "--text-only", "--db-path", db_path])
+ assert result.exit_code == 0
+ assert "3 emails" in result.output
+
+
+def test_digest_no_cache(tmp_path):
+ from openjarvis.cli import cli
+
+ db_path = str(tmp_path / "empty.db")
+ runner = CliRunner()
+ result = runner.invoke(cli, ["digest", "--db-path", db_path])
+ assert result.exit_code == 0
+ assert "No digest for today" in result.output
+```
+
+- [ ] **Step 6: Run all tests**
+
+Run: `uv run pytest tests/cli/test_digest_cmd.py -v`
+Expected: All PASS
+
+- [ ] **Step 7: Commit**
+
+```bash
+git add src/openjarvis/cli/digest_cmd.py tests/cli/test_digest_cmd.py src/openjarvis/cli/__init__.py
+git commit -m "feat: add 'jarvis digest' CLI command with text + audio playback"
+```
+
+---
+
+### Task 15: API Endpoints for Digest
+
+**Files:**
+- Create: `src/openjarvis/server/digest_routes.py`
+- Create: `tests/server/test_digest_routes.py`
+- Modify: `src/openjarvis/server/app.py`
+
+- [ ] **Step 1: Write the failing test**
+
+```python
+# tests/server/test_digest_routes.py
+"""Tests for /api/digest endpoints."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+from openjarvis.agents.digest_store import DigestArtifact, DigestStore
+
+
+def store(tmp_path):
+ db_path = str(tmp_path / "digest.db")
+ s = DigestStore(db_path=db_path)
+ s.save(DigestArtifact(
+ text="Good morning sir.",
+ audio_path=tmp_path / "digest.mp3",
+ sections={"messages": "3 emails"},
+ sources_used=["gmail"],
+ generated_at=datetime.now(),
+ model_used="test",
+ voice_used="jarvis",
+ ))
+ # Write fake audio file
+ (tmp_path / "digest.mp3").write_bytes(b"fake-mp3")
+ yield s
+ s.close()
+
+
+def test_get_digest(store, tmp_path):
+ from fastapi.testclient import TestClient
+ from openjarvis.server.digest_routes import create_digest_router
+
+ from fastapi import FastAPI
+
+ app = FastAPI()
+ app.include_router(create_digest_router(db_path=str(tmp_path / "digest.db")))
+
+ client = TestClient(app)
+ resp = client.get("/api/digest")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["text"] == "Good morning sir."
+ assert data["sources_used"] == ["gmail"]
+```
+
+- [ ] **Step 2: Run test to verify it fails**
+
+Run: `uv run pytest tests/server/test_digest_routes.py::test_get_digest -v`
+Expected: FAIL — module not found
+
+- [ ] **Step 3: Write the digest routes**
+
+```python
+# src/openjarvis/server/digest_routes.py
+"""FastAPI routes for the morning digest."""
+
+from __future__ import annotations
+
+from fastapi import APIRouter, HTTPException
+from fastapi.responses import FileResponse
+
+from openjarvis.agents.digest_store import DigestStore
+
+
+def create_digest_router(*, db_path: str = "") -> APIRouter:
+ """Create a digest API router with the given store path."""
+ router = APIRouter(prefix="/api/digest", tags=["digest"])
+ store = DigestStore(db_path=db_path) if db_path else DigestStore()
+
+ @router.get("")
+ async def get_digest():
+ """Return the latest digest artifact."""
+ artifact = store.get_today()
+ if artifact is None:
+ raise HTTPException(status_code=404, detail="No digest for today")
+ return {
+ "text": artifact.text,
+ "sections": artifact.sections,
+ "sources_used": artifact.sources_used,
+ "generated_at": artifact.generated_at.isoformat(),
+ "model_used": artifact.model_used,
+ "voice_used": artifact.voice_used,
+ "audio_available": artifact.audio_path.exists() if artifact.audio_path.name else False,
+ }
+
+ @router.get("/audio")
+ async def get_digest_audio():
+ """Stream the digest audio file."""
+ artifact = store.get_today()
+ if artifact is None:
+ raise HTTPException(status_code=404, detail="No digest for today")
+ if not artifact.audio_path.exists():
+ raise HTTPException(status_code=404, detail="Audio not available")
+ return FileResponse(
+ str(artifact.audio_path),
+ media_type="audio/mpeg",
+ filename="digest.mp3",
+ )
+
+ @router.post("/generate")
+ async def generate_digest():
+ """Force re-generation of the digest."""
+ try:
+ from openjarvis.sdk import Jarvis
+
+ with Jarvis() as j:
+ result = j.ask("Generate my morning digest", agent="morning_digest")
+ return {"status": "ok", "text": result}
+ except Exception as exc:
+ raise HTTPException(status_code=500, detail=str(exc))
+
+ @router.get("/history")
+ async def get_digest_history():
+ """Return past digests."""
+ history = store.history(limit=10)
+ return [
+ {
+ "text": a.text[:200],
+ "generated_at": a.generated_at.isoformat(),
+ "model_used": a.model_used,
+ "voice_used": a.voice_used,
+ }
+ for a in history
+ ]
+
+ return router
+```
+
+- [ ] **Step 4: Write additional route tests**
+
+Add to `tests/server/test_digest_routes.py`:
+
+```python
+def test_get_digest_audio(store, tmp_path):
+ from fastapi.testclient import TestClient
+ from openjarvis.server.digest_routes import create_digest_router
+ from fastapi import FastAPI
+
+ app = FastAPI()
+ app.include_router(create_digest_router(db_path=str(tmp_path / "digest.db")))
+
+ client = TestClient(app)
+ resp = client.get("/api/digest/audio")
+ assert resp.status_code == 200
+ assert resp.content == b"fake-mp3"
+
+
+def test_get_digest_404(tmp_path):
+ from fastapi.testclient import TestClient
+ from openjarvis.server.digest_routes import create_digest_router
+ from fastapi import FastAPI
+
+ app = FastAPI()
+ app.include_router(create_digest_router(db_path=str(tmp_path / "empty.db")))
+
+ client = TestClient(app)
+ resp = client.get("/api/digest")
+ assert resp.status_code == 404
+
+
+def test_get_history(store, tmp_path):
+ from fastapi.testclient import TestClient
+ from openjarvis.server.digest_routes import create_digest_router
+ from fastapi import FastAPI
+
+ app = FastAPI()
+ app.include_router(create_digest_router(db_path=str(tmp_path / "digest.db")))
+
+ client = TestClient(app)
+ resp = client.get("/api/digest/history")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert len(data) == 1
+ assert data[0]["voice_used"] == "jarvis"
+```
+
+- [ ] **Step 5: Mount the router in server/app.py**
+
+Add to `src/openjarvis/server/app.py` where other routers are mounted:
+
+```python
+from openjarvis.server.digest_routes import create_digest_router
+app.include_router(create_digest_router())
+```
+
+- [ ] **Step 6: Run all tests**
+
+Run: `uv run pytest tests/server/test_digest_routes.py -v`
+Expected: All PASS
+
+- [ ] **Step 7: Commit**
+
+```bash
+git add src/openjarvis/server/digest_routes.py tests/server/test_digest_routes.py src/openjarvis/server/app.py
+git commit -m "feat: add /api/digest REST endpoints for digest delivery"
+```
+
+---
+
+## PR 5: Configuration + Integration
+
+---
+
+### Task 16: DigestConfig Dataclass
+
+**Files:**
+- Modify: `src/openjarvis/core/config.py`
+
+- [ ] **Step 1: Add DigestConfig to config.py**
+
+Add the following dataclass to `src/openjarvis/core/config.py` near the other config dataclasses:
+
+```python
+@dataclass
+class DigestSectionConfig:
+ """Configuration for a single digest section."""
+ sources: List[str] = field(default_factory=list)
+ max_items: int = 10
+ priority_contacts: List[str] = field(default_factory=list)
+
+
+@dataclass
+class DigestConfig:
+ """Configuration for the morning digest feature."""
+ enabled: bool = False
+ schedule: str = "0 6 * * *"
+ timezone: str = "America/Los_Angeles"
+ persona: str = "jarvis"
+ sections: List[str] = field(default_factory=lambda: ["messages", "calendar", "health", "world"])
+ optional_sections: List[str] = field(default_factory=lambda: ["github", "financial", "music", "fitness"])
+ voice_id: str = ""
+ tts_backend: str = "cartesia"
+ messages: DigestSectionConfig = field(default_factory=lambda: DigestSectionConfig(sources=["gmail", "slack", "google_tasks"]))
+ calendar: DigestSectionConfig = field(default_factory=lambda: DigestSectionConfig(sources=["gcalendar"]))
+ health: DigestSectionConfig = field(default_factory=lambda: DigestSectionConfig(sources=["oura"]))
+ world: DigestSectionConfig = field(default_factory=lambda: DigestSectionConfig(sources=[]))
+```
+
+Add `digest: DigestConfig = field(default_factory=DigestConfig)` to the `JarvisConfig` dataclass.
+
+- [ ] **Step 2: Verify existing tests still pass**
+
+Run: `uv run pytest tests/core/ -v --tb=short`
+Expected: All PASS (no regressions)
+
+- [ ] **Step 3: Commit**
+
+```bash
+git add src/openjarvis/core/config.py
+git commit -m "feat: add DigestConfig dataclass to JarvisConfig"
+```
+
+---
+
+### Task 17: End-to-End Integration Test
+
+**Files:**
+- Create: `tests/test_digest_integration.py`
+
+- [ ] **Step 1: Write the integration test**
+
+```python
+# tests/test_digest_integration.py
+"""End-to-end integration test for the morning digest pipeline.
+
+Uses mocked connectors and engine to verify the full flow:
+digest_collect → LLM synthesis → TTS → DigestStore → CLI delivery.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from openjarvis.agents.digest_store import DigestStore
+from openjarvis.connectors._stubs import Document
+from openjarvis.core.types import ToolResult
+
+
+def test_full_digest_pipeline(tmp_path):
+ """Verify collect → synthesize → TTS → store → retrieve."""
+ from openjarvis.agents.morning_digest import MorningDigestAgent
+
+ # Mock engine returns a narrative
+ mock_engine = MagicMock()
+ mock_engine.generate.return_value = {
+ "content": (
+ "Good morning, sir. You slept 7.5 hours with a readiness score of 78. "
+ "You have 2 meetings today and 5 unread emails. "
+ "In the news, a new GPT-5 paper dropped on Arxiv."
+ ),
+ "finish_reason": "stop",
+ "usage": {},
+ }
+
+ # Mock tool results
+ collect_result = ToolResult(
+ tool_name="digest_collect",
+ content="## gmail (3 items)\n## oura (1 items)\n## gcalendar (2 items)",
+ success=True,
+ metadata={"total_items": 6},
+ )
+ tts_result = ToolResult(
+ tool_name="text_to_speech",
+ content=str(tmp_path / "digest.mp3"),
+ success=True,
+ metadata={"audio_path": str(tmp_path / "digest.mp3")},
+ )
+
+ # Write fake audio
+ (tmp_path / "digest.mp3").write_bytes(b"fake-mp3-audio")
+
+ db_path = str(tmp_path / "digest.db")
+
+ agent = MorningDigestAgent(
+ mock_engine,
+ "claude-sonnet-4-6",
+ tools=[],
+ persona="neutral",
+ digest_store_path=db_path,
+ )
+
+ with patch.object(agent._executor, "execute", side_effect=[collect_result, tts_result]):
+ result = agent.run("Generate morning digest")
+
+ # Verify agent result
+ assert "Good morning" in result.content
+ assert result.metadata["audio_path"] == str(tmp_path / "digest.mp3")
+
+ # Verify stored in DigestStore
+ store = DigestStore(db_path=db_path)
+ artifact = store.get_latest()
+ assert artifact is not None
+ assert "Good morning" in artifact.text
+ assert artifact.model_used == "claude-sonnet-4-6"
+ store.close()
+```
+
+- [ ] **Step 2: Run the integration test**
+
+Run: `uv run pytest tests/test_digest_integration.py -v`
+Expected: PASS
+
+- [ ] **Step 3: Commit**
+
+```bash
+git add tests/test_digest_integration.py
+git commit -m "test: add end-to-end integration test for morning digest pipeline"
+```
+
+---
+
+## Not Covered (Future Follow-ups)
+
+These items from the spec are intentionally deferred from this plan:
+
+- **"Good morning Jarvis" trigger detection** — Routing a natural language greeting to the digest delivery flow requires adding a routing instruction to the default agent's system prompt. This is a prompt engineering task that should be done after the core pipeline works end-to-end.
+- **Frontend audio player component** — The `/api/digest/audio` endpoint is ready, but the React/Vite component to render text + audio in the chat UI is frontend work. Should be a separate PR.
+- **Stretch connectors** (Apple Health, Apple Music, SoundCloud) — Deferred per spec. Can follow the same pattern as Tasks 1–4.
+- **AgentScheduler cron integration** — The `MorningDigestAgent` works on-demand. Wiring it into `AgentScheduler` for automatic 6am pre-computation requires a config + scheduler setup task after the agent is proven.
+
+---
+
+## Summary
+
+| PR | Tasks | What ships |
+|----|-------|-----------|
+| **PR 1: Connectors** | Tasks 1–5 | Oura, Strava, Spotify, Google Tasks connectors + live smoke tests |
+| **PR 2: TTS Infrastructure** | Tasks 6–9 | TTSBackend ABC, Cartesia/Kokoro/OpenAI backends, text_to_speech tool |
+| **PR 3: Digest Agent + Store** | Tasks 10–13 | DigestStore, digest_collect tool, persona prompts, MorningDigestAgent |
+| **PR 4: Delivery Layer** | Tasks 14–15 | `jarvis digest` CLI, /api/digest REST endpoints |
+| **PR 5: Config + Integration** | Tasks 16–17 | DigestConfig, end-to-end integration test |
+
+Each task follows TDD: write failing test → implement → verify → commit. PRs are ordered by dependency and can be reviewed independently.
diff --git a/docs/superpowers/specs/2026-04-01-morning-digest-design.md b/docs/superpowers/specs/2026-04-01-morning-digest-design.md
new file mode 100644
index 00000000..6b06ee52
--- /dev/null
+++ b/docs/superpowers/specs/2026-04-01-morning-digest-design.md
@@ -0,0 +1,482 @@
+# Morning Digest with Jarvis Voice — Design Spec
+
+**Date:** 2026-04-01
+**Author:** Jon Saad-Falcon
+**Status:** Draft
+
+## Overview
+
+A "Deep Research / Morning Digest" feature for OpenJarvis that pre-computes a personalized daily briefing from multiple data sources and delivers it with a configurable AI voice (default: Jarvis from Iron Man). The digest is scheduled to run automatically (e.g., 6am) but only delivered when the user explicitly triggers it — instant when you're ready, never interrupting before you are.
+
+This is a standard OpenJarvis config using all five primitives: Intelligence, Engine, Agent, Tools, and Learning.
+
+## Goals
+
+1. **Killer first use case** for OpenJarvis — a daily briefing that feels like having a personal AI assistant
+2. **Config-driven and extensible** — new data sources and digest sections added without touching agent code
+3. **Voice-first with text companion** — audio narration with Jarvis persona + formatted text
+4. **On-device where possible** — Cartesia for fast local TTS, local models for synthesis
+
+## Non-Goals
+
+- Real-time voice conversation (future work)
+- Push notifications / unsolicited delivery
+- Mobile app (v1 targets CLI + frontend/desktop app)
+
+## Constraints
+
+- **Target audio duration:** 2-5 minutes for a full digest narration
+- **Apple Health:** No direct API; requires HealthKit Shortcut export or XML parse (see Connectors section)
+- **Staleness:** A cached digest is "fresh" if generated on the same calendar day in the configured timezone
+
+---
+
+## Architecture
+
+### Approach: Agent + Pipeline Hybrid
+
+The `MorningDigestAgent` is a thin orchestrator that delegates to pipeline-stage tools: `digest_collect` (fetches data from sources), LLM synthesis (narrative generation), and `text_to_speech` (audio). The agent's system prompt controls personality and section ordering. Each tool is independently registered and testable.
+
+This maps cleanly to the existing OpenJarvis architecture (registry pattern, agent + tools), gives clear work boundaries (each connector and tool is a self-contained unit), and keeps personality/voice/sections all configurable without touching code.
+
+### Data Flow & Lifecycle
+
+**Phase 1 — Pre-compute (scheduled, e.g., 6am)**
+
+```
+AgentScheduler (cron trigger)
+ -> MorningDigestAgent.run()
+ -> digest_collect tool (calls connectors: Gmail, Slack, Oura, Calendar, etc.)
+ -> web_search tool (news, weather, Arxiv)
+ -> LLM synthesis (narrative with Jarvis persona)
+ -> text_to_speech tool (generates audio from narrative)
+ -> Stores result as DigestArtifact in DigestStore
+```
+
+**Phase 2 — Hold (waits for user trigger)**
+
+```
+DigestStore holds the latest artifact:
+ - text: structured markdown per section
+ - audio: mp3/wav file path
+ - metadata: timestamp, sources used, section summaries
+ - staleness: artifact is "fresh" if generated today (same calendar day in
+ configured timezone). Otherwise stale and re-generated on demand.
+```
+
+**Phase 3 — Deliver (user-triggered)**
+
+```
+User says "Good morning Jarvis" or runs `jarvis digest`
+ -> System checks DigestStore for today's pre-computed artifact
+ -> If fresh: deliver immediately (text + audio playback)
+ -> If stale/missing: run Phase 1 on-demand, then deliver
+
+CLI: prints formatted text + plays audio simultaneously
+Frontend/Desktop: renders text in chat + plays audio in browser/Tauri
+```
+
+The agent does the heavy lifting once. Delivery is just reading from a cache. If the user never triggers it, nothing is wasted except compute.
+
+---
+
+## New MCP Connectors
+
+> **Implementation note:** All MCP connectors below must be created and tested with real data from actual API accounts. This should be a **separate initial PR** before any digest agent work builds on top.
+
+Each connector follows the existing `BaseConnector` pattern with `@ConnectorRegistry.register()`. They sync data into the `KnowledgeStore` so the digest agent can query them uniformly.
+
+### Connector Interface
+
+```python
+class OuraConnector(BaseConnector):
+ def sync(self) -> List[Document] # Full sync
+ def fetch_recent(self, since: datetime) -> List[Document] # For digest
+ def list_sync_sources(self) -> dict # Metadata
+```
+
+The digest agent calls `fetch_recent(since=yesterday)` across all enabled connectors to get fresh data without a full re-sync.
+
+### Health & Fitness
+
+| Connector | API | Auth | Data Fetched |
+|-----------|-----|------|--------------|
+| `oura` | Oura Ring REST API v2 | OAuth2 | Sleep score, readiness, HRV, body temp, activity |
+| `apple_health` | Apple Health export (XML) or HealthKit via Shortcut | Local file / Shortcut | Steps, heart rate, workouts, stand hours |
+| `strava` | Strava REST API v3 | OAuth2 | Recent activities, distance, pace, PRs |
+
+**Apple Watch / Apple Health note:** There is no direct API for Apple Watch data. Apple Health is the unified source — data flows Apple Watch -> Apple Health automatically. Implementation options: (1) HealthKit Shortcut that exports JSON to a known path, or (2) parse the Apple Health XML export. This is a known constraint.
+
+### Music & Entertainment
+
+| Connector | API | Auth | Data Fetched |
+|-----------|-----|------|--------------|
+| `spotify` | Spotify Web API | OAuth2 | Recently played, top tracks, currently playing |
+| `apple_music` | Apple Music API | Developer token + MUT | Recently played, library stats |
+| `soundcloud` | SoundCloud API | OAuth2 | Likes, reposts, recent plays |
+
+### Productivity
+
+| Connector | API | Auth | Data Fetched |
+|-----------|-----|------|--------------|
+| `google_tasks` | Google Tasks API v1 | OAuth2 | Tasks due today, overdue, recently completed |
+
+### v1 Priority
+
+**Primary (clean REST APIs with OAuth2):** Oura, Strava, Spotify, Google Tasks
+
+**Stretch (ecosystem constraints):** Apple Health, Apple Music, SoundCloud
+
+---
+
+## Morning Digest Agent
+
+### Registration
+
+```python
[email protected]("morning_digest")
+class MorningDigestAgent(ToolUsingAgent):
+ agent_id = "morning_digest"
+```
+
+### System Prompt & Persona
+
+The agent's system prompt defines:
+
+1. **Persona** — Jarvis personality (professional, dry wit, concise). Loaded from a configurable prompt file so it's swappable.
+2. **Section ordering** — Which sections to include and in what order, driven by config.
+3. **Date/time context** — Injected dynamically so the LLM knows "today."
+4. **Prioritization rules** — e.g., "Highlight emails from direct manager. Deprioritize marketing newsletters. Flag meetings starting in <2 hours."
+
+Example system prompt skeleton:
+
+```
+You are JARVIS, a professional AI assistant with dry wit.
+Today is {date}, {day_of_week}. The time is {time} in {timezone}.
+The user is {user_name}.
+
+Generate a morning briefing from the data below. Be concise but
+insightful. Open with a greeting. Organize by these sections:
+{sections}
+
+Prioritization rules:
+{priority_rules}
+
+Collected data:
+{digest_data}
+```
+
+### Agent Flow
+
+```
+MorningDigestAgent.run()
+ 1. Call digest_collect tool -> returns structured data per source
+ 2. Inject collected data into system prompt
+ 3. Single LLM call to synthesize narrative
+ 4. Call text_to_speech tool -> generates audio
+ 5. Store DigestArtifact (text + audio path + metadata)
+ 6. Return AgentResult
+```
+
+This is intentionally not a multi-turn tool loop. The agent makes 2-3 deterministic tool calls, one LLM synthesis call, and one TTS call. Predictable, fast, debuggable. But since it extends `ToolUsingAgent`, interactive follow-ups can be added later ("Tell me more about that email from Alice").
+
+### DigestArtifact
+
+```python
+@dataclass
+class DigestArtifact:
+ text: str # Full narrative markdown
+ audio_path: Path # Path to generated audio file
+ sections: dict[str, str] # Per-section text for selective delivery
+ sources_used: list[str] # Which connectors contributed
+ generated_at: datetime
+ model_used: str
+ voice_used: str
+```
+
+Stored in a `DigestStore` (SQLite-backed, following the existing `SessionStore` pattern) so past digests are browsable.
+
+---
+
+## Text-to-Speech Pipeline
+
+### TTS Backend Architecture
+
+Follows the same pattern as the existing `SpeechBackend` (which handles STT). A new `TTSBackend` ABC with swappable implementations:
+
+```python
+class TTSBackend(ABC):
+ async def synthesize(self, text: str, voice_id: str, **kwargs) -> AudioResult
+
[email protected]("cartesia")
+class CartesiaTTSBackend(TTSBackend): ...
+
+class KokoroTTSBackend(TTSBackend): ...
+
+class OpenAITTSBackend(TTSBackend): ...
+```
+
+### Cartesia as Default
+
+- **Cartesia Ink** — fast, low-latency, high-quality voices. Ideal for on-device TTS.
+- Supports voice cloning/design for creating a custom Jarvis voice.
+- REST API + streaming support.
+- Falls back to OpenAI TTS or Kokoro (fully open-source, runs locally) if unavailable.
+
+### The `text_to_speech` Tool
+
+Registered as a normal tool so any agent can use it:
+
+```python
[email protected]("text_to_speech")
+class TextToSpeechTool(BaseTool):
+ def execute(self, text: str, voice_id: str = "jarvis-v1",
+ backend: str = "cartesia") -> ToolResult:
+ # Delegates to TTSRegistry.get(backend).synthesize()
+ # Returns: audio file path, duration, format
+```
+
+### Audio Output by Delivery Target
+
+- **CLI**: `sounddevice`, `pygame.mixer`, or shell out to `afplay`/`aplay`/`ffplay`
+- **Frontend**: HTML5 `<audio>` element, streamed from the API server
+- **Desktop (Tauri)**: Same as frontend, or native audio playback
+
+---
+
+## Delivery Layer
+
+### CLI: `jarvis digest`
+
+New subcommand on the existing CLI entry point:
+
+```bash
+# Play today's digest (text + voice)
+jarvis digest
+
+# Text only, no audio
+jarvis digest --text-only
+
+# Re-generate fresh (skip cache)
+jarvis digest --fresh
+
+# Show past digests
+jarvis digest --history
+
+# Play a specific section only
+jarvis digest --section health
+```
+
+Behavior:
+
+1. Check `DigestStore` for today's artifact.
+2. If found and fresh: print formatted text to terminal (rich/markdown) **and** play audio simultaneously in a background thread.
+3. If stale/missing: run the digest agent on-demand, then deliver.
+4. Text prints section by section with headers, audio plays the full narrative.
+
+### Frontend / Desktop App
+
+Delivered as a regular chat message through the existing channel system:
+
+1. User types "Good morning Jarvis" (or hits a digest button in the UI).
+2. Server endpoint `/api/digest` checks DigestStore, returns the artifact.
+3. Frontend renders text in chat bubble (formatted markdown per section) + audio player component at top (auto-plays).
+4. Sections are collapsible for quick scanning.
+
+No new channel type needed — the existing chat UI + an audio player component handles it.
+
+### API Endpoints
+
+```
+GET /api/digest -> Latest digest artifact (text + audio URL)
+GET /api/digest/audio -> Audio file stream
+POST /api/digest/generate -> Force re-generation
+GET /api/digest/history -> Past digests
+```
+
+These sit in the existing FastAPI server (`src/openjarvis/server/`).
+
+### Trigger Detection
+
+For "Good morning Jarvis" natural language trigger: the system prompt for the default agent includes a routing instruction — if the user's message matches a greeting/digest intent, delegate to the digest delivery flow. Simple pattern matching as fast path, LLM classification as fallback.
+
+---
+
+## Configuration
+
+### Full TOML Config
+
+```toml
+[intelligence]
+default_model = "claude-sonnet-4-6"
+
+[agent]
+default_agent = "morning_digest"
+tools = "digest_collect,web_search,text_to_speech"
+
+[agent.morning_digest]
+schedule = "0 6 * * *"
+persona = "jarvis"
+sections = ["messages", "calendar", "health", "world"]
+optional_sections = ["github", "financial", "music", "fitness"]
+
+[digest]
+enabled = true
+timezone = "America/Los_Angeles"
+
+[digest.messages]
+sources = ["gmail", "slack", "google_tasks"]
+priority_contacts = ["[email protected]", "team-channel"]
+max_items = 10
+
+[digest.calendar]
+sources = ["gcalendar"]
+lookahead_hours = 14
+
+[digest.health]
+sources = ["oura", "apple_health"]
+
+[digest.world]
+news_topics = ["artificial intelligence", "machine learning"]
+arxiv_categories = ["cs.AI", "cs.CL", "cs.LG"]
+include_weather = true
+weather_location = "Stanford, CA"
+
+[digest.github]
+repos = ["OpenJarvis/OpenJarvis"]
+include_prs = true
+include_issues = true
+
+[digest.financial]
+tickers = ["NVDA", "GOOGL", "MSFT"]
+
+[speech]
+tts_backend = "cartesia"
+tts_model = "sonic"
+voice_id = "jarvis-v1"
+speed = 1.0
+output_format = "mp3"
+
+[speech.cartesia]
+api_key = "${CARTESIA_API_KEY}"
+
+[speech.kokoro]
+model_path = "~/.openjarvis/models/kokoro-v1"
+device = "auto"
+```
+
+### Digest Sections
+
+**Core sections (always present):**
+
+| Section | Sources | Content |
+|---------|---------|---------|
+| `messages` | Gmail, Slack, iMessage (existing connector), Google Tasks | Important emails, messages, and tasks prioritized by relevance |
+| `calendar` | Google Calendar | Today's meetings with prep notes |
+| `health` | Oura Ring, Apple Health | Sleep score, readiness, activity summary |
+| `world` | Web search (Tavily), Arxiv API, OpenWeatherMap API | Headlines, AI/tech news, papers, local forecast |
+
+**Optional/pluggable sections:**
+
+| Section | Sources | Content |
+|---------|---------|---------|
+| `github` | GitHub API | PRs, issues, CI status on configured repos |
+| `financial` | Market data API | Ticker movements, portfolio summary |
+| `music` | Spotify, Apple Music | Yesterday's listening, new releases |
+| `fitness` | Strava | Recent workouts, streaks, PRs |
+
+### Adding a New Section
+
+1. **Create a connector** (if new data source) — `@ConnectorRegistry.register("foo")`
+2. **Add section config** — new `[digest.section_name]` block in TOML
+3. **Update persona prompt** — add instructions for how Jarvis narrates that section
+
+No code changes to the digest agent. The `digest_collect` tool reads `config.digest.sections`, iterates over enabled connectors, and returns structured data. The LLM handles the rest.
+
+### Persona System
+
+Personas live as prompt files, swappable via config:
+
+```
+prompts/personas/jarvis.md -- Professional, dry wit, "Good morning sir"
+prompts/personas/friday.md -- Warmer, more casual
+prompts/personas/neutral.md -- Straight facts, no personality
+prompts/personas/custom.md -- User-defined
+```
+
+Selected via `persona = "jarvis"` in config. The persona file is injected into the agent's system prompt at runtime.
+
+---
+
+## Testing Strategy
+
+### Connector Tests
+- Each connector tested against real APIs with real account data
+- Integration tests verify `fetch_recent()` returns valid `Document` objects
+- Mock tests for offline CI using recorded API responses (VCR pattern)
+
+### Agent Tests
+- Unit test: given mock collected data, verify LLM prompt is constructed correctly
+- Integration test: end-to-end digest generation with stubbed connectors
+- Snapshot tests for digest output format
+
+### TTS Tests
+- Unit test: `TTSBackend` interface compliance for each backend
+- Integration test: Cartesia API produces valid audio bytes
+- Audio duration sanity check (digest should be 2-5 minutes)
+
+### Delivery Tests
+- CLI: verify text output formatting and audio playback trigger
+- API: endpoint returns correct artifact structure
+- Frontend: component renders text + audio player
+
+### Markers
+- `@pytest.mark.cloud` for tests hitting real APIs (Cartesia, Oura, Spotify, etc.)
+- `@pytest.mark.live` for tests needing a running engine
+- Standard offline tests run in CI without credentials
+
+---
+
+## Implementation Sequence
+
+### PR 1: MCP Connectors (separate, foundational)
+Build and test all new connectors with real API data:
+- Oura Ring connector
+- Strava connector
+- Spotify connector
+- Google Tasks connector
+- Apple Health connector (stretch)
+- Apple Music connector (stretch)
+- SoundCloud connector (stretch)
+
+### PR 2: TTS Backend Infrastructure
+- `TTSBackend` ABC + `TTSRegistry`
+- Cartesia backend implementation
+- Kokoro backend implementation (open-source fallback)
+- OpenAI TTS backend implementation
+- `text_to_speech` tool registration
+- Config section `[speech]` for TTS
+
+### PR 3: Digest Agent + Store
+- `MorningDigestAgent` registration
+- `digest_collect` tool
+- `DigestArtifact` dataclass
+- `DigestStore` (SQLite-backed)
+- Persona prompt files (jarvis, neutral)
+- Agent scheduler integration
+- Config section `[digest]`
+
+### PR 4: Delivery Layer
+- CLI `jarvis digest` subcommand with audio playback
+- API endpoints (`/api/digest`, `/api/digest/audio`, etc.)
+- Frontend audio player component
+- "Good morning Jarvis" trigger detection
+
+### PR 5: Polish & Integration
+- End-to-end testing with all connectors live
+- Digest quality tuning (prompt engineering)
+- Voice tuning (Cartesia voice design)
+- Documentation
diff --git a/frontend/src/components/setup/SourceConnectFlow.tsx b/frontend/src/components/setup/SourceConnectFlow.tsx
index b977b275..c5a5b7bb 100644
--- a/frontend/src/components/setup/SourceConnectFlow.tsx
+++ b/frontend/src/components/setup/SourceConnectFlow.tsx
@@ -8,7 +8,8 @@ import {
Loader2,
} from 'lucide-react';
import { SOURCE_CATALOG } from '../../types/connectors';
-import { connectSource } from '../../lib/connectors-api';
+import { connectSource, getConnector } from '../../lib/connectors-api';
+import { getBase } from '../../lib/api';
import type { ConnectRequest, ConnectorMeta } from '../../types/connectors';
// ---------------------------------------------------------------------------
@@ -138,89 +139,71 @@ function FilesystemPanel({
function OAuthPanel({
displayName,
authUrl,
+ connectorId,
onConnect,
onSkip,
isConnecting,
}: {
displayName: string;
authUrl?: string;
+ connectorId: string;
onConnect: (req: ConnectRequest) => void;
onSkip: () => void;
isConnecting: boolean;
}) {
- const [token, setToken] = useState('');
- const [phase, setPhase] = useState<'start' | 'paste'>('start');
-
- const openBrowser = () => {
- if (authUrl) {
- window.open(authUrl, '_blank');
- }
- setPhase('paste');
+ const [waiting, setWaiting] = useState(false);
+
+ const startOAuth = () => {
+ // Open the server's OAuth start endpoint which redirects to the provider
+ const oauthUrl = `${getBase()}/v1/connectors/${encodeURIComponent(connectorId)}/oauth/start`;
+ window.open(oauthUrl, '_blank', 'width=600,height=700');
+ setWaiting(true);
+
+ // Poll for connection status
+ const interval = setInterval(async () => {
+ try {
+ const info = await getConnector(connectorId);
+ if (info.connected) {
+ clearInterval(interval);
+ setWaiting(false);
+ onConnect({});
+ }
+ } catch {
+ // ignore polling errors
+ }
+ }, 2000);
+
+ // Stop polling after 3 minutes
+ setTimeout(() => {
+ clearInterval(interval);
+ setWaiting(false);
+ }, 180000);
};
return (
<div className="flex flex-col gap-4">
- {phase === 'start' ? (
- <>
- <p className="text-sm" style={{ color: 'var(--color-text-secondary)' }}>
- Authorize OpenJarvis to access your {displayName} account.
- </p>
- <button
- onClick={openBrowser}
- className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium self-start transition-all"
- style={{
- background: 'var(--color-accent)',
- color: 'white',
- }}
- >
- <ExternalLink size={14} />
- Open in browser
- </button>
- </>
+ <p className="text-sm" style={{ color: 'var(--color-text-secondary)' }}>
+ {waiting
+ ? `Waiting for ${displayName} authorization... Complete it in the browser window.`
+ : `Connect your ${displayName} account with one click.`}
+ </p>
+ {waiting ? (
+ <div className="flex items-center gap-2 text-sm" style={{ color: 'var(--color-accent)' }}>
+ <Loader2 size={16} className="animate-spin" />
+ Waiting for authorization...
+ </div>
) : (
- <>
- <p className="text-sm" style={{ color: 'var(--color-text-secondary)' }}>
- After authorizing, paste the token or code below.
- </p>
- <textarea
- value={token}
- onChange={(e) => setToken(e.target.value)}
- rows={3}
- placeholder="Paste auth token or code here..."
- className="w-full px-3 py-2 rounded-lg text-sm outline-none resize-none font-mono"
- style={{
- background: 'var(--color-surface)',
- border: '1px solid var(--color-border)',
- color: 'var(--color-text)',
- }}
- />
- <div className="flex gap-2">
- <button
- onClick={() => onConnect({ token, code: token })}
- disabled={!token.trim() || isConnecting}
- className="px-4 py-2 rounded-lg text-sm font-medium flex items-center gap-2 transition-all"
- style={{
- background: token.trim() ? 'var(--color-accent)' : 'var(--color-bg-tertiary)',
- color: token.trim() ? 'white' : 'var(--color-text-tertiary)',
- cursor: token.trim() && !isConnecting ? 'pointer' : 'not-allowed',
- }}
- >
- {isConnecting && <Loader2 size={14} className="animate-spin" />}
- Confirm
- </button>
- <button
- onClick={() => setPhase('start')}
- className="px-4 py-2 rounded-lg text-sm font-medium transition-all"
- style={{
- background: 'var(--color-surface)',
- border: '1px solid var(--color-border)',
- color: 'var(--color-text-secondary)',
- }}
- >
- Back
- </button>
- </div>
- </>
+ <button
+ onClick={startOAuth}
+ className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium self-start transition-all"
+ style={{
+ background: 'var(--color-accent)',
+ color: 'white',
+ }}
+ >
+ <ExternalLink size={14} />
+ Connect {displayName}
+ </button>
)}
<button
onClick={onSkip}
@@ -589,6 +572,7 @@ export function SourceConnectFlow({
<OAuthPanel
displayName={activeCard.display_name}
authUrl={undefined}
+ connectorId={activeEntry.id}
onConnect={(req) => handleConnect(activeEntry.id, req)}
onSkip={() => handleSkip(activeEntry.id)}
isConnecting={activeEntry.state === 'connecting'}
diff --git a/scripts/oauth_all.py b/scripts/oauth_all.py
new file mode 100644
index 00000000..7e969c27
--- /dev/null
+++ b/scripts/oauth_all.py
@@ -0,0 +1,341 @@
+#!/usr/bin/env python3
+"""Run OAuth flows for Google, Strava, and Spotify in sequence.
+
+Usage:
+ uv run python scripts/oauth_all.py [--google] [--strava] [--spotify]
+ uv run python scripts/oauth_all.py # runs all three
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import webbrowser
+from http.server import BaseHTTPRequestHandler, HTTPServer
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+from urllib.parse import parse_qs, urlencode, urlparse
+
+import httpx
+
+CONFIG_DIR = Path.home() / ".openjarvis" / "connectors"
+CONFIG_DIR.mkdir(parents=True, exist_ok=True)
+
+CALLBACK_PORT = 8789
+REDIRECT_URI = f"http://localhost:{CALLBACK_PORT}/callback"
+
+# ── Credentials (read from stored files, then env vars) ──────────────────────
+
+
+def _load_creds(filename: str) -> Dict[str, str]:
+ """Load client_id/client_secret from a stored credential file."""
+ path = CONFIG_DIR / filename
+ if path.exists():
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ return {
+ "client_id": data.get("client_id", ""),
+ "client_secret": data.get("client_secret", ""),
+ }
+ except (json.JSONDecodeError, OSError):
+ pass
+ return {"client_id": "", "client_secret": ""}
+
+
+_google = _load_creds("google.json")
+GOOGLE_CLIENT_ID = os.environ.get("OPENJARVIS_GOOGLE_CLIENT_ID", "") or _google["client_id"]
+GOOGLE_CLIENT_SECRET = os.environ.get("OPENJARVIS_GOOGLE_CLIENT_SECRET", "") or _google["client_secret"]
+
+_strava = _load_creds("strava.json")
+STRAVA_CLIENT_ID = os.environ.get("OPENJARVIS_STRAVA_CLIENT_ID", "") or _strava["client_id"]
+STRAVA_CLIENT_SECRET = os.environ.get("OPENJARVIS_STRAVA_CLIENT_SECRET", "") or _strava["client_secret"]
+
+_spotify = _load_creds("spotify.json")
+SPOTIFY_CLIENT_ID = os.environ.get("OPENJARVIS_SPOTIFY_CLIENT_ID", "") or _spotify["client_id"]
+SPOTIFY_CLIENT_SECRET = os.environ.get("OPENJARVIS_SPOTIFY_CLIENT_SECRET", "") or _spotify["client_secret"]
+
+# ── Generic OAuth helpers ────────────────────────────────────────────────────
+
+
+def _wait_for_code(port: int = CALLBACK_PORT, timeout: int = 120) -> str:
+ """Start a localhost server and wait for the OAuth callback with ?code=."""
+ auth_code: List[str] = []
+ error: List[str] = []
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self) -> None:
+ params = parse_qs(urlparse(self.path).query)
+ if "code" in params:
+ auth_code.append(params["code"][0])
+ self.send_response(200)
+ self.send_header("Content-Type", "text/html")
+ self.end_headers()
+ self.wfile.write(
+ b"<html><body><h2>Success!</h2>"
+ b"<p>You can close this tab.</p></body></html>"
+ )
+ else:
+ error.append(params.get("error", ["unknown"])[0])
+ self.send_response(400)
+ self.send_header("Content-Type", "text/html")
+ self.end_headers()
+ self.wfile.write(b"<html><body><h2>Failed</h2></body></html>")
+
+ def log_message(self, *args: Any) -> None:
+ pass
+
+ server = HTTPServer(("127.0.0.1", port), Handler)
+ server.timeout = timeout
+ while not auth_code and not error:
+ server.handle_request()
+ server.server_close()
+
+ if error:
+ raise RuntimeError(f"OAuth error: {error[0]}")
+ if not auth_code:
+ raise RuntimeError("OAuth timed out")
+ return auth_code[0]
+
+
+def _save(path: Path, data: Dict[str, Any]) -> None:
+ path.write_text(json.dumps(data, indent=2), encoding="utf-8")
+ path.chmod(0o600)
+ print(f" Saved tokens to {path}")
+
+
+# ── Google ───────────────────────────────────────────────────────────────────
+
+
+def do_google() -> None:
+ print("\n=== Google OAuth (Drive, Calendar, Contacts, Gmail, Tasks) ===")
+ scopes = [
+ "openid", "email", "profile",
+ "https://www.googleapis.com/auth/drive.readonly",
+ "https://www.googleapis.com/auth/calendar.readonly",
+ "https://www.googleapis.com/auth/contacts.readonly",
+ "https://www.googleapis.com/auth/gmail.readonly",
+ "https://www.googleapis.com/auth/tasks.readonly",
+ ]
+ url = (
+ "https://accounts.google.com/o/oauth2/v2/auth?"
+ + urlencode({
+ "client_id": GOOGLE_CLIENT_ID,
+ "redirect_uri": REDIRECT_URI,
+ "response_type": "code",
+ "scope": " ".join(scopes),
+ "access_type": "offline",
+ "prompt": "consent",
+ })
+ )
+ print(f" Opening browser...")
+ webbrowser.open(url)
+ code = _wait_for_code()
+
+ resp = httpx.post(
+ "https://oauth2.googleapis.com/token",
+ data={
+ "code": code,
+ "client_id": GOOGLE_CLIENT_ID,
+ "client_secret": GOOGLE_CLIENT_SECRET,
+ "redirect_uri": REDIRECT_URI,
+ "grant_type": "authorization_code",
+ },
+ timeout=30.0,
+ )
+ resp.raise_for_status()
+ tokens = resp.json()
+
+ payload = {
+ "access_token": tokens["access_token"],
+ "refresh_token": tokens.get("refresh_token", ""),
+ "token_type": tokens.get("token_type", "Bearer"),
+ "expires_in": tokens.get("expires_in", 3600),
+ "client_id": GOOGLE_CLIENT_ID,
+ "client_secret": GOOGLE_CLIENT_SECRET,
+ }
+
+ # Save to shared + all connector-specific files
+ for name in ["google", "gdrive", "gcalendar", "gcontacts", "gmail", "google_tasks"]:
+ _save(CONFIG_DIR / f"{name}.json", payload)
+
+ print(" Google OAuth complete!")
+
+
+# ── Strava ───────────────────────────────────────────────────────────────────
+
+
+def do_strava() -> None:
+ print("\n=== Strava OAuth ===")
+ url = (
+ "https://www.strava.com/oauth/authorize?"
+ + urlencode({
+ "client_id": STRAVA_CLIENT_ID,
+ "redirect_uri": REDIRECT_URI,
+ "response_type": "code",
+ "scope": "activity:read_all",
+ })
+ )
+ print(f" Opening browser...")
+ webbrowser.open(url)
+ code = _wait_for_code()
+
+ resp = httpx.post(
+ "https://www.strava.com/oauth/token",
+ data={
+ "client_id": STRAVA_CLIENT_ID,
+ "client_secret": STRAVA_CLIENT_SECRET,
+ "code": code,
+ "grant_type": "authorization_code",
+ },
+ timeout=30.0,
+ )
+ resp.raise_for_status()
+ tokens = resp.json()
+
+ payload = {
+ "access_token": tokens["access_token"],
+ "refresh_token": tokens.get("refresh_token", ""),
+ "client_id": STRAVA_CLIENT_ID,
+ "client_secret": STRAVA_CLIENT_SECRET,
+ }
+ _save(CONFIG_DIR / "strava.json", payload)
+ print(" Strava OAuth complete!")
+
+
+# ── Spotify ──────────────────────────────────────────────────────────────────
+
+
+def _make_self_signed_cert() -> tuple[str, str]:
+ """Generate a temporary self-signed cert for localhost HTTPS."""
+ import ssl
+ import subprocess
+ import tempfile
+
+ cert_dir = Path(tempfile.mkdtemp())
+ key_path = str(cert_dir / "key.pem")
+ cert_path = str(cert_dir / "cert.pem")
+ subprocess.run(
+ [
+ "openssl", "req", "-x509", "-newkey", "rsa:2048",
+ "-keyout", key_path, "-out", cert_path,
+ "-days", "1", "-nodes",
+ "-subj", "/CN=localhost",
+ ],
+ capture_output=True, check=True,
+ )
+ return cert_path, key_path
+
+
+def _wait_for_code_https(port: int = 8888, timeout: int = 120) -> str:
+ """Like _wait_for_code but serves over HTTPS with a self-signed cert."""
+ import ssl
+
+ cert_path, key_path = _make_self_signed_cert()
+
+ auth_code: List[str] = []
+ error: List[str] = []
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self) -> None:
+ params = parse_qs(urlparse(self.path).query)
+ if "code" in params:
+ auth_code.append(params["code"][0])
+ self.send_response(200)
+ self.send_header("Content-Type", "text/html")
+ self.end_headers()
+ self.wfile.write(
+ b"<html><body><h2>Success!</h2>"
+ b"<p>You can close this tab.</p></body></html>"
+ )
+ else:
+ error.append(params.get("error", ["unknown"])[0])
+ self.send_response(400)
+ self.send_header("Content-Type", "text/html")
+ self.end_headers()
+ self.wfile.write(b"<html><body><h2>Failed</h2></body></html>")
+
+ def log_message(self, *args: Any) -> None:
+ pass
+
+ server = HTTPServer(("127.0.0.1", port), Handler)
+ ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+ ctx.load_cert_chain(cert_path, key_path)
+ server.socket = ctx.wrap_socket(server.socket, server_side=True)
+ server.timeout = timeout
+
+ while not auth_code and not error:
+ server.handle_request()
+ server.server_close()
+
+ if error:
+ raise RuntimeError(f"OAuth error: {error[0]}")
+ if not auth_code:
+ raise RuntimeError("OAuth timed out")
+ return auth_code[0]
+
+
+def do_spotify() -> None:
+ print("\n=== Spotify OAuth ===")
+ spotify_port = 8888
+ spotify_redirect = f"http://127.0.0.1:{spotify_port}/callback"
+ url = (
+ "https://accounts.spotify.com/authorize?"
+ + urlencode({
+ "client_id": SPOTIFY_CLIENT_ID,
+ "redirect_uri": spotify_redirect,
+ "response_type": "code",
+ "scope": "user-read-recently-played",
+ })
+ )
+ print(f" Opening browser...")
+ webbrowser.open(url)
+ code = _wait_for_code(port=spotify_port)
+
+ import base64
+ auth_header = base64.b64encode(
+ f"{SPOTIFY_CLIENT_ID}:{SPOTIFY_CLIENT_SECRET}".encode()
+ ).decode()
+
+ resp = httpx.post(
+ "https://accounts.spotify.com/api/token",
+ headers={"Authorization": f"Basic {auth_header}"},
+ data={
+ "code": code,
+ "redirect_uri": spotify_redirect,
+ "grant_type": "authorization_code",
+ },
+ timeout=30.0,
+ )
+ resp.raise_for_status()
+ tokens = resp.json()
+
+ payload = {
+ "access_token": tokens["access_token"],
+ "refresh_token": tokens.get("refresh_token", ""),
+ "client_id": SPOTIFY_CLIENT_ID,
+ "client_secret": SPOTIFY_CLIENT_SECRET,
+ }
+ _save(CONFIG_DIR / "spotify.json", payload)
+ print(" Spotify OAuth complete!")
+
+
+# ── Main ─────────────────────────────────────────────────────────────────────
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="Run OAuth flows for OpenJarvis connectors")
+ parser.add_argument("--google", action="store_true", help="Only Google")
+ parser.add_argument("--strava", action="store_true", help="Only Strava")
+ parser.add_argument("--spotify", action="store_true", help="Only Spotify")
+ args = parser.parse_args()
+
+ run_all = not (args.google or args.strava or args.spotify)
+
+ if run_all or args.google:
+ do_google()
+ if run_all or args.strava:
+ do_strava()
+ if run_all or args.spotify:
+ do_spotify()
+
+ print("\nDone! All OAuth flows complete.")
diff --git a/src/openjarvis/agents/__init__.py b/src/openjarvis/agents/__init__.py
index ebf6ec6c..c9c7b1bf 100644
--- a/src/openjarvis/agents/__init__.py
+++ b/src/openjarvis/agents/__init__.py
@@ -74,6 +74,11 @@ try:
except ImportError:
pass
+try:
+ import openjarvis.agents.morning_digest # noqa: F401
+except ImportError:
+ pass
+
# Registry alias: "react" -> NativeReActAgent (for backward compat)
try:
from openjarvis.core.registry import AgentRegistry
diff --git a/src/openjarvis/agents/digest_store.py b/src/openjarvis/agents/digest_store.py
new file mode 100644
index 00000000..b164b244
--- /dev/null
+++ b/src/openjarvis/agents/digest_store.py
@@ -0,0 +1,124 @@
+"""DigestStore — SQLite-backed storage for pre-computed digest artifacts."""
+
+from __future__ import annotations
+
+import json
+import sqlite3
+from dataclasses import dataclass
+from datetime import datetime
+from pathlib import Path
+from typing import Dict, List, Optional
+
+
+@dataclass
+class DigestArtifact:
+ """A pre-computed morning digest ready for delivery."""
+
+ text: str
+ audio_path: Path
+ sections: Dict[str, str]
+ sources_used: List[str]
+ generated_at: datetime
+ model_used: str
+ voice_used: str
+
+
+class DigestStore:
+ """SQLite store for digest artifacts."""
+
+ def __init__(self, db_path: str = "") -> None:
+ if not db_path:
+ db_path = str(Path.home() / ".openjarvis" / "digest.db")
+ self._db_path = db_path
+ self._conn = sqlite3.connect(db_path)
+ self._conn.execute("PRAGMA journal_mode=WAL")
+ self._conn.execute(
+ """
+ CREATE TABLE IF NOT EXISTS digests (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ text TEXT NOT NULL,
+ audio_path TEXT NOT NULL,
+ sections TEXT NOT NULL,
+ sources_used TEXT NOT NULL,
+ generated_at TEXT NOT NULL,
+ model_used TEXT NOT NULL,
+ voice_used TEXT NOT NULL
+ )
+ """
+ )
+ self._conn.commit()
+
+ def save(self, artifact: DigestArtifact) -> None:
+ """Save a digest artifact."""
+ self._conn.execute(
+ """
+ INSERT INTO digests
+ (text, audio_path, sections, sources_used,
+ generated_at, model_used, voice_used)
+ VALUES (?, ?, ?, ?, ?, ?, ?)
+ """,
+ (
+ artifact.text,
+ str(artifact.audio_path),
+ json.dumps(artifact.sections),
+ json.dumps(artifact.sources_used),
+ artifact.generated_at.isoformat(),
+ artifact.model_used,
+ artifact.voice_used,
+ ),
+ )
+ self._conn.commit()
+
+ def _row_to_artifact(self, row: tuple) -> DigestArtifact:
+ return DigestArtifact(
+ text=row[0],
+ audio_path=Path(row[1]),
+ sections=json.loads(row[2]),
+ sources_used=json.loads(row[3]),
+ generated_at=datetime.fromisoformat(row[4]),
+ model_used=row[5],
+ voice_used=row[6],
+ )
+
+ def get_latest(self) -> Optional[DigestArtifact]:
+ """Return the most recent digest, or None."""
+ row = self._conn.execute(
+ "SELECT text, audio_path, sections, sources_used,"
+ " generated_at, model_used, voice_used"
+ " FROM digests ORDER BY id DESC LIMIT 1"
+ ).fetchone()
+ if row is None:
+ return None
+ return self._row_to_artifact(row)
+
+ def get_today(self, timezone_name: str = "UTC") -> Optional[DigestArtifact]:
+ """Return today's digest if it exists, or None."""
+ try:
+ from zoneinfo import ZoneInfo
+
+ today = datetime.now(ZoneInfo(timezone_name)).strftime("%Y-%m-%d")
+ except ImportError:
+ today = datetime.now().strftime("%Y-%m-%d")
+
+ row = self._conn.execute(
+ "SELECT text, audio_path, sections, sources_used,"
+ " generated_at, model_used, voice_used"
+ " FROM digests WHERE generated_at LIKE ? ORDER BY id DESC LIMIT 1",
+ (f"{today}%",),
+ ).fetchone()
+ if row is None:
+ return None
+ return self._row_to_artifact(row)
+
+ def history(self, limit: int = 10) -> List[DigestArtifact]:
+ """Return the N most recent digests."""
+ rows = self._conn.execute(
+ "SELECT text, audio_path, sections, sources_used,"
+ " generated_at, model_used, voice_used"
+ " FROM digests ORDER BY id DESC LIMIT ?",
+ (limit,),
+ ).fetchall()
+ return [self._row_to_artifact(r) for r in rows]
+
+ def close(self) -> None:
+ self._conn.close()
diff --git a/src/openjarvis/agents/morning_digest.py b/src/openjarvis/agents/morning_digest.py
new file mode 100644
index 00000000..876f63ef
--- /dev/null
+++ b/src/openjarvis/agents/morning_digest.py
@@ -0,0 +1,159 @@
+"""Morning Digest Agent — synthesizes a daily briefing from multiple sources.
+
+Thin orchestrator that delegates to digest_collect (data fetching),
+the LLM (narrative synthesis), and text_to_speech (audio generation).
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime
+from pathlib import Path
+from typing import Any, List, Optional
+
+from openjarvis.agents._stubs import AgentContext, AgentResult, ToolUsingAgent
+from openjarvis.agents.digest_store import DigestArtifact, DigestStore
+from openjarvis.core.registry import AgentRegistry
+from openjarvis.core.types import Message, Role, ToolCall
+
+
+def _load_persona(persona_name: str) -> str:
+ """Load a persona prompt file by name."""
+ search_paths = [
+ Path("configs/openjarvis/prompts/personas") / f"{persona_name}.md",
+ Path.home() / ".openjarvis" / "prompts" / "personas" / f"{persona_name}.md",
+ ]
+ for p in search_paths:
+ if p.exists():
+ return p.read_text(encoding="utf-8")
+ return ""
+
+
[email protected]("morning_digest")
+class MorningDigestAgent(ToolUsingAgent):
+ """Pre-compute a daily digest from configured data sources."""
+
+ agent_id = "morning_digest"
+
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ # Extract digest-specific kwargs before passing to parent
+ self._persona = kwargs.pop("persona", "jarvis")
+ self._sections = kwargs.pop(
+ "sections", ["messages", "calendar", "health", "world"]
+ )
+ self._section_sources = kwargs.pop("section_sources", {})
+ self._timezone = kwargs.pop("timezone", "America/Los_Angeles")
+ self._voice_id = kwargs.pop("voice_id", "")
+ self._tts_backend = kwargs.pop("tts_backend", "cartesia")
+ self._digest_store_path = kwargs.pop("digest_store_path", "")
+ super().__init__(*args, **kwargs)
+
+ def _build_system_prompt(self) -> str:
+ """Assemble the system prompt from persona + context."""
+ persona_text = _load_persona(self._persona)
+ now = datetime.now()
+
+ return (
+ f"{persona_text}\n\n"
+ f"Today is {now.strftime('%A, %B %d, %Y')}. "
+ f"The time is {now.strftime('%I:%M %p')} in {self._timezone}.\n\n"
+ f"Generate a morning briefing covering these sections in order: "
+ f"{', '.join(self._sections)}.\n\n"
+ "Be concise — the entire briefing should be readable in 2-3 minutes "
+ "and listenable in under 5 minutes when spoken aloud.\n\n"
+ "Format your response in clean markdown with section headers."
+ )
+
+ def _resolve_sources(self) -> List[str]:
+ """Get the list of connector IDs to query."""
+ default_source_map = {
+ "messages": ["gmail", "slack", "google_tasks"],
+ "calendar": ["gcalendar"],
+ "health": ["oura"],
+ "world": [], # Handled by web_search, not connectors
+ }
+ sources = set()
+ for section in self._sections:
+ section_sources = self._section_sources.get(
+ section, default_source_map.get(section, [])
+ )
+ sources.update(section_sources)
+ return list(sources)
+
+ def run(
+ self,
+ input: str,
+ context: Optional[AgentContext] = None,
+ **kwargs: Any,
+ ) -> AgentResult:
+ self._emit_turn_start(input)
+
+ # Step 1: Collect data from connectors
+ sources = self._resolve_sources()
+ collect_call = ToolCall(
+ id="digest-collect-1",
+ name="digest_collect",
+ arguments=json.dumps({"sources": sources, "hours_back": 24}),
+ )
+ collect_result = self._executor.execute(collect_call)
+ collected_data = collect_result.content
+
+ # Step 2: Synthesize narrative via LLM
+ system_prompt = self._build_system_prompt()
+ messages = [
+ Message(role=Role.SYSTEM, content=system_prompt),
+ Message(
+ role=Role.USER,
+ content=(
+ f"Here is the collected data from my sources:\n\n"
+ f"{collected_data}\n\n"
+ f"Please synthesize my morning briefing."
+ ),
+ ),
+ ]
+
+ result = self._generate(messages)
+ narrative = self._strip_think_tags(result.get("content", ""))
+
+ # Step 3: Generate audio via TTS
+ tts_call = ToolCall(
+ id="digest-tts-1",
+ name="text_to_speech",
+ arguments=json.dumps(
+ {
+ "text": narrative,
+ "voice_id": self._voice_id,
+ "backend": self._tts_backend,
+ }
+ ),
+ )
+ tts_result = self._executor.execute(tts_call)
+ audio_path = (
+ tts_result.metadata.get("audio_path", "") if tts_result.success else ""
+ )
+
+ # Step 4: Store the artifact
+ artifact = DigestArtifact(
+ text=narrative,
+ audio_path=Path(audio_path) if audio_path else Path(""),
+ sections={},
+ sources_used=sources,
+ generated_at=datetime.now(),
+ model_used=self._model,
+ voice_used=self._voice_id,
+ )
+
+ store = DigestStore(db_path=self._digest_store_path)
+ store.save(artifact)
+ store.close()
+
+ self._emit_turn_end(turns=1)
+ return AgentResult(
+ content=narrative,
+ tool_results=[collect_result, tts_result],
+ turns=1,
+ metadata={
+ "audio_path": audio_path,
+ "sources_used": sources,
+ },
+ )
diff --git a/src/openjarvis/cli/__init__.py b/src/openjarvis/cli/__init__.py
index 1589944f..e640620b 100644
--- a/src/openjarvis/cli/__init__.py
+++ b/src/openjarvis/cli/__init__.py
@@ -36,6 +36,7 @@ from openjarvis.cli.skill_cmd import skill
from openjarvis.cli.telemetry_cmd import telemetry
from openjarvis.cli.tool_cmd import tool
from openjarvis.cli.vault_cmd import vault
+from openjarvis.cli.digest_cmd import digest
from openjarvis.cli.workflow_cmd import workflow
@@ -94,6 +95,7 @@ cli.add_command(registry, "registry")
cli.add_command(config, "config")
cli.add_command(scan, "scan")
cli.add_command(connect, "connect")
+cli.add_command(digest, "digest")
cli.add_command(deep_research_setup, "deep-research-setup")
cli.add_command(deep_research_setup, "research")
diff --git a/src/openjarvis/cli/connect_cmd.py b/src/openjarvis/cli/connect_cmd.py
index d1eb090c..cd42ee07 100644
--- a/src/openjarvis/cli/connect_cmd.py
+++ b/src/openjarvis/cli/connect_cmd.py
@@ -95,18 +95,74 @@ def _connect_source(registry: object, source: str, path: str = "") -> None:
)
elif auth_type == "oauth":
- # OAuth connectors need browser-based auth
+ # OAuth connectors — auto-open browser + catch callback
+ from openjarvis.connectors.oauth import (
+ get_client_credentials,
+ get_provider_for_connector,
+ run_connector_oauth,
+ save_client_credentials,
+ )
+
try:
instance = connector_cls()
- url = instance.auth_url()
- console.print(f"[cyan]Open this URL to authorise {source}:[/cyan]")
- console.print(url)
- code = click.prompt("Enter the authorisation code")
- instance.handle_callback(code)
+ if instance.is_connected():
+ console.print(
+ f"[green]{source} is already connected.[/green]"
+ )
+ return
+
+ provider = get_provider_for_connector(source)
+ if provider is None:
+ console.print(
+ f"[red]No OAuth provider configured for {source}.[/red]"
+ )
+ return
+
+ client_id, client_secret = get_client_credentials(provider)
+
+ if not client_id or not client_secret:
+ console.print(
+ f"[cyan]First-time setup for {source}.[/cyan]"
+ )
+ console.print(
+ f"[yellow]Create an OAuth app at: {provider.setup_url}[/yellow]"
+ )
+ console.print(f"[dim]{provider.setup_hint}[/dim]")
+ client_id = click.prompt("Client ID")
+ client_secret = click.prompt("Client Secret")
+ save_client_credentials(provider, client_id, client_secret)
+
+ run_connector_oauth(source, client_id, client_secret)
console.print(f"[green]{source} authorised successfully.[/green]")
except Exception as exc: # noqa: BLE001
console.print(f"[red]OAuth flow failed for {source}: {exc}[/red]")
+ elif auth_type == "token":
+ # Token-based connectors (e.g. Oura) — prompt for personal access token
+ import json
+ from pathlib import Path
+
+ from openjarvis.connectors.oauth import save_tokens
+ from openjarvis.core.config import DEFAULT_CONFIG_DIR
+
+ try:
+ instance = connector_cls()
+ if instance.is_connected():
+ console.print(
+ f"[green]{source} is already connected.[/green]"
+ )
+ return
+
+ token = click.prompt(f"Enter your {source} personal access token")
+ token_dir = Path(DEFAULT_CONFIG_DIR) / "connectors"
+ token_dir.mkdir(parents=True, exist_ok=True)
+ token_file = token_dir / f"{source}.json"
+ token_file.write_text(json.dumps({"token": token}))
+ save_tokens(source, {"token": token})
+ console.print(f"[green]{source} connected successfully.[/green]")
+ except Exception as exc: # noqa: BLE001
+ console.print(f"[red]Token setup failed for {source}: {exc}[/red]")
+
else:
# Generic / bridge connectors
try:
@@ -154,8 +210,7 @@ def connect(
) -> None:
"""Manage data source connections (Gmail, Obsidian, etc.)."""
# Lazy imports to avoid top-level side effects
- import openjarvis.connectors.gmail # noqa: F401
- import openjarvis.connectors.obsidian # noqa: F401
+ import openjarvis.connectors # noqa: F401 — registers all connectors
from openjarvis.core.registry import ConnectorRegistry
if list_sources:
diff --git a/src/openjarvis/cli/digest_cmd.py b/src/openjarvis/cli/digest_cmd.py
new file mode 100644
index 00000000..c414485b
--- /dev/null
+++ b/src/openjarvis/cli/digest_cmd.py
@@ -0,0 +1,113 @@
+"""``jarvis digest`` — display and play the morning digest."""
+
+from __future__ import annotations
+
+import subprocess
+import threading
+
+import click
+from rich.console import Console
+from rich.markdown import Markdown
+
+from openjarvis.agents.digest_store import DigestStore
+
+
+def _play_audio(audio_path: str) -> None:
+ """Play audio file in background using available system player."""
+ players = ["ffplay -nodisp -autoexit", "aplay", "afplay", "paplay"]
+ for player in players:
+ cmd_parts = player.split() + [audio_path]
+ try:
+ subprocess.run(
+ cmd_parts,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ check=True,
+ )
+ return
+ except (FileNotFoundError, subprocess.CalledProcessError):
+ continue
+
+
[email protected]("digest", help="Display and play the morning digest.")
[email protected]("--text-only", is_flag=True, help="Print text without audio playback.")
[email protected]("--fresh", is_flag=True, help="Re-generate the digest (skip cache).")
[email protected]("--history", is_flag=True, help="Show past digests.")
[email protected]("--section", type=str, default="", help="Show only a specific section.")
[email protected]("--db-path", type=str, default="", help="Path to digest database.")
+def digest(
+ text_only: bool,
+ fresh: bool,
+ history: bool,
+ section: str,
+ db_path: str,
+) -> None:
+ """Display and optionally play the morning digest."""
+ console = Console()
+ store = DigestStore(db_path=db_path) if db_path else DigestStore()
+
+ if history:
+ past = store.history(limit=10)
+ if not past:
+ console.print("[dim]No past digests found.[/dim]")
+ store.close()
+ return
+ for artifact in past:
+ console.print(
+ f"[bold]{artifact.generated_at.strftime('%Y-%m-%d %H:%M')}[/bold]"
+ f" — {artifact.model_used} / {artifact.voice_used}"
+ )
+ console.print(artifact.text[:200] + "...\n")
+ store.close()
+ return
+
+ if fresh:
+ # Trigger on-demand generation
+ console.print("[yellow]Generating fresh digest...[/yellow]")
+ try:
+ from openjarvis.sdk import Jarvis
+
+ with Jarvis() as j:
+ result = j.ask("Generate my morning digest", agent="morning_digest")
+ console.print(Markdown(result))
+ except Exception as exc:
+ console.print(f"[red]Failed to generate digest: {exc}[/red]")
+ store.close()
+ return
+
+ # Try to load today's cached digest
+ artifact = store.get_today()
+ if artifact is None:
+ console.print("[dim]No digest for today. Use --fresh to generate one.[/dim]")
+ store.close()
+ return
+
+ # Display text
+ text = artifact.text
+ if section:
+ # Try to extract just the requested section
+ lines = text.split("\n")
+ in_section = False
+ section_lines = []
+ for line in lines:
+ if line.strip().lower().startswith(
+ f"## {section.lower()}"
+ ) or line.strip().lower().startswith(f"# {section.lower()}"):
+ in_section = True
+ section_lines.append(line)
+ elif in_section and line.strip().startswith("#"):
+ break
+ elif in_section:
+ section_lines.append(line)
+ text = "\n".join(section_lines) if section_lines else text
+
+ # Play audio in background while text renders
+ audio_path = str(artifact.audio_path)
+ if not text_only and audio_path and artifact.audio_path.exists():
+ audio_thread = threading.Thread(
+ target=_play_audio, args=(audio_path,), daemon=True
+ )
+ audio_thread.start()
+
+ console.print(Markdown(text))
+ store.close()
diff --git a/src/openjarvis/connectors/__init__.py b/src/openjarvis/connectors/__init__.py
index e28758c5..32e40474 100644
--- a/src/openjarvis/connectors/__init__.py
+++ b/src/openjarvis/connectors/__init__.py
@@ -50,6 +50,11 @@ try:
except ImportError:
pass
+try:
+ import openjarvis.connectors.apple_music # noqa: F401
+except ImportError:
+ pass
+
try:
import openjarvis.connectors.slack_connector # noqa: F401
except ImportError:
@@ -74,3 +79,28 @@ try:
import openjarvis.connectors.whatsapp # noqa: F401
except ImportError:
pass
+
+try:
+ import openjarvis.connectors.oura # noqa: F401
+except ImportError:
+ pass
+
+try:
+ import openjarvis.connectors.apple_health # noqa: F401
+except ImportError:
+ pass
+
+try:
+ import openjarvis.connectors.strava # noqa: F401
+except ImportError:
+ pass
+
+try:
+ import openjarvis.connectors.spotify # noqa: F401
+except ImportError:
+ pass
+
+try:
+ import openjarvis.connectors.google_tasks # noqa: F401
+except ImportError:
+ pass
diff --git a/src/openjarvis/connectors/apple_health.py b/src/openjarvis/connectors/apple_health.py
new file mode 100644
index 00000000..8795f00c
--- /dev/null
+++ b/src/openjarvis/connectors/apple_health.py
@@ -0,0 +1,419 @@
+"""Apple Health connector -- reads HealthKit SQLite DB or iPhone Health export XML.
+
+Two data sources are tried in order:
+1. HealthKit SQLite DB at ``~/Library/Health/healthdb_secure.sqlite`` (macOS
+ with HealthKit sync enabled).
+2. Health Export XML placed by the user at
+ ``~/.openjarvis/connectors/apple_health_export/export.xml``.
+
+Both are local-only; no API keys are needed.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import logging
+import sqlite3
+import xml.etree.ElementTree as ET
+from collections import defaultdict
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+from typing import Any, Dict, Iterator, List, Optional
+
+from openjarvis.connectors._stubs import BaseConnector, Document, SyncStatus
+from openjarvis.core.config import DEFAULT_CONFIG_DIR
+from openjarvis.core.registry import ConnectorRegistry
+
+logger = logging.getLogger(__name__)
+
+_DEFAULT_EXPORT_PATH = str(
+ DEFAULT_CONFIG_DIR / "connectors" / "apple_health_export" / "export.xml"
+)
+_DEFAULT_HEALTHKIT_DB_PATH = str(
+ Path.home() / "Library" / "Health" / "healthdb_secure.sqlite"
+)
+
+# HK record type identifiers we care about
+_STEP_COUNT = "HKQuantityTypeIdentifierStepCount"
+_SLEEP_ANALYSIS = "HKCategoryTypeIdentifierSleepAnalysis"
+_HEART_RATE = "HKQuantityTypeIdentifierHeartRate"
+_RESTING_HEART_RATE = "HKQuantityTypeIdentifierRestingHeartRate"
+_ACTIVE_ENERGY = "HKQuantityTypeIdentifierActiveEnergyBurned"
+
+
+def _parse_health_date(date_str: str) -> datetime:
+ """Parse date strings from Apple Health export XML.
+
+ Format is typically ``2024-03-15 08:00:00 -0700``.
+ """
+ # Strip sub-second precision if present, then parse
+ try:
+ return datetime.strptime(date_str.strip(), "%Y-%m-%d %H:%M:%S %z")
+ except ValueError:
+ # Fallback: try ISO-8601
+ return datetime.fromisoformat(date_str.strip())
+
+
+def _day_key(dt: datetime) -> str:
+ """Return ``YYYY-MM-DD`` for a datetime."""
+ return dt.strftime("%Y-%m-%d")
+
+
+def _format_duration(seconds: float) -> str:
+ """Return a human-readable duration like ``7h 23m``."""
+ hours = int(seconds // 3600)
+ minutes = int((seconds % 3600) // 60)
+ if hours and minutes:
+ return f"{hours}h {minutes:02d}m"
+ if hours:
+ return f"{hours}h"
+ return f"{minutes}m"
+
+
[email protected]("apple_health")
+class AppleHealthConnector(BaseConnector):
+ """Sync health data from Apple Health (local files only)."""
+
+ connector_id = "apple_health"
+ display_name = "Apple Health"
+ auth_type = "local"
+
+ def __init__(
+ self,
+ *,
+ export_path: str = _DEFAULT_EXPORT_PATH,
+ healthkit_db_path: str = _DEFAULT_HEALTHKIT_DB_PATH,
+ ) -> None:
+ self._export_path = Path(export_path)
+ self._healthkit_db_path = Path(healthkit_db_path)
+ self._status = SyncStatus()
+
+ # ------------------------------------------------------------------
+ # BaseConnector interface
+ # ------------------------------------------------------------------
+
+ def is_connected(self) -> bool:
+ return self._healthkit_db_path.exists() or self._export_path.exists()
+
+ def disconnect(self) -> None:
+ # Local connector -- nothing to revoke.
+ pass
+
+ def sync(
+ self, *, since: Optional[datetime] = None, cursor: Optional[str] = None
+ ) -> Iterator[Document]:
+ """Yield health Documents, preferring HealthKit DB over export XML."""
+ self._status.state = "syncing"
+ try:
+ # Try HealthKit SQLite first
+ if self._healthkit_db_path.exists():
+ try:
+ yield from self._sync_healthkit_db(since=since)
+ self._status.state = "idle"
+ self._status.last_sync = datetime.now()
+ return
+ except Exception:
+ logger.debug(
+ "HealthKit DB not readable, falling back to export XML",
+ exc_info=True,
+ )
+
+ # Fall back to export XML
+ if self._export_path.exists():
+ yield from self._sync_export_xml(since=since)
+
+ self._status.state = "idle"
+ self._status.last_sync = datetime.now()
+ except Exception as exc:
+ self._status.state = "error"
+ self._status.error = str(exc)
+ raise
+
+ def sync_status(self) -> SyncStatus:
+ return self._status
+
+ # ------------------------------------------------------------------
+ # HealthKit SQLite DB
+ # ------------------------------------------------------------------
+
+ def _sync_healthkit_db(
+ self, *, since: Optional[datetime] = None
+ ) -> Iterator[Document]:
+ """Read health data from the local HealthKit SQLite database."""
+ conn = sqlite3.connect(str(self._healthkit_db_path))
+ conn.row_factory = sqlite3.Row
+ try:
+ # Query quantity_samples joined with samples for step count,
+ # heart rate, active energy. The schema uses Apple's CF
+ # absolute time (seconds since 2001-01-01).
+ cf_epoch = datetime(2001, 1, 1, tzinfo=timezone.utc)
+ since_cf = (
+ (since - cf_epoch).total_seconds()
+ if since and since.tzinfo
+ else (
+ (since.replace(tzinfo=timezone.utc) - cf_epoch).total_seconds()
+ if since
+ else 0
+ )
+ )
+
+ # Steps
+ steps_by_day: Dict[str, float] = defaultdict(float)
+ rows = conn.execute(
+ """
+ SELECT s.start_date, qs.quantity
+ FROM samples s
+ JOIN quantity_samples qs ON s.data_id = qs.data_id
+ WHERE s.data_type = 7 AND s.start_date > ?
+ """,
+ (since_cf,),
+ ).fetchall()
+ for row in rows:
+ dt = cf_epoch.replace(tzinfo=timezone.utc) + timedelta(
+ seconds=row["start_date"]
+ )
+ steps_by_day[_day_key(dt)] += row["quantity"]
+
+ for day, total in sorted(steps_by_day.items()):
+ yield Document(
+ doc_id=f"apple_health-steps-{day}",
+ source="apple_health",
+ doc_type="steps",
+ content=json.dumps({"date": day, "steps": int(total)}),
+ title=f"{int(total):,} steps",
+ timestamp=datetime.fromisoformat(day),
+ metadata={"data_type": "steps", "day": day},
+ )
+ finally:
+ conn.close()
+
+ # ------------------------------------------------------------------
+ # Export XML
+ # ------------------------------------------------------------------
+
+ def _sync_export_xml(
+ self, *, since: Optional[datetime] = None
+ ) -> Iterator[Document]:
+ """Stream-parse the Apple Health export XML and yield Documents."""
+ steps_by_day: Dict[str, float] = defaultdict(float)
+ sleep_by_day: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
+ hr_by_day: Dict[str, List[float]] = defaultdict(list)
+ energy_by_day: Dict[str, float] = defaultdict(float)
+ workouts: List[Dict[str, Any]] = []
+
+ for event, elem in ET.iterparse(str(self._export_path), events=("end",)):
+ tag = elem.tag
+
+ if tag == "Record":
+ rec_type = elem.get("type", "")
+ start_str = elem.get("startDate", "")
+ if not start_str:
+ elem.clear()
+ continue
+
+ try:
+ start_dt = _parse_health_date(start_str)
+ except (ValueError, TypeError):
+ elem.clear()
+ continue
+
+ if since and start_dt.replace(tzinfo=None) < since.replace(tzinfo=None):
+ elem.clear()
+ continue
+
+ day = _day_key(start_dt)
+
+ if rec_type == _STEP_COUNT:
+ val = float(elem.get("value", 0))
+ steps_by_day[day] += val
+
+ elif rec_type == _SLEEP_ANALYSIS:
+ end_str = elem.get("endDate", start_str)
+ try:
+ end_dt = _parse_health_date(end_str)
+ except (ValueError, TypeError):
+ end_dt = start_dt
+ sleep_by_day[day].append(
+ {
+ "start": start_str,
+ "end": end_str,
+ "value": elem.get("value", ""),
+ "duration_seconds": (end_dt - start_dt).total_seconds(),
+ }
+ )
+
+ elif rec_type in (_HEART_RATE, _RESTING_HEART_RATE):
+ try:
+ hr_by_day[day].append(float(elem.get("value", 0)))
+ except (ValueError, TypeError):
+ pass
+
+ elif rec_type == _ACTIVE_ENERGY:
+ try:
+ energy_by_day[day] += float(elem.get("value", 0))
+ except (ValueError, TypeError):
+ pass
+
+ elem.clear()
+
+ elif tag == "Workout":
+ start_str = elem.get("startDate", "")
+ if not start_str:
+ elem.clear()
+ continue
+
+ try:
+ start_dt = _parse_health_date(start_str)
+ except (ValueError, TypeError):
+ elem.clear()
+ continue
+
+ if since and start_dt.replace(tzinfo=None) < since.replace(tzinfo=None):
+ elem.clear()
+ continue
+
+ workouts.append(
+ {
+ "activity_type": elem.get("workoutActivityType", ""),
+ "duration_seconds": float(elem.get("duration", 0)),
+ "start": start_str,
+ "end": elem.get("endDate", ""),
+ "total_distance": elem.get("totalDistance", ""),
+ "total_energy_burned": elem.get("totalEnergyBurned", ""),
+ }
+ )
+ elem.clear()
+
+ else:
+ # Don't clear the root or other structural elements yet
+ pass
+
+ # Yield aggregated documents
+ yield from self._yield_step_docs(steps_by_day)
+ yield from self._yield_sleep_docs(sleep_by_day)
+ yield from self._yield_hr_docs(hr_by_day)
+ yield from self._yield_energy_docs(energy_by_day)
+ yield from self._yield_workout_docs(workouts)
+
+ # ------------------------------------------------------------------
+ # Document builders
+ # ------------------------------------------------------------------
+
+ @staticmethod
+ def _yield_step_docs(
+ steps_by_day: Dict[str, float],
+ ) -> Iterator[Document]:
+ for day in sorted(steps_by_day):
+ total = int(steps_by_day[day])
+ yield Document(
+ doc_id=f"apple_health-steps-{day}",
+ source="apple_health",
+ doc_type="steps",
+ content=json.dumps({"date": day, "steps": total}),
+ title=f"{total:,} steps",
+ timestamp=datetime.fromisoformat(day),
+ metadata={"data_type": "steps", "day": day},
+ )
+
+ @staticmethod
+ def _yield_sleep_docs(
+ sleep_by_day: Dict[str, List[Dict[str, Any]]],
+ ) -> Iterator[Document]:
+ for day in sorted(sleep_by_day):
+ entries = sleep_by_day[day]
+ total_seconds = sum(e["duration_seconds"] for e in entries)
+ yield Document(
+ doc_id=f"apple_health-sleep-{day}",
+ source="apple_health",
+ doc_type="sleep",
+ content=json.dumps(
+ {"date": day, "total_seconds": total_seconds, "entries": entries}
+ ),
+ title=f"{_format_duration(total_seconds)} sleep",
+ timestamp=datetime.fromisoformat(day),
+ metadata={"data_type": "sleep", "day": day},
+ )
+
+ @staticmethod
+ def _yield_hr_docs(
+ hr_by_day: Dict[str, List[float]],
+ ) -> Iterator[Document]:
+ for day in sorted(hr_by_day):
+ values = hr_by_day[day]
+ avg = round(sum(values) / len(values), 1) if values else 0
+ yield Document(
+ doc_id=f"apple_health-heart_rate-{day}",
+ source="apple_health",
+ doc_type="heart_rate",
+ content=json.dumps(
+ {
+ "date": day,
+ "avg_bpm": avg,
+ "min_bpm": min(values),
+ "max_bpm": max(values),
+ "samples": len(values),
+ }
+ ),
+ title=f"Avg {avg} bpm heart rate",
+ timestamp=datetime.fromisoformat(day),
+ metadata={"data_type": "heart_rate", "day": day},
+ )
+
+ @staticmethod
+ def _yield_energy_docs(
+ energy_by_day: Dict[str, float],
+ ) -> Iterator[Document]:
+ for day in sorted(energy_by_day):
+ total = round(energy_by_day[day], 1)
+ yield Document(
+ doc_id=f"apple_health-active_energy-{day}",
+ source="apple_health",
+ doc_type="active_energy",
+ content=json.dumps({"date": day, "kcal": total}),
+ title=f"{total} kcal active energy",
+ timestamp=datetime.fromisoformat(day),
+ metadata={"data_type": "active_energy", "day": day},
+ )
+
+ @staticmethod
+ def _yield_workout_docs(
+ workouts: List[Dict[str, Any]],
+ ) -> Iterator[Document]:
+ for w in workouts:
+ # Friendly activity name
+ raw = w["activity_type"]
+ activity = (
+ raw.replace("HKWorkoutActivityType", "")
+ if raw.startswith("HKWorkoutActivityType")
+ else raw
+ )
+
+ # Build a descriptive title
+ parts = [activity]
+ if w.get("total_distance"):
+ try:
+ parts.append(f"{float(w['total_distance']):.1f} km")
+ except (ValueError, TypeError):
+ pass
+ duration_s = w.get("duration_seconds", 0)
+ if duration_s:
+ parts.append(_format_duration(float(duration_s)))
+
+ title = " -- ".join(parts) if len(parts) > 1 else activity
+
+ # Deterministic doc_id from workout content
+ digest = hashlib.sha256(json.dumps(w, sort_keys=True).encode()).hexdigest()[
+ :12
+ ]
+ yield Document(
+ doc_id=f"apple_health-workout-{digest}",
+ source="apple_health",
+ doc_type="workout",
+ content=json.dumps(w),
+ title=title,
+ timestamp=datetime.fromisoformat(
+ _day_key(_parse_health_date(w["start"]))
+ ),
+ metadata={"data_type": "workout", "activity": activity},
+ )
diff --git a/src/openjarvis/connectors/apple_music.py b/src/openjarvis/connectors/apple_music.py
new file mode 100644
index 00000000..a8fb5033
--- /dev/null
+++ b/src/openjarvis/connectors/apple_music.py
@@ -0,0 +1,242 @@
+"""Apple Music connector -- reads tracks from the local Music.app via AppleScript.
+
+Uses ``osascript`` subprocess calls to query Music.app on macOS. No API keys
+or network access required; everything stays local.
+
+Requires macOS (``sys.platform == "darwin"``) and the Music app to be
+available.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import logging
+import subprocess
+import sys
+from datetime import datetime
+from typing import Iterator, Optional
+
+from openjarvis.connectors._stubs import BaseConnector, Document, SyncStatus
+from openjarvis.core.registry import ConnectorRegistry
+
+logger = logging.getLogger(__name__)
+
+# ---------------------------------------------------------------------------
+# AppleScript helpers
+# ---------------------------------------------------------------------------
+
+_LIBRARY_CHECK_SCRIPT = 'tell application "Music" to get name of playlist "Library"'
+
+_TRACKS_SCRIPT = """
+tell application "Music"
+ set output to ""
+ set allTracks to every track of playlist "Library"
+ repeat with t in allTracks
+ set trackName to name of t
+ set trackArtist to artist of t
+ set trackAlbum to album of t
+ set trackDuration to duration of t
+ set trackGenre to genre of t
+ set trackPlayCount to played count of t
+ try
+ set pd to played date of t as string
+ on error
+ set pd to "never"
+ end try
+ set sep to "|||"
+ set row to trackName & sep & trackArtist & sep & trackAlbum
+ set row to row & sep & trackDuration & sep & trackGenre
+ set row to row & sep & trackPlayCount & sep & pd
+ set output to output & row & linefeed
+ end repeat
+ return output
+end tell
+"""
+
+
+def _run_osascript(script: str, *, timeout: int = 120) -> Optional[str]:
+ """Execute an AppleScript via ``osascript`` and return stdout.
+
+ Returns None on failure.
+ """
+ try:
+ result = subprocess.run(
+ ["osascript", "-e", script],
+ capture_output=True,
+ text=True,
+ timeout=timeout,
+ )
+ if result.returncode == 0:
+ return result.stdout.strip()
+ logger.debug("osascript failed (rc=%d): %s", result.returncode, result.stderr)
+ return None
+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as exc:
+ logger.debug("osascript error: %s", exc)
+ return None
+
+
+def _track_doc_id(name: str, artist: str) -> str:
+ """Deterministic doc_id from track name + artist."""
+ key = f"{name}:{artist}"
+ h = hashlib.sha256(key.encode("utf-8")).hexdigest()[:12]
+ return f"apple_music-{h}"
+
+
+def _parse_played_date(raw: str) -> Optional[datetime]:
+ """Try to parse an AppleScript date string; return None if unparseable."""
+ if not raw or raw.strip().lower() == "never":
+ return None
+ # AppleScript renders dates in the user's locale. Common macOS formats:
+ # "Saturday, March 15, 2026 at 2:30:00 PM"
+ # "2026-03-15 14:30:00"
+ for fmt in (
+ "%A, %B %d, %Y at %I:%M:%S %p",
+ "%A, %B %d, %Y at %H:%M:%S",
+ "%Y-%m-%d %H:%M:%S",
+ "%m/%d/%Y %I:%M:%S %p",
+ "%d/%m/%Y %H:%M:%S",
+ ):
+ try:
+ return datetime.strptime(raw.strip(), fmt)
+ except ValueError:
+ continue
+ logger.debug("Could not parse played_date: %r", raw)
+ return None
+
+
+# ---------------------------------------------------------------------------
+# AppleMusicConnector
+# ---------------------------------------------------------------------------
+
+
[email protected]("apple_music")
+class AppleMusicConnector(BaseConnector):
+ """Read tracks from the local Music.app library via AppleScript.
+
+ Only works on macOS where ``osascript`` is available and Music.app is
+ installed (ships with the OS).
+ """
+
+ connector_id = "apple_music"
+ display_name = "Apple Music"
+ auth_type = "local"
+
+ def __init__(self) -> None:
+ self._status = SyncStatus()
+
+ # ------------------------------------------------------------------
+ # BaseConnector interface
+ # ------------------------------------------------------------------
+
+ def is_connected(self) -> bool:
+ """Return True if running on macOS and Music.app responds."""
+ if sys.platform != "darwin":
+ return False
+ result = _run_osascript(_LIBRARY_CHECK_SCRIPT, timeout=10)
+ return result is not None
+
+ def disconnect(self) -> None:
+ """No-op -- local connector with no credentials to revoke."""
+
+ def sync(
+ self,
+ *,
+ since: Optional[datetime] = None,
+ cursor: Optional[str] = None, # noqa: ARG002
+ ) -> Iterator[Document]:
+ """Query Music.app for all tracks and yield one Document per track.
+
+ Parameters
+ ----------
+ since:
+ If provided, only yield tracks whose last-played date is after
+ this datetime.
+ cursor:
+ Not used for this local connector (included for API
+ compatibility).
+
+ Yields
+ ------
+ Document
+ One document per track in the Music library.
+ """
+ raw = _run_osascript(_TRACKS_SCRIPT)
+ if raw is None:
+ logger.warning("Could not retrieve tracks from Music.app")
+ self._status.state = "error"
+ self._status.error = "AppleScript query failed"
+ return
+
+ lines = [line for line in raw.split("\n") if line.strip()]
+ self._status.items_total = len(lines)
+ synced = 0
+
+ for line in lines:
+ parts = line.split("|||")
+ if len(parts) < 7:
+ logger.debug("Skipping malformed line: %r", line)
+ continue
+
+ name = parts[0].strip()
+ artist = parts[1].strip()
+ album = parts[2].strip()
+ duration_raw = parts[3].strip()
+ genre = parts[4].strip()
+ play_count_raw = parts[5].strip()
+ played_date_raw = parts[6].strip()
+
+ # Parse numeric fields
+ try:
+ duration_s = round(float(duration_raw), 2)
+ except (ValueError, TypeError):
+ duration_s = 0.0
+ try:
+ play_count = int(play_count_raw)
+ except (ValueError, TypeError):
+ play_count = 0
+
+ played_date = _parse_played_date(played_date_raw)
+ timestamp = played_date if played_date else datetime.now()
+
+ # Apply since filter
+ if since is not None and played_date is not None:
+ if played_date <= since:
+ continue
+
+ track_data = {
+ "name": name,
+ "artist": artist,
+ "album": album,
+ "duration_s": duration_s,
+ "genre": genre,
+ "play_count": play_count,
+ "played_date": played_date_raw,
+ }
+
+ doc = Document(
+ doc_id=_track_doc_id(name, artist),
+ source="apple_music",
+ doc_type="track",
+ content=json.dumps(track_data),
+ title=f"{name} \u2014 {artist}",
+ author=artist,
+ timestamp=timestamp,
+ metadata={
+ "album": album,
+ "duration_s": duration_s,
+ "genre": genre,
+ "play_count": play_count,
+ },
+ )
+ synced += 1
+ yield doc
+
+ self._status.items_synced = synced
+ self._status.state = "idle"
+ self._status.last_sync = datetime.now()
+ self._status.error = None
+
+ def sync_status(self) -> SyncStatus:
+ """Return sync progress from the most recent :meth:`sync` call."""
+ return self._status
diff --git a/src/openjarvis/connectors/gcalendar.py b/src/openjarvis/connectors/gcalendar.py
index bc730d96..5a3d68d3 100644
--- a/src/openjarvis/connectors/gcalendar.py
+++ b/src/openjarvis/connectors/gcalendar.py
@@ -14,9 +14,11 @@ import httpx
from openjarvis.connectors._stubs import BaseConnector, Document, SyncStatus
from openjarvis.connectors.oauth import (
+ GOOGLE_ALL_SCOPES,
build_google_auth_url,
delete_tokens,
load_tokens,
+ resolve_google_credentials,
run_oauth_flow,
save_tokens,
)
@@ -204,7 +206,9 @@ class GCalendarConnector(BaseConnector):
auth_type = "oauth"
def __init__(self, credentials_path: str = "") -> None:
- self._credentials_path = credentials_path or _DEFAULT_CREDENTIALS_PATH
+ self._credentials_path = resolve_google_credentials(
+ credentials_path or _DEFAULT_CREDENTIALS_PATH
+ )
self._items_synced: int = 0
self._items_total: int = 0
self._last_sync: Optional[datetime] = None
@@ -236,7 +240,7 @@ class GCalendarConnector(BaseConnector):
return "https://console.cloud.google.com/apis/credentials"
return build_google_auth_url(
client_id=client_id,
- scopes=[_GCAL_SCOPE],
+ scopes=GOOGLE_ALL_SCOPES,
)
def handle_callback(self, code: str) -> None:
@@ -265,7 +269,7 @@ class GCalendarConnector(BaseConnector):
run_oauth_flow(
client_id=client_id.strip(),
client_secret=client_secret.strip(),
- scopes=[_GCAL_SCOPE],
+ scopes=GOOGLE_ALL_SCOPES,
credentials_path=self._credentials_path,
)
except Exception: # noqa: BLE001
diff --git a/src/openjarvis/connectors/gcontacts.py b/src/openjarvis/connectors/gcontacts.py
index 88350b65..58852ba9 100644
--- a/src/openjarvis/connectors/gcontacts.py
+++ b/src/openjarvis/connectors/gcontacts.py
@@ -14,9 +14,11 @@ import httpx
from openjarvis.connectors._stubs import BaseConnector, Document, SyncStatus
from openjarvis.connectors.oauth import (
+ GOOGLE_ALL_SCOPES,
build_google_auth_url,
delete_tokens,
load_tokens,
+ resolve_google_credentials,
run_oauth_flow,
save_tokens,
)
@@ -151,7 +153,9 @@ class GContactsConnector(BaseConnector):
auth_type = "oauth"
def __init__(self, credentials_path: str = "") -> None:
- self._credentials_path = credentials_path or _DEFAULT_CREDENTIALS_PATH
+ self._credentials_path = resolve_google_credentials(
+ credentials_path or _DEFAULT_CREDENTIALS_PATH
+ )
self._items_synced: int = 0
self._items_total: int = 0
self._last_sync: Optional[datetime] = None
@@ -183,7 +187,7 @@ class GContactsConnector(BaseConnector):
return "https://console.cloud.google.com/apis/credentials"
return build_google_auth_url(
client_id=client_id,
- scopes=[_GCONTACTS_SCOPE],
+ scopes=GOOGLE_ALL_SCOPES,
)
def handle_callback(self, code: str) -> None:
@@ -212,7 +216,7 @@ class GContactsConnector(BaseConnector):
run_oauth_flow(
client_id=client_id.strip(),
client_secret=client_secret.strip(),
- scopes=[_GCONTACTS_SCOPE],
+ scopes=GOOGLE_ALL_SCOPES,
credentials_path=self._credentials_path,
)
except Exception: # noqa: BLE001
diff --git a/src/openjarvis/connectors/gdrive.py b/src/openjarvis/connectors/gdrive.py
index 19e912a1..18cf0455 100644
--- a/src/openjarvis/connectors/gdrive.py
+++ b/src/openjarvis/connectors/gdrive.py
@@ -14,9 +14,11 @@ import httpx
from openjarvis.connectors._stubs import BaseConnector, Document, SyncStatus
from openjarvis.connectors.oauth import (
+ GOOGLE_ALL_SCOPES,
build_google_auth_url,
delete_tokens,
load_tokens,
+ resolve_google_credentials,
run_oauth_flow,
save_tokens,
)
@@ -134,7 +136,9 @@ class GDriveConnector(BaseConnector):
auth_type = "oauth"
def __init__(self, credentials_path: str = "") -> None:
- self._credentials_path = credentials_path or _DEFAULT_CREDENTIALS_PATH
+ self._credentials_path = resolve_google_credentials(
+ credentials_path or _DEFAULT_CREDENTIALS_PATH
+ )
self._items_synced: int = 0
self._items_total: int = 0
self._last_sync: Optional[datetime] = None
@@ -166,7 +170,7 @@ class GDriveConnector(BaseConnector):
return "https://console.cloud.google.com/apis/credentials"
return build_google_auth_url(
client_id=client_id,
- scopes=[_GDRIVE_SCOPE],
+ scopes=GOOGLE_ALL_SCOPES,
)
def handle_callback(self, code: str) -> None:
@@ -197,7 +201,7 @@ class GDriveConnector(BaseConnector):
run_oauth_flow(
client_id=client_id.strip(),
client_secret=client_secret.strip(),
- scopes=[_GDRIVE_SCOPE],
+ scopes=GOOGLE_ALL_SCOPES,
credentials_path=self._credentials_path,
)
except Exception: # noqa: BLE001
diff --git a/src/openjarvis/connectors/gmail.py b/src/openjarvis/connectors/gmail.py
index 5c0a9959..9412ae2d 100644
--- a/src/openjarvis/connectors/gmail.py
+++ b/src/openjarvis/connectors/gmail.py
@@ -16,9 +16,11 @@ import httpx
from openjarvis.connectors._stubs import BaseConnector, Document, SyncStatus
from openjarvis.connectors.oauth import (
+ GOOGLE_ALL_SCOPES,
build_google_auth_url,
delete_tokens,
load_tokens,
+ resolve_google_credentials,
save_tokens,
)
from openjarvis.core.config import DEFAULT_CONFIG_DIR
@@ -184,7 +186,9 @@ class GmailConnector(BaseConnector):
auth_type = "oauth"
def __init__(self, credentials_path: str = "") -> None:
- self._credentials_path = credentials_path or _DEFAULT_CREDENTIALS_PATH
+ self._credentials_path = resolve_google_credentials(
+ credentials_path or _DEFAULT_CREDENTIALS_PATH
+ )
self._items_synced: int = 0
self._items_total: int = 0
self._last_sync: Optional[datetime] = None
@@ -211,7 +215,7 @@ class GmailConnector(BaseConnector):
"""Return a Google OAuth consent URL requesting ``gmail.readonly`` scope."""
return build_google_auth_url(
client_id="", # placeholder — real client_id from config
- scopes=[_GMAIL_SCOPE],
+ scopes=GOOGLE_ALL_SCOPES,
)
def handle_callback(self, code: str) -> None:
diff --git a/src/openjarvis/connectors/google_tasks.py b/src/openjarvis/connectors/google_tasks.py
new file mode 100644
index 00000000..eff4490a
--- /dev/null
+++ b/src/openjarvis/connectors/google_tasks.py
@@ -0,0 +1,120 @@
+"""Google Tasks connector — tasks due today, overdue, and recently completed.
+
+Uses OAuth2 tokens via the shared Google OAuth helper module.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+from typing import Any, Dict, Iterator, Optional
+
+import httpx
+
+from openjarvis.connectors._stubs import BaseConnector, Document, SyncStatus
+from openjarvis.connectors.oauth import load_tokens, resolve_google_credentials
+from openjarvis.core.config import DEFAULT_CONFIG_DIR
+from openjarvis.core.registry import ConnectorRegistry
+
+_TASKS_API_BASE = "https://tasks.googleapis.com/tasks/v1"
+_DEFAULT_CREDENTIALS_PATH = str(
+ DEFAULT_CONFIG_DIR / "connectors" / "google_tasks.json"
+)
+
+
+def _tasks_api_get(
+ token: str, endpoint: str, params: Optional[Dict[str, str]] = None
+) -> Dict[str, Any]:
+ """Call a Google Tasks API v1 endpoint."""
+ resp = httpx.get(
+ f"{_TASKS_API_BASE}/{endpoint}",
+ headers={"Authorization": f"Bearer {token}"},
+ params=params or {},
+ timeout=30.0,
+ )
+ resp.raise_for_status()
+ return resp.json()
+
+
[email protected]("google_tasks")
+class GoogleTasksConnector(BaseConnector):
+ """Sync tasks from Google Tasks."""
+
+ connector_id = "google_tasks"
+ display_name = "Google Tasks"
+ auth_type = "oauth"
+
+ def __init__(self, *, credentials_path: str = "") -> None:
+ self._credentials_path = Path(
+ resolve_google_credentials(
+ credentials_path or _DEFAULT_CREDENTIALS_PATH
+ )
+ )
+ self._status = SyncStatus()
+
+ def _get_access_token(self) -> str:
+ tokens = load_tokens(str(self._credentials_path))
+ return tokens.get("access_token") or tokens.get("token", "")
+
+ def is_connected(self) -> bool:
+ return self._credentials_path.exists()
+
+ def disconnect(self) -> None:
+ if self._credentials_path.exists():
+ self._credentials_path.unlink()
+
+ def sync(
+ self, *, since: Optional[datetime] = None, cursor: Optional[str] = None
+ ) -> Iterator[Document]:
+ token = self._get_access_token()
+
+ # List all task lists first
+ task_lists = _tasks_api_get(token, "users/@me/lists")
+
+ for tl in task_lists.get("items", []):
+ tl_id = tl["id"]
+ tl_title = tl.get("title", "My Tasks")
+
+ # Get tasks from this list, updated since cutoff
+ params: Dict[str, str] = {
+ "showCompleted": "true",
+ "showHidden": "false",
+ }
+ if since:
+ params["updatedMin"] = since.isoformat() + "Z"
+
+ tasks = _tasks_api_get(token, f"lists/{tl_id}/tasks", params=params)
+
+ for task in tasks.get("items", []):
+ due = task.get("due", "")
+ status = task.get("status", "needsAction")
+
+ ts = (
+ datetime.fromisoformat(
+ task.get("updated", "").replace("Z", "+00:00")
+ )
+ if task.get("updated")
+ else datetime.now()
+ )
+
+ yield Document(
+ doc_id=f"gtasks-{task['id']}",
+ source="google_tasks",
+ doc_type="task",
+ content=task.get("notes", ""),
+ title=task.get("title", "Untitled Task"),
+ timestamp=ts,
+ url=task.get("selfLink", ""),
+ metadata={
+ "task_list": tl_title,
+ "status": status,
+ "due": due,
+ "completed": task.get("completed", ""),
+ },
+ )
+
+ self._status.state = "idle"
+ self._status.last_sync = datetime.now()
+
+ def sync_status(self) -> SyncStatus:
+ return self._status
diff --git a/src/openjarvis/connectors/oauth.py b/src/openjarvis/connectors/oauth.py
index 4283236a..998347c8 100644
--- a/src/openjarvis/connectors/oauth.py
+++ b/src/openjarvis/connectors/oauth.py
@@ -1,21 +1,186 @@
-"""Shared OAuth 2.0 helpers for Google connectors.
+"""Shared OAuth 2.0 helpers for all connectors.
-Provides URL builder, token persistence, and token cleanup utilities
-that are reused by gmail, drive, calendar, and contacts connectors.
+Provides:
+- ``OAuthProvider`` registry with configs for Google, Strava, Spotify
+- Generic ``run_connector_oauth()`` that opens browser + catches callback
+- URL builder, token persistence, and token cleanup utilities
"""
from __future__ import annotations
+import base64
import json
import os
+from dataclasses import dataclass, field
from pathlib import Path
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urlencode
+from openjarvis.core.config import DEFAULT_CONFIG_DIR
+
+# ---------------------------------------------------------------------------
+# Connector credentials directory
+# ---------------------------------------------------------------------------
+
+_CONNECTORS_DIR = DEFAULT_CONFIG_DIR / "connectors"
+
# ---------------------------------------------------------------------------
-# Google OAuth endpoints / defaults
+# OAuth provider registry
# ---------------------------------------------------------------------------
+
+@dataclass(frozen=True)
+class OAuthProvider:
+ """Configuration for an OAuth 2.0 provider."""
+
+ name: str # "google", "strava", "spotify"
+ display_name: str
+ auth_endpoint: str
+ token_endpoint: str
+ scopes: List[str]
+ setup_url: str # URL where user creates OAuth credentials
+ setup_hint: str # One-line instruction for setup
+ callback_port: int = 8789
+ callback_host: str = "127.0.0.1"
+ callback_path: str = "/callback"
+ token_auth: str = "body" # "body" or "basic"
+ extra_auth_params: Dict[str, str] = field(default_factory=dict)
+ # Which connector IDs this provider covers (one flow → all connected)
+ connector_ids: Tuple[str, ...] = ()
+ # Filenames in ~/.openjarvis/connectors/ to save tokens to
+ credential_files: Tuple[str, ...] = ()
+
+
+# Combined scopes for all Google connectors so a single OAuth consent
+# authorises Drive, Calendar, Contacts, Gmail, and Tasks at once.
+GOOGLE_ALL_SCOPES: List[str] = [
+ "openid",
+ "email",
+ "profile",
+ "https://www.googleapis.com/auth/drive.readonly",
+ "https://www.googleapis.com/auth/calendar.readonly",
+ "https://www.googleapis.com/auth/contacts.readonly",
+ "https://www.googleapis.com/auth/gmail.readonly",
+ "https://www.googleapis.com/auth/tasks.readonly",
+]
+
+OAUTH_PROVIDERS: Dict[str, OAuthProvider] = {
+ "google": OAuthProvider(
+ name="google",
+ display_name="Google",
+ auth_endpoint="https://accounts.google.com/o/oauth2/v2/auth",
+ token_endpoint="https://oauth2.googleapis.com/token",
+ scopes=GOOGLE_ALL_SCOPES,
+ setup_url="https://console.cloud.google.com/apis/credentials",
+ setup_hint="Create an OAuth 2.0 Client ID (Desktop app type)",
+ extra_auth_params={"access_type": "offline", "prompt": "consent"},
+ connector_ids=(
+ "gdrive",
+ "gcalendar",
+ "gcontacts",
+ "gmail",
+ "google_tasks",
+ ),
+ credential_files=(
+ "google.json",
+ "gdrive.json",
+ "gcalendar.json",
+ "gcontacts.json",
+ "gmail.json",
+ "google_tasks.json",
+ ),
+ ),
+ "strava": OAuthProvider(
+ name="strava",
+ display_name="Strava",
+ auth_endpoint="https://www.strava.com/oauth/authorize",
+ token_endpoint="https://www.strava.com/oauth/token",
+ scopes=["activity:read_all"],
+ setup_url="https://www.strava.com/settings/api",
+ setup_hint="Create an API Application (callback domain: localhost)",
+ connector_ids=("strava",),
+ credential_files=("strava.json",),
+ ),
+ "spotify": OAuthProvider(
+ name="spotify",
+ display_name="Spotify",
+ auth_endpoint="https://accounts.spotify.com/authorize",
+ token_endpoint="https://accounts.spotify.com/api/token",
+ scopes=["user-read-recently-played"],
+ setup_url="https://developer.spotify.com/dashboard",
+ setup_hint=(
+ "Create an app, add redirect URI: "
+ "http://127.0.0.1:8888/callback"
+ ),
+ callback_port=8888,
+ token_auth="basic",
+ connector_ids=("spotify",),
+ credential_files=("spotify.json",),
+ ),
+}
+
+
+def get_provider_for_connector(connector_id: str) -> Optional[OAuthProvider]:
+ """Return the OAuthProvider that covers *connector_id*, or ``None``."""
+ for provider in OAUTH_PROVIDERS.values():
+ if connector_id in provider.connector_ids:
+ return provider
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Credential helpers
+# ---------------------------------------------------------------------------
+
+
+def get_client_credentials(
+ provider: OAuthProvider,
+) -> Optional[Tuple[str, str]]:
+ """Load stored client_id and client_secret for *provider*.
+
+ Checks credential files in ``~/.openjarvis/connectors/`` and falls
+ back to environment variables ``OPENJARVIS_{NAME}_CLIENT_ID`` and
+ ``OPENJARVIS_{NAME}_CLIENT_SECRET``.
+ """
+ # Check credential files
+ for filename in provider.credential_files:
+ path = _CONNECTORS_DIR / filename
+ tokens = load_tokens(str(path))
+ if tokens and tokens.get("client_id") and tokens.get("client_secret"):
+ return tokens["client_id"], tokens["client_secret"]
+
+ # Check environment variables
+ prefix = f"OPENJARVIS_{provider.name.upper()}"
+ env_id = os.environ.get(f"{prefix}_CLIENT_ID", "")
+ env_secret = os.environ.get(f"{prefix}_CLIENT_SECRET", "")
+ if env_id and env_secret:
+ return env_id, env_secret
+
+ return None
+
+
+def save_client_credentials(
+ provider: OAuthProvider,
+ client_id: str,
+ client_secret: str,
+) -> None:
+ """Persist client credentials so the user never has to enter them again."""
+ for filename in provider.credential_files:
+ path = _CONNECTORS_DIR / filename
+ existing = load_tokens(str(path)) or {}
+ existing["client_id"] = client_id
+ existing["client_secret"] = client_secret
+ save_tokens(str(path), existing)
+
+
+# ---------------------------------------------------------------------------
+# Shared credentials file — one OAuth flow covers all Google connectors
+# ---------------------------------------------------------------------------
+
+_SHARED_GOOGLE_CREDENTIALS_PATH: str = str(
+ _CONNECTORS_DIR / "google.json"
+)
+
_GOOGLE_AUTH_ENDPOINT = "https://accounts.google.com/o/oauth2/v2/auth"
_DEFAULT_REDIRECT_URI = "http://localhost:8789/callback"
_DEFAULT_SCOPES: List[str] = ["openid", "email", "profile"]
@@ -63,6 +228,20 @@ def build_google_auth_url(
return f"{_GOOGLE_AUTH_ENDPOINT}?{urlencode(params)}"
+def resolve_google_credentials(connector_path: str) -> str:
+ """Return the best available Google credentials file path.
+
+ Checks the connector-specific file first, then falls back to the
+ shared ``google.json``. Returns *connector_path* if neither exists
+ (so ``is_connected()`` correctly returns ``False``).
+ """
+ if Path(connector_path).exists():
+ return connector_path
+ if Path(_SHARED_GOOGLE_CREDENTIALS_PATH).exists():
+ return _SHARED_GOOGLE_CREDENTIALS_PATH
+ return connector_path
+
+
def load_tokens(path: str) -> Optional[Dict[str, Any]]:
"""Load OAuth tokens from a JSON file.
@@ -281,16 +460,214 @@ def run_oauth_flow(
)
# Persist tokens together with client credentials (needed for refresh)
- save_tokens(
- credentials_path,
- {
- "access_token": tokens.get("access_token", ""),
- "refresh_token": tokens.get("refresh_token", ""),
- "token_type": tokens.get("token_type", "Bearer"),
- "expires_in": tokens.get("expires_in", 3600),
- "client_id": client_id,
- "client_secret": client_secret,
- },
+ token_payload = {
+ "access_token": tokens.get("access_token", ""),
+ "refresh_token": tokens.get("refresh_token", ""),
+ "token_type": tokens.get("token_type", "Bearer"),
+ "expires_in": tokens.get("expires_in", 3600),
+ "client_id": client_id,
+ "client_secret": client_secret,
+ }
+ save_tokens(credentials_path, token_payload)
+
+ # Also save to the shared Google credentials file so that all Google
+ # connectors can use this token without a separate OAuth flow.
+ if credentials_path != _SHARED_GOOGLE_CREDENTIALS_PATH:
+ save_tokens(_SHARED_GOOGLE_CREDENTIALS_PATH, token_payload)
+
+ return tokens
+
+
+# ---------------------------------------------------------------------------
+# Generic OAuth flow — works with any OAuthProvider
+# ---------------------------------------------------------------------------
+
+
+def _wait_for_callback_code(
+ host: str = "127.0.0.1",
+ port: int = 8789,
+ path: str = "/callback",
+ timeout: int = 120,
+) -> str:
+ """Start a localhost HTTP server and wait for ``?code=`` on *path*.
+
+ Returns the authorization code received from the OAuth redirect.
+ """
+ from http.server import BaseHTTPRequestHandler, HTTPServer
+ from urllib.parse import parse_qs, urlparse
+
+ auth_code: List[str] = []
+ error: List[str] = []
+
+ class _Handler(BaseHTTPRequestHandler):
+ def do_GET(self) -> None: # noqa: N802
+ params = parse_qs(urlparse(self.path).query)
+ if "code" in params:
+ auth_code.append(params["code"][0])
+ self.send_response(200)
+ self.send_header("Content-Type", "text/html")
+ self.end_headers()
+ self.wfile.write(
+ b"<html><body style='font-family:system-ui;text-align:center;"
+ b"padding:60px'>"
+ b"<h2 style='color:#22c55e'>Connected!</h2>"
+ b"<p>You can close this tab and return to OpenJarvis.</p>"
+ b"</body></html>"
+ )
+ elif "error" in params:
+ error.append(params.get("error", ["unknown"])[0])
+ self.send_response(400)
+ self.send_header("Content-Type", "text/html")
+ self.end_headers()
+ self.wfile.write(
+ b"<html><body style='font-family:system-ui;text-align:center;"
+ b"padding:60px'>"
+ b"<h2 style='color:#ef4444'>Authorization Failed</h2>"
+ b"<p>Please close this tab and try again.</p>"
+ b"</body></html>"
+ )
+ else:
+ self.send_response(400)
+ self.end_headers()
+
+ def log_message(self, *_args: Any) -> None:
+ pass
+
+ # Ensure port is free
+ import socket
+
+ test_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ try:
+ test_sock.bind((host, port))
+ except OSError:
+ pass
+ finally:
+ test_sock.close()
+
+ import time
+
+ time.sleep(0.3)
+
+ server = HTTPServer((host, port), _Handler)
+ server.timeout = timeout
+
+ while not auth_code and not error:
+ server.handle_request()
+ server.server_close()
+
+ if error:
+ raise RuntimeError(f"OAuth authorization denied: {error[0]}")
+ if not auth_code:
+ raise RuntimeError("OAuth callback timed out")
+ return auth_code[0]
+
+
+def _exchange_token(
+ provider: OAuthProvider,
+ code: str,
+ client_id: str,
+ client_secret: str,
+ redirect_uri: str,
+) -> Dict[str, Any]:
+ """Exchange an authorization *code* for tokens using *provider* config."""
+ import httpx
+
+ data: Dict[str, str] = {
+ "code": code,
+ "redirect_uri": redirect_uri,
+ "grant_type": "authorization_code",
+ }
+ headers: Dict[str, str] = {}
+
+ if provider.token_auth == "basic":
+ creds = base64.b64encode(
+ f"{client_id}:{client_secret}".encode()
+ ).decode()
+ headers["Authorization"] = f"Basic {creds}"
+ else:
+ data["client_id"] = client_id
+ data["client_secret"] = client_secret
+
+ resp = httpx.post(
+ provider.token_endpoint, data=data, headers=headers, timeout=30.0
+ )
+ resp.raise_for_status()
+ return resp.json()
+
+
+def run_connector_oauth(
+ connector_id: str,
+ client_id: str = "",
+ client_secret: str = "",
+) -> Dict[str, Any]:
+ """Run a complete OAuth flow for *connector_id*.
+
+ 1. Look up the ``OAuthProvider``
+ 2. Resolve client credentials (arg → stored → env)
+ 3. Build auth URL and open the user's browser
+ 4. Start localhost callback server and wait for the code
+ 5. Exchange the code for tokens
+ 6. Save tokens to all relevant credential files
+
+ Returns the raw token response dict.
+ """
+ import webbrowser
+
+ provider = get_provider_for_connector(connector_id)
+ if provider is None:
+ raise ValueError(f"No OAuth provider configured for '{connector_id}'")
+
+ # Resolve credentials
+ if not (client_id and client_secret):
+ creds = get_client_credentials(provider)
+ if creds:
+ client_id, client_secret = creds
+ if not (client_id and client_secret):
+ raise RuntimeError(
+ f"No client credentials for {provider.display_name}. "
+ f"Set them up at: {provider.setup_url}"
+ )
+
+ redirect_uri = (
+ f"http://{provider.callback_host}:{provider.callback_port}"
+ f"{provider.callback_path}"
+ )
+
+ # Build auth URL
+ params: Dict[str, str] = {
+ "client_id": client_id,
+ "redirect_uri": redirect_uri,
+ "response_type": "code",
+ "scope": " ".join(provider.scopes),
+ **provider.extra_auth_params,
+ }
+ auth_url = f"{provider.auth_endpoint}?{urlencode(params)}"
+
+ # Open browser and wait for callback
+ webbrowser.open(auth_url)
+ code = _wait_for_callback_code(
+ host=provider.callback_host,
+ port=provider.callback_port,
+ path=provider.callback_path,
+ )
+
+ # Exchange code for tokens
+ tokens = _exchange_token(
+ provider, code, client_id, client_secret, redirect_uri
)
+ # Build payload with client credentials included (needed for refresh)
+ payload = {
+ "access_token": tokens.get("access_token", ""),
+ "refresh_token": tokens.get("refresh_token", ""),
+ "token_type": tokens.get("token_type", "Bearer"),
+ "expires_in": tokens.get("expires_in", 3600),
+ "client_id": client_id,
+ "client_secret": client_secret,
+ }
+
+ # Save to all credential files for this provider
+ for filename in provider.credential_files:
+ save_tokens(str(_CONNECTORS_DIR / filename), payload)
+
return tokens
diff --git a/src/openjarvis/connectors/oura.py b/src/openjarvis/connectors/oura.py
new file mode 100644
index 00000000..a5969448
--- /dev/null
+++ b/src/openjarvis/connectors/oura.py
@@ -0,0 +1,90 @@
+"""Oura Ring connector — sleep, readiness, and activity via REST API v2.
+
+Uses a Personal Access Token (PAT) stored in the connector config dir.
+All API calls are in module-level functions for easy mocking in tests.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime, timedelta
+from pathlib import Path
+from typing import Any, Dict, Iterator, Optional
+
+import httpx
+
+from openjarvis.connectors._stubs import BaseConnector, Document, SyncStatus
+from openjarvis.core.config import DEFAULT_CONFIG_DIR
+from openjarvis.core.registry import ConnectorRegistry
+
+_OURA_API_BASE = "https://api.ouraring.com/v2/usercollection"
+_DEFAULT_TOKEN_PATH = str(DEFAULT_CONFIG_DIR / "connectors" / "oura.json")
+
+
+def _oura_api_get(
+ token: str, endpoint: str, params: Optional[Dict[str, str]] = None
+) -> Dict[str, Any]:
+ """Call an Oura API v2 endpoint."""
+ resp = httpx.get(
+ f"{_OURA_API_BASE}/{endpoint}",
+ headers={"Authorization": f"Bearer {token}"},
+ params=params or {},
+ timeout=30.0,
+ )
+ resp.raise_for_status()
+ return resp.json()
+
+
+class OuraConnector(BaseConnector):
+ """Sync sleep, readiness, and activity data from Oura Ring."""
+
+ connector_id = "oura"
+ display_name = "Oura Ring"
+ auth_type = "token"
+
+ def __init__(self, *, token_path: str = _DEFAULT_TOKEN_PATH) -> None:
+ self._token_path = Path(token_path)
+ self._status = SyncStatus()
+
+ def _load_token(self) -> str:
+ """Load the Oura PAT from disk."""
+ data = json.loads(self._token_path.read_text(encoding="utf-8"))
+ return data["token"]
+
+ def is_connected(self) -> bool:
+ return self._token_path.exists()
+
+ def disconnect(self) -> None:
+ if self._token_path.exists():
+ self._token_path.unlink()
+
+ def sync(
+ self, *, since: Optional[datetime] = None, cursor: Optional[str] = None
+ ) -> Iterator[Document]:
+ """Yield Documents for sleep, readiness, and activity."""
+ token = self._load_token()
+ start = (since or datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d")
+ end = datetime.now().strftime("%Y-%m-%d")
+
+ for data_type in ("sleep", "daily_readiness", "daily_activity"):
+ data = _oura_api_get(
+ token, data_type, params={"start_date": start, "end_date": end}
+ )
+ for item in data.get("data", []):
+ day = item.get("day", start)
+ yield Document(
+ doc_id=f"oura-{data_type}-{day}",
+ source="oura",
+ doc_type=data_type,
+ content=json.dumps(item),
+ title=f"Oura {data_type.replace('_', ' ').title()} — {day}",
+ timestamp=datetime.fromisoformat(day),
+ metadata={"data_type": data_type, "day": day},
+ )
+
+ self._status.state = "idle"
+ self._status.last_sync = datetime.now()
+
+ def sync_status(self) -> SyncStatus:
+ return self._status
diff --git a/src/openjarvis/connectors/spotify.py b/src/openjarvis/connectors/spotify.py
new file mode 100644
index 00000000..b11655e0
--- /dev/null
+++ b/src/openjarvis/connectors/spotify.py
@@ -0,0 +1,157 @@
+"""Spotify connector — recently played tracks via Spotify Web API.
+
+Uses OAuth2 tokens stored locally. Requires user-read-recently-played scope.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime, timedelta
+from pathlib import Path
+from typing import Any, Dict, Iterator, Optional
+
+import httpx
+
+from openjarvis.connectors._stubs import BaseConnector, Document, SyncStatus
+from openjarvis.core.config import DEFAULT_CONFIG_DIR
+from openjarvis.core.registry import ConnectorRegistry
+
+_SPOTIFY_API_BASE = "https://api.spotify.com/v1"
+_SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token"
+_DEFAULT_TOKEN_PATH = str(DEFAULT_CONFIG_DIR / "connectors" / "spotify.json")
+
+
+def _spotify_api_get(
+ token: str, endpoint: str, params: Optional[Dict[str, Any]] = None
+) -> Dict[str, Any]:
+ """Call a Spotify Web API endpoint."""
+ resp = httpx.get(
+ f"{_SPOTIFY_API_BASE}/{endpoint}",
+ headers={"Authorization": f"Bearer {token}"},
+ params=params or {},
+ timeout=30.0,
+ )
+ resp.raise_for_status()
+ return resp.json()
+
+
+class SpotifyConnector(BaseConnector):
+ """Sync recently played tracks from Spotify."""
+
+ connector_id = "spotify"
+ display_name = "Spotify"
+ auth_type = "oauth"
+
+ def __init__(self, *, token_path: str = _DEFAULT_TOKEN_PATH) -> None:
+ self._token_path = Path(token_path)
+ self._status = SyncStatus()
+
+ def _load_tokens(self) -> Dict[str, str]:
+ return json.loads(self._token_path.read_text(encoding="utf-8"))
+
+ def _get_access_token(self) -> str:
+ return self._load_tokens()["access_token"]
+
+ def is_connected(self) -> bool:
+ return self._token_path.exists()
+
+ def disconnect(self) -> None:
+ if self._token_path.exists():
+ self._token_path.unlink()
+
+ def auth_url(self) -> str:
+ """Return Spotify OAuth authorization URL."""
+ from urllib.parse import urlencode
+
+ from openjarvis.connectors.oauth import (
+ get_client_credentials,
+ get_provider_for_connector,
+ )
+
+ provider = get_provider_for_connector("spotify")
+ if not provider:
+ return "https://developer.spotify.com/dashboard"
+ creds = get_client_credentials(provider)
+ if not creds:
+ return "https://developer.spotify.com/dashboard"
+ client_id, _ = creds
+ redirect_uri = f"http://{provider.callback_host}:{provider.callback_port}{provider.callback_path}"
+ params = {
+ "client_id": client_id,
+ "redirect_uri": redirect_uri,
+ "response_type": "code",
+ "scope": " ".join(provider.scopes),
+ }
+ return f"{provider.auth_endpoint}?{urlencode(params)}"
+
+ def handle_callback(self, code: str) -> None:
+ """Exchange authorization code for tokens and save."""
+ from openjarvis.connectors.oauth import (
+ _CONNECTORS_DIR,
+ _exchange_token,
+ get_client_credentials,
+ get_provider_for_connector,
+ save_tokens,
+ )
+
+ provider = get_provider_for_connector("spotify")
+ creds = get_client_credentials(provider) if provider else None
+ if not provider or not creds:
+ raise RuntimeError("Spotify client credentials not configured")
+ client_id, client_secret = creds
+ redirect_uri = f"http://{provider.callback_host}:{provider.callback_port}{provider.callback_path}"
+ tokens = _exchange_token(provider, code, client_id, client_secret, redirect_uri)
+ payload = {
+ "access_token": tokens.get("access_token", ""),
+ "refresh_token": tokens.get("refresh_token", ""),
+ "client_id": client_id,
+ "client_secret": client_secret,
+ }
+ for filename in provider.credential_files:
+ save_tokens(str(_CONNECTORS_DIR / filename), payload)
+
+ def sync(
+ self, *, since: Optional[datetime] = None, cursor: Optional[str] = None
+ ) -> Iterator[Document]:
+ token = self._get_access_token()
+ after_ms = int((since or datetime.now() - timedelta(days=1)).timestamp() * 1000)
+
+ data = _spotify_api_get(
+ token,
+ "me/player/recently-played",
+ params={"limit": "50", "after": str(after_ms)},
+ )
+
+ for item in data.get("items", []):
+ track = item.get("track", {})
+ played_at = item.get("played_at", "")
+ artists = ", ".join(a["name"] for a in track.get("artists", []))
+
+ ts = (
+ datetime.fromisoformat(played_at.replace("Z", "+00:00"))
+ if played_at
+ else datetime.now()
+ )
+
+ yield Document(
+ doc_id=f"spotify-{track.get('id', '')}-{played_at}",
+ source="spotify",
+ doc_type="recently_played",
+ content=json.dumps(item),
+ title=f"{track.get('name', 'Unknown')} — {artists}",
+ author=artists,
+ timestamp=ts,
+ url=track.get("external_urls", {}).get("spotify", ""),
+ metadata={
+ "track_name": track.get("name", ""),
+ "album": track.get("album", {}).get("name", ""),
+ "duration_ms": track.get("duration_ms", 0),
+ },
+ )
+
+ self._status.state = "idle"
+ self._status.last_sync = datetime.now()
+
+ def sync_status(self) -> SyncStatus:
+ return self._status
diff --git a/src/openjarvis/connectors/strava.py b/src/openjarvis/connectors/strava.py
new file mode 100644
index 00000000..c641ab9b
--- /dev/null
+++ b/src/openjarvis/connectors/strava.py
@@ -0,0 +1,173 @@
+"""Strava connector — recent activities via REST API v3.
+
+Uses OAuth2 tokens stored locally. Refresh handled automatically.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime, timedelta
+from pathlib import Path
+from typing import Any, Dict, Iterator, Optional
+
+import httpx
+
+from openjarvis.connectors._stubs import BaseConnector, Document, SyncStatus
+from openjarvis.core.config import DEFAULT_CONFIG_DIR
+from openjarvis.core.registry import ConnectorRegistry
+
+_STRAVA_API_BASE = "https://www.strava.com/api/v3"
+_STRAVA_TOKEN_URL = "https://www.strava.com/oauth/token"
+_DEFAULT_TOKEN_PATH = str(DEFAULT_CONFIG_DIR / "connectors" / "strava.json")
+
+
+def _strava_api_get(
+ token: str, endpoint: str, params: Optional[Dict[str, Any]] = None
+) -> Any:
+ """Call a Strava API v3 endpoint."""
+ resp = httpx.get(
+ f"{_STRAVA_API_BASE}/{endpoint}",
+ headers={"Authorization": f"Bearer {token}"},
+ params=params or {},
+ timeout=30.0,
+ )
+ resp.raise_for_status()
+ return resp.json()
+
+
+def _strava_refresh_token(
+ client_id: str, client_secret: str, refresh_token: str
+) -> Dict[str, Any]:
+ """Refresh an expired Strava OAuth2 token."""
+ resp = httpx.post(
+ _STRAVA_TOKEN_URL,
+ data={
+ "client_id": client_id,
+ "client_secret": client_secret,
+ "refresh_token": refresh_token,
+ "grant_type": "refresh_token",
+ },
+ timeout=30.0,
+ )
+ resp.raise_for_status()
+ return resp.json()
+
+
+class StravaConnector(BaseConnector):
+ """Sync recent activities from Strava."""
+
+ connector_id = "strava"
+ display_name = "Strava"
+ auth_type = "oauth"
+
+ def __init__(self, *, token_path: str = _DEFAULT_TOKEN_PATH) -> None:
+ self._token_path = Path(token_path)
+ self._status = SyncStatus()
+
+ def _load_tokens(self) -> Dict[str, str]:
+ return json.loads(self._token_path.read_text(encoding="utf-8"))
+
+ def _save_tokens(self, tokens: Dict[str, str]) -> None:
+ self._token_path.write_text(json.dumps(tokens), encoding="utf-8")
+
+ def _get_access_token(self) -> str:
+ tokens = self._load_tokens()
+ return tokens["access_token"]
+
+ def is_connected(self) -> bool:
+ return self._token_path.exists()
+
+ def disconnect(self) -> None:
+ if self._token_path.exists():
+ self._token_path.unlink()
+
+ def auth_url(self) -> str:
+ """Return Strava OAuth authorization URL."""
+ from urllib.parse import urlencode
+
+ from openjarvis.connectors.oauth import (
+ get_client_credentials,
+ get_provider_for_connector,
+ )
+
+ provider = get_provider_for_connector("strava")
+ if not provider:
+ return "https://www.strava.com/settings/api"
+ creds = get_client_credentials(provider)
+ if not creds:
+ return "https://www.strava.com/settings/api"
+ client_id, _ = creds
+ redirect_uri = f"http://{provider.callback_host}:{provider.callback_port}{provider.callback_path}"
+ params = {
+ "client_id": client_id,
+ "redirect_uri": redirect_uri,
+ "response_type": "code",
+ "scope": " ".join(provider.scopes),
+ }
+ return f"{provider.auth_endpoint}?{urlencode(params)}"
+
+ def handle_callback(self, code: str) -> None:
+ """Exchange authorization code for tokens and save."""
+ from openjarvis.connectors.oauth import (
+ _CONNECTORS_DIR,
+ _exchange_token,
+ get_client_credentials,
+ get_provider_for_connector,
+ save_tokens,
+ )
+
+ provider = get_provider_for_connector("strava")
+ creds = get_client_credentials(provider) if provider else None
+ if not provider or not creds:
+ raise RuntimeError("Strava client credentials not configured")
+ client_id, client_secret = creds
+ redirect_uri = f"http://{provider.callback_host}:{provider.callback_port}{provider.callback_path}"
+ tokens = _exchange_token(provider, code, client_id, client_secret, redirect_uri)
+ payload = {
+ "access_token": tokens.get("access_token", ""),
+ "refresh_token": tokens.get("refresh_token", ""),
+ "client_id": client_id,
+ "client_secret": client_secret,
+ }
+ for filename in provider.credential_files:
+ save_tokens(str(_CONNECTORS_DIR / filename), payload)
+
+ def sync(
+ self, *, since: Optional[datetime] = None, cursor: Optional[str] = None
+ ) -> Iterator[Document]:
+ token = self._get_access_token()
+ after_epoch = int((since or datetime.now() - timedelta(days=7)).timestamp())
+
+ activities = _strava_api_get(
+ token,
+ "athlete/activities",
+ params={"after": str(after_epoch), "per_page": "50"},
+ )
+
+ for act in activities:
+ ts = (
+ datetime.fromisoformat(act["start_date_local"].replace("Z", "+00:00"))
+ if "start_date_local" in act
+ else datetime.now()
+ )
+
+ yield Document(
+ doc_id=f"strava-{act['id']}",
+ source="strava",
+ doc_type=act.get("type", "Activity").lower(),
+ content=json.dumps(act),
+ title=act.get("name", "Untitled Activity"),
+ timestamp=ts,
+ metadata={
+ "distance_m": act.get("distance", 0),
+ "moving_time_s": act.get("moving_time", 0),
+ "sport_type": act.get("sport_type", ""),
+ },
+ )
+
+ self._status.state = "idle"
+ self._status.last_sync = datetime.now()
+
+ def sync_status(self) -> SyncStatus:
+ return self._status
diff --git a/src/openjarvis/core/config.py b/src/openjarvis/core/config.py
index 86dca2f0..ddc45297 100644
--- a/src/openjarvis/core/config.py
+++ b/src/openjarvis/core/config.py
@@ -1235,6 +1235,47 @@ class SkillsConfig:
auto_discover: bool = True
+@dataclass
+class DigestSectionConfig:
+ """Configuration for a single digest section."""
+
+ sources: list = field(default_factory=list)
+ max_items: int = 10
+ priority_contacts: list = field(default_factory=list)
+
+
+@dataclass
+class DigestConfig:
+ """Configuration for the morning digest feature."""
+
+ enabled: bool = False
+ schedule: str = "0 6 * * *"
+ timezone: str = "America/Los_Angeles"
+ persona: str = "jarvis"
+ sections: list = field(
+ default_factory=lambda: ["messages", "calendar", "health", "world"]
+ )
+ optional_sections: list = field(
+ default_factory=lambda: ["github", "financial", "music", "fitness"]
+ )
+ voice_id: str = ""
+ tts_backend: str = "cartesia"
+ messages: DigestSectionConfig = field(
+ default_factory=lambda: DigestSectionConfig(
+ sources=["gmail", "slack", "google_tasks"]
+ )
+ )
+ calendar: DigestSectionConfig = field(
+ default_factory=lambda: DigestSectionConfig(sources=["gcalendar"])
+ )
+ health: DigestSectionConfig = field(
+ default_factory=lambda: DigestSectionConfig(sources=["oura"])
+ )
+ world: DigestSectionConfig = field(
+ default_factory=lambda: DigestSectionConfig(sources=[])
+ )
+
+
@dataclass
class JarvisConfig:
"""Top-level configuration for OpenJarvis."""
@@ -1263,6 +1304,7 @@ class JarvisConfig:
system_prompt: SystemPromptConfig = field(default_factory=SystemPromptConfig)
compression: CompressionConfig = field(default_factory=CompressionConfig)
skills: SkillsConfig = field(default_factory=SkillsConfig)
+ digest: DigestConfig = field(default_factory=DigestConfig)
@property
def memory(self) -> StorageConfig:
diff --git a/src/openjarvis/core/registry.py b/src/openjarvis/core/registry.py
index ec055efa..3739da33 100644
--- a/src/openjarvis/core/registry.py
+++ b/src/openjarvis/core/registry.py
@@ -145,6 +145,10 @@ class CompressionRegistry(RegistryBase[Any]):
"""Registry for context compression strategies."""
+class TTSRegistry(RegistryBase[Any]):
+ """Registry for text-to-speech backend implementations."""
+
+
class ConnectorRegistry(RegistryBase[Any]):
"""Registry for data source connectors (Gmail, Slack, etc.)."""
@@ -163,5 +167,6 @@ __all__ = [
"RouterPolicyRegistry",
"SkillRegistry",
"SpeechRegistry",
+ "TTSRegistry",
"ToolRegistry",
]
diff --git a/src/openjarvis/server/app.py b/src/openjarvis/server/app.py
index 5868b204..38bfba31 100644
--- a/src/openjarvis/server/app.py
+++ b/src/openjarvis/server/app.py
@@ -13,6 +13,7 @@ from fastapi.staticfiles import StaticFiles
from openjarvis.server.api_routes import include_all_routes
from openjarvis.server.comparison import comparison_router
from openjarvis.server.connectors_router import create_connectors_router
+from openjarvis.server.digest_routes import create_digest_router
from openjarvis.server.dashboard import dashboard_router
from openjarvis.server.routes import router
from openjarvis.server.upload_router import router as upload_router
@@ -223,6 +224,7 @@ def create_app(
app.include_router(dashboard_router)
app.include_router(comparison_router)
app.include_router(create_connectors_router())
+ app.include_router(create_digest_router())
app.include_router(upload_router)
include_all_routes(app)
diff --git a/src/openjarvis/server/connectors_router.py b/src/openjarvis/server/connectors_router.py
index bf946cca..bac50057 100644
--- a/src/openjarvis/server/connectors_router.py
+++ b/src/openjarvis/server/connectors_router.py
@@ -78,7 +78,7 @@ def create_connectors_router():
this package.
"""
try:
- from fastapi import APIRouter, HTTPException
+ from fastapi import APIRouter, HTTPException, Request
except ImportError as exc:
raise ImportError(
"fastapi and pydantic are required for the connectors router"
@@ -175,6 +175,26 @@ def create_connectors_router():
except Exception:
pass
+ # Include OAuth provider setup info if applicable
+ oauth_setup = None
+ try:
+ from openjarvis.connectors.oauth import (
+ get_client_credentials,
+ get_provider_for_connector,
+ )
+
+ provider = get_provider_for_connector(connector_id)
+ if provider:
+ has_creds = get_client_credentials(provider) is not None
+ oauth_setup = {
+ "provider": provider.name,
+ "setup_url": provider.setup_url,
+ "setup_hint": provider.setup_hint,
+ "has_credentials": has_creds,
+ }
+ except Exception:
+ pass
+
return {
"connector_id": connector_id,
"display_name": getattr(instance, "display_name", connector_id),
@@ -182,6 +202,7 @@ def create_connectors_router():
"connected": instance.is_connected(),
"auth_url": auth_url,
"mcp_tools": mcp_tools,
+ "oauth_setup": oauth_setup,
}
@router.post("/{connector_id}/connect")
@@ -282,6 +303,143 @@ def create_connectors_router():
"status": "disconnected",
}
+ @router.get("/{connector_id}/oauth/start")
+ async def oauth_start(connector_id: str, request: Request):
+ """Redirect to the OAuth provider's consent page.
+
+ The callback will come back to /v1/connectors/{id}/oauth/callback.
+ """
+ from urllib.parse import urlencode
+
+ from openjarvis.connectors.oauth import (
+ get_client_credentials,
+ get_provider_for_connector,
+ )
+
+ _ensure_connectors_registered()
+ if not ConnectorRegistry.contains(connector_id):
+ raise HTTPException(404, f"Connector '{connector_id}' not found")
+
+ provider = get_provider_for_connector(connector_id)
+ if not provider:
+ raise HTTPException(400, f"No OAuth provider for '{connector_id}'")
+
+ creds = get_client_credentials(provider)
+ if not creds:
+ raise HTTPException(
+ 400,
+ f"No client credentials configured for {provider.display_name}. "
+ f"Set up at: {provider.setup_url}",
+ )
+
+ client_id, _ = creds
+ # Build callback URL pointing to our own server
+ base_url = str(request.base_url).rstrip("/")
+ callback_url = f"{base_url}/v1/connectors/{connector_id}/oauth/callback"
+
+ params = {
+ "client_id": client_id,
+ "redirect_uri": callback_url,
+ "response_type": "code",
+ "scope": " ".join(provider.scopes),
+ **provider.extra_auth_params,
+ }
+ auth_url = f"{provider.auth_endpoint}?{urlencode(params)}"
+
+ from fastapi.responses import RedirectResponse
+
+ return RedirectResponse(url=auth_url)
+
+ @router.get("/{connector_id}/oauth/callback")
+ async def oauth_callback(
+ connector_id: str,
+ code: str = "",
+ error: str = "",
+ request: Request = None,
+ ):
+ """Handle OAuth callback from the provider."""
+ from fastapi.responses import HTMLResponse
+
+ from openjarvis.connectors.oauth import (
+ _CONNECTORS_DIR,
+ _exchange_token,
+ get_client_credentials,
+ get_provider_for_connector,
+ save_tokens,
+ )
+
+ _ensure_connectors_registered()
+
+ if error:
+ _style = "font-family:system-ui;text-align:center;padding:60px"
+ return HTMLResponse(
+ content=(
+ f"<html><body style='{_style}'>"
+ f"<h2 style='color:#ef4444'>Authorization Failed</h2>"
+ f"<p>{error}</p>"
+ "<script>setTimeout(()=>window.close(),3000)</script>"
+ "</body></html>"
+ ),
+ status_code=400,
+ )
+
+ if not code:
+ raise HTTPException(400, "Missing authorization code")
+
+ provider = get_provider_for_connector(connector_id)
+ if not provider:
+ raise HTTPException(400, f"No OAuth provider for '{connector_id}'")
+
+ creds = get_client_credentials(provider)
+ if not creds:
+ raise HTTPException(400, "No client credentials configured")
+
+ client_id, client_secret = creds
+ base_url = str(request.base_url).rstrip("/")
+ redirect_uri = f"{base_url}/v1/connectors/{connector_id}/oauth/callback"
+
+ try:
+ tokens = _exchange_token(
+ provider, code, client_id, client_secret, redirect_uri
+ )
+ except Exception as exc:
+ _style = "font-family:system-ui;text-align:center;padding:60px"
+ return HTMLResponse(
+ content=(
+ f"<html><body style='{_style}'>"
+ f"<h2 style='color:#ef4444'>Token Exchange Failed</h2>"
+ f"<p>{exc}</p>"
+ "</body></html>"
+ ),
+ status_code=500,
+ )
+
+ payload = {
+ "access_token": tokens.get("access_token", ""),
+ "refresh_token": tokens.get("refresh_token", ""),
+ "token_type": tokens.get("token_type", "Bearer"),
+ "expires_in": tokens.get("expires_in", 3600),
+ "client_id": client_id,
+ "client_secret": client_secret,
+ }
+
+ for filename in provider.credential_files:
+ save_tokens(str(_CONNECTORS_DIR / filename), payload)
+
+ # Clear cached instance so it picks up new credentials
+ _instances.pop(connector_id, None)
+
+ _style = "font-family:system-ui;text-align:center;padding:60px"
+ return HTMLResponse(
+ content=(
+ f"<html><body style='{_style}'>"
+ "<h2 style='color:#22c55e'>Connected!</h2>"
+ "<p>You can close this tab and return to OpenJarvis.</p>"
+ "<script>setTimeout(()=>window.close(),2000)</script>"
+ "</body></html>"
+ )
+ )
+
# Track background sync state per connector
_sync_threads: Dict[str, Any] = {}
_sync_state: Dict[str, Dict[str, Any]] = {} # {connector_id: {state, error}}
diff --git a/src/openjarvis/server/digest_routes.py b/src/openjarvis/server/digest_routes.py
new file mode 100644
index 00000000..ce92a4f1
--- /dev/null
+++ b/src/openjarvis/server/digest_routes.py
@@ -0,0 +1,74 @@
+"""FastAPI routes for the morning digest."""
+
+from __future__ import annotations
+
+from fastapi import APIRouter, HTTPException
+from fastapi.responses import FileResponse
+
+from openjarvis.agents.digest_store import DigestStore
+
+
+def create_digest_router(*, db_path: str = "") -> APIRouter:
+ """Create a digest API router with the given store path."""
+ router = APIRouter(prefix="/api/digest", tags=["digest"])
+ store = DigestStore(db_path=db_path) if db_path else DigestStore()
+
+ @router.get("")
+ async def get_digest():
+ """Return the latest digest artifact."""
+ artifact = store.get_today()
+ if artifact is None:
+ raise HTTPException(status_code=404, detail="No digest for today")
+ return {
+ "text": artifact.text,
+ "sections": artifact.sections,
+ "sources_used": artifact.sources_used,
+ "generated_at": artifact.generated_at.isoformat(),
+ "model_used": artifact.model_used,
+ "voice_used": artifact.voice_used,
+ "audio_available": (
+ artifact.audio_path.exists() if artifact.audio_path.name else False
+ ),
+ }
+
+ @router.get("/audio")
+ async def get_digest_audio():
+ """Stream the digest audio file."""
+ artifact = store.get_today()
+ if artifact is None:
+ raise HTTPException(status_code=404, detail="No digest for today")
+ if not artifact.audio_path.exists():
+ raise HTTPException(status_code=404, detail="Audio not available")
+ return FileResponse(
+ str(artifact.audio_path),
+ media_type="audio/mpeg",
+ filename="digest.mp3",
+ )
+
+ @router.post("/generate")
+ async def generate_digest():
+ """Force re-generation of the digest."""
+ try:
+ from openjarvis.sdk import Jarvis
+
+ with Jarvis() as j:
+ result = j.ask("Generate my morning digest", agent="morning_digest")
+ return {"status": "ok", "text": result}
+ except Exception as exc:
+ raise HTTPException(status_code=500, detail=str(exc))
+
+ @router.get("/history")
+ async def get_digest_history():
+ """Return past digests."""
+ history = store.history(limit=10)
+ return [
+ {
+ "text": a.text[:200],
+ "generated_at": a.generated_at.isoformat(),
+ "model_used": a.model_used,
+ "voice_used": a.voice_used,
+ }
+ for a in history
+ ]
+
+ return router
diff --git a/src/openjarvis/speech/__init__.py b/src/openjarvis/speech/__init__.py
index 7fa6ea36..449f6214 100644
--- a/src/openjarvis/speech/__init__.py
+++ b/src/openjarvis/speech/__init__.py
@@ -1,10 +1,17 @@
-"""Speech subsystem — speech-to-text backends."""
+"""Speech subsystem — speech-to-text and text-to-speech backends."""
import importlib
-# Optional backends — each registers itself via @SpeechRegistry.register()
+# Optional STT backends — each registers itself via @SpeechRegistry.register()
for _mod in ("faster_whisper", "openai_whisper", "deepgram"):
try:
importlib.import_module(f".{_mod}", __name__)
except ImportError:
pass
+
+# Optional TTS backends — each registers itself via @TTSRegistry.register()
+for _mod in ("cartesia_tts", "kokoro_tts", "openai_tts"):
+ try:
+ importlib.import_module(f".{_mod}", __name__)
+ except ImportError:
+ pass
diff --git a/src/openjarvis/speech/cartesia_tts.py b/src/openjarvis/speech/cartesia_tts.py
new file mode 100644
index 00000000..21a15a58
--- /dev/null
+++ b/src/openjarvis/speech/cartesia_tts.py
@@ -0,0 +1,104 @@
+"""Cartesia text-to-speech backend.
+
+Uses the Cartesia REST API for high-quality, low-latency voice synthesis.
+Requires CARTESIA_API_KEY environment variable or config.
+"""
+
+from __future__ import annotations
+
+import os
+from typing import List
+
+import httpx
+
+from openjarvis.core.registry import TTSRegistry
+from openjarvis.speech.tts import TTSBackend, TTSResult
+
+_CARTESIA_API_BASE = "https://api.cartesia.ai"
+
+
+def _cartesia_synthesize(
+ api_key: str,
+ text: str,
+ voice_id: str,
+ model: str = "sonic",
+ output_format: str = "mp3",
+ speed: float = 1.0,
+) -> bytes:
+ """Call the Cartesia TTS API and return raw audio bytes."""
+ resp = httpx.post(
+ f"{_CARTESIA_API_BASE}/tts/bytes",
+ headers={
+ "X-API-Key": api_key,
+ "Cartesia-Version": "2024-06-10",
+ },
+ json={
+ "model_id": model,
+ "transcript": text,
+ "voice": {"mode": "id", "id": voice_id},
+ "output_format": {
+ "container": output_format,
+ "sample_rate": 24000,
+ "encoding": "mp3" if output_format == "mp3" else "pcm_f32le",
+ },
+ "language": "en",
+ },
+ timeout=120.0,
+ )
+ resp.raise_for_status()
+ return resp.content
+
+
[email protected]("cartesia")
+class CartesiaTTSBackend(TTSBackend):
+ """Cartesia TTS backend — fast, high-quality synthesis."""
+
+ backend_id = "cartesia"
+
+ def __init__(self, *, api_key: str = "", model: str = "sonic") -> None:
+ self._api_key = api_key or os.environ.get("CARTESIA_API_KEY", "")
+ self._model = model
+
+ def synthesize(
+ self,
+ text: str,
+ *,
+ voice_id: str = "",
+ speed: float = 1.0,
+ output_format: str = "mp3",
+ ) -> TTSResult:
+ if not self._api_key:
+ raise RuntimeError("CARTESIA_API_KEY not set")
+
+ audio = _cartesia_synthesize(
+ self._api_key,
+ text,
+ voice_id=voice_id,
+ model=self._model,
+ output_format=output_format,
+ speed=speed,
+ )
+
+ return TTSResult(
+ audio=audio,
+ format=output_format,
+ voice_id=voice_id,
+ metadata={"backend": "cartesia", "model": self._model},
+ )
+
+ def available_voices(self) -> List[str]:
+ if not self._api_key:
+ return []
+ resp = httpx.get(
+ f"{_CARTESIA_API_BASE}/voices",
+ headers={
+ "X-API-Key": self._api_key,
+ "Cartesia-Version": "2024-06-10",
+ },
+ timeout=30.0,
+ )
+ resp.raise_for_status()
+ return [v["id"] for v in resp.json()]
+
+ def health(self) -> bool:
+ return bool(self._api_key)
diff --git a/src/openjarvis/speech/kokoro_tts.py b/src/openjarvis/speech/kokoro_tts.py
new file mode 100644
index 00000000..23c1028f
--- /dev/null
+++ b/src/openjarvis/speech/kokoro_tts.py
@@ -0,0 +1,80 @@
+"""Kokoro TTS backend — fully open-source, runs locally.
+
+Requires the kokoro package: pip install kokoro
+Falls back gracefully if not installed.
+"""
+
+from __future__ import annotations
+
+import io
+from typing import List
+
+from openjarvis.core.registry import TTSRegistry
+from openjarvis.speech.tts import TTSBackend, TTSResult
+
+
+class KokoroTTSBackend(TTSBackend):
+ """Kokoro TTS — local open-source voice synthesis."""
+
+ backend_id = "kokoro"
+
+ def __init__(self, *, model_path: str = "", device: str = "auto") -> None:
+ self._model_path = model_path
+ self._device = device
+ self._pipeline = None
+
+ def _ensure_pipeline(self) -> None:
+ if self._pipeline is not None:
+ return
+ try:
+ from kokoro import KPipeline
+
+ self._pipeline = KPipeline(lang_code="a")
+ except ImportError:
+ raise RuntimeError(
+ "kokoro package not installed. Install with: pip install kokoro"
+ )
+
+ def synthesize(
+ self,
+ text: str,
+ *,
+ voice_id: str = "af_heart",
+ speed: float = 1.0,
+ output_format: str = "wav",
+ ) -> TTSResult:
+ self._ensure_pipeline()
+ import numpy as np
+ import soundfile as sf
+
+ samples = []
+ for _, _, audio in self._pipeline(text, voice=voice_id, speed=speed):
+ samples.append(audio)
+
+ if not samples:
+ return TTSResult(audio=b"", format=output_format, voice_id=voice_id)
+
+ combined = np.concatenate(samples)
+ buf = io.BytesIO()
+ sf.write(buf, combined, 24000, format=output_format.upper())
+ buf.seek(0)
+
+ return TTSResult(
+ audio=buf.read(),
+ format=output_format,
+ voice_id=voice_id,
+ sample_rate=24000,
+ duration_seconds=len(combined) / 24000,
+ metadata={"backend": "kokoro"},
+ )
+
+ def available_voices(self) -> List[str]:
+ return ["af_heart", "af_bella", "am_adam", "am_michael"]
+
+ def health(self) -> bool:
+ try:
+ self._ensure_pipeline()
+ return True
+ except RuntimeError:
+ return False
diff --git a/src/openjarvis/speech/openai_tts.py b/src/openjarvis/speech/openai_tts.py
new file mode 100644
index 00000000..2f999359
--- /dev/null
+++ b/src/openjarvis/speech/openai_tts.py
@@ -0,0 +1,82 @@
+"""OpenAI TTS backend — cloud-based voice synthesis via OpenAI API."""
+
+from __future__ import annotations
+
+import os
+from typing import List
+
+import httpx
+
+from openjarvis.core.registry import TTSRegistry
+from openjarvis.speech.tts import TTSBackend, TTSResult
+
+_OPENAI_TTS_URL = "https://api.openai.com/v1/audio/speech"
+
+
+def _openai_tts_request(
+ api_key: str,
+ text: str,
+ voice: str,
+ model: str = "tts-1",
+ speed: float = 1.0,
+ response_format: str = "mp3",
+) -> bytes:
+ """Call the OpenAI TTS API and return raw audio bytes."""
+ resp = httpx.post(
+ _OPENAI_TTS_URL,
+ headers={"Authorization": f"Bearer {api_key}"},
+ json={
+ "model": model,
+ "input": text,
+ "voice": voice,
+ "speed": speed,
+ "response_format": response_format,
+ },
+ timeout=120.0,
+ )
+ resp.raise_for_status()
+ return resp.content
+
+
[email protected]("openai_tts")
+class OpenAITTSBackend(TTSBackend):
+ """OpenAI TTS backend — cloud synthesis."""
+
+ backend_id = "openai_tts"
+
+ def __init__(self, *, api_key: str = "", model: str = "tts-1") -> None:
+ self._api_key = api_key or os.environ.get("OPENAI_API_KEY", "")
+ self._model = model
+
+ def synthesize(
+ self,
+ text: str,
+ *,
+ voice_id: str = "nova",
+ speed: float = 1.0,
+ output_format: str = "mp3",
+ ) -> TTSResult:
+ if not self._api_key:
+ raise RuntimeError("OPENAI_API_KEY not set")
+
+ audio = _openai_tts_request(
+ self._api_key,
+ text,
+ voice=voice_id,
+ model=self._model,
+ speed=speed,
+ response_format=output_format,
+ )
+
+ return TTSResult(
+ audio=audio,
+ format=output_format,
+ voice_id=voice_id,
+ metadata={"backend": "openai_tts", "model": self._model},
+ )
+
+ def available_voices(self) -> List[str]:
+ return ["alloy", "echo", "fable", "onyx", "nova", "shimmer"]
+
+ def health(self) -> bool:
+ return bool(self._api_key)
diff --git a/src/openjarvis/speech/tts.py b/src/openjarvis/speech/tts.py
new file mode 100644
index 00000000..82ca8d91
--- /dev/null
+++ b/src/openjarvis/speech/tts.py
@@ -0,0 +1,53 @@
+"""Abstract base classes and data types for text-to-speech backends."""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Dict, List
+
+
+@dataclass
+class TTSResult:
+ """Result of a text-to-speech synthesis."""
+
+ audio: bytes
+ format: str = "mp3"
+ duration_seconds: float = 0.0
+ voice_id: str = ""
+ sample_rate: int = 24000
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+ def save(self, path: Path) -> Path:
+ """Write audio bytes to a file and return the path."""
+ path.write_bytes(self.audio)
+ return path
+
+
+class TTSBackend(ABC):
+ """Abstract base class for text-to-speech backends."""
+
+ backend_id: str = ""
+
+ @abstractmethod
+ def synthesize(
+ self,
+ text: str,
+ *,
+ voice_id: str = "",
+ speed: float = 1.0,
+ output_format: str = "mp3",
+ ) -> TTSResult:
+ """Synthesize text to audio."""
+
+ @abstractmethod
+ def available_voices(self) -> List[str]:
+ """Return list of available voice IDs."""
+
+ @abstractmethod
+ def health(self) -> bool:
+ """Check if the backend is ready."""
+
+
+__all__ = ["TTSBackend", "TTSResult"]
diff --git a/src/openjarvis/tools/__init__.py b/src/openjarvis/tools/__init__.py
index 522e5fde..8f11ab22 100644
--- a/src/openjarvis/tools/__init__.py
+++ b/src/openjarvis/tools/__init__.py
@@ -131,4 +131,14 @@ try:
except ImportError:
pass
+try:
+ import openjarvis.tools.text_to_speech # noqa: F401
+except ImportError:
+ pass
+
+try:
+ import openjarvis.tools.digest_collect # noqa: F401
+except ImportError:
+ pass
+
__all__ = ["BaseTool", "ToolExecutor", "ToolSpec"]
diff --git a/src/openjarvis/tools/digest_collect.py b/src/openjarvis/tools/digest_collect.py
new file mode 100644
index 00000000..31f45156
--- /dev/null
+++ b/src/openjarvis/tools/digest_collect.py
@@ -0,0 +1,110 @@
+"""Digest collection tool — fetches recent data from configured connectors."""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime, timedelta
+from typing import Any, Dict, List
+
+from openjarvis.core.registry import ConnectorRegistry, ToolRegistry
+from openjarvis.core.types import ToolResult
+from openjarvis.tools._stubs import BaseTool, ToolSpec
+
+
[email protected]("digest_collect")
+class DigestCollectTool(BaseTool):
+ """Collect recent data from multiple connectors for digest synthesis."""
+
+ tool_id = "digest_collect"
+ is_local = True
+
+ @property
+ def spec(self) -> ToolSpec:
+ return ToolSpec(
+ name="digest_collect",
+ description=(
+ "Fetch recent data from configured connectors (email, calendar, "
+ "health, tasks, etc.) and return a structured summary for digest "
+ "synthesis."
+ ),
+ parameters={
+ "type": "object",
+ "properties": {
+ "sources": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": (
+ "List of connector IDs to fetch from "
+ "(e.g., ['gmail', 'oura', 'gcalendar'])."
+ ),
+ },
+ "hours_back": {
+ "type": "number",
+ "description": "How many hours back to look (default: 24).",
+ },
+ },
+ "required": ["sources"],
+ },
+ category="data",
+ timeout_seconds=60.0,
+ )
+
+ def execute(self, **params: Any) -> ToolResult:
+ sources: List[str] = params.get("sources", [])
+ hours_back: float = params.get("hours_back", 24)
+ since = datetime.now() - timedelta(hours=hours_back)
+
+ collected: Dict[str, List[Dict[str, Any]]] = {}
+ errors: List[str] = []
+
+ for source in sources:
+ if not ConnectorRegistry.contains(source):
+ errors.append(f"Connector '{source}' not available")
+ continue
+
+ try:
+ connector_cls = ConnectorRegistry.get(source)
+ connector = connector_cls()
+
+ if not connector.is_connected():
+ errors.append(
+ f"Connector '{source}' not connected (no credentials)"
+ )
+ continue
+
+ docs = list(connector.sync(since=since))
+ collected[source] = [
+ {
+ "title": d.title,
+ "content": d.content,
+ "doc_type": d.doc_type,
+ "author": d.author,
+ "timestamp": d.timestamp.isoformat(),
+ "metadata": d.metadata,
+ }
+ for d in docs
+ ]
+ except Exception as exc:
+ errors.append(f"Error fetching from '{source}': {exc}")
+
+ summary_parts = []
+ for source, docs in collected.items():
+ summary_parts.append(f"## {source} ({len(docs)} items)")
+ for doc in docs:
+ summary_parts.append(json.dumps(doc, default=str))
+
+ if errors:
+ summary_parts.append("\n## Errors")
+ summary_parts.extend(errors)
+
+ return ToolResult(
+ tool_name="digest_collect",
+ content="\n".join(summary_parts),
+ success=True,
+ metadata={
+ "sources_queried": sources,
+ "sources_ok": list(collected.keys()),
+ "sources_failed": errors,
+ "total_items": sum(len(v) for v in collected.values()),
+ },
+ )
diff --git a/src/openjarvis/tools/text_to_speech.py b/src/openjarvis/tools/text_to_speech.py
new file mode 100644
index 00000000..d17ebd82
--- /dev/null
+++ b/src/openjarvis/tools/text_to_speech.py
@@ -0,0 +1,102 @@
+"""Text-to-speech tool — synthesize text to audio via configurable TTS backend."""
+
+from __future__ import annotations
+
+import tempfile
+from pathlib import Path
+from typing import Any
+
+from openjarvis.core.registry import ToolRegistry, TTSRegistry
+from openjarvis.core.types import ToolResult
+from openjarvis.tools._stubs import BaseTool, ToolSpec
+
+
[email protected]("text_to_speech")
+class TextToSpeechTool(BaseTool):
+ """Synthesize text into spoken audio using a TTS backend."""
+
+ tool_id = "text_to_speech"
+ is_local = False
+
+ @property
+ def spec(self) -> ToolSpec:
+ return ToolSpec(
+ name="text_to_speech",
+ description=(
+ "Convert text to spoken audio. Returns the file path to the "
+ "generated audio file."
+ ),
+ parameters={
+ "type": "object",
+ "properties": {
+ "text": {
+ "type": "string",
+ "description": "The text to synthesize into speech.",
+ },
+ "voice_id": {
+ "type": "string",
+ "description": "Voice identifier for the TTS backend.",
+ },
+ "backend": {
+ "type": "string",
+ "description": "TTS backend (cartesia, kokoro, openai_tts).",
+ },
+ "output_dir": {
+ "type": "string",
+ "description": "Directory to save the audio file.",
+ },
+ },
+ "required": ["text"],
+ },
+ category="audio",
+ timeout_seconds=120.0,
+ )
+
+ def execute(self, **params: Any) -> ToolResult:
+ text = params.get("text", "")
+ voice_id = params.get("voice_id", "")
+ backend_key = params.get("backend", "cartesia")
+ output_dir = params.get("output_dir", "")
+
+ if not text:
+ return ToolResult(
+ tool_name="text_to_speech",
+ content="No text provided.",
+ success=False,
+ )
+
+ if not TTSRegistry.contains(backend_key):
+ return ToolResult(
+ tool_name="text_to_speech",
+ content=f"TTS backend '{backend_key}' not available.",
+ success=False,
+ )
+
+ backend_cls = TTSRegistry.get(backend_key)
+ backend = backend_cls()
+
+ result = backend.synthesize(text, voice_id=voice_id)
+
+ # Save to file
+ if output_dir:
+ out_dir = Path(output_dir)
+ else:
+ out_dir = Path(tempfile.mkdtemp(prefix="jarvis-tts-"))
+
+ out_dir.mkdir(parents=True, exist_ok=True)
+ ext = result.format or "mp3"
+ audio_path = out_dir / f"digest.{ext}"
+ result.save(audio_path)
+
+ return ToolResult(
+ tool_name="text_to_speech",
+ content=str(audio_path),
+ success=True,
+ metadata={
+ "audio_path": str(audio_path),
+ "format": ext,
+ "duration_seconds": result.duration_seconds,
+ "voice_id": result.voice_id,
+ "backend": backend_key,
+ },
+ )
diff --git a/tests/agents/test_digest_store.py b/tests/agents/test_digest_store.py
new file mode 100644
index 00000000..51874a0f
--- /dev/null
+++ b/tests/agents/test_digest_store.py
@@ -0,0 +1,79 @@
+"""Tests for DigestStore and DigestArtifact."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+import pytest
+
+from openjarvis.agents.digest_store import DigestArtifact, DigestStore
+
+
+def test_store_and_retrieve(tmp_path):
+ store = DigestStore(db_path=str(tmp_path / "digest.db"))
+
+ artifact = DigestArtifact(
+ text="Good morning sir.",
+ audio_path=Path("/tmp/digest.mp3"),
+ sections={"messages": "You have 3 emails.", "calendar": "2 meetings today."},
+ sources_used=["gmail", "gcalendar"],
+ generated_at=datetime(2026, 4, 1, 6, 0, 0),
+ model_used="claude-sonnet-4-6",
+ voice_used="jarvis-v1",
+ )
+
+ store.save(artifact)
+ retrieved = store.get_latest()
+
+ assert retrieved is not None
+ assert retrieved.text == "Good morning sir."
+ assert retrieved.sections["messages"] == "You have 3 emails."
+ assert retrieved.sources_used == ["gmail", "gcalendar"]
+ assert retrieved.voice_used == "jarvis-v1"
+
+ store.close()
+
+
+def test_get_today(tmp_path):
+ store = DigestStore(db_path=str(tmp_path / "digest.db"))
+ artifact = DigestArtifact(
+ text="Today's digest",
+ audio_path=Path("/tmp/today.mp3"),
+ sections={"messages": "Nothing urgent."},
+ sources_used=["gmail"],
+ generated_at=datetime.now(),
+ model_used="test-model",
+ voice_used="jarvis",
+ )
+ store.save(artifact)
+ today = store.get_today()
+ assert today is not None
+ assert today.text == "Today's digest"
+ store.close()
+
+
+def test_get_today_returns_none_when_empty(tmp_path):
+ store = DigestStore(db_path=str(tmp_path / "digest.db"))
+ assert store.get_today() is None
+ store.close()
+
+
+def test_history(tmp_path):
+ store = DigestStore(db_path=str(tmp_path / "digest.db"))
+ for i in range(3):
+ store.save(
+ DigestArtifact(
+ text=f"Digest {i}",
+ audio_path=Path(f"/tmp/d{i}.mp3"),
+ sections={},
+ sources_used=[],
+ generated_at=datetime(2026, 4, 1 + i, 6, 0, 0),
+ model_used="test",
+ voice_used="jarvis",
+ )
+ )
+ history = store.history(limit=2)
+ assert len(history) == 2
+ assert history[0].text == "Digest 2" # Most recent first
+ store.close()
diff --git a/tests/agents/test_morning_digest.py b/tests/agents/test_morning_digest.py
new file mode 100644
index 00000000..49a9ec5e
--- /dev/null
+++ b/tests/agents/test_morning_digest.py
@@ -0,0 +1,74 @@
+"""Tests for MorningDigestAgent."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from openjarvis.agents._stubs import AgentResult
+from openjarvis.core.registry import AgentRegistry
+from openjarvis.core.types import ToolResult
+
+
+def test_morning_digest_registered():
+ from openjarvis.agents.morning_digest import MorningDigestAgent
+
+ AgentRegistry.register_value("morning_digest", MorningDigestAgent)
+ assert AgentRegistry.contains("morning_digest")
+
+
+def test_morning_digest_run(tmp_path):
+ from openjarvis.agents.morning_digest import MorningDigestAgent
+
+ mock_engine = MagicMock()
+ mock_engine.generate.return_value = {
+ "content": "Good morning sir. You have 3 emails and 2 meetings today.",
+ "finish_reason": "stop",
+ "usage": {},
+ }
+
+ # Mock collect result
+ mock_collect_result = ToolResult(
+ tool_name="digest_collect",
+ content="## gmail (2 items)\n...",
+ success=True,
+ metadata={"total_items": 2},
+ )
+
+ # Mock TTS result
+ mock_tts_result = ToolResult(
+ tool_name="text_to_speech",
+ content=str(tmp_path / "digest.mp3"),
+ success=True,
+ metadata={"audio_path": str(tmp_path / "digest.mp3")},
+ )
+
+ agent = MorningDigestAgent(
+ mock_engine,
+ "test-model",
+ tools=[],
+ persona="neutral",
+ digest_store_path=str(tmp_path / "digest.db"),
+ )
+
+ with patch.object(
+ agent._executor,
+ "execute",
+ side_effect=[mock_collect_result, mock_tts_result],
+ ):
+ result = agent.run("Generate morning digest")
+
+ assert isinstance(result, AgentResult)
+ assert "Good morning" in result.content
+ assert result.turns == 1
+ assert len(result.tool_results) == 2
+
+
+def test_load_persona():
+ from openjarvis.agents.morning_digest import _load_persona
+
+ # Nonexistent persona returns empty string
+ result = _load_persona("nonexistent_persona_xyz")
+ assert result == ""
diff --git a/tests/cli/test_digest_cmd.py b/tests/cli/test_digest_cmd.py
new file mode 100644
index 00000000..5f99dceb
--- /dev/null
+++ b/tests/cli/test_digest_cmd.py
@@ -0,0 +1,55 @@
+"""Tests for `jarvis digest` CLI command."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+import pytest
+from click.testing import CliRunner
+
+from openjarvis.agents.digest_store import DigestArtifact, DigestStore
+
+
+def test_digest_command_exists():
+ """The digest command is registered on the CLI."""
+ from openjarvis.cli import cli
+
+ runner = CliRunner()
+ result = runner.invoke(cli, ["digest", "--help"])
+ assert result.exit_code == 0
+ assert "digest" in result.output.lower()
+
+
+def test_digest_displays_cached(tmp_path):
+ from openjarvis.cli import cli
+
+ db_path = str(tmp_path / "digest.db")
+ store = DigestStore(db_path=db_path)
+ store.save(
+ DigestArtifact(
+ text="# Messages\nYou have 3 emails.\n# Calendar\n2 meetings today.",
+ audio_path=Path("/nonexistent/audio.mp3"),
+ sections={},
+ sources_used=["gmail"],
+ generated_at=datetime.now(),
+ model_used="test",
+ voice_used="jarvis",
+ )
+ )
+ store.close()
+
+ runner = CliRunner()
+ result = runner.invoke(cli, ["digest", "--text-only", "--db-path", db_path])
+ assert result.exit_code == 0
+ assert "3 emails" in result.output
+
+
+def test_digest_no_cache(tmp_path):
+ from openjarvis.cli import cli
+
+ db_path = str(tmp_path / "empty.db")
+ runner = CliRunner()
+ result = runner.invoke(cli, ["digest", "--db-path", db_path])
+ assert result.exit_code == 0
+ assert "No digest for today" in result.output
diff --git a/tests/conftest.py b/tests/conftest.py
index 8c2a9295..e2deda4d 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -20,6 +20,7 @@ from openjarvis.core.registry import (
ModelRegistry,
RouterPolicyRegistry,
SpeechRegistry,
+ TTSRegistry,
ToolRegistry,
)
@@ -38,6 +39,7 @@ def _clean_registries() -> None:
SpeechRegistry.clear()
CompressionRegistry.clear()
ConnectorRegistry.clear()
+ TTSRegistry.clear()
reset_event_bus()
diff --git a/tests/connectors/test_apple_health.py b/tests/connectors/test_apple_health.py
new file mode 100644
index 00000000..28c76a5d
--- /dev/null
+++ b/tests/connectors/test_apple_health.py
@@ -0,0 +1,161 @@
+"""Tests for AppleHealthConnector -- local HealthKit DB / export XML."""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime
+
+from openjarvis.connectors._stubs import Document
+from openjarvis.core.registry import ConnectorRegistry
+
+_SAMPLE_EXPORT_XML = """\
+<?xml version="1.0" encoding="UTF-8"?>
+<HealthData>
+ <Record type="HKQuantityTypeIdentifierStepCount" \
+startDate="2024-03-15 08:00:00 -0700" \
+endDate="2024-03-15 08:30:00 -0700" \
+value="1234" sourceName="iPhone" unit="count"/>
+ <Record type="HKQuantityTypeIdentifierStepCount" \
+startDate="2024-03-15 12:00:00 -0700" \
+endDate="2024-03-15 12:15:00 -0700" \
+value="500" sourceName="iPhone" unit="count"/>
+ <Record type="HKCategoryTypeIdentifierSleepAnalysis" \
+startDate="2024-03-15 22:00:00 -0700" \
+endDate="2024-03-16 06:00:00 -0700" \
+value="HKCategoryValueSleepAnalysisAsleepCore" sourceName="iPhone"/>
+ <Record type="HKQuantityTypeIdentifierHeartRate" \
+startDate="2024-03-15 09:00:00 -0700" \
+value="65" unit="count/min" sourceName="iPhone"/>
+ <Record type="HKQuantityTypeIdentifierHeartRate" \
+startDate="2024-03-15 15:00:00 -0700" \
+value="75" unit="count/min" sourceName="iPhone"/>
+ <Record type="HKQuantityTypeIdentifierActiveEnergyBurned" \
+startDate="2024-03-15 07:30:00 -0700" \
+value="350" unit="kcal" sourceName="iPhone"/>
+ <Workout workoutActivityType="HKWorkoutActivityTypeRunning" \
+duration="1800" \
+startDate="2024-03-15 07:00:00 -0700" \
+endDate="2024-03-15 07:30:00 -0700" \
+totalDistance="5.2" totalEnergyBurned="300"/>
+</HealthData>
+"""
+
+
+def test_apple_health_registered():
+ """AppleHealthConnector is discoverable via ConnectorRegistry."""
+ from openjarvis.connectors.apple_health import AppleHealthConnector
+
+ ConnectorRegistry.register_value("apple_health", AppleHealthConnector)
+ assert ConnectorRegistry.contains("apple_health")
+ cls = ConnectorRegistry.get("apple_health")
+ assert cls.connector_id == "apple_health"
+ assert cls.display_name == "Apple Health"
+ assert cls.auth_type == "local"
+
+
+def test_not_connected_no_files(tmp_path):
+ """is_connected() returns False when neither data source exists."""
+ from openjarvis.connectors.apple_health import AppleHealthConnector
+
+ connector = AppleHealthConnector(
+ export_path=str(tmp_path / "nope.xml"),
+ healthkit_db_path=str(tmp_path / "nope.sqlite"),
+ )
+ assert connector.is_connected() is False
+
+
+def test_connected_with_export(tmp_path):
+ """is_connected() returns True when the export XML exists."""
+ from openjarvis.connectors.apple_health import AppleHealthConnector
+
+ export_file = tmp_path / "export.xml"
+ export_file.write_text(_SAMPLE_EXPORT_XML, encoding="utf-8")
+
+ connector = AppleHealthConnector(
+ export_path=str(export_file),
+ healthkit_db_path=str(tmp_path / "nope.sqlite"),
+ )
+ assert connector.is_connected() is True
+
+
+def test_sync_export_xml(tmp_path):
+ """Sync from export XML yields correct Documents for each data type."""
+ from openjarvis.connectors.apple_health import AppleHealthConnector
+
+ export_file = tmp_path / "export.xml"
+ export_file.write_text(_SAMPLE_EXPORT_XML, encoding="utf-8")
+
+ connector = AppleHealthConnector(
+ export_path=str(export_file),
+ healthkit_db_path=str(tmp_path / "nope.sqlite"),
+ )
+ docs = list(connector.sync())
+ assert all(isinstance(d, Document) for d in docs)
+
+ by_type = {}
+ for d in docs:
+ by_type.setdefault(d.doc_type, []).append(d)
+
+ # Steps: two records on 2024-03-15 should be summed (1234 + 500 = 1734)
+ assert "steps" in by_type
+ step_doc = by_type["steps"][0]
+ assert step_doc.source == "apple_health"
+ step_data = json.loads(step_doc.content)
+ assert step_data["steps"] == 1734
+ assert "1,734" in step_doc.title
+
+ # Sleep
+ assert "sleep" in by_type
+ sleep_doc = by_type["sleep"][0]
+ sleep_data = json.loads(sleep_doc.content)
+ assert sleep_data["total_seconds"] == 28800.0 # 8 hours
+ assert "8h" in sleep_doc.title
+
+ # Heart rate: avg of 65 and 75 = 70
+ assert "heart_rate" in by_type
+ hr_doc = by_type["heart_rate"][0]
+ hr_data = json.loads(hr_doc.content)
+ assert hr_data["avg_bpm"] == 70.0
+ assert hr_data["min_bpm"] == 65.0
+ assert hr_data["max_bpm"] == 75.0
+
+ # Active energy
+ assert "active_energy" in by_type
+ energy_doc = by_type["active_energy"][0]
+ energy_data = json.loads(energy_doc.content)
+ assert energy_data["kcal"] == 350.0
+
+ # Workout
+ assert "workout" in by_type
+ workout_doc = by_type["workout"][0]
+ assert "Running" in workout_doc.title
+ assert "5.2" in workout_doc.title
+ workout_data = json.loads(workout_doc.content)
+ assert workout_data["duration_seconds"] == 1800.0
+
+
+def test_sync_with_since_filter(tmp_path):
+ """Only records after the ``since`` date are included."""
+ from openjarvis.connectors.apple_health import AppleHealthConnector
+
+ export_file = tmp_path / "export.xml"
+ export_file.write_text(_SAMPLE_EXPORT_XML, encoding="utf-8")
+
+ connector = AppleHealthConnector(
+ export_path=str(export_file),
+ healthkit_db_path=str(tmp_path / "nope.sqlite"),
+ )
+ # All sample data is from 2024-03-15; filtering after that should yield nothing
+ docs = list(connector.sync(since=datetime(2025, 1, 1)))
+ assert len(docs) == 0
+
+
+def test_disconnect_is_noop(tmp_path):
+ """disconnect() does not raise for a local connector."""
+ from openjarvis.connectors.apple_health import AppleHealthConnector
+
+ connector = AppleHealthConnector(
+ export_path=str(tmp_path / "nope.xml"),
+ healthkit_db_path=str(tmp_path / "nope.sqlite"),
+ )
+ connector.disconnect() # should not raise
diff --git a/tests/connectors/test_apple_music.py b/tests/connectors/test_apple_music.py
new file mode 100644
index 00000000..9ba6cb07
--- /dev/null
+++ b/tests/connectors/test_apple_music.py
@@ -0,0 +1,177 @@
+"""Tests for AppleMusicConnector -- local Music.app via AppleScript.
+
+All tests mock ``subprocess.run`` so no actual Music.app interaction is needed.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime
+from typing import List
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from openjarvis.connectors._stubs import Document
+from openjarvis.core.registry import ConnectorRegistry
+
+# ---------------------------------------------------------------------------
+# Sample AppleScript output
+# ---------------------------------------------------------------------------
+
+_SAMPLE_OUTPUT = (
+ "Bohemian Rhapsody|||Queen|||A Night at the Opera|||354.0|||Rock|||42|||"
+ "Saturday, March 15, 2026 at 2:30:00 PM\n"
+ "Blinding Lights|||The Weeknd|||After Hours|||200.0|||Pop|||18|||never\n"
+)
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+def connector():
+ """Return a fresh AppleMusicConnector."""
+ from openjarvis.connectors.apple_music import AppleMusicConnector
+
+ return AppleMusicConnector()
+
+
+# ---------------------------------------------------------------------------
+# Test 1 -- registry
+# ---------------------------------------------------------------------------
+
+
+def test_apple_music_registered():
+ """AppleMusicConnector is discoverable via ConnectorRegistry."""
+ from openjarvis.connectors.apple_music import AppleMusicConnector
+
+ ConnectorRegistry.register_value("apple_music", AppleMusicConnector)
+ assert ConnectorRegistry.contains("apple_music")
+ cls = ConnectorRegistry.get("apple_music")
+ assert cls.connector_id == "apple_music"
+ assert cls.display_name == "Apple Music"
+ assert cls.auth_type == "local"
+
+
+# ---------------------------------------------------------------------------
+# Test 2 -- is_connected on macOS (happy path)
+# ---------------------------------------------------------------------------
+
+
+def test_is_connected_on_macos(connector):
+ """is_connected() returns True on macOS when Music.app responds."""
+ mock_result = MagicMock()
+ mock_result.returncode = 0
+ mock_result.stdout = "Library"
+
+ with (
+ patch("openjarvis.connectors.apple_music.sys") as mock_sys,
+ patch("openjarvis.connectors.apple_music.subprocess") as mock_subprocess,
+ ):
+ mock_sys.platform = "darwin"
+ mock_subprocess.run.return_value = mock_result
+ mock_subprocess.TimeoutExpired = TimeoutError
+ assert connector.is_connected() is True
+
+
+# ---------------------------------------------------------------------------
+# Test 3 -- is_connected on Linux
+# ---------------------------------------------------------------------------
+
+
+def test_is_connected_on_linux(connector):
+ """is_connected() returns False on non-macOS platforms."""
+ with patch("openjarvis.connectors.apple_music.sys") as mock_sys:
+ mock_sys.platform = "linux"
+ assert connector.is_connected() is False
+
+
+# ---------------------------------------------------------------------------
+# Test 4 -- sync yields Documents
+# ---------------------------------------------------------------------------
+
+
+def test_sync_yields_tracks(connector):
+ """sync() parses AppleScript output and yields correct Documents."""
+ mock_result = MagicMock()
+ mock_result.returncode = 0
+ mock_result.stdout = _SAMPLE_OUTPUT
+
+ with patch(
+ "openjarvis.connectors.apple_music._run_osascript",
+ return_value=_SAMPLE_OUTPUT,
+ ):
+ docs: List[Document] = list(connector.sync())
+
+ assert len(docs) == 2
+ assert all(isinstance(d, Document) for d in docs)
+ assert all(d.source == "apple_music" for d in docs)
+ assert all(d.doc_type == "track" for d in docs)
+
+ # First track
+ assert docs[0].author == "Queen"
+ assert "Bohemian Rhapsody" in docs[0].title
+ content0 = json.loads(docs[0].content)
+ assert content0["album"] == "A Night at the Opera"
+ assert content0["play_count"] == 42
+ assert docs[0].metadata["genre"] == "Rock"
+ assert docs[0].metadata["duration_s"] == 354.0
+
+ # Second track
+ assert docs[1].author == "The Weeknd"
+ assert "Blinding Lights" in docs[1].title
+ content1 = json.loads(docs[1].content)
+ assert content1["genre"] == "Pop"
+ assert docs[1].metadata["play_count"] == 18
+
+
+# ---------------------------------------------------------------------------
+# Test 5 -- sync with since filter
+# ---------------------------------------------------------------------------
+
+
+def test_sync_filters_by_since(connector):
+ """sync(since=...) skips tracks with played_date before the threshold."""
+ with patch(
+ "openjarvis.connectors.apple_music._run_osascript",
+ return_value=_SAMPLE_OUTPUT,
+ ):
+ # The first track was played 2026-03-15; filter after that
+ docs = list(connector.sync(since=datetime(2026, 3, 16)))
+
+ # Only tracks with played_date > since are included.
+ # "Blinding Lights" has played_date "never" so since filter is not applied
+ # (since filter only applies when played_date is not None).
+ # "Bohemian Rhapsody" was played 2026-03-15 which is <= 2026-03-16, so skipped.
+ assert len(docs) == 1
+ assert "Blinding Lights" in docs[0].title
+
+
+# ---------------------------------------------------------------------------
+# Test 6 -- sync handles Music.app failure gracefully
+# ---------------------------------------------------------------------------
+
+
+def test_sync_handles_failure(connector):
+ """sync() returns empty when AppleScript fails."""
+ with patch(
+ "openjarvis.connectors.apple_music._run_osascript",
+ return_value=None,
+ ):
+ docs = list(connector.sync())
+
+ assert len(docs) == 0
+ assert connector.sync_status().state == "error"
+
+
+# ---------------------------------------------------------------------------
+# Test 7 -- disconnect is a no-op
+# ---------------------------------------------------------------------------
+
+
+def test_disconnect_is_noop(connector):
+ """disconnect() does nothing (local connector)."""
+ connector.disconnect() # should not raise
diff --git a/tests/connectors/test_gdrive.py b/tests/connectors/test_gdrive.py
index 2d80055d..06d1cbbb 100644
--- a/tests/connectors/test_gdrive.py
+++ b/tests/connectors/test_gdrive.py
@@ -55,7 +55,12 @@ def connector(tmp_path: Path):
from openjarvis.connectors.gdrive import GDriveConnector # noqa: PLC0415
creds_path = str(tmp_path / "gdrive.json")
- return GDriveConnector(credentials_path=creds_path)
+ # Prevent fallback to shared google.json on machines with real credentials
+ with patch(
+ "openjarvis.connectors.oauth._SHARED_GOOGLE_CREDENTIALS_PATH",
+ str(tmp_path / "google_shared.json"),
+ ):
+ yield GDriveConnector(credentials_path=creds_path)
# ---------------------------------------------------------------------------
diff --git a/tests/connectors/test_google_tasks.py b/tests/connectors/test_google_tasks.py
new file mode 100644
index 00000000..246b06c2
--- /dev/null
+++ b/tests/connectors/test_google_tasks.py
@@ -0,0 +1,73 @@
+"""Tests for GoogleTasksConnector — Google Tasks API v1."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from unittest.mock import patch
+
+import pytest
+
+from openjarvis.connectors._stubs import Document
+from openjarvis.core.registry import ConnectorRegistry
+
+
+def test_google_tasks_registered():
+ from openjarvis.connectors.google_tasks import GoogleTasksConnector
+
+ ConnectorRegistry.register_value("google_tasks", GoogleTasksConnector)
+ assert ConnectorRegistry.contains("google_tasks")
+ cls = ConnectorRegistry.get("google_tasks")
+ assert cls.connector_id == "google_tasks"
+ assert cls.display_name == "Google Tasks"
+ assert cls.auth_type == "oauth"
+
+
+_TASK_LISTS_RESPONSE = {"items": [{"id": "list1", "title": "My Tasks"}]}
+
+_TASKS_RESPONSE = {
+ "items": [
+ {
+ "id": "task1",
+ "title": "Review PR #42",
+ "notes": "Check the auth middleware changes",
+ "status": "needsAction",
+ "due": "2026-04-01T00:00:00.000Z",
+ "updated": "2026-03-31T20:00:00.000Z",
+ "selfLink": "https://tasks.googleapis.com/tasks/v1/lists/list1/tasks/task1",
+ },
+ {
+ "id": "task2",
+ "title": "Submit expense report",
+ "notes": "",
+ "status": "completed",
+ "due": "2026-03-31T00:00:00.000Z",
+ "completed": "2026-03-31T15:00:00.000Z",
+ "updated": "2026-03-31T15:00:00.000Z",
+ "selfLink": "https://tasks.googleapis.com/tasks/v1/lists/list1/tasks/task2",
+ },
+ ]
+}
+
+
+def connector(tmp_path):
+ from openjarvis.connectors.google_tasks import GoogleTasksConnector
+
+ creds = tmp_path / "google_tasks.json"
+ creds.write_text('{"token": "fake-token"}', encoding="utf-8")
+ return GoogleTasksConnector(credentials_path=str(creds))
+
+
+def test_sync_yields_tasks(connector):
+ with patch(
+ "openjarvis.connectors.google_tasks._tasks_api_get",
+ side_effect=[_TASK_LISTS_RESPONSE, _TASKS_RESPONSE],
+ ):
+ docs = list(connector.sync(since=datetime(2026, 3, 31)))
+
+ assert len(docs) == 2
+ assert docs[0].source == "google_tasks"
+ assert docs[0].doc_type == "task"
+ assert docs[0].title == "Review PR #42"
+ assert docs[0].metadata["status"] == "needsAction"
+ assert docs[1].metadata["status"] == "completed"
diff --git a/tests/connectors/test_new_connectors_live.py b/tests/connectors/test_new_connectors_live.py
new file mode 100644
index 00000000..beda5140
--- /dev/null
+++ b/tests/connectors/test_new_connectors_live.py
@@ -0,0 +1,57 @@
+"""Live smoke tests for new connectors — require real API credentials.
+
+Run with: uv run pytest tests/connectors/test_new_connectors_live.py -v -m cloud
+"""
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta
+
+import pytest
+
+from openjarvis.connectors._stubs import Document
+
+
+class TestOuraLive:
+ def test_sync_returns_documents(self):
+ from openjarvis.connectors.oura import OuraConnector
+
+ conn = OuraConnector() # Uses default token path
+ docs = list(conn.sync(since=datetime.now() - timedelta(days=1)))
+ assert len(docs) > 0
+ assert all(isinstance(d, Document) for d in docs)
+ assert all(d.source == "oura" for d in docs)
+
+
+class TestStravaLive:
+ def test_sync_returns_documents(self):
+ from openjarvis.connectors.strava import StravaConnector
+
+ conn = StravaConnector()
+ docs = list(conn.sync(since=datetime.now() - timedelta(days=7)))
+ assert all(isinstance(d, Document) for d in docs)
+ assert all(d.source == "strava" for d in docs)
+
+
+class TestSpotifyLive:
+ def test_sync_returns_documents(self):
+ from openjarvis.connectors.spotify import SpotifyConnector
+
+ conn = SpotifyConnector()
+ docs = list(conn.sync(since=datetime.now() - timedelta(days=1)))
+ assert all(isinstance(d, Document) for d in docs)
+ assert all(d.source == "spotify" for d in docs)
+
+
+class TestGoogleTasksLive:
+ def test_sync_returns_documents(self):
+ from openjarvis.connectors.google_tasks import GoogleTasksConnector
+
+ conn = GoogleTasksConnector()
+ docs = list(conn.sync(since=datetime.now() - timedelta(days=7)))
+ assert all(isinstance(d, Document) for d in docs)
+ assert all(d.source == "google_tasks" for d in docs)
diff --git a/tests/connectors/test_oura.py b/tests/connectors/test_oura.py
new file mode 100644
index 00000000..6dbb8c82
--- /dev/null
+++ b/tests/connectors/test_oura.py
@@ -0,0 +1,95 @@
+"""Tests for OuraConnector — Oura Ring REST API v2."""
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta
+from unittest.mock import patch
+
+import pytest
+
+from openjarvis.connectors._stubs import Document
+from openjarvis.core.registry import ConnectorRegistry
+
+
+def test_oura_registered():
+ """OuraConnector is discoverable via ConnectorRegistry."""
+ from openjarvis.connectors.oura import OuraConnector
+
+ ConnectorRegistry.register_value("oura", OuraConnector)
+ assert ConnectorRegistry.contains("oura")
+ cls = ConnectorRegistry.get("oura")
+ assert cls.connector_id == "oura"
+ assert cls.display_name == "Oura Ring"
+ assert cls.auth_type == "token"
+
+
+_SLEEP_RESPONSE = {
+ "data": [
+ {
+ "day": "2026-04-01",
+ "score": 85,
+ "total_sleep_duration": 28800,
+ "rem_sleep_duration": 5400,
+ "deep_sleep_duration": 7200,
+ }
+ ]
+}
+
+_READINESS_RESPONSE = {
+ "data": [
+ {
+ "day": "2026-04-01",
+ "score": 78,
+ "temperature_deviation": 0.1,
+ }
+ ]
+}
+
+_ACTIVITY_RESPONSE = {
+ "data": [
+ {
+ "day": "2026-04-01",
+ "score": 92,
+ "steps": 8500,
+ "active_calories": 450,
+ }
+ ]
+}
+
+
+def connector(tmp_path):
+ """OuraConnector with fake token file."""
+ from openjarvis.connectors.oura import OuraConnector
+
+ token_path = tmp_path / "oura.json"
+ token_path.write_text('{"token": "fake-pat"}', encoding="utf-8")
+ return OuraConnector(token_path=str(token_path))
+
+
+def test_is_connected(connector):
+ assert connector.is_connected() is True
+
+
+def test_sync_yields_documents(connector):
+ """Sync returns Documents for sleep, readiness, and activity."""
+ with (
+ patch(
+ "openjarvis.connectors.oura._oura_api_get",
+ side_effect=[_SLEEP_RESPONSE, _READINESS_RESPONSE, _ACTIVITY_RESPONSE],
+ ),
+ ):
+ docs = list(connector.sync(since=datetime(2026, 4, 1)))
+
+ assert len(docs) == 3
+ assert all(isinstance(d, Document) for d in docs)
+ assert docs[0].source == "oura"
+ assert docs[0].doc_type == "sleep"
+ assert docs[1].doc_type == "daily_readiness"
+ assert docs[2].doc_type == "daily_activity"
+ assert "85" in docs[0].content # sleep score
+
+
+def test_disconnect(connector):
+ connector.disconnect()
+ assert connector.is_connected() is False
diff --git a/tests/connectors/test_spotify.py b/tests/connectors/test_spotify.py
new file mode 100644
index 00000000..907d905a
--- /dev/null
+++ b/tests/connectors/test_spotify.py
@@ -0,0 +1,77 @@
+"""Tests for SpotifyConnector — Spotify Web API."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from unittest.mock import patch
+
+import pytest
+
+from openjarvis.connectors._stubs import Document
+from openjarvis.core.registry import ConnectorRegistry
+
+
+def test_spotify_registered():
+ from openjarvis.connectors.spotify import SpotifyConnector
+
+ ConnectorRegistry.register_value("spotify", SpotifyConnector)
+ assert ConnectorRegistry.contains("spotify")
+ cls = ConnectorRegistry.get("spotify")
+ assert cls.connector_id == "spotify"
+ assert cls.display_name == "Spotify"
+ assert cls.auth_type == "oauth"
+
+
+_RECENTLY_PLAYED_RESPONSE = {
+ "items": [
+ {
+ "played_at": "2026-04-01T08:30:00Z",
+ "track": {
+ "id": "track1",
+ "name": "Bohemian Rhapsody",
+ "artists": [{"name": "Queen"}],
+ "album": {"name": "A Night at the Opera"},
+ "duration_ms": 354000,
+ "external_urls": {
+ "spotify": "https://open.spotify.com/track/track1"
+ },
+ },
+ },
+ {
+ "played_at": "2026-04-01T08:25:00Z",
+ "track": {
+ "id": "track2",
+ "name": "Stairway to Heaven",
+ "artists": [{"name": "Led Zeppelin"}],
+ "album": {"name": "Led Zeppelin IV"},
+ "duration_ms": 482000,
+ "external_urls": {
+ "spotify": "https://open.spotify.com/track/track2"
+ },
+ },
+ },
+ ]
+}
+
+
+def connector(tmp_path):
+ from openjarvis.connectors.spotify import SpotifyConnector
+
+ token_path = tmp_path / "spotify.json"
+ token_path.write_text('{"access_token": "fake-token"}', encoding="utf-8")
+ return SpotifyConnector(token_path=str(token_path))
+
+
+def test_sync_yields_tracks(connector):
+ with patch(
+ "openjarvis.connectors.spotify._spotify_api_get",
+ return_value=_RECENTLY_PLAYED_RESPONSE,
+ ):
+ docs = list(connector.sync(since=datetime(2026, 4, 1)))
+
+ assert len(docs) == 2
+ assert docs[0].source == "spotify"
+ assert docs[0].doc_type == "recently_played"
+ assert "Queen" in docs[0].title
+ assert docs[0].metadata["track_name"] == "Bohemian Rhapsody"
diff --git a/tests/connectors/test_strava.py b/tests/connectors/test_strava.py
new file mode 100644
index 00000000..829ba055
--- /dev/null
+++ b/tests/connectors/test_strava.py
@@ -0,0 +1,76 @@
+"""Tests for StravaConnector — Strava REST API v3."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from unittest.mock import patch
+
+import pytest
+
+from openjarvis.connectors._stubs import Document
+from openjarvis.core.registry import ConnectorRegistry
+
+
+def test_strava_registered():
+ from openjarvis.connectors.strava import StravaConnector
+
+ ConnectorRegistry.register_value("strava", StravaConnector)
+ assert ConnectorRegistry.contains("strava")
+ cls = ConnectorRegistry.get("strava")
+ assert cls.connector_id == "strava"
+ assert cls.display_name == "Strava"
+ assert cls.auth_type == "oauth"
+
+
+_ACTIVITIES_RESPONSE = [
+ {
+ "id": 12345,
+ "name": "Morning Run",
+ "type": "Run",
+ "sport_type": "Run",
+ "start_date_local": "2026-04-01T07:30:00",
+ "distance": 5200.0,
+ "moving_time": 1560,
+ "elapsed_time": 1620,
+ "total_elevation_gain": 45.0,
+ "average_heartrate": 155.0,
+ },
+ {
+ "id": 12346,
+ "name": "Evening Ride",
+ "type": "Ride",
+ "sport_type": "Ride",
+ "start_date_local": "2026-04-01T18:00:00",
+ "distance": 15000.0,
+ "moving_time": 2700,
+ "elapsed_time": 2900,
+ "total_elevation_gain": 120.0,
+ },
+]
+
+
+def connector(tmp_path):
+ from openjarvis.connectors.strava import StravaConnector
+
+ token_path = tmp_path / "strava.json"
+ token_path.write_text(
+ '{"access_token": "fake-token", "refresh_token": "fake-refresh"}',
+ encoding="utf-8",
+ )
+ return StravaConnector(token_path=str(token_path))
+
+
+def test_sync_yields_activities(connector):
+ with patch(
+ "openjarvis.connectors.strava._strava_api_get",
+ return_value=_ACTIVITIES_RESPONSE,
+ ):
+ docs = list(connector.sync(since=datetime(2026, 4, 1)))
+
+ assert len(docs) == 2
+ assert docs[0].source == "strava"
+ assert docs[0].doc_type == "run"
+ assert docs[0].title == "Morning Run"
+ assert docs[1].doc_type == "ride"
+ assert docs[0].metadata["distance_m"] == 5200.0
diff --git a/tests/server/test_digest_routes.py b/tests/server/test_digest_routes.py
new file mode 100644
index 00000000..7198ed0d
--- /dev/null
+++ b/tests/server/test_digest_routes.py
@@ -0,0 +1,104 @@
+"""Tests for /api/digest endpoints."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+import pytest
+
+pytest.importorskip("fastapi", reason="openjarvis[server] not installed")
+
+from openjarvis.agents.digest_store import DigestArtifact, DigestStore
+
+
+def store(tmp_path):
+ db_path = str(tmp_path / "digest.db")
+ s = DigestStore(db_path=db_path)
+ s.save(
+ DigestArtifact(
+ text="Good morning sir.",
+ audio_path=tmp_path / "digest.mp3",
+ sections={"messages": "3 emails"},
+ sources_used=["gmail"],
+ generated_at=datetime.now(),
+ model_used="test",
+ voice_used="jarvis",
+ )
+ )
+ # Write fake audio file
+ (tmp_path / "digest.mp3").write_bytes(b"fake-mp3")
+ yield s
+ s.close()
+
+
+def test_get_digest(store, tmp_path):
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ from openjarvis.server.digest_routes import create_digest_router
+
+ app = FastAPI()
+ app.include_router(
+ create_digest_router(db_path=str(tmp_path / "digest.db"))
+ )
+
+ client = TestClient(app)
+ resp = client.get("/api/digest")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["text"] == "Good morning sir."
+ assert data["sources_used"] == ["gmail"]
+
+
+def test_get_digest_audio(store, tmp_path):
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ from openjarvis.server.digest_routes import create_digest_router
+
+ app = FastAPI()
+ app.include_router(
+ create_digest_router(db_path=str(tmp_path / "digest.db"))
+ )
+
+ client = TestClient(app)
+ resp = client.get("/api/digest/audio")
+ assert resp.status_code == 200
+ assert resp.content == b"fake-mp3"
+
+
+def test_get_digest_404(tmp_path):
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ from openjarvis.server.digest_routes import create_digest_router
+
+ app = FastAPI()
+ app.include_router(
+ create_digest_router(db_path=str(tmp_path / "empty.db"))
+ )
+
+ client = TestClient(app)
+ resp = client.get("/api/digest")
+ assert resp.status_code == 404
+
+
+def test_get_history(store, tmp_path):
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ from openjarvis.server.digest_routes import create_digest_router
+
+ app = FastAPI()
+ app.include_router(
+ create_digest_router(db_path=str(tmp_path / "digest.db"))
+ )
+
+ client = TestClient(app)
+ resp = client.get("/api/digest/history")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert len(data) == 1
+ assert data[0]["voice_used"] == "jarvis"
diff --git a/tests/speech/test_tts_backends.py b/tests/speech/test_tts_backends.py
new file mode 100644
index 00000000..8758b497
--- /dev/null
+++ b/tests/speech/test_tts_backends.py
@@ -0,0 +1,109 @@
+"""Tests for TTS backend infrastructure."""
+
+from __future__ import annotations
+
+from unittest.mock import patch
+
+import pytest
+
+from openjarvis.core.registry import TTSRegistry
+from openjarvis.speech.tts import TTSBackend, TTSResult
+
+
+# ---------------------------------------------------------------------------
+# TTSResult tests
+# ---------------------------------------------------------------------------
+
+
+def test_tts_result_dataclass():
+ result = TTSResult(
+ audio=b"fake-audio-bytes",
+ format="mp3",
+ duration_seconds=3.5,
+ voice_id="jarvis-v1",
+ )
+ assert result.audio == b"fake-audio-bytes"
+ assert result.format == "mp3"
+ assert result.duration_seconds == 3.5
+
+
+def test_tts_result_save(tmp_path):
+ result = TTSResult(audio=b"fake-mp3-data", format="mp3")
+ out = result.save(tmp_path / "test.mp3")
+ assert out.exists()
+ assert out.read_bytes() == b"fake-mp3-data"
+
+
+# ---------------------------------------------------------------------------
+# Cartesia backend tests
+# ---------------------------------------------------------------------------
+
+
+def test_cartesia_registered():
+ from openjarvis.speech.cartesia_tts import CartesiaTTSBackend
+
+ TTSRegistry.register_value("cartesia", CartesiaTTSBackend)
+ assert TTSRegistry.contains("cartesia")
+
+
+def test_cartesia_synthesize():
+ from openjarvis.speech.cartesia_tts import CartesiaTTSBackend
+
+ backend = CartesiaTTSBackend(api_key="fake-key")
+
+ with patch(
+ "openjarvis.speech.cartesia_tts._cartesia_synthesize",
+ return_value=b"fake-audio-mp3-bytes",
+ ):
+ result = backend.synthesize("Hello world", voice_id="test-voice")
+
+ assert result.audio == b"fake-audio-mp3-bytes"
+ assert result.format == "mp3"
+ assert result.voice_id == "test-voice"
+
+
+# ---------------------------------------------------------------------------
+# Kokoro backend tests
+# ---------------------------------------------------------------------------
+
+
+def test_kokoro_registered():
+ from openjarvis.speech.kokoro_tts import KokoroTTSBackend
+
+ TTSRegistry.register_value("kokoro", KokoroTTSBackend)
+ assert TTSRegistry.contains("kokoro")
+
+
+def test_kokoro_health_false_without_package():
+ from openjarvis.speech.kokoro_tts import KokoroTTSBackend
+
+ backend = KokoroTTSBackend()
+ # Without kokoro installed, health returns False
+ assert backend.health() is False
+
+
+# ---------------------------------------------------------------------------
+# OpenAI TTS backend tests
+# ---------------------------------------------------------------------------
+
+
+def test_openai_tts_registered():
+ from openjarvis.speech.openai_tts import OpenAITTSBackend
+
+ TTSRegistry.register_value("openai_tts", OpenAITTSBackend)
+ assert TTSRegistry.contains("openai_tts")
+
+
+def test_openai_tts_synthesize():
+ from openjarvis.speech.openai_tts import OpenAITTSBackend
+
+ backend = OpenAITTSBackend(api_key="fake-key")
+
+ with patch(
+ "openjarvis.speech.openai_tts._openai_tts_request",
+ return_value=b"fake-openai-audio",
+ ):
+ result = backend.synthesize("Hello", voice_id="nova")
+
+ assert result.audio == b"fake-openai-audio"
+ assert result.voice_id == "nova"
diff --git a/tests/test_digest_integration.py b/tests/test_digest_integration.py
new file mode 100644
index 00000000..f0c4e867
--- /dev/null
+++ b/tests/test_digest_integration.py
@@ -0,0 +1,79 @@
+"""End-to-end integration test for the morning digest pipeline.
+
+Uses mocked connectors and engine to verify the full flow:
+digest_collect -> LLM synthesis -> TTS -> DigestStore -> CLI delivery.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from openjarvis.agents.digest_store import DigestStore
+from openjarvis.core.types import ToolResult
+
+
+def test_full_digest_pipeline(tmp_path):
+ """Verify collect -> synthesize -> TTS -> store -> retrieve."""
+ from openjarvis.agents.morning_digest import MorningDigestAgent
+
+ # Mock engine returns a narrative
+ mock_engine = MagicMock()
+ mock_engine.generate.return_value = {
+ "content": (
+ "Good morning, sir. You slept 7.5 hours with a readiness score of 78. "
+ "You have 2 meetings today and 5 unread emails. "
+ "In the news, a new GPT-5 paper dropped on Arxiv."
+ ),
+ "finish_reason": "stop",
+ "usage": {},
+ }
+
+ # Mock tool results
+ collect_result = ToolResult(
+ tool_name="digest_collect",
+ content="## gmail (3 items)\n## oura (1 items)\n## gcalendar (2 items)",
+ success=True,
+ metadata={"total_items": 6},
+ )
+ tts_result = ToolResult(
+ tool_name="text_to_speech",
+ content=str(tmp_path / "digest.mp3"),
+ success=True,
+ metadata={"audio_path": str(tmp_path / "digest.mp3")},
+ )
+
+ # Write fake audio
+ (tmp_path / "digest.mp3").write_bytes(b"fake-mp3-audio")
+
+ db_path = str(tmp_path / "digest.db")
+
+ agent = MorningDigestAgent(
+ mock_engine,
+ "claude-sonnet-4-6",
+ tools=[],
+ persona="neutral",
+ digest_store_path=db_path,
+ )
+
+ with patch.object(
+ agent._executor,
+ "execute",
+ side_effect=[collect_result, tts_result],
+ ):
+ result = agent.run("Generate morning digest")
+
+ # Verify agent result
+ assert "Good morning" in result.content
+ assert result.metadata["audio_path"] == str(tmp_path / "digest.mp3")
+
+ # Verify stored in DigestStore
+ store = DigestStore(db_path=db_path)
+ artifact = store.get_latest()
+ assert artifact is not None
+ assert "Good morning" in artifact.text
+ assert artifact.model_used == "claude-sonnet-4-6"
+ store.close()
diff --git a/tests/tools/test_digest_collect.py b/tests/tools/test_digest_collect.py
new file mode 100644
index 00000000..ffe5d60b
--- /dev/null
+++ b/tests/tools/test_digest_collect.py
@@ -0,0 +1,60 @@
+"""Tests for the digest_collect tool."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from openjarvis.connectors._stubs import Document
+from openjarvis.core.registry import ConnectorRegistry, ToolRegistry
+
+
+def test_digest_collect_registered():
+ from openjarvis.tools.digest_collect import DigestCollectTool
+
+ ToolRegistry.register_value("digest_collect", DigestCollectTool)
+ assert ToolRegistry.contains("digest_collect")
+
+
+def test_digest_collect_executes():
+ from openjarvis.tools.digest_collect import DigestCollectTool
+
+ tool = DigestCollectTool()
+
+ mock_docs = [
+ Document(
+ doc_id="test-1",
+ source="gmail",
+ doc_type="email",
+ content="Meeting at 3pm",
+ title="Team standup",
+ author="[email protected]",
+ timestamp=datetime(2026, 4, 1, 10, 0),
+ )
+ ]
+
+ mock_connector = MagicMock()
+ mock_connector.return_value.is_connected.return_value = True
+ mock_connector.return_value.sync.return_value = mock_docs
+
+ with patch.object(ConnectorRegistry, "contains", return_value=True):
+ with patch.object(ConnectorRegistry, "get", return_value=mock_connector):
+ result = tool.execute(sources=["gmail"], hours_back=24)
+
+ assert result.success is True
+ assert "gmail (1 items)" in result.content
+ assert result.metadata["total_items"] == 1
+
+
+def test_digest_collect_missing_connector():
+ from openjarvis.tools.digest_collect import DigestCollectTool
+
+ tool = DigestCollectTool()
+
+ with patch.object(ConnectorRegistry, "contains", return_value=False):
+ result = tool.execute(sources=["nonexistent"])
+
+ assert result.success is True # Partial success
+ assert "not available" in result.content
diff --git a/tests/tools/test_text_to_speech.py b/tests/tools/test_text_to_speech.py
new file mode 100644
index 00000000..88ca18c1
--- /dev/null
+++ b/tests/tools/test_text_to_speech.py
@@ -0,0 +1,57 @@
+"""Tests for the text_to_speech tool."""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from openjarvis.core.registry import ToolRegistry
+from openjarvis.speech.tts import TTSResult
+
+
+def test_tts_tool_registered():
+ from openjarvis.tools.text_to_speech import TextToSpeechTool
+
+ ToolRegistry.register_value("text_to_speech", TextToSpeechTool)
+ assert ToolRegistry.contains("text_to_speech")
+
+
+def test_tts_tool_execute(tmp_path):
+ from openjarvis.tools.text_to_speech import TextToSpeechTool
+
+ tool = TextToSpeechTool()
+ mock_result = TTSResult(
+ audio=b"fake-audio-data",
+ format="mp3",
+ voice_id="jarvis",
+ duration_seconds=2.5,
+ )
+
+ with patch(
+ "openjarvis.tools.text_to_speech.TTSRegistry"
+ ) as mock_registry:
+ mock_backend_cls = MagicMock()
+ mock_backend_cls.return_value.synthesize.return_value = mock_result
+ mock_registry.contains.return_value = True
+ mock_registry.get.return_value = mock_backend_cls
+
+ result = tool.execute(
+ text="Good morning sir.",
+ voice_id="jarvis",
+ backend="cartesia",
+ output_dir=str(tmp_path),
+ )
+
+ assert result.success is True
+ assert "digest.mp3" in result.content
+ assert (tmp_path / "digest.mp3").exists()
+ assert (tmp_path / "digest.mp3").read_bytes() == b"fake-audio-data"
+
+
+def test_tts_tool_empty_text():
+ from openjarvis.tools.text_to_speech import TextToSpeechTool
+
+ tool = TextToSpeechTool()
+ result = tool.execute(text="")
+ assert result.success is False