Skip to content

Personal AI, On Personal Devices

Python

fix: resolve all ruff lint and format errors for CI

Jon Saad-Falcon842086aa546c
diff --git a/:memory: b/:memory:
new file mode 100644
index 00000000..e69de29b
diff --git a/src/openjarvis/agents/native_react.py b/src/openjarvis/agents/native_react.py
index 2a8cab5d..2c3cf4cb 100644
--- a/src/openjarvis/agents/native_react.py
+++ b/src/openjarvis/agents/native_react.py
@@ -194,7 +194,8 @@ class NativeReActAgent(ToolUsingAgent):
# Max turns exceeded
msg_dicts = [_message_to_dict(m) for m in messages]
return self._max_turns_result(
- all_tool_results, turns,
+ all_tool_results,
+ turns,
metadata={**total_usage, "messages": msg_dicts},
)
diff --git a/src/openjarvis/channels/sendblue.py b/src/openjarvis/channels/sendblue.py
index c691b05c..6bf27020 100644
--- a/src/openjarvis/channels/sendblue.py
+++ b/src/openjarvis/channels/sendblue.py
@@ -57,15 +57,11 @@ class SendBlueChannel(BaseChannel):
webhook_secret: str = "",
bus: Optional[EventBus] = None,
) -> None:
- self._api_key_id = api_key_id or os.environ.get(
- "SENDBLUE_API_KEY_ID", ""
- )
+ self._api_key_id = api_key_id or os.environ.get("SENDBLUE_API_KEY_ID", "")
self._api_secret_key = api_secret_key or os.environ.get(
"SENDBLUE_API_SECRET_KEY", ""
)
- self._from_number = from_number or os.environ.get(
- "SENDBLUE_FROM_NUMBER", ""
- )
+ self._from_number = from_number or os.environ.get("SENDBLUE_FROM_NUMBER", "")
self._webhook_secret = webhook_secret
self._bus = bus
self._handlers: List[ChannelHandler] = []
@@ -215,9 +211,7 @@ class SendBlueChannel(BaseChannel):
# -- internal helpers -------------------------------------------------------
- def _publish_sent(
- self, channel: str, content: str, conversation_id: str
- ) -> None:
+ def _publish_sent(self, channel: str, content: str, conversation_id: str) -> None:
"""Publish a CHANNEL_MESSAGE_SENT event on the bus."""
if self._bus is not None:
self._bus.publish(
diff --git a/src/openjarvis/channels/slack_daemon.py b/src/openjarvis/channels/slack_daemon.py
index e6e0db55..c4def051 100644
--- a/src/openjarvis/channels/slack_daemon.py
+++ b/src/openjarvis/channels/slack_daemon.py
@@ -63,7 +63,10 @@ def run_slack_daemon(
engine = OllamaEngine()
tools = _build_deep_research_tools(engine=engine, model=model)
agent = DeepResearchAgent(
- engine=engine, model=model, tools=tools, max_turns=5,
+ engine=engine,
+ model=model,
+ tools=tools,
+ max_turns=5,
)
logger.info("Slack daemon: agent ready with %d tools", len(tools))
@@ -143,11 +146,15 @@ def start_slack_daemon(
proc = subprocess.Popen(
[
- sys.executable, "-m",
+ sys.executable,
+ "-m",
"openjarvis.channels.slack_daemon",
- "--bot-token", bot_token,
- "--app-token", app_token,
- "--model", model,
+ "--bot-token",
+ bot_token,
+ "--app-token",
+ app_token,
+ "--model",
+ model,
],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
diff --git a/src/openjarvis/cli/__init__.py b/src/openjarvis/cli/__init__.py
index e640620b..0b460a90 100644
--- a/src/openjarvis/cli/__init__.py
+++ b/src/openjarvis/cli/__init__.py
@@ -17,6 +17,7 @@ from openjarvis.cli.config_cmd import config
from openjarvis.cli.connect_cmd import connect
from openjarvis.cli.daemon_cmd import restart, start, status, stop
from openjarvis.cli.deep_research_setup_cmd import deep_research_setup
+from openjarvis.cli.digest_cmd import digest
from openjarvis.cli.doctor_cmd import doctor
from openjarvis.cli.eval_cmd import eval_group
from openjarvis.cli.feedback_cmd import feedback_group
@@ -36,7 +37,6 @@ 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
diff --git a/src/openjarvis/cli/channel_cmd.py b/src/openjarvis/cli/channel_cmd.py
index a78228d8..c9b50fed 100644
--- a/src/openjarvis/cli/channel_cmd.py
+++ b/src/openjarvis/cli/channel_cmd.py
@@ -138,9 +138,7 @@ def _get_channel(
import os
kwargs["api_key_id"] = os.environ.get("SENDBLUE_API_KEY_ID", "")
- kwargs["api_secret_key"] = os.environ.get(
- "SENDBLUE_API_SECRET_KEY", ""
- )
+ kwargs["api_secret_key"] = os.environ.get("SENDBLUE_API_SECRET_KEY", "")
kwargs["from_number"] = os.environ.get("SENDBLUE_FROM_NUMBER", "")
sbc = getattr(config.channel, "sendblue", None)
if sbc:
diff --git a/src/openjarvis/cli/connect_cmd.py b/src/openjarvis/cli/connect_cmd.py
index cd42ee07..30de233f 100644
--- a/src/openjarvis/cli/connect_cmd.py
+++ b/src/openjarvis/cli/connect_cmd.py
@@ -106,24 +106,18 @@ def _connect_source(registry: object, source: str, path: str = "") -> None:
try:
instance = connector_cls()
if instance.is_connected():
- console.print(
- f"[green]{source} is already connected.[/green]"
- )
+ 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]"
- )
+ 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"[cyan]First-time setup for {source}.[/cyan]")
console.print(
f"[yellow]Create an OAuth app at: {provider.setup_url}[/yellow]"
)
@@ -148,9 +142,7 @@ def _connect_source(registry: object, source: str, path: str = "") -> None:
try:
instance = connector_cls()
if instance.is_connected():
- console.print(
- f"[green]{source} is already connected.[/green]"
- )
+ console.print(f"[green]{source} is already connected.[/green]")
return
token = click.prompt(f"Enter your {source} personal access token")
diff --git a/src/openjarvis/connectors/gcalendar.py b/src/openjarvis/connectors/gcalendar.py
index b5ccfda9..c2548812 100644
--- a/src/openjarvis/connectors/gcalendar.py
+++ b/src/openjarvis/connectors/gcalendar.py
@@ -328,7 +328,9 @@ class GCalendarConnector(BaseConnector):
while True:
try:
events_resp = _gcal_api_events_list(
- token, calendar_id, page_token=page_token,
+ token,
+ calendar_id,
+ page_token=page_token,
time_min=time_min,
)
except httpx.HTTPStatusError:
diff --git a/src/openjarvis/connectors/google_tasks.py b/src/openjarvis/connectors/google_tasks.py
index eff4490a..0f5e0c47 100644
--- a/src/openjarvis/connectors/google_tasks.py
+++ b/src/openjarvis/connectors/google_tasks.py
@@ -17,9 +17,7 @@ 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"
-)
+_DEFAULT_CREDENTIALS_PATH = str(DEFAULT_CONFIG_DIR / "connectors" / "google_tasks.json")
def _tasks_api_get(
@@ -46,9 +44,7 @@ class GoogleTasksConnector(BaseConnector):
def __init__(self, *, credentials_path: str = "") -> None:
self._credentials_path = Path(
- resolve_google_credentials(
- credentials_path or _DEFAULT_CREDENTIALS_PATH
- )
+ resolve_google_credentials(credentials_path or _DEFAULT_CREDENTIALS_PATH)
)
self._status = SyncStatus()
diff --git a/src/openjarvis/connectors/news_rss.py b/src/openjarvis/connectors/news_rss.py
index d4a61e4d..7809e05e 100644
--- a/src/openjarvis/connectors/news_rss.py
+++ b/src/openjarvis/connectors/news_rss.py
@@ -39,12 +39,14 @@ def _parse_rss_items(xml_text: str, max_items: int = 5) -> List[Dict[str, str]]:
for item_el in root.iter("item"):
if len(items) >= max_items:
break
- items.append({
- "title": (item_el.findtext("title") or "").strip(),
- "description": (item_el.findtext("description") or "").strip()[:200],
- "link": (item_el.findtext("link") or "").strip(),
- "pubDate": (item_el.findtext("pubDate") or "").strip(),
- })
+ items.append(
+ {
+ "title": (item_el.findtext("title") or "").strip(),
+ "description": (item_el.findtext("description") or "").strip()[:200],
+ "link": (item_el.findtext("link") or "").strip(),
+ "pubDate": (item_el.findtext("pubDate") or "").strip(),
+ }
+ )
# Atom: <feed><entry>
if not items:
@@ -56,14 +58,16 @@ def _parse_rss_items(xml_text: str, max_items: int = 5) -> List[Dict[str, str]]:
link_href = link_el.get("href", "") if link_el is not None else ""
summary = entry_el.findtext("{http://www.w3.org/2005/Atom}summary") or ""
updated = entry_el.findtext("{http://www.w3.org/2005/Atom}updated") or ""
- items.append({
- "title": (
- entry_el.findtext("{http://www.w3.org/2005/Atom}title") or ""
- ).strip(),
- "description": summary.strip()[:200],
- "link": link_href.strip(),
- "pubDate": updated.strip(),
- })
+ items.append(
+ {
+ "title": (
+ entry_el.findtext("{http://www.w3.org/2005/Atom}title") or ""
+ ).strip(),
+ "description": summary.strip()[:200],
+ "link": link_href.strip(),
+ "pubDate": updated.strip(),
+ }
+ )
return items
diff --git a/src/openjarvis/connectors/oauth.py b/src/openjarvis/connectors/oauth.py
index 998347c8..7538386f 100644
--- a/src/openjarvis/connectors/oauth.py
+++ b/src/openjarvis/connectors/oauth.py
@@ -108,10 +108,7 @@ OAUTH_PROVIDERS: Dict[str, OAuthProvider] = {
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"
- ),
+ setup_hint=("Create an app, add redirect URI: http://127.0.0.1:8888/callback"),
callback_port=8888,
token_auth="basic",
connector_ids=("spotify",),
@@ -177,9 +174,7 @@ def save_client_credentials(
# Shared credentials file — one OAuth flow covers all Google connectors
# ---------------------------------------------------------------------------
-_SHARED_GOOGLE_CREDENTIALS_PATH: str = str(
- _CONNECTORS_DIR / "google.json"
-)
+_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"
@@ -580,17 +575,13 @@ def _exchange_token(
headers: Dict[str, str] = {}
if provider.token_auth == "basic":
- creds = base64.b64encode(
- f"{client_id}:{client_secret}".encode()
- ).decode()
+ 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 = httpx.post(provider.token_endpoint, data=data, headers=headers, timeout=30.0)
resp.raise_for_status()
return resp.json()
@@ -652,9 +643,7 @@ def run_connector_oauth(
)
# Exchange code for tokens
- tokens = _exchange_token(
- provider, code, client_id, client_secret, redirect_uri
- )
+ tokens = _exchange_token(provider, code, client_id, client_secret, redirect_uri)
# Build payload with client credentials included (needed for refresh)
payload = {
diff --git a/src/openjarvis/connectors/slack_connector.py b/src/openjarvis/connectors/slack_connector.py
index 65c8a715..1eb58c25 100644
--- a/src/openjarvis/connectors/slack_connector.py
+++ b/src/openjarvis/connectors/slack_connector.py
@@ -302,7 +302,9 @@ class SlackConnector(BaseConnector):
# Try to join the public channel
try:
join_resp = _slack_api_with_retry(
- "conversations.join", token, {"channel": chan_id},
+ "conversations.join",
+ token,
+ {"channel": chan_id},
http_method="POST",
)
if not join_resp.get("ok"):
diff --git a/src/openjarvis/connectors/weather.py b/src/openjarvis/connectors/weather.py
index c92291fa..90559742 100644
--- a/src/openjarvis/connectors/weather.py
+++ b/src/openjarvis/connectors/weather.py
@@ -20,9 +20,7 @@ from openjarvis.core.registry import ConnectorRegistry
_DEFAULT_TOKEN_PATH = str(DEFAULT_CONFIG_DIR / "connectors" / "weather.json")
-def _weather_api_get(
- url: str, params: Dict[str, str]
-) -> Dict[str, Any]:
+def _weather_api_get(url: str, params: Dict[str, str]) -> Dict[str, Any]:
"""Call an OpenWeatherMap API endpoint."""
resp = httpx.get(url, params=params, timeout=30.0)
resp.raise_for_status()
@@ -112,9 +110,7 @@ class WeatherConnector(BaseConnector):
for entry in forecast.get("list", []):
dt_txt = entry.get("dt_txt", "")
temp = entry.get("main", {}).get("temp")
- desc = ", ".join(
- w.get("description", "") for w in entry.get("weather", [])
- )
+ desc = ", ".join(w.get("description", "") for w in entry.get("weather", []))
summaries.append(f"{dt_txt}: {temp}°F, {desc}")
forecast_content = "Forecast:\n" + "\n".join(summaries)
diff --git a/src/openjarvis/core/config.py b/src/openjarvis/core/config.py
index 7d6c9821..77260d52 100644
--- a/src/openjarvis/core/config.py
+++ b/src/openjarvis/core/config.py
@@ -1271,9 +1271,7 @@ class DigestConfig:
default_factory=lambda: DigestSectionConfig(sources=["gcalendar"])
)
health: DigestSectionConfig = field(
- default_factory=lambda: DigestSectionConfig(
- sources=["oura", "apple_health"]
- )
+ default_factory=lambda: DigestSectionConfig(sources=["oura", "apple_health"])
)
world: DigestSectionConfig = field(
default_factory=lambda: DigestSectionConfig(sources=[])
diff --git a/src/openjarvis/evals/cli.py b/src/openjarvis/evals/cli.py
index 69c9506a..b3bdeeeb 100644
--- a/src/openjarvis/evals/cli.py
+++ b/src/openjarvis/evals/cli.py
@@ -326,6 +326,7 @@ def _build_dataset(benchmark: str, subset: str | None = None):
return PinchBenchDataset(path=subset)
elif benchmark == "taubench":
from openjarvis.evals.datasets.taubench import TauBenchDataset
+
domains = subset.split(",") if subset else None
return TauBenchDataset(domains=domains)
elif benchmark == "livecodebench":
@@ -478,6 +479,7 @@ def _build_scorer(benchmark: str, judge_backend, judge_model: str):
return PinchBenchScorer(judge_backend, judge_model)
elif benchmark == "taubench":
from openjarvis.evals.scorers.taubench import TauBenchScorer
+
return TauBenchScorer(judge_backend, judge_model)
elif benchmark == "livecodebench":
from openjarvis.evals.scorers.livecodebench import LiveCodeBenchScorer
diff --git a/src/openjarvis/evals/core/runner.py b/src/openjarvis/evals/core/runner.py
index ec66648e..1c8eeadf 100644
--- a/src/openjarvis/evals/core/runner.py
+++ b/src/openjarvis/evals/core/runner.py
@@ -361,9 +361,7 @@ class EvalRunner:
"completion_tokens", 0
)
if param_b > 0 and total_tokens > 0:
- flops_per_tok = estimate_model_flops_per_token(
- param_b, active_b
- )
+ flops_per_tok = estimate_model_flops_per_token(param_b, active_b)
estimated_flops = flops_per_tok * total_tokens
# Extract derived and ITL metrics from _telemetry dict
@@ -1098,12 +1096,8 @@ def _summary_to_dict(s: RunSummary) -> Dict[str, Any]:
"energy_stats": _metric_stats_to_dict(s.energy_stats),
"power_stats": _metric_stats_to_dict(s.power_stats),
"flops_stats": _metric_stats_to_dict(s.flops_stats),
- "ipw": (
- s.efficiency.get("ipw") if s.efficiency else None
- ),
- "ipj": (
- s.efficiency.get("ipj") if s.efficiency else None
- ),
+ "ipw": (s.efficiency.get("ipw") if s.efficiency else None),
+ "ipj": (s.efficiency.get("ipj") if s.efficiency else None),
},
}
diff --git a/src/openjarvis/evals/datasets/livecodebench.py b/src/openjarvis/evals/datasets/livecodebench.py
index ddaf0250..12f9e69e 100644
--- a/src/openjarvis/evals/datasets/livecodebench.py
+++ b/src/openjarvis/evals/datasets/livecodebench.py
@@ -163,25 +163,17 @@ class LiveCodeBenchDataset(DatasetProvider):
# Extract title
title = str(
- raw.get("question_title")
- or raw.get("title")
- or raw.get("name")
- or ""
+ raw.get("question_title") or raw.get("title") or raw.get("name") or ""
).strip()
# Extract difficulty
difficulty = str(
- raw.get("difficulty")
- or raw.get("question_difficulty")
- or ""
+ raw.get("difficulty") or raw.get("question_difficulty") or ""
).strip()
# Extract platform/source
platform = str(
- raw.get("platform")
- or raw.get("source")
- or raw.get("contest_source")
- or ""
+ raw.get("platform") or raw.get("source") or raw.get("contest_source") or ""
).strip()
# Extract input/output format (may not always be separate fields)
@@ -266,8 +258,10 @@ class LiveCodeBenchDataset(DatasetProvider):
metadata[key] = val
# Build subject from platform and difficulty
- subject = f"{platform}/{difficulty}" if platform and difficulty else (
- platform or difficulty or "competitive-programming"
+ subject = (
+ f"{platform}/{difficulty}"
+ if platform and difficulty
+ else (platform or difficulty or "competitive-programming")
)
return EvalRecord(
diff --git a/src/openjarvis/evals/datasets/taubench.py b/src/openjarvis/evals/datasets/taubench.py
index 6fbb1d5a..896a17f8 100644
--- a/src/openjarvis/evals/datasets/taubench.py
+++ b/src/openjarvis/evals/datasets/taubench.py
@@ -129,6 +129,7 @@ class TauBenchDataset(DatasetProvider):
# Load tasks, filtering to test split when available
from tau2.runner import load_task_splits
+
try:
task_splits = load_task_splits(domain)
test_ids = (
@@ -144,12 +145,14 @@ class TauBenchDataset(DatasetProvider):
tasks = [t for t in tasks if str(t.id) in test_ids]
LOGGER.info(
"TauBench: loaded %d test-split tasks for domain '%s'",
- len(tasks), domain,
+ len(tasks),
+ domain,
)
else:
LOGGER.info(
"TauBench: loaded %d tasks for domain '%s' (no test split)",
- len(tasks), domain,
+ len(tasks),
+ domain,
)
for task in tasks:
@@ -206,6 +209,7 @@ class TauBenchDataset(DatasetProvider):
if seed is not None:
import random
+
random.Random(seed).shuffle(all_records)
if max_samples is not None:
all_records = all_records[:max_samples]
@@ -226,6 +230,7 @@ class TauBenchDataset(DatasetProvider):
def create_task_env(self, record: EvalRecord):
"""Create a TauBench task environment for evaluation."""
from openjarvis.evals.execution.taubench_env import TauBenchTaskEnv
+
return TauBenchTaskEnv(
record,
engine_key=self._engine_key,
diff --git a/src/openjarvis/evals/datasets/toolcall15.py b/src/openjarvis/evals/datasets/toolcall15.py
index 4b2225c1..1b0dcd5c 100644
--- a/src/openjarvis/evals/datasets/toolcall15.py
+++ b/src/openjarvis/evals/datasets/toolcall15.py
@@ -310,18 +310,18 @@ SCENARIOS: List[Dict[str, Any]] = [
"category": "A-ToolSelection",
"user_message": "What's the weather like in Berlin right now?",
"mock_tool_outputs": {
- "get_weather": json.dumps({
- "location": "Berlin",
- "temperature": 8,
- "units": "celsius",
- "condition": "Overcast",
- "humidity": 72,
- }),
- "web_search": json.dumps({
- "results": [
- {"snippet": "Berlin weather right now: 8C and overcast."}
- ]
- }),
+ "get_weather": json.dumps(
+ {
+ "location": "Berlin",
+ "temperature": 8,
+ "units": "celsius",
+ "condition": "Overcast",
+ "humidity": 72,
+ }
+ ),
+ "web_search": json.dumps(
+ {"results": [{"snippet": "Berlin weather right now: 8C and overcast."}]}
+ ),
},
},
{
@@ -330,18 +330,18 @@ SCENARIOS: List[Dict[str, Any]] = [
"category": "A-ToolSelection",
"user_message": "What is the current price of AAPL stock?",
"mock_tool_outputs": {
- "get_stock_price": json.dumps({
- "ticker": "AAPL",
- "price": 187.42,
- "currency": "USD",
- "change": "+1.23",
- "change_percent": "+0.66%",
- }),
- "web_search": json.dumps({
- "results": [
- {"snippet": "AAPL is trading around $187.42."}
- ]
- }),
+ "get_stock_price": json.dumps(
+ {
+ "ticker": "AAPL",
+ "price": 187.42,
+ "currency": "USD",
+ "change": "+1.23",
+ "change_percent": "+0.66%",
+ }
+ ),
+ "web_search": json.dumps(
+ {"results": [{"snippet": "AAPL is trading around $187.42."}]}
+ ),
},
},
{
@@ -350,15 +350,15 @@ SCENARIOS: List[Dict[str, Any]] = [
"category": "A-ToolSelection",
"user_message": "I need to let Sarah know the meeting moved to 3pm.",
"mock_tool_outputs": {
- "get_contacts": json.dumps({
- "results": [
- {"name": "Sarah Chen", "email": "[email protected]"}
- ]
- }),
- "send_email": json.dumps({
- "status": "sent",
- "message_id": "msg_8821",
- }),
+ "get_contacts": json.dumps(
+ {"results": [{"name": "Sarah Chen", "email": "[email protected]"}]}
+ ),
+ "send_email": json.dumps(
+ {
+ "status": "sent",
+ "message_id": "msg_8821",
+ }
+ ),
},
},
# --- Category B: Parameter Precision ---
@@ -368,21 +368,25 @@ SCENARIOS: List[Dict[str, Any]] = [
"category": "B-ParameterPrecision",
"user_message": "What's the temperature in Tokyo in Fahrenheit?",
"mock_tool_outputs": {
- "get_weather": json.dumps({
- "location": "Tokyo",
- "temperature": 64,
- "units": "fahrenheit",
- "condition": "Clear",
- "humidity": 55,
- }),
+ "get_weather": json.dumps(
+ {
+ "location": "Tokyo",
+ "temperature": 64,
+ "units": "fahrenheit",
+ "condition": "Clear",
+ "humidity": 55,
+ }
+ ),
# Default (celsius) mock for partial-credit scoring
- "get_weather__default": json.dumps({
- "location": "Tokyo",
- "temperature": 18,
- "units": "celsius",
- "condition": "Clear",
- "humidity": 55,
- }),
+ "get_weather__default": json.dumps(
+ {
+ "location": "Tokyo",
+ "temperature": 18,
+ "units": "celsius",
+ "condition": "Clear",
+ "humidity": 55,
+ }
+ ),
},
},
{
@@ -394,18 +398,22 @@ SCENARIOS: List[Dict[str, Any]] = [
"30 minutes, with Alex and Jamie."
),
"mock_tool_outputs": {
- "get_contacts": json.dumps({
- "results": [
- {"name": "Alex Stone", "email": "[email protected]"},
- {"name": "Jamie Liu", "email": "[email protected]"},
- ]
- }),
- "create_calendar_event": json.dumps({
- "event_id": "evt_4412",
- "status": "created",
- "title": "Team Standup",
- "date": "2026-03-23",
- }),
+ "get_contacts": json.dumps(
+ {
+ "results": [
+ {"name": "Alex Stone", "email": "[email protected]"},
+ {"name": "Jamie Liu", "email": "[email protected]"},
+ ]
+ }
+ ),
+ "create_calendar_event": json.dumps(
+ {
+ "event_id": "evt_4412",
+ "status": "created",
+ "title": "Team Standup",
+ "date": "2026-03-23",
+ }
+ ),
},
# Reference date is 2026-03-20 (Friday), next Monday = 2026-03-23
"reference_date": "2026-03-20",
@@ -419,12 +427,16 @@ SCENARIOS: List[Dict[str, Any]] = [
"from English to both Spanish and Japanese."
),
"mock_tool_outputs": {
- "translate_text__spanish": json.dumps({
- "translated": "\u00bfD\u00f3nde est\u00e1 el hospital m\u00e1s cercano?",
- }),
- "translate_text__japanese": json.dumps({
- "translated": "\u6700\u5bc4\u308a\u306e\u75c5\u9662\u306f\u3069\u3053\u3067\u3059\u304b\uff1f",
- }),
+ "translate_text__spanish": json.dumps(
+ {
+ "translated": "\u00bfD\u00f3nde est\u00e1 el hospital m\u00e1s cercano?",
+ }
+ ),
+ "translate_text__japanese": json.dumps(
+ {
+ "translated": "\u6700\u5bc4\u308a\u306e\u75c5\u9662\u306f\u3069\u3053\u3067\u3059\u304b\uff1f",
+ }
+ ),
},
},
# --- Category C: Multi-Step Chains ---
@@ -436,29 +448,35 @@ SCENARIOS: List[Dict[str, Any]] = [
"Find the Q3 budget report and email the total to my manager."
),
"mock_tool_outputs": {
- "search_files": json.dumps({
- "results": [
- {
- "file_id": "file_091",
- "name": "Q3_Budget_Report_2025.xlsx",
- }
- ]
- }),
- "read_file": json.dumps({
- "content": (
- "Department budgets: Engineering $2.1M, Marketing $800K, "
- "Sales $1.5M. Total: $4.4M"
- ),
- }),
- "get_contacts": json.dumps({
- "results": [
- {
- "name": "Jordan Park",
- "email": "[email protected]",
- "role": "manager",
- }
- ]
- }),
+ "search_files": json.dumps(
+ {
+ "results": [
+ {
+ "file_id": "file_091",
+ "name": "Q3_Budget_Report_2025.xlsx",
+ }
+ ]
+ }
+ ),
+ "read_file": json.dumps(
+ {
+ "content": (
+ "Department budgets: Engineering $2.1M, Marketing $800K, "
+ "Sales $1.5M. Total: $4.4M"
+ ),
+ }
+ ),
+ "get_contacts": json.dumps(
+ {
+ "results": [
+ {
+ "name": "Jordan Park",
+ "email": "[email protected]",
+ "role": "manager",
+ }
+ ]
+ }
+ ),
"send_email": json.dumps({"status": "sent"}),
},
},
@@ -471,16 +489,20 @@ SCENARIOS: List[Dict[str, Any]] = [
"remind me to bring an umbrella tomorrow at 8am."
),
"mock_tool_outputs": {
- "get_weather": json.dumps({
- "location": "Paris",
- "temperature": 11,
- "condition": "Light rain",
- "humidity": 89,
- }),
- "set_reminder": json.dumps({
- "reminder_id": "rem_553",
- "status": "set",
- }),
+ "get_weather": json.dumps(
+ {
+ "location": "Paris",
+ "temperature": 11,
+ "condition": "Light rain",
+ "humidity": 89,
+ }
+ ),
+ "set_reminder": json.dumps(
+ {
+ "reminder_id": "rem_553",
+ "status": "set",
+ }
+ ),
},
"reference_date": "2026-03-20",
},
@@ -488,29 +510,33 @@ SCENARIOS: List[Dict[str, Any]] = [
"id": "TC-09",
"name": "Parallel Independence",
"category": "C-MultiStepChains",
- "user_message": (
- "What's the weather in London and the stock price of MSFT?"
- ),
+ "user_message": ("What's the weather in London and the stock price of MSFT?"),
"mock_tool_outputs": {
- "get_weather": json.dumps({
- "location": "London",
- "temperature": 12,
- "condition": "Cloudy",
- }),
- "get_stock_price": json.dumps({
- "ticker": "MSFT",
- "price": 412.78,
- "currency": "USD",
- }),
- "web_search": json.dumps({
- "results": [
- {
- "snippet": (
- "London is cloudy at 12C and MSFT is around $412.78."
- )
- }
- ]
- }),
+ "get_weather": json.dumps(
+ {
+ "location": "London",
+ "temperature": 12,
+ "condition": "Cloudy",
+ }
+ ),
+ "get_stock_price": json.dumps(
+ {
+ "ticker": "MSFT",
+ "price": 412.78,
+ "currency": "USD",
+ }
+ ),
+ "web_search": json.dumps(
+ {
+ "results": [
+ {
+ "snippet": (
+ "London is cloudy at 12C and MSFT is around $412.78."
+ )
+ }
+ ]
+ }
+ ),
},
},
# --- Category D: Restraint & Refusal ---
@@ -546,14 +572,16 @@ SCENARIOS: List[Dict[str, Any]] = [
"mock_tool_outputs": {
# First call returns empty, second (broader) returns a result
"search_files__first": json.dumps({"results": []}),
- "search_files__retry": json.dumps({
- "results": [
- {
- "file_id": "file_117",
- "name": "Johnson_Project_Proposal_v2.docx",
- }
- ]
- }),
+ "search_files__retry": json.dumps(
+ {
+ "results": [
+ {
+ "file_id": "file_117",
+ "name": "Johnson_Project_Proposal_v2.docx",
+ }
+ ]
+ }
+ ),
},
},
{
@@ -562,14 +590,14 @@ SCENARIOS: List[Dict[str, Any]] = [
"category": "E-ErrorRecovery",
"user_message": "What's Apple's stock price?",
"mock_tool_outputs": {
- "get_stock_price": json.dumps({
- "error": "Service temporarily unavailable. Rate limit exceeded.",
- }),
- "web_search": json.dumps({
- "results": [
- {"snippet": "Apple (AAPL) is trading around $187.42."}
- ]
- }),
+ "get_stock_price": json.dumps(
+ {
+ "error": "Service temporarily unavailable. Rate limit exceeded.",
+ }
+ ),
+ "web_search": json.dumps(
+ {"results": [{"snippet": "Apple (AAPL) is trading around $187.42."}]}
+ ),
},
},
{
@@ -577,20 +605,21 @@ SCENARIOS: List[Dict[str, Any]] = [
"name": "Conflicting Information",
"category": "E-ErrorRecovery",
"user_message": (
- "Search for the population of Iceland "
- "and calculate what 2% of it would be."
+ "Search for the population of Iceland and calculate what 2% of it would be."
),
"mock_tool_outputs": {
- "web_search": json.dumps({
- "results": [
- {
- "snippet": (
- "Iceland has a population of approximately "
- "372,520 as of 2025."
- )
- }
- ]
- }),
+ "web_search": json.dumps(
+ {
+ "results": [
+ {
+ "snippet": (
+ "Iceland has a population of approximately "
+ "372,520 as of 2025."
+ )
+ }
+ ]
+ }
+ ),
"calculator": json.dumps({"result": 7450.4}),
},
},
@@ -629,9 +658,7 @@ class ToolCall15Dataset(DatasetProvider):
scenarios = [
s
for s in scenarios
- if any(
- s["category"].upper().startswith(fc) for fc in filter_cats
- )
+ if any(s["category"].upper().startswith(fc) for fc in filter_cats)
]
if seed is not None:
diff --git a/src/openjarvis/evals/execution/taubench_env.py b/src/openjarvis/evals/execution/taubench_env.py
index 0b5dcee2..925f4494 100644
--- a/src/openjarvis/evals/execution/taubench_env.py
+++ b/src/openjarvis/evals/execution/taubench_env.py
@@ -22,6 +22,7 @@ LOGGER = logging.getLogger(__name__)
# Message conversion helpers
# ---------------------------------------------------------------------------
+
def _tau2_to_oj_messages(
tau2_messages: list,
) -> list:
@@ -59,13 +60,12 @@ def _tau2_to_oj_messages(
)
)
else:
- oj_msgs.append(
- Message(role=Role.ASSISTANT, content=m.content or "")
- )
+ oj_msgs.append(Message(role=Role.ASSISTANT, content=m.content or ""))
elif role_str == "tool":
# tau2 ToolMessage uses 'id', not 'tool_call_id'
raw_id = getattr(m, "id", "") or getattr(m, "tool_call_id", "") or ""
import re as _re
+
clean_id = _re.sub(r"[^a-zA-Z0-9_-]", "_", raw_id)
oj_msgs.append(
Message(
@@ -111,6 +111,7 @@ def _oj_result_to_tau2_msg(result: dict):
# Jarvis-powered tau2 agent
# ---------------------------------------------------------------------------
+
class JarvisHalfDuplexAgent:
"""A tau2 HalfDuplexAgent backed by OpenJarvis's inference engine.
@@ -139,6 +140,7 @@ class JarvisHalfDuplexAgent:
@property
def system_prompt(self) -> str:
from tau2.agent.llm_agent import AGENT_INSTRUCTION, SYSTEM_PROMPT
+
return SYSTEM_PROMPT.format(
domain_policy=self.domain_policy,
agent_instruction=AGENT_INSTRUCTION,
@@ -147,6 +149,7 @@ class JarvisHalfDuplexAgent:
def get_init_state(self, message_history=None):
from tau2.agent.llm_agent import LLMAgentState
from tau2.data_model.message import SystemMessage
+
return LLMAgentState(
system_messages=[
SystemMessage(role="system", content=self.system_prompt),
@@ -211,6 +214,7 @@ class JarvisHalfDuplexAgent:
# Task environment
# ---------------------------------------------------------------------------
+
class TauBenchTaskEnv:
"""Per-task environment for TauBench evaluation.
@@ -315,9 +319,7 @@ class TauBenchTaskEnv:
)
reward = (
- simulation.reward_info.reward
- if simulation.reward_info
- else 0.0
+ simulation.reward_info.reward if simulation.reward_info else 0.0
)
info: dict = {}
if simulation.reward_info:
@@ -331,11 +333,16 @@ class TauBenchTaskEnv:
trial_label = (
f" (trial {trial + 1}/{self._num_trials})"
- if self._num_trials > 1 else ""
+ if self._num_trials > 1
+ else ""
)
LOGGER.info(
"TauBench %s/%s: reward=%.2f messages=%d%s",
- domain, task_id, reward, n_messages, trial_label,
+ domain,
+ task_id,
+ reward,
+ n_messages,
+ trial_label,
)
if reward > best_reward:
@@ -350,7 +357,9 @@ class TauBenchTaskEnv:
except Exception as exc:
LOGGER.error(
"TauBench simulation failed for %s/%s: %s",
- domain, task_id, exc,
+ domain,
+ task_id,
+ exc,
)
self._record.metadata["tau_reward"] = best_reward
diff --git a/src/openjarvis/evals/scorers/livecodebench.py b/src/openjarvis/evals/scorers/livecodebench.py
index 2233820d..38ad7348 100644
--- a/src/openjarvis/evals/scorers/livecodebench.py
+++ b/src/openjarvis/evals/scorers/livecodebench.py
@@ -43,11 +43,21 @@ def _extract_code(answer: str) -> str:
in_code = False
for line in lines:
stripped = line.lstrip()
- if stripped.startswith((
- "def ", "class ", "from ", "import ",
- "n = ", "t = ", "for ", "while ",
- "input(", "sys.stdin", "print(",
- )):
+ if stripped.startswith(
+ (
+ "def ",
+ "class ",
+ "from ",
+ "import ",
+ "n = ",
+ "t = ",
+ "for ",
+ "while ",
+ "input(",
+ "sys.stdin",
+ "print(",
+ )
+ ):
in_code = True
if in_code:
code_lines.append(line)
@@ -211,11 +221,13 @@ class LiveCodeBenchScorer(Scorer):
ok, detail = _run_single_test(code, inp, expected, timeout=timeout)
if ok:
passed += 1
- test_details.append({
- "test_index": i,
- "passed": ok,
- "detail": detail,
- })
+ test_details.append(
+ {
+ "test_index": i,
+ "passed": ok,
+ "detail": detail,
+ }
+ )
if total == 0:
return None, {"reason": "no_test_cases_after_filtering"}
diff --git a/src/openjarvis/evals/scorers/liveresearch.py b/src/openjarvis/evals/scorers/liveresearch.py
index a7db6649..a744fff0 100644
--- a/src/openjarvis/evals/scorers/liveresearch.py
+++ b/src/openjarvis/evals/scorers/liveresearch.py
@@ -277,9 +277,7 @@ class LiveResearchBenchScorer(LLMJudgeScorer):
try:
raw = self._ask_judge(prompt, temperature=0.0, max_tokens=4096)
except Exception as exc:
- LOGGER.error(
- "LLM judge call failed for %s: %s", record.record_id, exc
- )
+ LOGGER.error("LLM judge call failed for %s: %s", record.record_id, exc)
return None, {"error": str(exc), "score": 0.0}
parsed = _parse_judge_response(raw)
diff --git a/src/openjarvis/evals/scorers/taubench.py b/src/openjarvis/evals/scorers/taubench.py
index 227640de..35f9804a 100644
--- a/src/openjarvis/evals/scorers/taubench.py
+++ b/src/openjarvis/evals/scorers/taubench.py
@@ -28,7 +28,9 @@ class TauBenchScorer(Scorer):
self._judge_model = judge_model
def score(
- self, record: EvalRecord, model_answer: str,
+ self,
+ record: EvalRecord,
+ model_answer: str,
) -> Tuple[Optional[bool], Dict[str, Any]]:
reward = record.metadata.get("tau_reward", 0.0)
info = record.metadata.get("tau_info", {})
diff --git a/src/openjarvis/evals/scorers/toolcall15.py b/src/openjarvis/evals/scorers/toolcall15.py
index 40f72288..51c32946 100644
--- a/src/openjarvis/evals/scorers/toolcall15.py
+++ b/src/openjarvis/evals/scorers/toolcall15.py
@@ -35,19 +35,23 @@ def _extract_tool_calls(record: EvalRecord) -> List[Dict[str, Any]]:
for tc in getattr(turn, "tool_calls", []):
if tc is None:
continue
- tool_calls.append({
- "name": tc.get("name", ""),
- "arguments": tc.get("arguments") or {},
- })
+ tool_calls.append(
+ {
+ "name": tc.get("name", ""),
+ "arguments": tc.get("arguments") or {},
+ }
+ )
return tool_calls
# Try tool_results list (from JarvisAgentBackend)
tool_results = record.metadata.get("tool_results", [])
for tr in tool_results:
- tool_calls.append({
- "name": tr.get("tool_name", ""),
- "arguments": tr.get("arguments") or {},
- })
+ tool_calls.append(
+ {
+ "name": tr.get("tool_name", ""),
+ "arguments": tr.get("arguments") or {},
+ }
+ )
return tool_calls
@@ -84,7 +88,8 @@ def _arg_equals(tc: Dict[str, Any], key: str, value: str) -> bool:
def _score_tc01(
- tool_calls: List[Dict[str, Any]], answer: str,
+ tool_calls: List[Dict[str, Any]],
+ answer: str,
) -> Tuple[int, str]:
"""TC-01: Direct Specialist Match — get_weather for Berlin."""
weather = _tools_called(tool_calls, "get_weather")
@@ -102,7 +107,8 @@ def _score_tc01(
def _score_tc02(
- tool_calls: List[Dict[str, Any]], answer: str,
+ tool_calls: List[Dict[str, Any]],
+ answer: str,
) -> Tuple[int, str]:
"""TC-02: Distractor Resistance — get_stock_price for AAPL only."""
stock = _tools_called(tool_calls, "get_stock_price")
@@ -120,16 +126,15 @@ def _score_tc02(
def _score_tc03(
- tool_calls: List[Dict[str, Any]], answer: str,
+ tool_calls: List[Dict[str, Any]],
+ answer: str,
) -> Tuple[int, str]:
"""TC-03: Implicit Tool Need — get_contacts then send_email."""
contacts = _tools_called(tool_calls, "get_contacts")
email = _tools_called(tool_calls, "send_email")
if contacts and email:
- contact_has_sarah = any(
- _arg_contains(tc, "query", "sarah") for tc in contacts
- )
+ contact_has_sarah = any(_arg_contains(tc, "query", "sarah") for tc in contacts)
email_has_addr = any(
_arg_contains(tc, "to", "[email protected]") for tc in email
)
@@ -148,7 +153,8 @@ def _score_tc03(
def _score_tc04(
- tool_calls: List[Dict[str, Any]], answer: str,
+ tool_calls: List[Dict[str, Any]],
+ answer: str,
) -> Tuple[int, str]:
"""TC-04: Unit Handling — get_weather(Tokyo, units=fahrenheit)."""
weather = _tools_called(tool_calls, "get_weather")
@@ -170,7 +176,8 @@ def _score_tc04(
def _score_tc05(
- tool_calls: List[Dict[str, Any]], answer: str,
+ tool_calls: List[Dict[str, Any]],
+ answer: str,
) -> Tuple[int, str]:
"""TC-05: Date and Time Parsing — create_calendar_event with correct fields."""
events = _tools_called(tool_calls, "create_calendar_event")
@@ -190,7 +197,9 @@ def _score_tc05(
time_ok = time_val in ("09:30", "9:30")
duration_ok = duration == 30 or str(duration) == "30"
- attendees_lower = [a.lower() if isinstance(a, str) else "" for a in (attendees or [])]
+ attendees_lower = [
+ a.lower() if isinstance(a, str) else "" for a in (attendees or [])
+ ]
attendees_str = " ".join(attendees_lower)
has_alex = "alex" in attendees_str
has_jamie = "jamie" in attendees_str
@@ -203,7 +212,8 @@ def _score_tc05(
def _score_tc06(
- tool_calls: List[Dict[str, Any]], answer: str,
+ tool_calls: List[Dict[str, Any]],
+ answer: str,
) -> Tuple[int, str]:
"""TC-06: Multi-Value Extraction — two translate_text calls."""
translates = _tools_called(tool_calls, "translate_text")
@@ -229,7 +239,8 @@ def _score_tc06(
def _score_tc07(
- tool_calls: List[Dict[str, Any]], answer: str,
+ tool_calls: List[Dict[str, Any]],
+ answer: str,
) -> Tuple[int, str]:
"""TC-07: Search -> Read -> Act — 4-step chain."""
search = _tools_called(tool_calls, "search_files")
@@ -237,24 +248,20 @@ def _score_tc07(
contacts = _tools_called(tool_calls, "get_contacts")
email = _tools_called(tool_calls, "send_email")
- steps_done = sum([
- bool(search),
- bool(read),
- bool(contacts),
- bool(email),
- ])
+ steps_done = sum(
+ [
+ bool(search),
+ bool(read),
+ bool(contacts),
+ bool(email),
+ ]
+ )
if steps_done == 4:
# Verify data threading
- has_file_id = any(
- _arg_contains(tc, "file_id", "file_091") for tc in read
- )
- has_manager = any(
- _arg_contains(tc, "query", "manager") for tc in contacts
- )
- has_total = any(
- _arg_contains(tc, "body", "4.4") for tc in email
- )
+ has_file_id = any(_arg_contains(tc, "file_id", "file_091") for tc in read)
+ has_manager = any(_arg_contains(tc, "query", "manager") for tc in contacts)
+ has_total = any(_arg_contains(tc, "body", "4.4") for tc in email)
email_to = any(
_arg_contains(tc, "to", "[email protected]") for tc in email
)
@@ -268,16 +275,15 @@ def _score_tc07(
def _score_tc08(
- tool_calls: List[Dict[str, Any]], answer: str,
+ tool_calls: List[Dict[str, Any]],
+ answer: str,
) -> Tuple[int, str]:
"""TC-08: Conditional Branching — weather check then conditional reminder."""
weather = _tools_called(tool_calls, "get_weather")
reminder = _tools_called(tool_calls, "set_reminder")
if weather and reminder:
- weather_paris = any(
- _arg_contains(tc, "location", "paris") for tc in weather
- )
+ weather_paris = any(_arg_contains(tc, "location", "paris") for tc in weather)
reminder_umbrella = any(
_arg_contains(tc, "message", "umbrella") for tc in reminder
)
@@ -296,19 +302,16 @@ def _score_tc08(
def _score_tc09(
- tool_calls: List[Dict[str, Any]], answer: str,
+ tool_calls: List[Dict[str, Any]],
+ answer: str,
) -> Tuple[int, str]:
"""TC-09: Parallel Independence — weather AND stock price."""
weather = _tools_called(tool_calls, "get_weather")
stock = _tools_called(tool_calls, "get_stock_price")
web = _tools_called(tool_calls, "web_search")
- weather_london = any(
- _arg_contains(tc, "location", "london") for tc in weather
- )
- stock_msft = any(
- _arg_contains(tc, "ticker", "msft") for tc in stock
- )
+ weather_london = any(_arg_contains(tc, "location", "london") for tc in weather)
+ stock_msft = any(_arg_contains(tc, "ticker", "msft") for tc in stock)
if weather_london and stock_msft:
return 2, "PASS: both get_weather(London) and get_stock_price(MSFT)"
@@ -321,7 +324,8 @@ def _score_tc09(
def _score_tc10(
- tool_calls: List[Dict[str, Any]], answer: str,
+ tool_calls: List[Dict[str, Any]],
+ answer: str,
) -> Tuple[int, str]:
"""TC-10: Trivial Knowledge — answer without tools."""
if not tool_calls and "1945" in answer:
@@ -332,7 +336,8 @@ def _score_tc10(
def _score_tc11(
- tool_calls: List[Dict[str, Any]], answer: str,
+ tool_calls: List[Dict[str, Any]],
+ answer: str,
) -> Tuple[int, str]:
"""TC-11: Simple Math — answer without tools."""
if not tool_calls and "30" in answer:
@@ -351,14 +356,22 @@ def _score_tc11(
def _score_tc12(
- tool_calls: List[Dict[str, Any]], answer: str,
+ tool_calls: List[Dict[str, Any]],
+ answer: str,
) -> Tuple[int, str]:
"""TC-12: Impossible Request — refuse without tool calls."""
lower = answer.lower()
refusal_phrases = [
- "cannot", "can't", "do not have", "don't have",
- "not able", "unable", "no tool", "not available",
- "not possible", "no way to",
+ "cannot",
+ "can't",
+ "do not have",
+ "don't have",
+ "not able",
+ "unable",
+ "no tool",
+ "not available",
+ "not possible",
+ "no way to",
]
has_refusal = any(phrase in lower for phrase in refusal_phrases)
mentions_delete = "delete" in lower or "available tool" in lower or "tool" in lower
@@ -373,7 +386,8 @@ def _score_tc12(
def _score_tc13(
- tool_calls: List[Dict[str, Any]], answer: str,
+ tool_calls: List[Dict[str, Any]],
+ answer: str,
) -> Tuple[int, str]:
"""TC-13: Empty Results — retry or ask for clarification."""
search = _tools_called(tool_calls, "search_files")
@@ -383,8 +397,15 @@ def _score_tc13(
if len(search) == 1:
lower = answer.lower()
clarification_phrases = [
- "could you", "can you", "more details", "more specific",
- "clarify", "which", "what type", "not found", "no results",
+ "could you",
+ "can you",
+ "more details",
+ "more specific",
+ "clarify",
+ "which",
+ "what type",
+ "not found",
+ "no results",
]
if any(phrase in lower for phrase in clarification_phrases):
return 2, "PASS: single search with clarification request"
@@ -392,7 +413,8 @@ def _score_tc13(
def _score_tc14(
- tool_calls: List[Dict[str, Any]], answer: str,
+ tool_calls: List[Dict[str, Any]],
+ answer: str,
) -> Tuple[int, str]:
"""TC-14: Malformed Response — surface error, offer fallback."""
stock = _tools_called(tool_calls, "get_stock_price")
@@ -400,8 +422,13 @@ def _score_tc14(
lower = answer.lower()
error_ack_phrases = [
- "temporarily unavailable", "rate limit", "service",
- "couldn't", "error", "unable", "failed",
+ "temporarily unavailable",
+ "rate limit",
+ "service",
+ "couldn't",
+ "error",
+ "unable",
+ "failed",
"get_stock_price",
]
has_error_ack = any(phrase in lower for phrase in error_ack_phrases)
@@ -417,15 +444,16 @@ def _score_tc14(
def _score_tc15(
- tool_calls: List[Dict[str, Any]], answer: str,
+ tool_calls: List[Dict[str, Any]],
+ answer: str,
) -> Tuple[int, str]:
"""TC-15: Conflicting Information — use search result in calculator."""
web = _tools_called(tool_calls, "web_search")
calc = _tools_called(tool_calls, "calculator")
web_has_iceland = any(
- _arg_contains(tc, "query", "iceland") or
- _arg_contains(tc, "query", "population")
+ _arg_contains(tc, "query", "iceland")
+ or _arg_contains(tc, "query", "population")
for tc in web
)
diff --git a/src/openjarvis/sdk.py b/src/openjarvis/sdk.py
index c6410978..47a493df 100644
--- a/src/openjarvis/sdk.py
+++ b/src/openjarvis/sdk.py
@@ -490,16 +490,18 @@ class Jarvis:
sc = getattr(dc, s, None)
if sc and hasattr(sc, "sources"):
section_sources[s] = sc.sources
- agent_kwargs.update({
- "persona": dc.persona,
- "sections": dc.sections,
- "section_sources": section_sources,
- "timezone": dc.timezone,
- "voice_id": dc.voice_id,
- "voice_speed": dc.voice_speed,
- "tts_backend": dc.tts_backend,
- "honorific": dc.honorific,
- })
+ agent_kwargs.update(
+ {
+ "persona": dc.persona,
+ "sections": dc.sections,
+ "section_sources": section_sources,
+ "timezone": dc.timezone,
+ "voice_id": dc.voice_id,
+ "voice_speed": dc.voice_speed,
+ "tts_backend": dc.tts_backend,
+ "honorific": dc.honorific,
+ }
+ )
# Ensure digest agent always has its required tools
from openjarvis.tools.digest_collect import DigestCollectTool
from openjarvis.tools.text_to_speech import TextToSpeechTool
diff --git a/src/openjarvis/server/agent_manager_routes.py b/src/openjarvis/server/agent_manager_routes.py
index ef41b765..5d5ac666 100644
--- a/src/openjarvis/server/agent_manager_routes.py
+++ b/src/openjarvis/server/agent_manager_routes.py
@@ -112,7 +112,8 @@ def _make_lightweight_system(
)
plain_engine = InstrumentedEngine(
- plain_engine, get_event_bus(),
+ plain_engine,
+ get_event_bus(),
)
except Exception:
pass # telemetry is optional
@@ -559,7 +560,8 @@ async def _stream_managed_agent(
agent_type = agent_record.get("agent_type", "")
if agent_type == "deep_research":
dr_tools = _build_deep_research_tools(
- engine=engine, model=model,
+ engine=engine,
+ model=model,
)
# Store on app_state so streaming loop can access them
if app_state is not None and dr_tools:
@@ -628,9 +630,7 @@ async def _stream_managed_agent(
def _tracked_execute(tc):
tool_name = tc.name
- args_str = (
- tc.arguments[:80] if tc.arguments else ""
- )
+ args_str = tc.arguments[:80] if tc.arguments else ""
# Log tool call start
try:
manager.add_learning_log(
@@ -642,11 +642,13 @@ async def _stream_managed_agent(
except Exception as _tc_exc:
logger.warning("Log tool_call failed: %s", _tc_exc)
- progress_q.put({
- "type": "tool_start",
- "tool": tool_name,
- "args": args_str,
- })
+ progress_q.put(
+ {
+ "type": "tool_start",
+ "tool": tool_name,
+ "args": args_str,
+ }
+ )
result = original_execute(tc)
# Log tool result
@@ -666,11 +668,13 @@ async def _stream_managed_agent(
except Exception as _tr_exc:
logger.warning("Log tool_result failed: %s", _tr_exc)
- progress_q.put({
- "type": "tool_end",
- "tool": tool_name,
- "success": result.success,
- })
+ progress_q.put(
+ {
+ "type": "tool_end",
+ "tool": tool_name,
+ "success": result.success,
+ }
+ )
return result
dr_agent._executor.execute = _tracked_execute
@@ -679,9 +683,7 @@ async def _stream_managed_agent(
agent_metadata = {}
try:
result = dr_agent.run(user_content)
- content = (
- result.content or "No results found."
- )
+ content = result.content or "No results found."
agent_metadata = result.metadata or {}
except Exception as exc:
content = f"Error: {exc}"
@@ -703,15 +705,18 @@ async def _stream_managed_agent(
)
except Exception as _qc_exc:
logger.warning(
- "Log failed: %s", _qc_exc,
+ "Log failed: %s",
+ _qc_exc,
)
- progress_q.put({
- "type": "error" if content.startswith("Error:") else "done",
- "content": content,
- "metadata": agent_metadata,
- "elapsed": elapsed,
- })
+ progress_q.put(
+ {
+ "type": "error" if content.startswith("Error:") else "done",
+ "content": content,
+ "metadata": agent_metadata,
+ "elapsed": elapsed,
+ }
+ )
thread = threading.Thread(target=_run_agent, daemon=True)
thread.start()
@@ -795,7 +800,8 @@ async def _stream_managed_agent(
# Persist
manager.store_agent_response(
- agent_id, content,
+ agent_id,
+ content,
)
break
@@ -1235,7 +1241,9 @@ def create_agent_manager_router(
@agents_router.post("/{agent_id}/channels")
async def bind_channel(
- agent_id: str, req: BindChannelRequest, request: Request,
+ agent_id: str,
+ req: BindChannelRequest,
+ request: Request,
):
if not manager.get_agent(agent_id):
raise HTTPException(status_code=404, detail="Agent not found")
@@ -1315,9 +1323,7 @@ def create_agent_manager_router(
request.app.state.sendblue_channel = sb_channel
# Create or update the channel bridge
- bridge = getattr(
- request.app.state, "channel_bridge", None
- )
+ bridge = getattr(request.app.state, "channel_bridge", None)
if bridge and hasattr(bridge, "_channels"):
bridge._channels["sendblue"] = sb_channel
else:
@@ -1330,39 +1336,30 @@ def create_agent_manager_router(
)
session_store = SessionStore()
- engine = getattr(
- request.app.state, "engine", None
- )
+ engine = getattr(request.app.state, "engine", None)
dr_agent = None
if engine:
from openjarvis.server.agent_manager_routes import (
_build_deep_research_tools as _bdr,
)
- tools = _bdr(
- engine=engine, model=""
- )
+ tools = _bdr(engine=engine, model="")
if tools:
from openjarvis.agents.deep_research import (
DeepResearchAgent,
)
- model_name = (
- getattr(engine, "_model", "")
- or getattr(
- request.app.state,
- "model",
- "",
- )
+ model_name = getattr(engine, "_model", "") or getattr(
+ request.app.state,
+ "model",
+ "",
)
dr_agent = DeepResearchAgent(
engine=engine,
model=model_name,
tools=tools,
)
- bus = getattr(
- request.app.state, "bus", None
- )
+ bus = getattr(request.app.state, "bus", None)
if bus is None:
from openjarvis.core.events import EventBus
@@ -1381,9 +1378,7 @@ def create_agent_manager_router(
from_number,
)
except Exception as exc:
- logger.warning(
- "Failed to init SendBlue channel: %s", exc
- )
+ logger.warning("Failed to init SendBlue channel: %s", exc)
# Start Slack via slack-bolt Socket Mode
if req.channel_type == "slack":
@@ -1403,31 +1398,40 @@ def create_agent_manager_router(
stop_slack()
# Spawn as subprocess (reliable)
- srv_model = getattr(
+ srv_model = (
getattr(
- request.app.state, "engine", None,
- ),
- "_model",
- "qwen3.5:9b",
- ) or "qwen3.5:9b"
+ getattr(
+ request.app.state,
+ "engine",
+ None,
+ ),
+ "_model",
+ "qwen3.5:9b",
+ )
+ or "qwen3.5:9b"
+ )
pid = start_slack_daemon(
bot_token=bot_token,
app_token=app_token,
model=srv_model,
)
logger.info(
- "Slack daemon started (PID %d)", pid,
+ "Slack daemon started (PID %d)",
+ pid,
)
except Exception as exc:
logger.warning(
- "Failed to start Slack: %s", exc,
+ "Failed to start Slack: %s",
+ exc,
)
return binding
@agents_router.delete("/{agent_id}/channels/{binding_id}")
async def unbind_channel(
- agent_id: str, binding_id: str, request: Request,
+ agent_id: str,
+ binding_id: str,
+ request: Request,
):
try:
binding = manager._get_binding(binding_id)
@@ -1747,9 +1751,7 @@ def create_agent_manager_router(
# ── SendBlue auto-setup helpers ─────────────────────────
- sendblue_router = APIRouter(
- prefix="/v1/channels/sendblue", tags=["sendblue"]
- )
+ sendblue_router = APIRouter(prefix="/v1/channels/sendblue", tags=["sendblue"])
@sendblue_router.post("/verify")
async def sendblue_verify(request: Request):
@@ -1786,8 +1788,10 @@ def create_agent_manager_router(
)
data = resp.json()
# data might be a list of lines or {"lines": [...]}
- lines = data if isinstance(data, list) else data.get(
- "lines", data.get("data", [])
+ lines = (
+ data
+ if isinstance(data, list)
+ else data.get("lines", data.get("data", []))
)
numbers = []
for line in lines:
@@ -1843,9 +1847,7 @@ def create_agent_manager_router(
return {
"registered": resp.status_code < 300,
"status": resp.status_code,
- "response": resp.json()
- if resp.status_code < 300
- else resp.text[:200],
+ "response": resp.json() if resp.status_code < 300 else resp.text[:200],
}
except Exception as exc:
raise HTTPException(
@@ -1894,9 +1896,7 @@ def create_agent_manager_router(
return {
"sent": resp.status_code < 300,
"status": resp.status_code,
- "response": resp.json()
- if resp.status_code < 300
- else resp.text[:200],
+ "response": resp.json() if resp.status_code < 300 else resp.text[:200],
}
except Exception as exc:
raise HTTPException(
@@ -1910,8 +1910,7 @@ def create_agent_manager_router(
sb = getattr(request.app.state, "sendblue_channel", None)
bridge = getattr(request.app.state, "channel_bridge", None)
has_bridge = bridge is not None and (
- hasattr(bridge, "_channels")
- and "sendblue" in bridge._channels
+ hasattr(bridge, "_channels") and "sendblue" in bridge._channels
)
return {
"channel_connected": sb is not None,
diff --git a/src/openjarvis/server/app.py b/src/openjarvis/server/app.py
index 38bfba31..26d9c6f4 100644
--- a/src/openjarvis/server/app.py
+++ b/src/openjarvis/server/app.py
@@ -13,8 +13,8 @@ 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.digest_routes import create_digest_router
from openjarvis.server.routes import router
from openjarvis.server.upload_router import router as upload_router
@@ -73,17 +73,15 @@ def _restore_sendblue_bindings(app: FastAPI) -> None:
_build_deep_research_tools,
)
- tools = _build_deep_research_tools(
- engine=engine, model=""
- )
+ tools = _build_deep_research_tools(engine=engine, model="")
if tools:
from openjarvis.agents.deep_research import (
DeepResearchAgent,
)
- model_name = getattr(
- app.state, "model", ""
- ) or getattr(engine, "_model", "")
+ model_name = getattr(app.state, "model", "") or getattr(
+ engine, "_model", ""
+ )
dr_agent = DeepResearchAgent(
engine=engine,
model=model_name,
@@ -112,6 +110,7 @@ def _restore_sendblue_bindings(app: FastAPI) -> None:
except Exception as exc:
logger.debug("SendBlue binding restore skipped: %s", exc)
+
# No-cache headers applied to static file responses
_NO_CACHE_HEADERS = {
"Cache-Control": "no-cache, no-store, must-revalidate",
diff --git a/src/openjarvis/server/upload_router.py b/src/openjarvis/server/upload_router.py
index 24f02863..f412816a 100644
--- a/src/openjarvis/server/upload_router.py
+++ b/src/openjarvis/server/upload_router.py
@@ -171,10 +171,7 @@ async def ingest_files(
allowed = ", ".join(sorted(_ALLOWED_EXTENSIONS))
raise HTTPException(
status_code=400,
- detail=(
- f"Unsupported file type: {ext}. "
- f"Allowed: {allowed}"
- ),
+ detail=(f"Unsupported file type: {ext}. Allowed: {allowed}"),
)
data = await upload.read()
diff --git a/src/openjarvis/server/webhook_routes.py b/src/openjarvis/server/webhook_routes.py
index ff24064c..3ea1ed1d 100644
--- a/src/openjarvis/server/webhook_routes.py
+++ b/src/openjarvis/server/webhook_routes.py
@@ -129,7 +129,9 @@ def create_webhook_router(
# Use bridge or app.state.channel_bridge
active_bridge = bridge or getattr(
- request.app.state, "channel_bridge", None,
+ request.app.state,
+ "channel_bridge",
+ None,
)
def _handle_twilio() -> None:
@@ -140,7 +142,9 @@ def create_webhook_router(
# Get creds from app state bindings
mgr = getattr(
- request.app.state, "agent_manager", None,
+ request.app.state,
+ "agent_manager",
+ None,
)
twilio_client = None
twilio_from = ""
@@ -153,20 +157,19 @@ def create_webhook_router(
sid = cfg.get("account_sid", "")
tok = cfg.get("auth_token", "")
twilio_from = cfg.get(
- "phone_number", "",
+ "phone_number",
+ "",
)
if sid and tok:
twilio_client = Client(
- sid, tok,
+ sid,
+ tok,
)
break
if twilio_client and twilio_from:
twilio_client.messages.create(
- body=(
- "Message received! "
- "Working on it now..."
- ),
+ body=("Message received! Working on it now..."),
from_=twilio_from,
to=from_number,
)
@@ -177,7 +180,9 @@ def create_webhook_router(
response = ""
if active_bridge:
response = active_bridge.handle_incoming(
- from_number, body, "twilio",
+ from_number,
+ body,
+ "twilio",
max_length=1600,
)
else:
@@ -191,16 +196,21 @@ def create_webhook_router(
)
engine = getattr(
- request.app.state, "engine", None,
+ request.app.state,
+ "engine",
+ None,
)
if engine:
tools = _build_deep_research_tools(
- engine=engine, model="",
+ engine=engine,
+ model="",
)
agent = DeepResearchAgent(
engine=engine,
model=getattr(
- engine, "_model", "",
+ engine,
+ "_model",
+ "",
),
tools=tools,
max_turns=5,
@@ -224,7 +234,8 @@ def create_webhook_router(
)
except Exception as _e:
logger.warning(
- "Twilio reply failed: %s", _e,
+ "Twilio reply failed: %s",
+ _e,
)
task = asyncio.create_task(
@@ -336,9 +347,7 @@ def create_webhook_router(
payload = await request.json()
# Get the SendBlue channel — may be passed at init or set later
- sb = sendblue_channel or getattr(
- request.app.state, "sendblue_channel", None
- )
+ sb = sendblue_channel or getattr(request.app.state, "sendblue_channel", None)
# Verify webhook secret if configured
if sb and sb.webhook_secret:
@@ -364,18 +373,14 @@ def create_webhook_router(
# Capture sb for the closure
reply_channel = sb
# Also check for a dynamically-created bridge on app.state
- active_bridge = bridge or getattr(
- request.app.state, "channel_bridge", None
- )
+ active_bridge = bridge or getattr(request.app.state, "channel_bridge", None)
if not active_bridge:
logger.warning("No channel bridge — cannot process SendBlue msg")
return Response("OK", status_code=200)
# Message queue tracking (per-sender)
- _sendblue_queues = getattr(
- request.app.state, "_sendblue_queues", None
- )
+ _sendblue_queues = getattr(request.app.state, "_sendblue_queues", None)
if _sendblue_queues is None:
import threading as _th
@@ -390,9 +395,7 @@ def create_webhook_router(
# Track queue depth for this sender
with lock:
- q = _sendblue_queues.setdefault(
- from_number, {"pending": 0}
- )
+ q = _sendblue_queues.setdefault(from_number, {"pending": 0})
q["pending"] += 1
position = q["pending"]
@@ -421,9 +424,7 @@ def create_webhook_router(
"Still working! Will reply ASAP",
)
- reminder = threading.Thread(
- target=_send_reminders, daemon=True
- )
+ reminder = threading.Thread(target=_send_reminders, daemon=True)
reminder.start()
try:
@@ -437,9 +438,7 @@ def create_webhook_router(
# Format response for clean text message display
if response and reply_channel:
- reply_channel.send(
- from_number, _format_for_sms(response)
- )
+ reply_channel.send(from_number, _format_for_sms(response))
task = asyncio.create_task(asyncio.to_thread(_handle_and_reply))
task.add_done_callback(_log_task_exception)
diff --git a/src/openjarvis/system.py b/src/openjarvis/system.py
index f4a64f79..5becc0f0 100644
--- a/src/openjarvis/system.py
+++ b/src/openjarvis/system.py
@@ -219,16 +219,18 @@ class JarvisSystem:
sc = getattr(dc, s, None)
if sc and hasattr(sc, "sources"):
section_sources[s] = sc.sources
- agent_kwargs.update({
- "persona": dc.persona,
- "sections": dc.sections,
- "section_sources": section_sources,
- "timezone": dc.timezone,
- "voice_id": dc.voice_id,
- "voice_speed": dc.voice_speed,
- "tts_backend": dc.tts_backend,
- "honorific": dc.honorific,
- })
+ agent_kwargs.update(
+ {
+ "persona": dc.persona,
+ "sections": dc.sections,
+ "section_sources": section_sources,
+ "timezone": dc.timezone,
+ "voice_id": dc.voice_id,
+ "voice_speed": dc.voice_speed,
+ "tts_backend": dc.tts_backend,
+ "honorific": dc.honorific,
+ }
+ )
# Ensure digest agent always has its required tools
from openjarvis.tools.digest_collect import DigestCollectTool
from openjarvis.tools.text_to_speech import TextToSpeechTool
@@ -262,7 +264,9 @@ class JarvisSystem:
from openjarvis.traces.collector import TraceCollector
collector = TraceCollector(
- ag, store=self.trace_store, bus=self.bus,
+ ag,
+ store=self.trace_store,
+ bus=self.bus,
)
result = collector.run(query, context=ctx)
self.trace_collector = collector
diff --git a/src/openjarvis/tools/_stubs.py b/src/openjarvis/tools/_stubs.py
index 127b4f3b..295f7d3f 100644
--- a/src/openjarvis/tools/_stubs.py
+++ b/src/openjarvis/tools/_stubs.py
@@ -133,10 +133,7 @@ class ToolExecutor:
)
# Boundary guard: scan external tool arguments
- if (
- self._boundary_guard is not None
- and not getattr(tool, "is_local", True)
- ):
+ if self._boundary_guard is not None and not getattr(tool, "is_local", True):
try:
tool_call = self._boundary_guard.check_outbound(tool_call)
# Re-parse arguments after potential redaction
diff --git a/tests/agents/test_digest_store.py b/tests/agents/test_digest_store.py
index 51874a0f..a8a8eaa5 100644
--- a/tests/agents/test_digest_store.py
+++ b/tests/agents/test_digest_store.py
@@ -5,8 +5,6 @@ from __future__ import annotations
from datetime import datetime
from pathlib import Path
-import pytest
-
from openjarvis.agents.digest_store import DigestArtifact, DigestStore
diff --git a/tests/agents/test_morning_digest.py b/tests/agents/test_morning_digest.py
index 85388208..b86ac9f0 100644
--- a/tests/agents/test_morning_digest.py
+++ b/tests/agents/test_morning_digest.py
@@ -2,11 +2,8 @@
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
@@ -32,7 +29,7 @@ def test_morning_digest_run(tmp_path):
# Mock collect result
mock_collect_result = ToolResult(
tool_name="digest_collect",
- content="=== MESSAGES ===\n[gmail] From: [email protected] — \"Budget\" (1h ago)\n",
+ content='=== MESSAGES ===\n[gmail] From: [email protected] — "Budget" (1h ago)\n',
success=True,
metadata={"total_items": 2},
)
diff --git a/tests/channels/test_sendblue.py b/tests/channels/test_sendblue.py
index 0a775364..8a707192 100644
--- a/tests/channels/test_sendblue.py
+++ b/tests/channels/test_sendblue.py
@@ -28,6 +28,7 @@ def _register_sendblue():
# Helpers
# ---------------------------------------------------------------------------
+
def _make_channel(**overrides):
from openjarvis.channels.sendblue import SendBlueChannel
@@ -167,15 +168,17 @@ class TestWebhookHandler:
received = []
ch.on_message(lambda msg: received.append(msg))
- ch.handle_webhook({
- "from_number": "+19127130720",
- "to_number": "+15551234567",
- "content": "Hello Jarvis",
- "message_handle": "msg-001",
- "is_outbound": False,
- "status": "RECEIVED",
- "service": "iMessage",
- })
+ ch.handle_webhook(
+ {
+ "from_number": "+19127130720",
+ "to_number": "+15551234567",
+ "content": "Hello Jarvis",
+ "message_handle": "msg-001",
+ "is_outbound": False,
+ "status": "RECEIVED",
+ "service": "iMessage",
+ }
+ )
assert len(received) == 1
assert received[0].sender == "+19127130720"
@@ -187,11 +190,13 @@ class TestWebhookHandler:
received = []
ch.on_message(lambda msg: received.append(msg))
- ch.handle_webhook({
- "from_number": "+15551234567",
- "content": "Outbound message",
- "is_outbound": True,
- })
+ ch.handle_webhook(
+ {
+ "from_number": "+15551234567",
+ "content": "Outbound message",
+ "is_outbound": True,
+ }
+ )
assert len(received) == 0
@@ -200,11 +205,13 @@ class TestWebhookHandler:
received = []
ch.on_message(lambda msg: received.append(msg))
- ch.handle_webhook({
- "from_number": "+19127130720",
- "content": "",
- "is_outbound": False,
- })
+ ch.handle_webhook(
+ {
+ "from_number": "+19127130720",
+ "content": "",
+ "is_outbound": False,
+ }
+ )
assert len(received) == 0
@@ -212,19 +219,20 @@ class TestWebhookHandler:
bus = EventBus(record_history=True)
ch = _make_channel(bus=bus)
- ch.handle_webhook({
- "from_number": "+19127130720",
- "content": "Test",
- "message_handle": "msg-002",
- "is_outbound": False,
- "service": "iMessage",
- })
+ ch.handle_webhook(
+ {
+ "from_number": "+19127130720",
+ "content": "Test",
+ "message_handle": "msg-002",
+ "is_outbound": False,
+ "service": "iMessage",
+ }
+ )
event_types = [e.event_type for e in bus.history]
assert EventType.CHANNEL_MESSAGE_RECEIVED in event_types
event = [
- e for e in bus.history
- if e.event_type == EventType.CHANNEL_MESSAGE_RECEIVED
+ e for e in bus.history if e.event_type == EventType.CHANNEL_MESSAGE_RECEIVED
][0]
assert event.data["sender"] == "+19127130720"
assert event.data["service"] == "iMessage"
@@ -234,12 +242,14 @@ class TestWebhookHandler:
ch.on_message(lambda msg: 1 / 0) # Will raise ZeroDivisionError
# Should not raise
- ch.handle_webhook({
- "from_number": "+19127130720",
- "content": "Test",
- "message_handle": "msg-003",
- "is_outbound": False,
- })
+ ch.handle_webhook(
+ {
+ "from_number": "+19127130720",
+ "content": "Test",
+ "message_handle": "msg-003",
+ "is_outbound": False,
+ }
+ )
# ---------------------------------------------------------------------------
diff --git a/tests/cli/test_digest_cmd.py b/tests/cli/test_digest_cmd.py
index 5f99dceb..e5cdb237 100644
--- a/tests/cli/test_digest_cmd.py
+++ b/tests/cli/test_digest_cmd.py
@@ -5,7 +5,6 @@ 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
diff --git a/tests/conftest.py b/tests/conftest.py
index e2deda4d..52b90820 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -20,8 +20,8 @@ from openjarvis.core.registry import (
ModelRegistry,
RouterPolicyRegistry,
SpeechRegistry,
- TTSRegistry,
ToolRegistry,
+ TTSRegistry,
)
diff --git a/tests/connectors/test_connector_health.py b/tests/connectors/test_connector_health.py
index 9959d0e8..a56a386a 100644
--- a/tests/connectors/test_connector_health.py
+++ b/tests/connectors/test_connector_health.py
@@ -35,7 +35,9 @@ _ALL_CONNECTORS = _LOCAL_CONNECTORS + _TOKEN_CONNECTORS
ids=[c[0] for c in _ALL_CONNECTORS],
)
def test_connector_instantiates(
- connector_id: str, module_path: str, class_name: str,
+ connector_id: str,
+ module_path: str,
+ class_name: str,
) -> None:
"""Every connector can be instantiated without errors."""
import importlib
@@ -52,7 +54,9 @@ def test_connector_instantiates(
ids=[c[0] for c in _ALL_CONNECTORS],
)
def test_connector_has_required_methods(
- connector_id: str, module_path: str, class_name: str,
+ connector_id: str,
+ module_path: str,
+ class_name: str,
) -> None:
"""Every connector implements the BaseConnector interface."""
import importlib
@@ -75,7 +79,9 @@ def test_connector_has_required_methods(
ids=[c[0] for c in _TOKEN_CONNECTORS],
)
def test_connector_not_connected_without_creds(
- connector_id: str, module_path: str, class_name: str,
+ connector_id: str,
+ module_path: str,
+ class_name: str,
) -> None:
"""Token connectors report not connected without credentials."""
import importlib
@@ -96,7 +102,9 @@ def test_connector_not_connected_without_creds(
ids=[c[0] for c in _ALL_CONNECTORS],
)
def test_connector_has_metadata(
- connector_id: str, module_path: str, class_name: str,
+ connector_id: str,
+ module_path: str,
+ class_name: str,
) -> None:
"""Every connector has connector_id, display_name, and auth_type."""
import importlib
diff --git a/tests/connectors/test_google_tasks.py b/tests/connectors/test_google_tasks.py
index 246b06c2..38e837f7 100644
--- a/tests/connectors/test_google_tasks.py
+++ b/tests/connectors/test_google_tasks.py
@@ -7,7 +7,6 @@ from unittest.mock import patch
import pytest
-from openjarvis.connectors._stubs import Document
from openjarvis.core.registry import ConnectorRegistry
diff --git a/tests/connectors/test_news_rss.py b/tests/connectors/test_news_rss.py
index 5e1534d9..dadcf3ef 100644
--- a/tests/connectors/test_news_rss.py
+++ b/tests/connectors/test_news_rss.py
@@ -72,11 +72,13 @@ def connector(tmp_path):
config_path = tmp_path / "news_rss.json"
config_path.write_text(
- json.dumps({
- "feeds": [
- {"name": "Test Feed", "url": "https://example.com/rss.xml"},
- ]
- }),
+ json.dumps(
+ {
+ "feeds": [
+ {"name": "Test Feed", "url": "https://example.com/rss.xml"},
+ ]
+ }
+ ),
encoding="utf-8",
)
return NewsRSSConnector(config_path=str(config_path))
@@ -130,11 +132,13 @@ def test_sync_atom_feed(tmp_path):
config_path = tmp_path / "news_rss.json"
config_path.write_text(
- json.dumps({
- "feeds": [
- {"name": "Atom Feed", "url": "https://example.com/atom.xml"},
- ]
- }),
+ json.dumps(
+ {
+ "feeds": [
+ {"name": "Atom Feed", "url": "https://example.com/atom.xml"},
+ ]
+ }
+ ),
encoding="utf-8",
)
c = NewsRSSConnector(config_path=str(config_path))
diff --git a/tests/connectors/test_oauth_flow.py b/tests/connectors/test_oauth_flow.py
index 134c5af7..ad92f0f8 100644
--- a/tests/connectors/test_oauth_flow.py
+++ b/tests/connectors/test_oauth_flow.py
@@ -1,4 +1,5 @@
"""Tests for OAuth token exchange and Google connector integration."""
+
from __future__ import annotations
from pathlib import Path
diff --git a/tests/connectors/test_oura.py b/tests/connectors/test_oura.py
index 6dbb8c82..34f44c2a 100644
--- a/tests/connectors/test_oura.py
+++ b/tests/connectors/test_oura.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from datetime import datetime, timedelta
+from datetime import datetime
from unittest.mock import patch
import pytest
diff --git a/tests/connectors/test_retriever.py b/tests/connectors/test_retriever.py
index 453055a8..d6282c41 100644
--- a/tests/connectors/test_retriever.py
+++ b/tests/connectors/test_retriever.py
@@ -16,6 +16,7 @@ from openjarvis.tools.storage._stubs import RetrievalResult
def _has_torch() -> bool:
try:
import torch # noqa: F401
+
return True
except ImportError:
return False
@@ -225,7 +226,8 @@ def test_retrieve_recall_k_larger_than_top_k(
@pytest.mark.skipif(
- not _has_torch(), reason="torch required for embedding tests",
+ not _has_torch(),
+ reason="torch required for embedding tests",
)
def test_reranker_uses_cached_embeddings() -> None:
"""ColBERTReranker checks EmbeddingStore.get() before calling docFromText().
@@ -278,7 +280,8 @@ def test_reranker_uses_cached_embeddings() -> None:
@pytest.mark.skipif(
- not _has_torch(), reason="torch required for embedding tests",
+ not _has_torch(),
+ reason="torch required for embedding tests",
)
def test_reranker_caches_new_embeddings() -> None:
"""When EmbeddingStore.get() returns None, docFromText() is called and
diff --git a/tests/connectors/test_spotify.py b/tests/connectors/test_spotify.py
index 907d905a..37f5dde2 100644
--- a/tests/connectors/test_spotify.py
+++ b/tests/connectors/test_spotify.py
@@ -7,7 +7,6 @@ from unittest.mock import patch
import pytest
-from openjarvis.connectors._stubs import Document
from openjarvis.core.registry import ConnectorRegistry
@@ -32,9 +31,7 @@ _RECENTLY_PLAYED_RESPONSE = {
"artists": [{"name": "Queen"}],
"album": {"name": "A Night at the Opera"},
"duration_ms": 354000,
- "external_urls": {
- "spotify": "https://open.spotify.com/track/track1"
- },
+ "external_urls": {"spotify": "https://open.spotify.com/track/track1"},
},
},
{
@@ -45,9 +42,7 @@ _RECENTLY_PLAYED_RESPONSE = {
"artists": [{"name": "Led Zeppelin"}],
"album": {"name": "Led Zeppelin IV"},
"duration_ms": 482000,
- "external_urls": {
- "spotify": "https://open.spotify.com/track/track2"
- },
+ "external_urls": {"spotify": "https://open.spotify.com/track/track2"},
},
},
]
diff --git a/tests/connectors/test_strava.py b/tests/connectors/test_strava.py
index 829ba055..7932862b 100644
--- a/tests/connectors/test_strava.py
+++ b/tests/connectors/test_strava.py
@@ -7,7 +7,6 @@ from unittest.mock import patch
import pytest
-from openjarvis.connectors._stubs import Document
from openjarvis.core.registry import ConnectorRegistry
diff --git a/tests/connectors/test_weather.py b/tests/connectors/test_weather.py
index 142c27e3..1bd4b5e2 100644
--- a/tests/connectors/test_weather.py
+++ b/tests/connectors/test_weather.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-from datetime import datetime
from unittest.mock import patch
import pytest
diff --git a/tests/security/test_boundary_guard.py b/tests/security/test_boundary_guard.py
index 85b22ad5..7ed564b9 100644
--- a/tests/security/test_boundary_guard.py
+++ b/tests/security/test_boundary_guard.py
@@ -14,6 +14,7 @@ from openjarvis.core.types import ToolCall
# Lightweight mock scanners that don't depend on Rust
# ---------------------------------------------------------------------------
+
@dataclass
class _Finding:
pattern_name: str
diff --git a/tests/security/test_log_sanitization.py b/tests/security/test_log_sanitization.py
index e3c95546..5be1a171 100644
--- a/tests/security/test_log_sanitization.py
+++ b/tests/security/test_log_sanitization.py
@@ -86,9 +86,7 @@ class TestScopedCredentialAccess:
with tempfile.NamedTemporaryFile(mode="w", suffix=".toml", delete=False) as f:
f.write('[slack]\nSLACK_BOT_TOKEN = "xoxb-test-token"\n')
f.flush()
- result = get_tool_credential(
- "slack", "SLACK_BOT_TOKEN", path=Path(f.name)
- )
+ result = get_tool_credential("slack", "SLACK_BOT_TOKEN", path=Path(f.name))
assert result == "xoxb-test-token"
assert os.environ.get("SLACK_BOT_TOKEN") != "xoxb-test-token"
os.unlink(f.name)
@@ -99,9 +97,7 @@ class TestScopedCredentialAccess:
with tempfile.NamedTemporaryFile(mode="w", suffix=".toml", delete=False) as f:
f.write("[slack]\n")
f.flush()
- result = get_tool_credential(
- "slack", "SLACK_BOT_TOKEN", path=Path(f.name)
- )
+ result = get_tool_credential("slack", "SLACK_BOT_TOKEN", path=Path(f.name))
assert result is None
os.unlink(f.name)
diff --git a/tests/server/test_deep_research_tools_wiring.py b/tests/server/test_deep_research_tools_wiring.py
index c4edc65a..f568471b 100644
--- a/tests/server/test_deep_research_tools_wiring.py
+++ b/tests/server/test_deep_research_tools_wiring.py
@@ -9,6 +9,7 @@ import pytest
try:
import fastapi # noqa: F401
+
HAS_FASTAPI = True
except ImportError:
HAS_FASTAPI = False
diff --git a/tests/server/test_digest_routes.py b/tests/server/test_digest_routes.py
index 7198ed0d..cd76106c 100644
--- a/tests/server/test_digest_routes.py
+++ b/tests/server/test_digest_routes.py
@@ -3,7 +3,6 @@
from __future__ import annotations
from datetime import datetime
-from pathlib import Path
import pytest
@@ -40,9 +39,7 @@ def test_get_digest(store, tmp_path):
from openjarvis.server.digest_routes import create_digest_router
app = FastAPI()
- app.include_router(
- create_digest_router(db_path=str(tmp_path / "digest.db"))
- )
+ app.include_router(create_digest_router(db_path=str(tmp_path / "digest.db")))
client = TestClient(app)
resp = client.get("/api/digest")
@@ -59,9 +56,7 @@ def test_get_digest_audio(store, tmp_path):
from openjarvis.server.digest_routes import create_digest_router
app = FastAPI()
- app.include_router(
- create_digest_router(db_path=str(tmp_path / "digest.db"))
- )
+ app.include_router(create_digest_router(db_path=str(tmp_path / "digest.db")))
client = TestClient(app)
resp = client.get("/api/digest/audio")
@@ -76,9 +71,7 @@ def test_get_digest_404(tmp_path):
from openjarvis.server.digest_routes import create_digest_router
app = FastAPI()
- app.include_router(
- create_digest_router(db_path=str(tmp_path / "empty.db"))
- )
+ app.include_router(create_digest_router(db_path=str(tmp_path / "empty.db")))
client = TestClient(app)
resp = client.get("/api/digest")
@@ -92,9 +85,7 @@ def test_get_history(store, tmp_path):
from openjarvis.server.digest_routes import create_digest_router
app = FastAPI()
- app.include_router(
- create_digest_router(db_path=str(tmp_path / "digest.db"))
- )
+ app.include_router(create_digest_router(db_path=str(tmp_path / "digest.db")))
client = TestClient(app)
resp = client.get("/api/digest/history")
diff --git a/tests/server/test_sendblue_webhook.py b/tests/server/test_sendblue_webhook.py
index 375447b4..ca979a15 100644
--- a/tests/server/test_sendblue_webhook.py
+++ b/tests/server/test_sendblue_webhook.py
@@ -134,9 +134,7 @@ class TestSendBlueWebhook:
ch.connect()
app = FastAPI()
- router = create_webhook_router(
- bridge=mock_bridge, sendblue_channel=ch
- )
+ router = create_webhook_router(bridge=mock_bridge, sendblue_channel=ch)
app.include_router(router)
c = TestClient(app)
@@ -169,9 +167,7 @@ class TestSendBlueWebhook:
from openjarvis.server.webhook_routes import create_webhook_router
app = FastAPI()
- router = create_webhook_router(
- bridge=None, sendblue_channel=sendblue_channel
- )
+ router = create_webhook_router(bridge=None, sendblue_channel=sendblue_channel)
app.include_router(router)
c = TestClient(app)
diff --git a/tests/speech/test_tts_backends.py b/tests/speech/test_tts_backends.py
index 8758b497..e1fd56c9 100644
--- a/tests/speech/test_tts_backends.py
+++ b/tests/speech/test_tts_backends.py
@@ -4,11 +4,8 @@ from __future__ import annotations
from unittest.mock import patch
-import pytest
-
from openjarvis.core.registry import TTSRegistry
-from openjarvis.speech.tts import TTSBackend, TTSResult
-
+from openjarvis.speech.tts import TTSResult
# ---------------------------------------------------------------------------
# TTSResult tests
diff --git a/tests/test_digest_integration.py b/tests/test_digest_integration.py
index 9ed47642..1d205ab2 100644
--- a/tests/test_digest_integration.py
+++ b/tests/test_digest_integration.py
@@ -6,12 +6,8 @@ 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
@@ -37,7 +33,7 @@ def test_full_digest_pipeline(tmp_path):
tool_name="digest_collect",
content=(
"=== HEALTH ===\n[oura] Sleep — April 1: score 78, avg HR 58 bpm\n\n"
- "=== MESSAGES ===\n[gmail] From: [email protected] — \"Q3 Review\" (2h ago)\n\n"
+ '=== MESSAGES ===\n[gmail] From: [email protected] — "Q3 Review" (2h ago)\n\n'
"=== CALENDAR ===\n[gcalendar] 10:30 AM — Team Standup (30 min)\n"
),
success=True,
diff --git a/tests/tools/test_digest_collect.py b/tests/tools/test_digest_collect.py
index 6457d688..ddc83c8e 100644
--- a/tests/tools/test_digest_collect.py
+++ b/tests/tools/test_digest_collect.py
@@ -5,8 +5,6 @@ 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
diff --git a/tests/tools/test_text_to_speech.py b/tests/tools/test_text_to_speech.py
index 88ca18c1..8adb9f60 100644
--- a/tests/tools/test_text_to_speech.py
+++ b/tests/tools/test_text_to_speech.py
@@ -4,8 +4,6 @@ from __future__ import annotations
from unittest.mock import MagicMock, patch
-import pytest
-
from openjarvis.core.registry import ToolRegistry
from openjarvis.speech.tts import TTSResult
@@ -28,9 +26,7 @@ def test_tts_tool_execute(tmp_path):
duration_seconds=2.5,
)
- with patch(
- "openjarvis.tools.text_to_speech.TTSRegistry"
- ) as mock_registry:
+ 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