Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(tools): report how often each tool actually ran (#628)

Ruben Lütkee1783d6a5c12
diff --git a/jarvis/telemetry/tool_usage.py b/jarvis/telemetry/tool_usage.py
new file mode 100644
index 0000000000..64d89c832e
--- /dev/null
+++ b/jarvis/telemetry/tool_usage.py
@@ -0,0 +1,142 @@
+"""How often each tool actually ran, read from the flight recorder.
+
+The flight recorder already writes every ``ActionExecuted`` event, on every
+surface, into ``data/flight_recorder/YYYY-MM-DD.jsonl``. Nothing counted them:
+the question "which tools does this install really use" could only be answered
+per voice session (``jarvis/runs``), or as a days-used histogram that never
+filled. This module answers it for a window of days, from the files that are
+already there. It records nothing and changes no behaviour.
+
+The numbers exist to decide how many tools a model has to be SHOWN: when a
+dozen tools carry nine calls in ten, the rest can wait behind a lookup
+(``jarvis/brain/tool_shortlist.py``). ``coverage`` states exactly that.
+
+Synchronous file reads; call it off the event loop.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from collections.abc import Iterable
+from datetime import date, datetime, timedelta
+from pathlib import Path
+from typing import Any
+
+log = logging.getLogger(__name__)
+
+__all__ = ["DEFAULT_DATA_DIR", "tool_usage"]
+
+#: Where the desktop app's flight recorder writes (``server._init_flight_recorder``).
+DEFAULT_DATA_DIR = Path("data") / "flight_recorder"
+
+_EVENT = "ActionExecuted"
+#: Shares of all calls for which ``coverage`` says how many tools carry them.
+_COVERAGE_SHARES = (50, 80, 90, 95, 99)
+
+
+def _file_day(path: Path) -> date | None:
+ """The day a recorder file covers: ``2026-10-13.jsonl``, ``2026-10-13-2.jsonl``."""
+ try:
+ return date.fromisoformat(path.name[:10])
+ except ValueError: # not a recorder day file (a stray .jsonl in the folder)
+ return None
+
+
+def _executions(path: Path) -> Iterable[tuple[str, bool, int]]:
+ """``(tool name, succeeded, ts_ms)`` for every execution recorded in ``path``."""
+ try:
+ handle = path.open(encoding="utf-8", errors="replace")
+ except OSError as exc:
+ log.debug("tool usage: %s could not be opened: %s", path.name, exc)
+ return
+ with handle:
+ for line in handle:
+ # A day's file holds every bus event; skip the rest before parsing.
+ if _EVENT not in line:
+ continue
+ try:
+ record = json.loads(line)
+ except ValueError: # a line cut off by a crash in the middle of a write
+ continue
+ if not isinstance(record, dict) or record.get("event") != _EVENT:
+ continue
+ payload = record.get("payload")
+ name = payload.get("tool_name") if isinstance(payload, dict) else None
+ if not isinstance(name, str) or not name:
+ continue
+ ts_ns = record.get("ts_ns")
+ ts_ms = int(ts_ns) // 1_000_000 if isinstance(ts_ns, (int, float)) else 0
+ yield name, payload.get("success") is not False, ts_ms
+
+
+def tool_usage(
+ data_dir: Path = DEFAULT_DATA_DIR,
+ *,
+ days: int = 30,
+ registered: Iterable[str] | None = None,
+ today: date | None = None,
+) -> dict[str, Any]:
+ """Executions per tool over the last ``days`` days (today included).
+
+ ``registered`` are the tool names the brain currently holds; given, the
+ result also lists the ones that never ran in the window. ``days`` of ``0``
+ reads everything on disk.
+
+ Returns ``window_days``, ``total_calls``, ``distinct_tools``, ``tools``
+ (most used first, each with ``calls``, ``succeeded``, ``failed``,
+ ``days_used``, ``last_used_ms`` and ``share`` of all calls) and
+ ``coverage``: for each share in :data:`_COVERAGE_SHARES`, how many of the
+ most used tools carry that share of all calls.
+ """
+ end = today or datetime.now().date()
+ start = end - timedelta(days=days - 1) if days > 0 else None
+ calls: dict[str, int] = {}
+ failed: dict[str, int] = {}
+ last: dict[str, int] = {}
+ used_on: dict[str, set[date]] = {}
+ files = sorted(data_dir.glob("*.jsonl")) if data_dir.is_dir() else []
+ for path in files:
+ day = _file_day(path)
+ if day is None or day > end or (start is not None and day < start):
+ continue
+ for name, succeeded, ts_ms in _executions(path):
+ calls[name] = calls.get(name, 0) + 1
+ if not succeeded:
+ failed[name] = failed.get(name, 0) + 1
+ if ts_ms > last.get(name, 0):
+ last[name] = ts_ms
+ used_on.setdefault(name, set()).add(day)
+ total = sum(calls.values())
+ ranked = sorted(calls, key=lambda name: (-calls[name], name))
+ tools = [
+ {
+ "tool": name,
+ "calls": calls[name],
+ "succeeded": calls[name] - failed.get(name, 0),
+ "failed": failed.get(name, 0),
+ "days_used": len(used_on[name]),
+ "last_used_ms": last.get(name, 0),
+ "share": round(calls[name] / total, 4) if total else 0.0,
+ }
+ for name in ranked
+ ]
+ coverage: dict[str, int] = {}
+ running = 0
+ wanted = list(_COVERAGE_SHARES)
+ for position, name in enumerate(ranked, start=1):
+ running += calls[name]
+ while wanted and running * 100 >= wanted[0] * total:
+ coverage[str(wanted.pop(0))] = position
+ result: dict[str, Any] = {
+ "window_days": days,
+ "total_calls": total,
+ "distinct_tools": len(ranked),
+ "tools": tools,
+ "coverage": coverage,
+ }
+ if registered is not None:
+ names = sorted(set(registered))
+ result["registered"] = len(names)
+ result["never_used"] = [name for name in names if name not in calls]
+ return result
diff --git a/jarvis/ui/web/tools_routes.py b/jarvis/ui/web/tools_routes.py
index 2e480eb1ab..3bd403973e 100644
--- a/jarvis/ui/web/tools_routes.py
+++ b/jarvis/ui/web/tools_routes.py
@@ -88,3 +88,26 @@ async def list_tools_brief(request: Request) -> dict[str, Any]:
"total": full["total"],
"by_source": full["by_source"],
}
+
+
+async def tool_usage_report(request: Request, days: int = 30) -> dict[str, Any]:
+ """How often each tool actually ran over the last ``days`` days.
+
+ Read from the flight recorder's daily files, which already hold every
+ executed tool call on every surface; nothing extra is recorded.
+ ``coverage`` says how many of the most used tools carry 50, 80, 90, 95 and
+ 99 percent of all calls, and ``never_used`` lists the registered tools
+ that did not run once in the window. ``days=0`` reads everything on disk.
+ """
+ import asyncio
+
+ from jarvis.telemetry import tool_usage as usage
+
+ full = await list_tools(request)
+ registered = [t["name"] for t in full["tools"]]
+ window = max(0, min(int(days), 3650))
+ # The files are read off the event loop: a month of them is tens of MB.
+ return await asyncio.to_thread(
+ usage.tool_usage, usage.DEFAULT_DATA_DIR, days=window, registered=registered
+ )
diff --git a/tests/unit/telemetry/test_tool_usage.py b/tests/unit/telemetry/test_tool_usage.py
new file mode 100644
index 0000000000..f93c68f9c6
--- /dev/null
+++ b/tests/unit/telemetry/test_tool_usage.py
@@ -0,0 +1,106 @@
+"""Tool usage is counted from what the flight recorder already wrote."""
+from __future__ import annotations
+
+import json
+from datetime import date
+from pathlib import Path
+
+from jarvis.telemetry.tool_usage import tool_usage
+
+TODAY = date(2026, 10, 13)
+
+
+def _write(directory: Path, name: str, rows: list[dict]) -> None:
+ directory.mkdir(parents=True, exist_ok=True)
+ with (directory / name).open("a", encoding="utf-8") as handle:
+ for row in rows:
+ handle.write(json.dumps(row) + "\n")
+
+
+def _ran(tool: str, *, success: bool = True, ts_ns: int = 1_000_000_000) -> dict:
+ return {
+ "ts_ns": ts_ns,
+ "trace_id": "t",
+ "event": "ActionExecuted",
+ "layer": "",
+ "payload": {"tool_name": tool, "success": success, "duration_ms": 5},
+ }
+
+
+def test_counts_executions_per_tool_most_used_first(tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "2026-10-13.jsonl",
+ [_ran("search_web"), _ran("search_web", success=False), _ran("wiki-ingest")],
+ )
+ _write(tmp_path, "2026-10-12.jsonl", [_ran("search_web", ts_ns=9_000_000_000)])
+ report = tool_usage(tmp_path, days=30, today=TODAY)
+ assert report["total_calls"] == 4
+ assert report["distinct_tools"] == 2
+ top = report["tools"][0]
+ assert top == {
+ "tool": "search_web",
+ "calls": 3,
+ "succeeded": 2,
+ "failed": 1,
+ "days_used": 2,
+ "last_used_ms": 9_000,
+ "share": 0.75,
+ }
+ assert report["tools"][1]["tool"] == "wiki-ingest"
+
+
+def test_only_executions_count_not_proposals_or_other_events(tmp_path: Path) -> None:
+ proposed = {"event": "ActionProposed", "payload": {"tool_name": "gmail"}, "ts_ns": 1}
+ mention = {
+ "event": "ResponseGenerated",
+ "payload": {"text": "ActionExecuted is an event name"},
+ "ts_ns": 1,
+ }
+ _write(tmp_path, "2026-10-13.jsonl", [proposed, mention, _ran("gmail")])
+ report = tool_usage(tmp_path, days=1, today=TODAY)
+ assert [(t["tool"], t["calls"]) for t in report["tools"]] == [("gmail", 1)]
+
+
+def test_the_window_is_taken_from_the_file_names(tmp_path: Path) -> None:
+ _write(tmp_path, "2026-10-13.jsonl", [_ran("today")])
+ _write(tmp_path, "2026-10-07.jsonl", [_ran("a_week_ago")])
+ _write(tmp_path, "2026-08-01.jsonl", [_ran("long_ago")])
+ # A rotated file of the same day belongs to that day.
+ _write(tmp_path, "2026-10-13-2.jsonl", [_ran("today")])
+ week = tool_usage(tmp_path, days=7, today=TODAY)
+ assert {t["tool"]: t["calls"] for t in week["tools"]} == {"today": 2, "a_week_ago": 1}
+ everything = tool_usage(tmp_path, days=0, today=TODAY)
+ assert everything["distinct_tools"] == 3
+
+
+def test_coverage_says_how_few_tools_carry_most_calls(tmp_path: Path) -> None:
+ """The figure the report exists for: with one tool at 90 of 100 calls, a
+ model that is shown that one tool is covered nine times in ten."""
+ rows = [_ran("workhorse")] * 90 + [_ran(f"rare{i}") for i in range(10)]
+ _write(tmp_path, "2026-10-13.jsonl", rows)
+ report = tool_usage(tmp_path, days=1, today=TODAY)
+ assert report["coverage"]["50"] == 1
+ assert report["coverage"]["90"] == 1
+ assert report["coverage"]["95"] == 6
+ assert report["coverage"]["99"] == 10
+
+
+def test_registered_tools_that_never_ran_are_named(tmp_path: Path) -> None:
+ _write(tmp_path, "2026-10-13.jsonl", [_ran("search_web")])
+ report = tool_usage(
+ tmp_path, days=1, today=TODAY, registered=["search_web", "vercel", "slack"]
+ )
+ assert report["registered"] == 3
+ assert report["never_used"] == ["slack", "vercel"]
+
+
+def test_a_damaged_line_and_a_missing_directory_are_survived(tmp_path: Path) -> None:
+ (tmp_path / "2026-10-13.jsonl").write_text(
+ '{"event": "ActionExecuted", "payload": {"tool_name": "ok"}}\n'
+ '{"event": "ActionExecuted", "payload": {"tool_na\n',
+ encoding="utf-8",
+ )
+ assert tool_usage(tmp_path, days=1, today=TODAY)["total_calls"] == 1
+ empty = tool_usage(tmp_path / "absent", days=30, today=TODAY)
+ assert empty["total_calls"] == 0 and empty["tools"] == [] and empty["coverage"] == {}
diff --git a/tests/unit/ui/web/test_tools_routes.py b/tests/unit/ui/web/test_tools_routes.py
index ba527f74eb..c34b332697 100644
--- a/tests/unit/ui/web/test_tools_routes.py
+++ b/tests/unit/ui/web/test_tools_routes.py
@@ -54,3 +54,34 @@ def test_falls_back_to_user_mcp_registry_before_brain_ready() -> None:
assert body["total"] == 1
assert body["tools"][0]["name"] == "weather/search"
assert body["by_source"]["mcp"] == 1
+
+
+def test_usage_reports_what_ran_and_what_never_did(tmp_path, monkeypatch) -> None:
+ import json
+ from datetime import datetime
+
+ from jarvis.telemetry import tool_usage as usage
+
+ day = datetime.now().date().isoformat()
+ rows = [
+ {"ts_ns": 1, "event": "ActionExecuted", "payload": {"tool_name": "wiki-recall"}},
+ {"ts_ns": 2, "event": "ActionExecuted", "payload": {"tool_name": "wiki-recall"}},
+ ]
+ (tmp_path / f"{day}.jsonl").write_text(
+ "".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8"
+ )
+ monkeypatch.setattr(usage, "DEFAULT_DATA_DIR", tmp_path)
+
+ app = FastAPI()
+ app.include_router(router)
+ app.state.brain = SimpleNamespace(
+ _tools={"wiki-recall": _tool("wiki-recall"), "cli_gh": _tool("cli_gh")}
+ )
+ with TestClient(app) as client:
+ body = client.get("/api/tools/usage", params={"days": 7}).json()
+
+ assert body["window_days"] == 7
+ assert body["total_calls"] == 2
+ assert body["tools"][0]["tool"] == "wiki-recall"
+ assert body["registered"] == 2
+ assert body["never_used"] == ["cli_gh"]