Skip to content

API Reference

robotsix_cost_monitor

robotsix-cost-monitor — multi-Langfuse cost monitoring dashboard.

__version__ = '0.9.3' module-attribute

robotsix_cost_monitor.aggregations

Pure cost-aggregation and transformation functions over trace dicts.

No I/O, no HTTP, no LangfuseClient dependency — only typing and datetime. Trivially testable without httpx mocking.

BackendKind = Literal['openrouter', 'claude-sdk', 'all'] module-attribute

_PERIODIC_SESSION_RE = re.compile('(?:^|.*[·|]\\s*)([a-z_]+)-\\d{8}T\\d{6}Z-') module-attribute

LangfuseTrace

Bases: BaseModel

A single trace from the Langfuse /api/public/traces response.

Handles both sessionId (canonical Langfuse API key) and session_id (observed in some responses) via populate_by_name.

extra is "ignore" — and must stay that way. Cached trace lists are the dominant memory consumer in this process: a 168 h window across the fleet is ~21 k traces, and Langfuse returns each one with its full input / output / metadata payload. Under extra="allow" Pydantic retained all of it in __pydantic_extra__ — ~777 MB of raw JSON held live, which pegged the 2 GB container limit. Nothing here reads those fields (aggregation only needs the seven declared ones), so they are dropped at the validation boundary rather than cached forever.

Source code in src/robotsix_cost_monitor/clients/models.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class LangfuseTrace(BaseModel):
    """A single trace from the Langfuse ``/api/public/traces`` response.

    Handles both ``sessionId`` (canonical Langfuse API key) and
    ``session_id`` (observed in some responses) via ``populate_by_name``.

    ``extra`` is ``"ignore"`` — and must stay that way.  Cached trace lists are
    the dominant memory consumer in this process: a 168 h window across the
    fleet is ~21 k traces, and Langfuse returns each one with its full ``input``
    / ``output`` / ``metadata`` payload.  Under ``extra="allow"`` Pydantic
    retained all of it in ``__pydantic_extra__`` — ~777 MB of raw JSON held
    live, which pegged the 2 GB container limit.  Nothing here reads those
    fields (aggregation only needs the seven declared ones), so they are
    dropped at the validation boundary rather than cached forever.
    """

    id: str | None = None
    name: str | None = None
    session_id: str | None = Field(default=None, alias="sessionId")
    timestamp: str | None = None
    total_cost: float | None = Field(default=None, alias="totalCost")
    calculated_total_cost: float | None = Field(
        default=None, alias="calculatedTotalCost"
    )
    cost: float | None = None

    model_config = {"populate_by_name": True, "extra": "ignore"}

_empty_model_slot()

Source code in src/robotsix_cost_monitor/aggregations.py
54
55
56
57
58
59
60
61
def _empty_model_slot() -> dict[str, float]:
    return {
        "cost": 0.0,
        "input_tokens": 0.0,
        "output_tokens": 0.0,
        "total_tokens": 0.0,
        "observations": 0.0,
    }

_model_rows(acc)

Format a model→totals accumulator into rows sorted by cost desc.

Source code in src/robotsix_cost_monitor/aggregations.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def _model_rows(acc: dict[str, dict[str, float]]) -> list[dict[str, Any]]:
    """Format a model→totals accumulator into rows sorted by cost desc."""
    ordered = sorted(acc.items(), key=lambda kv: kv[1]["cost"], reverse=True)
    return [
        {
            "model": model,
            "backend": backend_for_model(model),
            "cost": round(v["cost"], 6),
            "input_tokens": int(v["input_tokens"]),
            "output_tokens": int(v["output_tokens"]),
            "total_tokens": int(v["total_tokens"]),
            "observations": int(v["observations"]),
        }
        for model, v in ordered
    ]

_parse_ts(trace)

Source code in src/robotsix_cost_monitor/aggregations.py
184
185
186
187
188
189
190
191
def _parse_ts(trace: LangfuseTrace) -> datetime | None:
    raw = trace.timestamp
    if not isinstance(raw, str):
        return None
    try:
        return datetime.fromisoformat(raw.replace("Z", "+00:00"))
    except ValueError:
        return None

_sorted_cost_rows(acc, key_field='name')

Convert a {key: {cost, count}} accumulator into rows sorted by cost desc.

Source code in src/robotsix_cost_monitor/aggregations.py
81
82
83
84
85
86
87
88
89
90
def _sorted_cost_rows(
    acc: dict[str, dict[str, float]],
    key_field: str = "name",
) -> list[dict[str, Any]]:
    """Convert a ``{key: {cost, count}}`` accumulator into rows sorted by cost desc."""
    ordered = sorted(acc.items(), key=lambda kv: kv[1]["cost"], reverse=True)
    return [
        {key_field: k, "cost": round(v["cost"], 6), "count": int(v["count"])}
        for k, v in ordered
    ]

_trace_cost(trace)

Extract a trace's total cost, tolerant of Langfuse field-name variants.

Source code in src/robotsix_cost_monitor/aggregations.py
31
32
33
34
35
36
37
def _trace_cost(trace: LangfuseTrace) -> float:
    """Extract a trace's total cost, tolerant of Langfuse field-name variants."""
    for key in ("total_cost", "calculated_total_cost", "cost"):
        v = getattr(trace, key, None)
        if isinstance(v, (int, float)):
            return float(v)
    return 0.0

_trace_label(trace)

Display label for a trace in the by-agent view.

Prefers the trace name (the stage/agent). Some traces reach Langfuse without a name (a pydantic-ai/claude_sdk span became the trace root in a context where the session was lost — see robotsix-llmio's trace-name handling); rather than dumping their cost into one opaque "(unnamed)" bucket, attribute it to its session so it's still actionable.

Source code in src/robotsix_cost_monitor/aggregations.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
def _trace_label(trace: LangfuseTrace) -> str:
    """Display label for a trace in the by-agent view.

    Prefers the trace name (the stage/agent). Some traces reach Langfuse
    without a name (a pydantic-ai/claude_sdk span became the trace root in a
    context where the session was lost — see robotsix-llmio's trace-name
    handling); rather than dumping their cost into one opaque "(unnamed)"
    bucket, attribute it to its session so it's still actionable.
    """
    name = trace.name
    if name:
        return str(name)
    sid = trace.session_id
    if sid and isinstance(sid, str):
        m = _PERIODIC_SESSION_RE.match(sid)
        if m:
            return m.group(1)
    return f"(unnamed) {sid}" if sid else "(unnamed)"

_utc_now()

Source code in src/robotsix_cost_monitor/aggregations.py
40
41
def _utc_now() -> datetime:
    return datetime.now(UTC)

aggregate_by_name(traces)

Cost + count grouped by trace name (the pipeline stage/agent).

Source code in src/robotsix_cost_monitor/aggregations.py
154
155
156
157
158
159
160
161
162
def aggregate_by_name(traces: list[LangfuseTrace]) -> list[dict[str, Any]]:
    """Cost + count grouped by trace name (the pipeline stage/agent)."""
    acc: dict[str, dict[str, float]] = {}
    for t in traces:
        name = _trace_label(t)
        slot = acc.setdefault(name, {"cost": 0.0, "count": 0.0})
        slot["cost"] += _trace_cost(t)
        slot["count"] += 1
    return _sorted_cost_rows(acc)

aggregate_by_name_backend(rows, backend)

Merge per-(stage, backend) observation rows for a single backend.

rows are pre-flattened dicts (each with at least name, backend, cost and count). Rows whose backend does not match are silently dropped. Multiple projects' rows can be passed together — they are summed by stage name, producing the {"name", "cost", "count"} shape returned by :func:aggregate_by_name.

Source code in src/robotsix_cost_monitor/aggregations.py
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
def aggregate_by_name_backend(
    rows: list[dict[str, Any]], backend: str
) -> list[dict[str, Any]]:
    """Merge per-(stage, backend) observation rows for a single backend.

    ``rows`` are pre-flattened dicts (each with at least ``name``, ``backend``,
    ``cost`` and ``count``).  Rows whose ``backend`` does not match are
    silently dropped.  Multiple projects' rows can be passed together — they
    are summed by stage name, producing the ``{"name", "cost", "count"}``
    shape returned by :func:`aggregate_by_name`.
    """
    acc: dict[str, dict[str, float]] = {}
    for r in rows:
        if r.get("backend") != backend:
            continue
        name = r["name"]
        slot = acc.setdefault(name, {"cost": 0.0, "count": 0.0})
        slot["cost"] += float(r.get("cost") or 0.0)
        slot["count"] += float(r.get("count") or 0.0)
    return _sorted_cost_rows(acc)

aggregate_by_session(traces)

Cost + trace-count grouped by sessionId.

What a session means is the traced component's business, not this dashboard's: a mill ticket run, a chat conversation, a cognee ingest batch. Group and report by the id; never name it after one component's unit of work.

Source code in src/robotsix_cost_monitor/aggregations.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
def aggregate_by_session(traces: list[LangfuseTrace]) -> list[dict[str, Any]]:
    """Cost + trace-count grouped by sessionId.

    What a session *means* is the traced component's business, not this
    dashboard's: a mill ticket run, a chat conversation, a cognee ingest
    batch.  Group and report by the id; never name it after one component's
    unit of work.
    """
    acc: dict[str, dict[str, float]] = {}
    for t in traces:
        sid = t.session_id
        if not sid:
            continue
        slot = acc.setdefault(sid, {"cost": 0.0, "count": 0.0})
        slot["cost"] += _trace_cost(t)
        slot["count"] += 1
    return _sorted_cost_rows(acc, "session_id")

backend_cost_series(parts, backend)

Merge per-project cost maps into a sorted time series.

{time_bucket -> {backend -> cost}} maps are merged into a cost series [{bucket_start, cost}] for backend (or the all-backends total when backend is "all"), sorted by time bucket.

Source code in src/robotsix_cost_monitor/aggregations.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def backend_cost_series(
    parts: list[dict[str, dict[str, float]]], backend: str
) -> list[dict[str, Any]]:
    """Merge per-project cost maps into a sorted time series.

    ``{time_bucket -> {backend -> cost}}`` maps are merged into a cost
    series ``[{bucket_start, cost}]`` for *backend* (or the all-backends total
    when *backend* is ``"all"``), sorted by time bucket.
    """
    merged: dict[str, dict[str, float]] = {}
    for part in parts:
        for date, by_backend in part.items():
            slot = merged.setdefault(date, {})
            for b, cost in by_backend.items():
                slot[b] = slot.get(b, 0.0) + cost
    series: list[dict[str, Any]] = []
    for date in sorted(merged):
        by_backend = merged[date]
        cost = (
            sum(by_backend.values())
            if backend == "all"
            else by_backend.get(backend, 0.0)
        )
        series.append({"bucket_start": date, "cost": round(cost, 6)})
    return series

backend_for_model(model)

Map a model name to its serving backend (transport).

Keys on the model-ID shape, not specific names, so it survives model version bumps: OpenRouter model IDs are always vendor/model (contain a /); the Claude SDK uses bare aliases (opus/haiku/sonnet).

Source code in src/robotsix_cost_monitor/aggregations.py
44
45
46
47
48
49
50
51
def backend_for_model(model: str) -> BackendKind:
    """Map a model name to its serving backend (transport).

    Keys on the model-ID *shape*, not specific names, so it survives model
    version bumps: OpenRouter model IDs are always ``vendor/model`` (contain a
    ``/``); the Claude SDK uses bare aliases (``opus``/``haiku``/``sonnet``).
    """
    return "openrouter" if "/" in model else "claude-sdk"

cost_trend(traces, hours, buckets=48)

Bucket total cost over the time window into buckets equal slots.

Source code in src/robotsix_cost_monitor/aggregations.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
def cost_trend(
    traces: list[LangfuseTrace], hours: int, buckets: int = 48
) -> list[dict[str, Any]]:
    """Bucket total cost over the time window into *buckets* equal slots."""
    now = _utc_now()
    start = now - timedelta(hours=hours)
    span = (now - start).total_seconds() or 1.0
    width = span / buckets
    totals = [0.0] * buckets
    for t in traces:
        ts = _parse_ts(t)
        if ts is None:
            continue
        idx = int((ts - start).total_seconds() / width)
        if idx < 0 or idx >= buckets:
            continue
        totals[idx] += _trace_cost(t)
    return [
        {
            "bucket_start": (start + timedelta(seconds=width * i)).isoformat(),
            "cost": round(totals[i], 6),
        }
        for i in range(buckets)
    ]

merge_model_costs(parts)

Merge per-model usage rows from several projects, summing by model.

Source code in src/robotsix_cost_monitor/aggregations.py
120
121
122
123
124
125
126
127
128
129
130
131
def merge_model_costs(parts: list[list[dict[str, Any]]]) -> list[dict[str, Any]]:
    """Merge per-model usage rows from several projects, summing by model."""
    acc: dict[str, dict[str, float]] = {}
    for rows in parts:
        for r in rows:
            slot = acc.setdefault(r["model"], _empty_model_slot())
            slot["cost"] += float(r.get("cost") or 0.0)
            slot["input_tokens"] += float(r.get("input_tokens") or 0.0)
            slot["output_tokens"] += float(r.get("output_tokens") or 0.0)
            slot["total_tokens"] += float(r.get("total_tokens") or 0.0)
            slot["observations"] += float(r.get("observations") or 0.0)
    return _model_rows(acc)

most_expensive_session(traces)

Return the single most-expensive session for cost display.

Source code in src/robotsix_cost_monitor/aggregations.py
256
257
258
259
def most_expensive_session(traces: list[LangfuseTrace]) -> dict[str, Any] | None:
    """Return the single most-expensive session for cost display."""
    rows = aggregate_by_session(traces)
    return rows[0] if rows else None

most_expensive_trace(traces)

Return the single most-expensive trace for cost display.

Source code in src/robotsix_cost_monitor/aggregations.py
242
243
244
245
246
247
248
249
250
251
252
253
def most_expensive_trace(traces: list[LangfuseTrace]) -> dict[str, Any] | None:
    """Return the single most-expensive trace for cost display."""
    if not traces:
        return None
    top = max(traces, key=_trace_cost)
    return {
        "id": top.id,
        "name": top.name,
        "session_id": top.session_id,
        "cost": round(_trace_cost(top), 6),
        "timestamp": top.timestamp,
    }

robotsix_cost_monitor.app

FastAPI app: cost dashboard + reconciliation endpoints, server-rendered UI.

_AUTH_EXEMPT_PATHS = ('/health', '/health/live', '/readyz', '/metrics') module-attribute

_WEB = Path(__file__).resolve().parent / 'web' module-attribute

__version__ = '0.9.3' module-attribute

cache_warm_failure = Counter('robotsix_cost_monitor_cache_warm_failure_total', 'Total number of failed dashboard cache warm-ups.') module-attribute

cache_warm_success = Counter('robotsix_cost_monitor_cache_warm_success_total', 'Total number of successful dashboard cache warm-ups.') module-attribute

config_router = APIRouter() module-attribute

logger = structlog.get_logger(__name__) module-attribute

router = APIRouter() module-attribute

Config

Bases: BaseModel

Top-level config: registry-driven project discovery + global settings.

Project credentials are discovered at runtime from the central-deploy registry — there is no hardcoded project list.

Source code in src/robotsix_cost_monitor/config/__init__.py
215
216
217
218
219
220
221
222
class Config(BaseModel):
    """Top-level config: registry-driven project discovery + global settings.

    Project credentials are discovered at runtime from the central-deploy
    registry — there is no hardcoded project list.
    """

    settings: Settings = Field(default_factory=Settings)

CostMonitorError

Bases: Exception

Base exception for all cost-monitor errors.

Source code in src/robotsix_cost_monitor/exceptions.py
26
27
28
29
30
31
32
33
34
35
36
37
38
class CostMonitorError(Exception):
    """Base exception for all cost-monitor errors."""

    status_code: int = 500
    error_code: str = "INTERNAL_ERROR"
    detail: str = ""

    def __init__(self, detail: str = "", *, status_code: int | None = None) -> None:
        """Initialise with an optional detail message and status code override."""
        self.detail = detail or self.detail
        if status_code is not None:
            self.status_code = status_code
        super().__init__(self.detail)

__init__(detail='', *, status_code=None)

Initialise with an optional detail message and status code override.

Source code in src/robotsix_cost_monitor/exceptions.py
33
34
35
36
37
38
def __init__(self, detail: str = "", *, status_code: int | None = None) -> None:
    """Initialise with an optional detail message and status code override."""
    self.detail = detail or self.detail
    if status_code is not None:
        self.status_code = status_code
    super().__init__(self.detail)

CostService

Cross-project cost aggregation service with per-window TTL cache.

All five internal caches share a single :attr:last_updated timestamp (the youngest refresh across all caches) so the dashboard can display data freshness.

Source code in src/robotsix_cost_monitor/service/core.py
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
class CostService:
    """Cross-project cost aggregation service with per-window TTL cache.

    All five internal caches share a single :attr:`last_updated` timestamp
    (the youngest refresh across *all* caches) so the dashboard can display
    data freshness.
    """

    def __init__(self, config: Config, registry_client: RegistryClient) -> None:
        """Initialise the service with config and a registry client.

        Starts with an empty project/client map — call :meth:`refresh_projects`
        during startup to populate from the registry.
        """
        self.config = config
        self._registry = registry_client
        self._project_map: dict[str, RegistryProject] = {}
        self._clients: dict[str, LangfuseClient] = {}
        ttl = self.config.settings.cache_ttl_seconds
        self._last_updated: datetime | None = None
        self._caches: list[TTLCache[Any, Any]] = []
        on_refresh = self._touch_last_updated

        def _mk[T](t: type[T]) -> TTLCache[Any, T]:
            c = TTLCache[Any, T](ttl, on_refresh=on_refresh)
            self._caches.append(c)
            return c

        # cache: (slug, hours) -> (traces, monotonic_deadline)
        self._cache = _mk(list[LangfuseTrace])
        # cache: (slug, hours) -> (per-model usage rows, monotonic_deadline)
        self._model_cache = _mk(list[dict[str, Any]])
        # cache: (slug, hours) -> ({time_bucket -> {backend -> cost}}, deadline)
        self._backend_cache = _mk(dict[str, dict[str, float]])
        # cache: (slug, hours) -> (per-(stage, backend) rows, monotonic_deadline)
        self._agent_usage_cache = _mk(list[dict[str, Any]])
        # cache: (slug, hours) -> (trace_count, monotonic_deadline)
        self._trace_count_cache = _mk(int)

    def _touch_last_updated(self) -> None:
        """Record the current wall-clock time as the last cache refresh."""
        self._last_updated = datetime.now(UTC)

    @property
    def last_updated(self) -> datetime | None:
        """UTC datetime of the most recent cache refresh, or ``None`` when cold."""
        return self._last_updated

    def invalidate_all(self) -> None:
        """Clear every internal cache so the next request fetches fresh data."""
        for c in self._caches:
            c.invalidate()
        self._last_updated = None

    async def refresh_projects(self) -> None:
        """Query the registry and rebuild the project/client map.

        Best-effort: on failure the existing project list is kept unchanged.
        """
        try:
            registry_projects = await self._registry.fetch_projects()
        except Exception:
            logger.warning("refresh_projects: registry fetch failed")
            return
        if not registry_projects:
            logger.warning("refresh_projects: registry returned no projects")
            return
        self._project_map = {p.slug: p for p in registry_projects}
        self._clients = {
            p.slug: LangfuseClient(
                public_key=p.langfuse_public_key,
                secret_key=p.langfuse_secret_key.get_secret_value(),
                base_url=p.langfuse_base_url,
            )
            for p in registry_projects
        }
        self.invalidate_all()
        logger.info(
            "refresh_projects: discovered %d project(s) across %d component(s)",
            len(self._project_map),
            len(self.components()),
        )

    def projects(self) -> list[RegistryProject]:
        """Return every discovered project, in registry order."""
        return list(self._project_map.values())

    def components(self) -> dict[str, list[RegistryProject]]:
        """Return discovered projects grouped by owning component.

        Insertion order follows the registry, so the dashboard's component list
        is stable across refreshes.  Projects whose component is unknown are
        grouped under their own slug rather than dropped.
        """
        out: dict[str, list[RegistryProject]] = {}
        for p in self._project_map.values():
            out.setdefault(p.component_id or p.slug, []).append(p)
        return out

    def _projects(self, slug: str | None) -> list[RegistryProject]:
        """Resolve a selector to the projects it covers.

        Accepts ``"all"``/empty (everything), a **component id** (every project
        that component owns), or a single **project slug**.  Resolving both
        levels here is what lets every endpoint be component-aware without any
        per-endpoint or per-component code.

        Project slugs win over component ids on collision: a project is the
        more specific thing, and the single-project component case (where the
        two names coincide) resolves identically either way.
        """
        if not slug or slug == "all":
            return list(self._project_map.values())
        if (p := self._project_map.get(slug)) is not None:
            return [p]
        result = [q for q in self._project_map.values() if q.component_id == slug]
        if not result:
            raise ProjectNotFoundError(
                f"Project '{slug}' not found — no configured project or "
                f"component matches this slug."
            )
        return result

    async def _safe_project_fetch[T](
        self,
        project: RegistryProject,
        fetch_fn: Callable[[], Awaitable[T]],
        label: str,
        default: T,
    ) -> T:
        try:
            return await fetch_fn()
        except ExternalServiceError, ExternalRateLimitError, CacheError:
            logger.warning("project %s %s failed transiently", project.slug, label)
            return default
        except Exception:
            logger.exception("project %s %s failed unexpectedly", project.slug, label)
            return default

    async def _cached_fetch(
        self,
        project: RegistryProject,
        hours: int,
        cache: TTLCache[tuple[str, int], _T],
        fetch_fn: Callable[[int], Awaitable[_T]],
    ) -> _T:
        key = (project.slug, hours)
        return await cache.get_or_fetch(key, lambda: fetch_fn(hours))

    async def _traces(
        self, project: RegistryProject, hours: int
    ) -> list[LangfuseTrace]:
        return await self._cached_fetch(
            project,
            hours,
            self._cache,
            lambda h: self._clients[project.slug].fetch_traces_window(h),
        )

    async def _trace_count(self, project: RegistryProject, hours: int) -> int:
        """Trace count for the window via a server-side metrics query (cached).

        Avoids paging every raw trace just to ``len()`` them — the headline
        ``summary`` only needs the count, not the trace bodies.
        """
        return await self._cached_fetch(
            project,
            hours,
            self._trace_count_cache,
            lambda h: self._clients[project.slug].fetch_trace_count_window(h),
        )

    async def _gather(
        self, slug: str | None, hours: int
    ) -> list[tuple[RegistryProject, list[LangfuseTrace]]]:
        out: list[tuple[RegistryProject, list[LangfuseTrace]]] = []
        for p in self._projects(slug):
            traces: list[LangfuseTrace] = await self._safe_project_fetch(
                p,
                lambda: self._traces(p, hours),  # noqa: B023
                "fetch traces",
                [],
            )
            out.append((p, traces))
        return out

    async def _gather_list_results(
        self,
        slug: str | None,
        hours: int,
        fetch: Callable[[RegistryProject, int], Awaitable[list[dict[str, Any]]]],
    ) -> list[dict[str, Any]]:
        parts: list[list[dict[str, Any]]] = []
        for p in self._projects(slug):
            result: list[dict[str, Any]] = await self._safe_project_fetch(
                p,
                lambda: fetch(p, hours),  # noqa: B023
                "fetch list results",
                [],
            )
            parts.append(result)
        return [r for part in parts for r in part]

    async def summary(
        self, slug: str | None, hours: int, backend: str = "all"
    ) -> dict[str, Any]:
        """Per-project totals + the aggregate, for the window.

        Cost is observation-based (the same window-accurate metrics source as the
        by-model / by-backend breakdowns), so the headline total, the per-model
        rows, and the per-backend totals all reconcile — a backend can never
        exceed the total. ``trace_count`` comes from a server-side ``view=traces``
        count metric (not by paging every trace), so this stays fast.

        When *backend* is not ``"all"``, only observation rows attributed to that
        backend are counted, so the per-component rollup and total reflect costs
        for the selected backend alone.
        """
        per_project: list[dict[str, Any]] = []
        total = 0.0
        for p in self._projects(slug):
            models: list[dict[str, Any]] = await self._safe_project_fetch(
                p,
                lambda: self._model_usage(p, hours),  # noqa: B023
                "model-usage",
                [],
            )
            if backend != "all":
                models = [m for m in models if m.get("backend") == backend]
            trace_count: int = await self._safe_project_fetch(
                p,
                lambda: self._trace_count(p, hours),  # noqa: B023
                "trace-count",
                0,
            )
            cost = round(sum(m["cost"] for m in models), 6)
            total += cost
            per_project.append(
                {
                    "name": p.name,
                    "slug": p.slug,
                    "component": p.component_id,
                    "cost": cost,
                    "trace_count": trace_count,
                }
            )
        total = round(total, 6)
        by_component: dict[str, dict[str, Any]] = {}
        for row in per_project:
            agg = by_component.setdefault(
                str(row["component"] or row["slug"]),
                {
                    "component": row["component"] or row["slug"],
                    "cost": 0.0,
                    "trace_count": 0,
                    "projects": [],
                },
            )
            agg["cost"] = round(agg["cost"] + float(row["cost"]), 6)
            agg["trace_count"] += int(row["trace_count"])
            agg["projects"].append(row)
        components = sorted(
            by_component.values(), key=lambda c: float(c["cost"]), reverse=True
        )
        if backend != "all":
            components = [c for c in components if c["cost"] > 0]
        return {
            "window_hours": hours,
            "total_cost": total,
            "projects": per_project,
            "components": components,
        }

    async def by_agent(
        self, slug: str | None, hours: int, backend: str = "all"
    ) -> list[dict[str, Any]]:
        """Cost by trace name (stage/agent), merged across selected projects.

        When ``backend`` is ``"all"`` (default), uses trace-level cost
        (``aggregate_by_name``) — unchanged from the original behavior.

        When a specific backend is selected, uses per-(stage, backend)
        observation-metrics so that each stage's cost is attributed to the
        backend(s) it actually used.
        """
        if backend == "all":
            gathered = await self._gather(slug, hours)
            all_traces = [t for _, traces in gathered for t in traces]
            return aggregate_by_name(all_traces)

        all_rows = await self._gather_list_results(slug, hours, self._agent_usage)
        return aggregate_by_name_backend(all_rows, backend)

    async def _model_usage(
        self, project: RegistryProject, hours: int
    ) -> list[dict[str, Any]]:
        return await self._cached_fetch(
            project,
            hours,
            self._model_cache,
            lambda h: self._clients[project.slug].fetch_model_usage_window(h),
        )

    async def by_model(self, slug: str | None, hours: int) -> list[dict[str, Any]]:
        """Cost + token usage by model, merged across selected projects.

        Window-accurate (see :meth:`LangfuseClient.fetch_model_usage_window`).
        """
        all_rows = await self._gather_list_results(slug, hours, self._model_usage)
        return merge_model_costs([all_rows])

    async def _backend_cost(
        self, project: RegistryProject, hours: int
    ) -> dict[str, dict[str, float]]:
        return await self._cached_fetch(
            project,
            hours,
            self._backend_cache,
            lambda h: self._clients[project.slug].fetch_backend_cost_window(h),
        )

    async def _agent_usage(
        self, project: RegistryProject, hours: int
    ) -> list[dict[str, Any]]:
        return await self._cached_fetch(
            project,
            hours,
            self._agent_usage_cache,
            lambda h: self._clients[project.slug].fetch_agent_usage_window(h),
        )

    async def backend_trend(
        self, slug: str | None, hours: int, backend: BackendKind
    ) -> list[dict[str, Any]]:
        """Return the cost trend for a backend, merged across selected projects.

        Window-accurate; time-bucket granularity scales with the window.
        """
        parts: list[dict[str, dict[str, float]]] = []
        for p in self._projects(slug):
            cost: dict[str, dict[str, float]] = await self._safe_project_fetch(
                p,
                lambda: self._backend_cost(p, hours),  # noqa: B023
                "backend-cost",
                {},
            )
            parts.append(cost)
        return backend_cost_series(parts, backend)

    async def trend(
        self, slug: str | None, hours: int, buckets: int = 48
    ) -> list[dict[str, Any]]:
        """Return a cost trend series across the window."""
        gathered = await self._gather(slug, hours)
        all_traces = [t for _, traces in gathered for t in traces]
        return cost_trend(all_traces, hours, buckets)

    async def highlights(
        self, slug: str | None, hours: int, backend: str = "all"
    ) -> dict[str, Any]:
        """Return dashboard highlights: top trace, session, and summary stats.

        When *backend* is not ``"all"``, traces are filtered to only those
        whose name appears in the agent-usage rows for that backend, keeping
        the highlights consistent with the backend selector.
        """
        gathered = await self._gather(slug, hours)
        all_traces = [t for _, traces in gathered for t in traces]
        if backend != "all":
            agent_rows = await self._gather_list_results(slug, hours, self._agent_usage)
            backend_names: set[str] = {
                r["name"] for r in agent_rows if r.get("backend") == backend
            }
            all_traces = [t for t in all_traces if t.name in backend_names]
        return {
            "most_expensive_trace": most_expensive_trace(all_traces),
            "most_expensive_session": most_expensive_session(all_traces),
            "session_cost_scope": backend if backend != "all" else "all",
        }

last_updated property

UTC datetime of the most recent cache refresh, or None when cold.

__init__(config, registry_client)

Initialise the service with config and a registry client.

Starts with an empty project/client map — call :meth:refresh_projects during startup to populate from the registry.

Source code in src/robotsix_cost_monitor/service/core.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def __init__(self, config: Config, registry_client: RegistryClient) -> None:
    """Initialise the service with config and a registry client.

    Starts with an empty project/client map — call :meth:`refresh_projects`
    during startup to populate from the registry.
    """
    self.config = config
    self._registry = registry_client
    self._project_map: dict[str, RegistryProject] = {}
    self._clients: dict[str, LangfuseClient] = {}
    ttl = self.config.settings.cache_ttl_seconds
    self._last_updated: datetime | None = None
    self._caches: list[TTLCache[Any, Any]] = []
    on_refresh = self._touch_last_updated

    def _mk[T](t: type[T]) -> TTLCache[Any, T]:
        c = TTLCache[Any, T](ttl, on_refresh=on_refresh)
        self._caches.append(c)
        return c

    # cache: (slug, hours) -> (traces, monotonic_deadline)
    self._cache = _mk(list[LangfuseTrace])
    # cache: (slug, hours) -> (per-model usage rows, monotonic_deadline)
    self._model_cache = _mk(list[dict[str, Any]])
    # cache: (slug, hours) -> ({time_bucket -> {backend -> cost}}, deadline)
    self._backend_cache = _mk(dict[str, dict[str, float]])
    # cache: (slug, hours) -> (per-(stage, backend) rows, monotonic_deadline)
    self._agent_usage_cache = _mk(list[dict[str, Any]])
    # cache: (slug, hours) -> (trace_count, monotonic_deadline)
    self._trace_count_cache = _mk(int)

backend_trend(slug, hours, backend) async

Return the cost trend for a backend, merged across selected projects.

Window-accurate; time-bucket granularity scales with the window.

Source code in src/robotsix_cost_monitor/service/core.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
async def backend_trend(
    self, slug: str | None, hours: int, backend: BackendKind
) -> list[dict[str, Any]]:
    """Return the cost trend for a backend, merged across selected projects.

    Window-accurate; time-bucket granularity scales with the window.
    """
    parts: list[dict[str, dict[str, float]]] = []
    for p in self._projects(slug):
        cost: dict[str, dict[str, float]] = await self._safe_project_fetch(
            p,
            lambda: self._backend_cost(p, hours),  # noqa: B023
            "backend-cost",
            {},
        )
        parts.append(cost)
    return backend_cost_series(parts, backend)

by_agent(slug, hours, backend='all') async

Cost by trace name (stage/agent), merged across selected projects.

When backend is "all" (default), uses trace-level cost (aggregate_by_name) — unchanged from the original behavior.

When a specific backend is selected, uses per-(stage, backend) observation-metrics so that each stage's cost is attributed to the backend(s) it actually used.

Source code in src/robotsix_cost_monitor/service/core.py
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
async def by_agent(
    self, slug: str | None, hours: int, backend: str = "all"
) -> list[dict[str, Any]]:
    """Cost by trace name (stage/agent), merged across selected projects.

    When ``backend`` is ``"all"`` (default), uses trace-level cost
    (``aggregate_by_name``) — unchanged from the original behavior.

    When a specific backend is selected, uses per-(stage, backend)
    observation-metrics so that each stage's cost is attributed to the
    backend(s) it actually used.
    """
    if backend == "all":
        gathered = await self._gather(slug, hours)
        all_traces = [t for _, traces in gathered for t in traces]
        return aggregate_by_name(all_traces)

    all_rows = await self._gather_list_results(slug, hours, self._agent_usage)
    return aggregate_by_name_backend(all_rows, backend)

by_model(slug, hours) async

Cost + token usage by model, merged across selected projects.

Window-accurate (see :meth:LangfuseClient.fetch_model_usage_window).

Source code in src/robotsix_cost_monitor/service/core.py
356
357
358
359
360
361
362
async def by_model(self, slug: str | None, hours: int) -> list[dict[str, Any]]:
    """Cost + token usage by model, merged across selected projects.

    Window-accurate (see :meth:`LangfuseClient.fetch_model_usage_window`).
    """
    all_rows = await self._gather_list_results(slug, hours, self._model_usage)
    return merge_model_costs([all_rows])

components()

Return discovered projects grouped by owning component.

Insertion order follows the registry, so the dashboard's component list is stable across refreshes. Projects whose component is unknown are grouped under their own slug rather than dropped.

Source code in src/robotsix_cost_monitor/service/core.py
140
141
142
143
144
145
146
147
148
149
150
def components(self) -> dict[str, list[RegistryProject]]:
    """Return discovered projects grouped by owning component.

    Insertion order follows the registry, so the dashboard's component list
    is stable across refreshes.  Projects whose component is unknown are
    grouped under their own slug rather than dropped.
    """
    out: dict[str, list[RegistryProject]] = {}
    for p in self._project_map.values():
        out.setdefault(p.component_id or p.slug, []).append(p)
    return out

highlights(slug, hours, backend='all') async

Return dashboard highlights: top trace, session, and summary stats.

When backend is not "all", traces are filtered to only those whose name appears in the agent-usage rows for that backend, keeping the highlights consistent with the backend selector.

Source code in src/robotsix_cost_monitor/service/core.py
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
async def highlights(
    self, slug: str | None, hours: int, backend: str = "all"
) -> dict[str, Any]:
    """Return dashboard highlights: top trace, session, and summary stats.

    When *backend* is not ``"all"``, traces are filtered to only those
    whose name appears in the agent-usage rows for that backend, keeping
    the highlights consistent with the backend selector.
    """
    gathered = await self._gather(slug, hours)
    all_traces = [t for _, traces in gathered for t in traces]
    if backend != "all":
        agent_rows = await self._gather_list_results(slug, hours, self._agent_usage)
        backend_names: set[str] = {
            r["name"] for r in agent_rows if r.get("backend") == backend
        }
        all_traces = [t for t in all_traces if t.name in backend_names]
    return {
        "most_expensive_trace": most_expensive_trace(all_traces),
        "most_expensive_session": most_expensive_session(all_traces),
        "session_cost_scope": backend if backend != "all" else "all",
    }

invalidate_all()

Clear every internal cache so the next request fetches fresh data.

Source code in src/robotsix_cost_monitor/service/core.py
101
102
103
104
105
def invalidate_all(self) -> None:
    """Clear every internal cache so the next request fetches fresh data."""
    for c in self._caches:
        c.invalidate()
    self._last_updated = None

projects()

Return every discovered project, in registry order.

Source code in src/robotsix_cost_monitor/service/core.py
136
137
138
def projects(self) -> list[RegistryProject]:
    """Return every discovered project, in registry order."""
    return list(self._project_map.values())

refresh_projects() async

Query the registry and rebuild the project/client map.

Best-effort: on failure the existing project list is kept unchanged.

Source code in src/robotsix_cost_monitor/service/core.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
async def refresh_projects(self) -> None:
    """Query the registry and rebuild the project/client map.

    Best-effort: on failure the existing project list is kept unchanged.
    """
    try:
        registry_projects = await self._registry.fetch_projects()
    except Exception:
        logger.warning("refresh_projects: registry fetch failed")
        return
    if not registry_projects:
        logger.warning("refresh_projects: registry returned no projects")
        return
    self._project_map = {p.slug: p for p in registry_projects}
    self._clients = {
        p.slug: LangfuseClient(
            public_key=p.langfuse_public_key,
            secret_key=p.langfuse_secret_key.get_secret_value(),
            base_url=p.langfuse_base_url,
        )
        for p in registry_projects
    }
    self.invalidate_all()
    logger.info(
        "refresh_projects: discovered %d project(s) across %d component(s)",
        len(self._project_map),
        len(self.components()),
    )

summary(slug, hours, backend='all') async

Per-project totals + the aggregate, for the window.

Cost is observation-based (the same window-accurate metrics source as the by-model / by-backend breakdowns), so the headline total, the per-model rows, and the per-backend totals all reconcile — a backend can never exceed the total. trace_count comes from a server-side view=traces count metric (not by paging every trace), so this stays fast.

When backend is not "all", only observation rows attributed to that backend are counted, so the per-component rollup and total reflect costs for the selected backend alone.

Source code in src/robotsix_cost_monitor/service/core.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
async def summary(
    self, slug: str | None, hours: int, backend: str = "all"
) -> dict[str, Any]:
    """Per-project totals + the aggregate, for the window.

    Cost is observation-based (the same window-accurate metrics source as the
    by-model / by-backend breakdowns), so the headline total, the per-model
    rows, and the per-backend totals all reconcile — a backend can never
    exceed the total. ``trace_count`` comes from a server-side ``view=traces``
    count metric (not by paging every trace), so this stays fast.

    When *backend* is not ``"all"``, only observation rows attributed to that
    backend are counted, so the per-component rollup and total reflect costs
    for the selected backend alone.
    """
    per_project: list[dict[str, Any]] = []
    total = 0.0
    for p in self._projects(slug):
        models: list[dict[str, Any]] = await self._safe_project_fetch(
            p,
            lambda: self._model_usage(p, hours),  # noqa: B023
            "model-usage",
            [],
        )
        if backend != "all":
            models = [m for m in models if m.get("backend") == backend]
        trace_count: int = await self._safe_project_fetch(
            p,
            lambda: self._trace_count(p, hours),  # noqa: B023
            "trace-count",
            0,
        )
        cost = round(sum(m["cost"] for m in models), 6)
        total += cost
        per_project.append(
            {
                "name": p.name,
                "slug": p.slug,
                "component": p.component_id,
                "cost": cost,
                "trace_count": trace_count,
            }
        )
    total = round(total, 6)
    by_component: dict[str, dict[str, Any]] = {}
    for row in per_project:
        agg = by_component.setdefault(
            str(row["component"] or row["slug"]),
            {
                "component": row["component"] or row["slug"],
                "cost": 0.0,
                "trace_count": 0,
                "projects": [],
            },
        )
        agg["cost"] = round(agg["cost"] + float(row["cost"]), 6)
        agg["trace_count"] += int(row["trace_count"])
        agg["projects"].append(row)
    components = sorted(
        by_component.values(), key=lambda c: float(c["cost"]), reverse=True
    )
    if backend != "all":
        components = [c for c in components if c["cost"] > 0]
    return {
        "window_hours": hours,
        "total_cost": total,
        "projects": per_project,
        "components": components,
    }

trend(slug, hours, buckets=48) async

Return a cost trend series across the window.

Source code in src/robotsix_cost_monitor/service/core.py
402
403
404
405
406
407
408
async def trend(
    self, slug: str | None, hours: int, buckets: int = 48
) -> list[dict[str, Any]]:
    """Return a cost trend series across the window."""
    gathered = await self._gather(slug, hours)
    all_traces = [t for _, traces in gathered for t in traces]
    return cost_trend(all_traces, hours, buckets)

MillAPIError

Bases: RuntimeError

The mill board API could not be queried (network or HTTP error).

Raised instead of returning an empty result so callers can tell a failed check apart from a successful check that found nothing. Callers must treat this as "unknown": preserve the last known stuck-ticket state rather than overwriting it with an empty list.

Source code in src/robotsix_cost_monitor/clients/mill.py
22
23
24
25
26
27
28
29
class MillAPIError(RuntimeError):
    """The mill board API could not be queried (network or HTTP error).

    Raised instead of returning an empty result so callers can tell a
    *failed* check apart from a successful check that found nothing.
    Callers must treat this as "unknown": preserve the last known
    stuck-ticket state rather than overwriting it with an empty list.
    """

MillClient dataclass

HTTP client for the robotsix-mill board API.

Used by the stuck-ticket background loop to periodically query the mill's GET /tickets endpoint and identify tickets that have been in a non-terminal state longer than the configured threshold.

Source code in src/robotsix_cost_monitor/clients/mill.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
@dataclass
class MillClient:
    """HTTP client for the robotsix-mill board API.

    Used by the stuck-ticket background loop to periodically query the
    mill's ``GET /tickets`` endpoint and identify tickets that have been
    in a non-terminal state longer than the configured threshold.
    """

    settings: Settings
    _http: httpx.AsyncClient | None = field(default=None, repr=False, init=False)

    def __post_init__(self) -> None:
        """Initialise lazy HTTP client holder to None."""
        self._http = None

    @property
    def base_url(self) -> str:
        """Return the mill API base URL with trailing slash stripped."""
        return self.settings.mill_base_url.rstrip("/")

    @property
    def _api_key(self) -> str:
        """Return the effective mill API key (env var or config)."""
        return resolve_mill_api_key(self.settings)

    @property
    def _threshold_hours(self) -> int:
        """Return the stuck-ticket threshold in hours."""
        return self.settings.stuck_ticket_threshold_hours

    @property
    def _enabled(self) -> bool:
        """Return True when stuck-ticket detection is configured and active."""
        return bool(self.base_url) and self._threshold_hours > 0

    async def _client(self) -> httpx.AsyncClient:
        """Lazy-init the HTTP client so it's not created at import time."""
        if self._http is None:
            self._http = httpx.AsyncClient(timeout=30.0)
        return self._http

    async def fetch_stuck_tickets(self) -> list[StuckTicket]:
        """Query the mill for tickets stuck in non-terminal states.

        Calls ``GET /tickets`` (``include_closed=false`` is the default,
        so terminal states are already excluded).  Each returned ticket
        whose ``updated_at`` is older than the configured threshold is
        flagged as stuck.

        Returns an empty list when detection is disabled.  Raises
        :class:`MillAPIError` when the mill API is unreachable, returns
        an error status, or returns an unexpected payload — the caller
        must then keep the previous results instead of treating the
        check as a clean empty result.
        """
        if not self._enabled:
            return []

        threshold = timedelta(hours=self._threshold_hours)
        cutoff = datetime.now(UTC) - threshold

        url = f"{self.base_url}/tickets"
        headers = {"X-API-Key": self._api_key} if self._api_key else {}
        try:
            client = await self._client()
            retry = RetryClient(client)
            resp = await retry.get(url, headers=headers)
            resp.raise_for_status()
            tickets = resp.json()
        except Exception as exc:
            logger.exception(
                "mill stuck-ticket check failed — keeping previous results"
            )
            raise MillAPIError(
                "mill board API unavailable — previous stuck-ticket results kept"
            ) from exc

        stuck: list[StuckTicket] = []
        if not isinstance(tickets, list):
            logger.warning("mill /tickets returned non-list payload: %s", type(tickets))
            raise MillAPIError(
                "mill board API returned an unexpected payload — "
                "previous stuck-ticket results kept"
            )

        for raw in tickets:
            if not isinstance(raw, dict):
                continue
            state = raw.get("state", "")
            if state not in NON_TERMINAL_STATES:
                continue
            updated_raw = raw.get("updated_at", "")
            try:
                updated = datetime.fromisoformat(updated_raw.replace("Z", "+00:00"))
            except ValueError, TypeError:
                continue
            if updated > cutoff:
                continue
            stuck_for = (datetime.now(UTC) - updated).total_seconds() / 3600.0
            stuck.append(
                StuckTicket(
                    ticket_id=raw.get("id", ""),
                    title=raw.get("title", ""),
                    state=state,
                    kind=raw.get("kind", ""),
                    source=raw.get("source", ""),
                    created_at=raw.get("created_at", ""),
                    updated_at=updated_raw,
                    stuck_for_hours=round(stuck_for, 1),
                )
            )
        return stuck

    async def close(self) -> None:
        """Release the underlying HTTP client."""
        if self._http is not None:
            await self._http.aclose()
            self._http = None

base_url property

Return the mill API base URL with trailing slash stripped.

__post_init__()

Initialise lazy HTTP client holder to None.

Source code in src/robotsix_cost_monitor/clients/mill.py
84
85
86
def __post_init__(self) -> None:
    """Initialise lazy HTTP client holder to None."""
    self._http = None

close() async

Release the underlying HTTP client.

Source code in src/robotsix_cost_monitor/clients/mill.py
186
187
188
189
190
async def close(self) -> None:
    """Release the underlying HTTP client."""
    if self._http is not None:
        await self._http.aclose()
        self._http = None

fetch_stuck_tickets() async

Query the mill for tickets stuck in non-terminal states.

Calls GET /tickets (include_closed=false is the default, so terminal states are already excluded). Each returned ticket whose updated_at is older than the configured threshold is flagged as stuck.

Returns an empty list when detection is disabled. Raises :class:MillAPIError when the mill API is unreachable, returns an error status, or returns an unexpected payload — the caller must then keep the previous results instead of treating the check as a clean empty result.

Source code in src/robotsix_cost_monitor/clients/mill.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
async def fetch_stuck_tickets(self) -> list[StuckTicket]:
    """Query the mill for tickets stuck in non-terminal states.

    Calls ``GET /tickets`` (``include_closed=false`` is the default,
    so terminal states are already excluded).  Each returned ticket
    whose ``updated_at`` is older than the configured threshold is
    flagged as stuck.

    Returns an empty list when detection is disabled.  Raises
    :class:`MillAPIError` when the mill API is unreachable, returns
    an error status, or returns an unexpected payload — the caller
    must then keep the previous results instead of treating the
    check as a clean empty result.
    """
    if not self._enabled:
        return []

    threshold = timedelta(hours=self._threshold_hours)
    cutoff = datetime.now(UTC) - threshold

    url = f"{self.base_url}/tickets"
    headers = {"X-API-Key": self._api_key} if self._api_key else {}
    try:
        client = await self._client()
        retry = RetryClient(client)
        resp = await retry.get(url, headers=headers)
        resp.raise_for_status()
        tickets = resp.json()
    except Exception as exc:
        logger.exception(
            "mill stuck-ticket check failed — keeping previous results"
        )
        raise MillAPIError(
            "mill board API unavailable — previous stuck-ticket results kept"
        ) from exc

    stuck: list[StuckTicket] = []
    if not isinstance(tickets, list):
        logger.warning("mill /tickets returned non-list payload: %s", type(tickets))
        raise MillAPIError(
            "mill board API returned an unexpected payload — "
            "previous stuck-ticket results kept"
        )

    for raw in tickets:
        if not isinstance(raw, dict):
            continue
        state = raw.get("state", "")
        if state not in NON_TERMINAL_STATES:
            continue
        updated_raw = raw.get("updated_at", "")
        try:
            updated = datetime.fromisoformat(updated_raw.replace("Z", "+00:00"))
        except ValueError, TypeError:
            continue
        if updated > cutoff:
            continue
        stuck_for = (datetime.now(UTC) - updated).total_seconds() / 3600.0
        stuck.append(
            StuckTicket(
                ticket_id=raw.get("id", ""),
                title=raw.get("title", ""),
                state=state,
                kind=raw.get("kind", ""),
                source=raw.get("source", ""),
                created_at=raw.get("created_at", ""),
                updated_at=updated_raw,
                stuck_for_hours=round(stuck_for, 1),
            )
        )
    return stuck

RegistryClient

Discovers Langfuse-enabled components from the central-deploy registry.

The central-deploy registry exposes an authenticated GET /fleet/langfuse endpoint that returns every registered component and, for each Langfuse-enabled one, its langfuse_host and projects (each with alias, public_key, secret_key).

Source code in src/robotsix_cost_monitor/clients/registry.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
class RegistryClient:
    """Discovers Langfuse-enabled components from the central-deploy registry.

    The central-deploy registry exposes an authenticated ``GET /fleet/langfuse``
    endpoint that returns every registered component and, for each
    Langfuse-enabled one, its ``langfuse_host`` and ``projects``
    (each with ``alias``, ``public_key``, ``secret_key``).
    """

    def __init__(self, base_url: str, api_key: str, timeout: float = 30.0) -> None:
        """Initialise with the central-deploy registry URL and API key."""
        self._base_url = base_url.rstrip("/")
        self._api_key = api_key
        self._timeout = timeout

    async def fetch_projects(self) -> list[RegistryProject]:
        """Query the registry for all Langfuse-enabled components.

        Returns a (possibly empty) list of RegistryProject instances.
        Logs and returns empty on any transient failure — the service
        keeps its last-known-good project list.
        """
        url = f"{self._base_url}/fleet/langfuse"
        headers = {"X-API-Key": self._api_key}
        try:
            async with httpx.AsyncClient(timeout=self._timeout) as http_client:
                client = RetryClient(http_client)
                resp = await client.get(url, headers=headers)
            resp.raise_for_status()
            payload = resp.json()
        except Exception:
            logger.exception("registry fetch failed — keeping existing projects")
            return []

        # 7af1 schema: the response is a list of component objects, each with
        # `langfuse_host` and `projects[] = {alias, public_key, secret_key}`.
        raw_components: Any = (
            payload if isinstance(payload, list) else payload.get("components", [])
        )

        projects: list[RegistryProject] = []
        for comp in raw_components:
            langfuse_host = comp.get("langfuse_host") or "https://cloud.langfuse.com"
            component_id = comp.get("component_id") or comp.get("name") or ""
            for proj in comp.get("projects", []):
                try:
                    alias = proj["alias"]
                    projects.append(
                        RegistryProject(
                            name=alias,
                            slug=alias,
                            component_id=str(component_id),
                            langfuse_public_key=proj["public_key"],
                            langfuse_secret_key=proj["secret_key"],
                            langfuse_base_url=langfuse_host,
                            # Present when the fleet knows which provider key
                            # paid for this LLM function; enables reconciliation.
                            openrouter_key=proj.get("openrouter_key") or None,
                        )
                    )
                except KeyError, TypeError:  # PEP 758 (py3.14): KeyError OR TypeError
                    logger.warning(
                        "skipping malformed registry project: %s",
                        proj.get("alias", repr(proj)),
                    )
        return projects

__init__(base_url, api_key, timeout=30.0)

Initialise with the central-deploy registry URL and API key.

Source code in src/robotsix_cost_monitor/clients/registry.py
30
31
32
33
34
def __init__(self, base_url: str, api_key: str, timeout: float = 30.0) -> None:
    """Initialise with the central-deploy registry URL and API key."""
    self._base_url = base_url.rstrip("/")
    self._api_key = api_key
    self._timeout = timeout

fetch_projects() async

Query the registry for all Langfuse-enabled components.

Returns a (possibly empty) list of RegistryProject instances. Logs and returns empty on any transient failure — the service keeps its last-known-good project list.

Source code in src/robotsix_cost_monitor/clients/registry.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
async def fetch_projects(self) -> list[RegistryProject]:
    """Query the registry for all Langfuse-enabled components.

    Returns a (possibly empty) list of RegistryProject instances.
    Logs and returns empty on any transient failure — the service
    keeps its last-known-good project list.
    """
    url = f"{self._base_url}/fleet/langfuse"
    headers = {"X-API-Key": self._api_key}
    try:
        async with httpx.AsyncClient(timeout=self._timeout) as http_client:
            client = RetryClient(http_client)
            resp = await client.get(url, headers=headers)
        resp.raise_for_status()
        payload = resp.json()
    except Exception:
        logger.exception("registry fetch failed — keeping existing projects")
        return []

    # 7af1 schema: the response is a list of component objects, each with
    # `langfuse_host` and `projects[] = {alias, public_key, secret_key}`.
    raw_components: Any = (
        payload if isinstance(payload, list) else payload.get("components", [])
    )

    projects: list[RegistryProject] = []
    for comp in raw_components:
        langfuse_host = comp.get("langfuse_host") or "https://cloud.langfuse.com"
        component_id = comp.get("component_id") or comp.get("name") or ""
        for proj in comp.get("projects", []):
            try:
                alias = proj["alias"]
                projects.append(
                    RegistryProject(
                        name=alias,
                        slug=alias,
                        component_id=str(component_id),
                        langfuse_public_key=proj["public_key"],
                        langfuse_secret_key=proj["secret_key"],
                        langfuse_base_url=langfuse_host,
                        # Present when the fleet knows which provider key
                        # paid for this LLM function; enables reconciliation.
                        openrouter_key=proj.get("openrouter_key") or None,
                    )
                )
            except KeyError, TypeError:  # PEP 758 (py3.14): KeyError OR TypeError
                logger.warning(
                    "skipping malformed registry project: %s",
                    proj.get("alias", repr(proj)),
                )
    return projects

_cache_refresh_loop(cfg, service, interval_s) async

Periodically re-fetch dashboard aggregates so the cache stays warm.

Runs forever until cancelled; sleeps interval_s between refreshes.

Source code in src/robotsix_cost_monitor/app.py
119
120
121
122
123
124
125
126
127
128
async def _cache_refresh_loop(
    cfg: Config, service: CostService, interval_s: int
) -> None:
    """Periodically re-fetch dashboard aggregates so the cache stays warm.

    Runs forever until cancelled; sleeps *interval_s* between refreshes.
    """
    while True:
        await asyncio.sleep(interval_s)
        await _warm_cache(cfg, service)

_cost_monitor_error_handler(request, exc) async

Render a typed :class:CostMonitorError via the canonical envelope.

Maps the domain exception onto :class:robotsix_http.fastapi.DomainError so its status_code / error_code drive the shared {"error": {"code", "detail"}} envelope built by :func:robotsix_http.fastapi.domain_error_handler.

Source code in src/robotsix_cost_monitor/app.py
39
40
41
42
43
44
45
46
47
48
49
50
51
async def _cost_monitor_error_handler(request: Request, exc: Exception) -> Response:
    """Render a typed :class:`CostMonitorError` via the canonical envelope.

    Maps the domain exception onto :class:`robotsix_http.fastapi.DomainError`
    so its ``status_code`` / ``error_code`` drive the shared
    ``{"error": {"code", "detail"}}`` envelope built by
    :func:`robotsix_http.fastapi.domain_error_handler`.
    """
    err = cast(CostMonitorError, exc)
    return await domain_error_handler(
        request,
        DomainError(err.detail, code=err.error_code, status_code=err.status_code),
    )

_readiness_checks(cfg, service)

Build the named readiness checks for the shared health router.

  • projects — the registry has yielded at least one Langfuse project (in-memory; populated by refresh_projects at startup and on poll). Without it every cost endpoint serves empty data.
  • data_dir — the reconciliation snapshot directory exists and is writable (reconcile persists snapshots there before comparing).
Source code in src/robotsix_cost_monitor/app.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
def _readiness_checks(cfg: Config, service: CostService) -> dict[str, HealthCheck]:
    """Build the named readiness checks for the shared health router.

    * ``projects`` — the registry has yielded at least one Langfuse project
      (in-memory; populated by ``refresh_projects`` at startup and on poll).
      Without it every cost endpoint serves empty data.
    * ``data_dir`` — the reconciliation snapshot directory exists and is
      writable (reconcile persists snapshots there before comparing).
    """

    async def _projects() -> None:
        if not service.projects():
            raise RuntimeError("no projects discovered from the registry")

    async def _data_dir() -> None:
        d = data_dir(cfg.settings) / "reconcile"
        # The failure text is served unauthenticated: never echo the path.
        try:
            d.mkdir(parents=True, exist_ok=True)
        except OSError:
            raise RuntimeError("reconcile data directory cannot be created") from None
        if not os.access(d, os.W_OK):
            raise RuntimeError("reconcile data directory is not writable")

    return {"projects": _projects, "data_dir": _data_dir}

_reconcile_loop(cfg, service, hours) async

Reconcile all projects on a schedule until cancelled.

Runs every hours hours (with an initial run so the banner has data immediately).

Source code in src/robotsix_cost_monitor/app.py
70
71
72
73
74
75
76
77
78
79
80
81
82
async def _reconcile_loop(cfg: Config, service: CostService, hours: float) -> None:
    """Reconcile all projects on a schedule until cancelled.

    Runs every *hours* hours (with an initial run so the banner has data
    immediately).
    """
    interval = max(1.0, hours) * 3600
    while True:
        try:
            await reconcile_all(cfg, service)
        except Exception:
            logger.exception("scheduled reconcile failed")
        await asyncio.sleep(interval)

_stuck_ticket_loop(mill, interval_s) async

Periodically check the mill board for tickets stuck in non-terminal states.

Each run queries GET /tickets and logs a warning for every ticket whose updated_at is older than stuck_ticket_threshold_hours. When the mill API is unreachable the gauge keeps its previous value — a failed check must never reset stuck_ticket_count to zero, otherwise downstream alerting would silently clear during outages.

Source code in src/robotsix_cost_monitor/app.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
async def _stuck_ticket_loop(mill: MillClient, interval_s: int) -> None:
    """Periodically check the mill board for tickets stuck in non-terminal states.

    Each run queries ``GET /tickets`` and logs a warning for every ticket
    whose ``updated_at`` is older than ``stuck_ticket_threshold_hours``.
    When the mill API is unreachable the gauge keeps its previous value —
    a failed check must never reset ``stuck_ticket_count`` to zero,
    otherwise downstream alerting would silently clear during outages.
    """
    from .metrics import stuck_ticket_check_runs, stuck_ticket_count

    while True:
        try:
            stuck = await mill.fetch_stuck_tickets()
            stuck_ticket_check_runs.inc()
            if stuck:
                stuck_ticket_count.set(len(stuck))
                logger.warning(
                    "stuck_ticket_check: %d tickets stuck in non-terminal state",
                    len(stuck),
                    stuck_tickets=[
                        {
                            "id": t.ticket_id,
                            "title": t.title,
                            "state": t.state,
                            "stuck_for_hours": t.stuck_for_hours,
                        }
                        for t in stuck
                    ],
                )
            else:
                stuck_ticket_count.set(0)
                logger.debug("stuck_ticket_check: no stuck tickets found")
        except MillAPIError:
            # The mill board API is unreachable — keep the previous gauge
            # value so alerting does not miss real stuck tickets.  The
            # underlying cause was already logged by MillClient.
            logger.warning(
                "stuck_ticket_check: mill API unavailable; "
                "keeping previous stuck-ticket gauge value"
            )
        except Exception:
            logger.exception("stuck_ticket_check failed")
        await asyncio.sleep(interval_s)

_warm_cache(cfg, service) async

Pre-fetch aggregates for all dashboard window presets on startup.

Every window-selector option is warmed so window switches are near-instant from the first page load. Best-effort — failures are logged and discarded.

Source code in src/robotsix_cost_monitor/app.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
async def _warm_cache(cfg: Config, service: CostService) -> None:
    """Pre-fetch aggregates for all dashboard window presets on startup.

    Every window-selector option is warmed so window switches are near-instant
    from the first page load.  Best-effort — failures are logged and discarded.
    """
    if not service._project_map:
        return
    from .service import DASHBOARD_WINDOW_PRESETS

    logger.info(
        "warming dashboard cache (%d projects, %d windows)",
        len(service._project_map),
        len(DASHBOARD_WINDOW_PRESETS),
    )
    failed = False
    for h in DASHBOARD_WINDOW_PRESETS:
        try:
            # summary() touches model_usage + trace_count per project
            await service.summary("all", h)
            # by_model() touches model_usage per project
            await service.by_model("all", h)
            # trend() touches traces per project
            await service.trend("all", h)
        except Exception:
            logger.exception("dashboard cache warm-up failed for window=%sh", h)
            failed = True
    if failed:
        cache_warm_failure.inc()
    else:
        cache_warm_success.inc()
    logger.info("dashboard cache warm complete")

create_app(config=None)

Assemble the FastAPI application.

Loads the project :class:~robotsix_cost_monitor.config.Config (when config is None, reads from the path given by ROBOTSIX_CONFIG_FILE), builds a :class:~robotsix_cost_monitor.service.CostService, wires the lifespan (reconciliation background loop), mounts the route handlers from :mod:robotsix_cost_monitor.routes, registers exception handlers, and serves the static web assets.

Source code in src/robotsix_cost_monitor/app.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
def create_app(config: Config | None = None) -> FastAPI:
    """Assemble the FastAPI application.

    Loads the project :class:`~robotsix_cost_monitor.config.Config` (when *config*
    is ``None``, reads from the path given by ``ROBOTSIX_CONFIG_FILE``), builds a
    :class:`~robotsix_cost_monitor.service.CostService`, wires the lifespan
    (reconciliation background loop), mounts the route handlers from
    :mod:`robotsix_cost_monitor.routes`, registers exception handlers, and serves
    the static web assets.
    """
    cfg = config or load_config()
    # Fleet-standard structlog + stdlib ProcessorFormatter bridge. Includes the
    # uvicorn loggers previously wired by the hand-rolled dictConfig so their
    # records render through the same renderer; correlation-id merging is
    # enabled (bind via robotsix_llmio.logging.bind_correlation_id).
    setup_structlog(
        level=cfg.settings.log_level,
        fmt=cfg.settings.log_format,
        loggers=(
            "robotsix_cost_monitor",
            "uvicorn",
            "uvicorn.error",
            "uvicorn.access",
        ),
        correlation_id=True,
    )
    registry = RegistryClient(
        base_url=cfg.settings.registry_base_url,
        api_key=resolve_registry_api_key(cfg.settings),
    )
    service = CostService(cfg, registry)
    mill = MillClient(cfg.settings)

    @contextlib.asynccontextmanager
    async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
        """ASGI lifespan: set up / tear down application state."""
        await service.refresh_projects()
        tasks: list[asyncio.Task[None]] = []
        rh = cfg.settings.reconcile_schedule_hours
        if rh > 0 and service._project_map:
            logger.info("starting reconcile scheduler (every %sh)", rh)
            tasks.append(asyncio.create_task(_reconcile_loop(cfg, service, rh)))
        # Periodic dashboard cache warming (keeps aggregates precomputed).
        di = cfg.settings.dashboard_refresh_interval_seconds
        if di > 0 and service._project_map:
            logger.info("starting dashboard cache-refresh loop (every %ss)", di)
            tasks.append(asyncio.create_task(_cache_refresh_loop(cfg, service, di)))
        # One-shot startup cache warm so the first page load is fast.
        tasks.append(asyncio.create_task(_warm_cache(cfg, service)))
        rpi = cfg.settings.registry_poll_interval_seconds
        if rpi > 0:

            async def _registry_poll_loop() -> None:
                while True:
                    await asyncio.sleep(rpi)
                    await service.refresh_projects()

            tasks.append(asyncio.create_task(_registry_poll_loop()))
        sti = cfg.settings.stuck_ticket_check_interval_seconds
        if sti > 0 and cfg.settings.mill_base_url:
            logger.info(
                "starting stuck-ticket check loop (every %ss, threshold=%sh)",
                sti,
                cfg.settings.stuck_ticket_threshold_hours,
            )
            tasks.append(asyncio.create_task(_stuck_ticket_loop(mill, sti)))
        try:
            yield
        finally:
            for t in tasks:
                t.cancel()
            for t in tasks:
                with contextlib.suppress(asyncio.CancelledError):
                    await t
            for c in service._caches:
                await c.aclose()
            await mill.close()

    app = FastAPI(title="robotsix-cost-monitor", version=__version__, lifespan=lifespan)
    app.state.config = cfg
    app.state.service = service
    app.state.mill = mill

    from prometheus_fastapi_instrumentator import Instrumentator

    Instrumentator().instrument(app).expose(
        app, endpoint="/metrics", include_in_schema=False
    )

    from asgi_correlation_id import CorrelationIdMiddleware

    app.add_middleware(CorrelationIdMiddleware)

    from secure import CacheControl, ContentSecurityPolicy, Secure
    from secure.middleware import SecureASGIMiddleware

    # Start from the fleet baseline (Preset.BALANCED) and only relax on top.
    secure_headers = Secure.with_default_headers()
    csp = next(
        h for h in secure_headers.headers_list if isinstance(h, ContentSecurityPolicy)
    )
    # The server-rendered dashboard uses inline <script>/<style> blocks.
    csp.script_src("'self'", "'unsafe-inline'").style_src("'self'", "'unsafe-inline'")
    # Authenticated, cost/config-bearing responses must never hit disk cache.
    secure_headers.headers_list.append(CacheControl().no_store().max_age(0))
    app.add_middleware(SecureASGIMiddleware, secure=secure_headers)

    # HTTP Basic auth — the dashboard has no other access control, so it must
    # be protected whenever it is reachable beyond loopback (e.g. via the
    # central-deploy gateway, which is an unauthenticated reverse proxy). When
    # unconfigured the check is a no-op (local dev / SSH tunnel). The probe
    # paths (/health, /health/live, /readyz) and /metrics are always exempt so
    # the container healthcheck and orchestrator/gateway probes keep working.
    _auth = cfg.settings.auth
    _auth_user = _auth.username
    _auth_pass = _auth.password.get_secret_value()
    if _auth_user and _auth_pass:
        import base64
        import binascii
        import hmac

        from fastapi.responses import PlainTextResponse

        _expected = f"{_auth_user}:{_auth_pass}"

        @app.middleware("http")
        async def _basic_auth(request: Request, call_next: Any) -> Any:
            if request.url.path in _AUTH_EXEMPT_PATHS:
                return await call_next(request)
            header = request.headers.get("authorization", "")
            if header.startswith("Basic "):
                try:
                    decoded = base64.b64decode(header[6:]).decode("utf-8")
                except binascii.Error, UnicodeDecodeError:
                    decoded = ""
                # Constant-time compare to avoid leaking the credential.
                if hmac.compare_digest(decoded, _expected):
                    return await call_next(request)
            return PlainTextResponse(
                "Unauthorized",
                status_code=401,
                headers={"WWW-Authenticate": 'Basic realm="cost-monitor"'},
            )

        logger.info("HTTP Basic auth enabled for the dashboard")
    else:
        logger.warning(
            "dashboard auth is DISABLED (settings.auth.username/password unset) "
            "— safe only on loopback; do not expose via the gateway"
        )

    register_error_handlers(app)
    app.include_router(
        create_health_router(
            ready_path="/readyz", checks=_readiness_checks(cfg, service)
        )
    )
    app.include_router(router)
    app.include_router(config_router)

    if (_WEB / "static").is_dir():
        app.mount("/static", StaticFiles(directory=_WEB / "static"), name="static")

    # robotsix-ui shared base CSS (compiled dist/style.css from @robotsix/ui)
    _ui_dist = Path("node_modules/@robotsix/ui/dist")
    if _ui_dist.is_dir():
        app.mount(
            "/static/robotsix-ui",
            StaticFiles(directory=_ui_dist),
            name="robotsix-ui",
        )

    return app

data_dir(settings=None)

Resolve the runtime-state directory for persistence.

When settings is given, the settings.data_dir field is used (relative paths are resolved against the repo root). Without settings the legacy default .data relative to the repo root is returned for backward compatibility.

Source code in src/robotsix_cost_monitor/config/__init__.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
def data_dir(settings: Settings | None = None) -> Path:
    """Resolve the runtime-state directory for persistence.

    When *settings* is given, the ``settings.data_dir`` field is used (relative
    paths are resolved against the repo root).  Without *settings* the legacy
    default ``.data`` relative to the repo root is returned for backward
    compatibility.
    """
    if settings is not None:
        path = Path(settings.data_dir)
        if not path.is_absolute():
            path = _REPO_ROOT / path
        return Path(os.path.abspath(path)).resolve()
    return Path(os.path.abspath(_REPO_ROOT / ".data")).resolve()

load_config(path=None)

Load and validate the configuration via ROBOTSIX_CONFIG_FILE.

When path is given (tests), passes it through directly to :func:robotsix_config.load_config.

Source code in src/robotsix_cost_monitor/config/__init__.py
241
242
243
244
245
246
247
248
249
def load_config(path: Path | None = None) -> Config:
    """Load and validate the configuration via ``ROBOTSIX_CONFIG_FILE``.

    When *path* is given (tests), passes it through directly to
    :func:`robotsix_config.load_config`.
    """
    if path is not None:
        return _load_config(Config, path=path)
    return _load_config(Config)

reconcile_all(config, service) async

Reconcile every project, persist the result, and return it.

The stored last.json powers the dashboard's warning banner and the /api/reconcile/last endpoint.

Source code in src/robotsix_cost_monitor/reconcile.py
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
async def reconcile_all(config: Config, service: CostService) -> dict[str, Any]:
    """Reconcile every project, persist the result, and return it.

    The stored ``last.json`` powers the dashboard's warning banner and the
    ``/api/reconcile/last`` endpoint.
    """
    reconcile_runs.inc()
    t0 = time.monotonic()
    projects = service.projects()
    results = [await reconcile_project(p, config.settings) for p in projects]
    reconcile_duration.set(time.monotonic() - t0)
    out: dict[str, Any] = {
        "generated_at": datetime.now(UTC).isoformat(),
        "status": reconcile_status(results),
        "tolerance_usd": config.settings.reconcile_tolerance_usd,
        "results": results,
    }
    _atomic_write_text(
        _last_path(config.settings),
        json.dumps(out, indent=2),
        root=_state_dir(config.settings),
    )
    return out

register_error_handlers(app)

Wire the shared exception-handler suite plus the domain-error adapter.

Delegates the standard handlers (validation, HTTPException, ExternalHTTPError, catch-all) to :func:robotsix_http.fastapi.register_exception_handlers, then registers :func:_cost_monitor_error_handler so the typed :class:CostMonitorError hierarchy keeps its status/code mapping.

Source code in src/robotsix_cost_monitor/app.py
54
55
56
57
58
59
60
61
62
63
64
def register_error_handlers(app: FastAPI) -> None:
    """Wire the shared exception-handler suite plus the domain-error adapter.

    Delegates the standard handlers (validation, ``HTTPException``,
    ``ExternalHTTPError``, catch-all) to
    :func:`robotsix_http.fastapi.register_exception_handlers`, then registers
    :func:`_cost_monitor_error_handler` so the typed :class:`CostMonitorError`
    hierarchy keeps its status/code mapping.
    """
    register_exception_handlers(app)
    app.add_exception_handler(CostMonitorError, _cost_monitor_error_handler)

resolve_registry_api_key(settings)

Return the effective registry API key.

When deployed by robotsix-central-deploy with the robotsix.deploy.access: "agent" label, the deploy API key is auto-injected as the DEPLOY_API_KEY environment variable — no manual config needed. Falls back to settings.registry_api_key for local development.

Source code in src/robotsix_cost_monitor/config/__init__.py
187
188
189
190
191
192
193
194
195
196
197
198
def resolve_registry_api_key(settings: Settings) -> str:
    """Return the effective registry API key.

    When deployed by robotsix-central-deploy with the ``robotsix.deploy.access:
    "agent"`` label, the deploy API key is auto-injected as the
    ``DEPLOY_API_KEY`` environment variable — no manual config needed.  Falls
    back to ``settings.registry_api_key`` for local development.
    """
    env_val = os.environ.get("DEPLOY_API_KEY", "")
    if env_val:
        return env_val
    return settings.registry_api_key.get_secret_value()

robotsix_cost_monitor.cli

Command-line entrypoint: run the dashboard server, or print a cost summary.

CostService

Cross-project cost aggregation service with per-window TTL cache.

All five internal caches share a single :attr:last_updated timestamp (the youngest refresh across all caches) so the dashboard can display data freshness.

Source code in src/robotsix_cost_monitor/service/core.py
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
class CostService:
    """Cross-project cost aggregation service with per-window TTL cache.

    All five internal caches share a single :attr:`last_updated` timestamp
    (the youngest refresh across *all* caches) so the dashboard can display
    data freshness.
    """

    def __init__(self, config: Config, registry_client: RegistryClient) -> None:
        """Initialise the service with config and a registry client.

        Starts with an empty project/client map — call :meth:`refresh_projects`
        during startup to populate from the registry.
        """
        self.config = config
        self._registry = registry_client
        self._project_map: dict[str, RegistryProject] = {}
        self._clients: dict[str, LangfuseClient] = {}
        ttl = self.config.settings.cache_ttl_seconds
        self._last_updated: datetime | None = None
        self._caches: list[TTLCache[Any, Any]] = []
        on_refresh = self._touch_last_updated

        def _mk[T](t: type[T]) -> TTLCache[Any, T]:
            c = TTLCache[Any, T](ttl, on_refresh=on_refresh)
            self._caches.append(c)
            return c

        # cache: (slug, hours) -> (traces, monotonic_deadline)
        self._cache = _mk(list[LangfuseTrace])
        # cache: (slug, hours) -> (per-model usage rows, monotonic_deadline)
        self._model_cache = _mk(list[dict[str, Any]])
        # cache: (slug, hours) -> ({time_bucket -> {backend -> cost}}, deadline)
        self._backend_cache = _mk(dict[str, dict[str, float]])
        # cache: (slug, hours) -> (per-(stage, backend) rows, monotonic_deadline)
        self._agent_usage_cache = _mk(list[dict[str, Any]])
        # cache: (slug, hours) -> (trace_count, monotonic_deadline)
        self._trace_count_cache = _mk(int)

    def _touch_last_updated(self) -> None:
        """Record the current wall-clock time as the last cache refresh."""
        self._last_updated = datetime.now(UTC)

    @property
    def last_updated(self) -> datetime | None:
        """UTC datetime of the most recent cache refresh, or ``None`` when cold."""
        return self._last_updated

    def invalidate_all(self) -> None:
        """Clear every internal cache so the next request fetches fresh data."""
        for c in self._caches:
            c.invalidate()
        self._last_updated = None

    async def refresh_projects(self) -> None:
        """Query the registry and rebuild the project/client map.

        Best-effort: on failure the existing project list is kept unchanged.
        """
        try:
            registry_projects = await self._registry.fetch_projects()
        except Exception:
            logger.warning("refresh_projects: registry fetch failed")
            return
        if not registry_projects:
            logger.warning("refresh_projects: registry returned no projects")
            return
        self._project_map = {p.slug: p for p in registry_projects}
        self._clients = {
            p.slug: LangfuseClient(
                public_key=p.langfuse_public_key,
                secret_key=p.langfuse_secret_key.get_secret_value(),
                base_url=p.langfuse_base_url,
            )
            for p in registry_projects
        }
        self.invalidate_all()
        logger.info(
            "refresh_projects: discovered %d project(s) across %d component(s)",
            len(self._project_map),
            len(self.components()),
        )

    def projects(self) -> list[RegistryProject]:
        """Return every discovered project, in registry order."""
        return list(self._project_map.values())

    def components(self) -> dict[str, list[RegistryProject]]:
        """Return discovered projects grouped by owning component.

        Insertion order follows the registry, so the dashboard's component list
        is stable across refreshes.  Projects whose component is unknown are
        grouped under their own slug rather than dropped.
        """
        out: dict[str, list[RegistryProject]] = {}
        for p in self._project_map.values():
            out.setdefault(p.component_id or p.slug, []).append(p)
        return out

    def _projects(self, slug: str | None) -> list[RegistryProject]:
        """Resolve a selector to the projects it covers.

        Accepts ``"all"``/empty (everything), a **component id** (every project
        that component owns), or a single **project slug**.  Resolving both
        levels here is what lets every endpoint be component-aware without any
        per-endpoint or per-component code.

        Project slugs win over component ids on collision: a project is the
        more specific thing, and the single-project component case (where the
        two names coincide) resolves identically either way.
        """
        if not slug or slug == "all":
            return list(self._project_map.values())
        if (p := self._project_map.get(slug)) is not None:
            return [p]
        result = [q for q in self._project_map.values() if q.component_id == slug]
        if not result:
            raise ProjectNotFoundError(
                f"Project '{slug}' not found — no configured project or "
                f"component matches this slug."
            )
        return result

    async def _safe_project_fetch[T](
        self,
        project: RegistryProject,
        fetch_fn: Callable[[], Awaitable[T]],
        label: str,
        default: T,
    ) -> T:
        try:
            return await fetch_fn()
        except ExternalServiceError, ExternalRateLimitError, CacheError:
            logger.warning("project %s %s failed transiently", project.slug, label)
            return default
        except Exception:
            logger.exception("project %s %s failed unexpectedly", project.slug, label)
            return default

    async def _cached_fetch(
        self,
        project: RegistryProject,
        hours: int,
        cache: TTLCache[tuple[str, int], _T],
        fetch_fn: Callable[[int], Awaitable[_T]],
    ) -> _T:
        key = (project.slug, hours)
        return await cache.get_or_fetch(key, lambda: fetch_fn(hours))

    async def _traces(
        self, project: RegistryProject, hours: int
    ) -> list[LangfuseTrace]:
        return await self._cached_fetch(
            project,
            hours,
            self._cache,
            lambda h: self._clients[project.slug].fetch_traces_window(h),
        )

    async def _trace_count(self, project: RegistryProject, hours: int) -> int:
        """Trace count for the window via a server-side metrics query (cached).

        Avoids paging every raw trace just to ``len()`` them — the headline
        ``summary`` only needs the count, not the trace bodies.
        """
        return await self._cached_fetch(
            project,
            hours,
            self._trace_count_cache,
            lambda h: self._clients[project.slug].fetch_trace_count_window(h),
        )

    async def _gather(
        self, slug: str | None, hours: int
    ) -> list[tuple[RegistryProject, list[LangfuseTrace]]]:
        out: list[tuple[RegistryProject, list[LangfuseTrace]]] = []
        for p in self._projects(slug):
            traces: list[LangfuseTrace] = await self._safe_project_fetch(
                p,
                lambda: self._traces(p, hours),  # noqa: B023
                "fetch traces",
                [],
            )
            out.append((p, traces))
        return out

    async def _gather_list_results(
        self,
        slug: str | None,
        hours: int,
        fetch: Callable[[RegistryProject, int], Awaitable[list[dict[str, Any]]]],
    ) -> list[dict[str, Any]]:
        parts: list[list[dict[str, Any]]] = []
        for p in self._projects(slug):
            result: list[dict[str, Any]] = await self._safe_project_fetch(
                p,
                lambda: fetch(p, hours),  # noqa: B023
                "fetch list results",
                [],
            )
            parts.append(result)
        return [r for part in parts for r in part]

    async def summary(
        self, slug: str | None, hours: int, backend: str = "all"
    ) -> dict[str, Any]:
        """Per-project totals + the aggregate, for the window.

        Cost is observation-based (the same window-accurate metrics source as the
        by-model / by-backend breakdowns), so the headline total, the per-model
        rows, and the per-backend totals all reconcile — a backend can never
        exceed the total. ``trace_count`` comes from a server-side ``view=traces``
        count metric (not by paging every trace), so this stays fast.

        When *backend* is not ``"all"``, only observation rows attributed to that
        backend are counted, so the per-component rollup and total reflect costs
        for the selected backend alone.
        """
        per_project: list[dict[str, Any]] = []
        total = 0.0
        for p in self._projects(slug):
            models: list[dict[str, Any]] = await self._safe_project_fetch(
                p,
                lambda: self._model_usage(p, hours),  # noqa: B023
                "model-usage",
                [],
            )
            if backend != "all":
                models = [m for m in models if m.get("backend") == backend]
            trace_count: int = await self._safe_project_fetch(
                p,
                lambda: self._trace_count(p, hours),  # noqa: B023
                "trace-count",
                0,
            )
            cost = round(sum(m["cost"] for m in models), 6)
            total += cost
            per_project.append(
                {
                    "name": p.name,
                    "slug": p.slug,
                    "component": p.component_id,
                    "cost": cost,
                    "trace_count": trace_count,
                }
            )
        total = round(total, 6)
        by_component: dict[str, dict[str, Any]] = {}
        for row in per_project:
            agg = by_component.setdefault(
                str(row["component"] or row["slug"]),
                {
                    "component": row["component"] or row["slug"],
                    "cost": 0.0,
                    "trace_count": 0,
                    "projects": [],
                },
            )
            agg["cost"] = round(agg["cost"] + float(row["cost"]), 6)
            agg["trace_count"] += int(row["trace_count"])
            agg["projects"].append(row)
        components = sorted(
            by_component.values(), key=lambda c: float(c["cost"]), reverse=True
        )
        if backend != "all":
            components = [c for c in components if c["cost"] > 0]
        return {
            "window_hours": hours,
            "total_cost": total,
            "projects": per_project,
            "components": components,
        }

    async def by_agent(
        self, slug: str | None, hours: int, backend: str = "all"
    ) -> list[dict[str, Any]]:
        """Cost by trace name (stage/agent), merged across selected projects.

        When ``backend`` is ``"all"`` (default), uses trace-level cost
        (``aggregate_by_name``) — unchanged from the original behavior.

        When a specific backend is selected, uses per-(stage, backend)
        observation-metrics so that each stage's cost is attributed to the
        backend(s) it actually used.
        """
        if backend == "all":
            gathered = await self._gather(slug, hours)
            all_traces = [t for _, traces in gathered for t in traces]
            return aggregate_by_name(all_traces)

        all_rows = await self._gather_list_results(slug, hours, self._agent_usage)
        return aggregate_by_name_backend(all_rows, backend)

    async def _model_usage(
        self, project: RegistryProject, hours: int
    ) -> list[dict[str, Any]]:
        return await self._cached_fetch(
            project,
            hours,
            self._model_cache,
            lambda h: self._clients[project.slug].fetch_model_usage_window(h),
        )

    async def by_model(self, slug: str | None, hours: int) -> list[dict[str, Any]]:
        """Cost + token usage by model, merged across selected projects.

        Window-accurate (see :meth:`LangfuseClient.fetch_model_usage_window`).
        """
        all_rows = await self._gather_list_results(slug, hours, self._model_usage)
        return merge_model_costs([all_rows])

    async def _backend_cost(
        self, project: RegistryProject, hours: int
    ) -> dict[str, dict[str, float]]:
        return await self._cached_fetch(
            project,
            hours,
            self._backend_cache,
            lambda h: self._clients[project.slug].fetch_backend_cost_window(h),
        )

    async def _agent_usage(
        self, project: RegistryProject, hours: int
    ) -> list[dict[str, Any]]:
        return await self._cached_fetch(
            project,
            hours,
            self._agent_usage_cache,
            lambda h: self._clients[project.slug].fetch_agent_usage_window(h),
        )

    async def backend_trend(
        self, slug: str | None, hours: int, backend: BackendKind
    ) -> list[dict[str, Any]]:
        """Return the cost trend for a backend, merged across selected projects.

        Window-accurate; time-bucket granularity scales with the window.
        """
        parts: list[dict[str, dict[str, float]]] = []
        for p in self._projects(slug):
            cost: dict[str, dict[str, float]] = await self._safe_project_fetch(
                p,
                lambda: self._backend_cost(p, hours),  # noqa: B023
                "backend-cost",
                {},
            )
            parts.append(cost)
        return backend_cost_series(parts, backend)

    async def trend(
        self, slug: str | None, hours: int, buckets: int = 48
    ) -> list[dict[str, Any]]:
        """Return a cost trend series across the window."""
        gathered = await self._gather(slug, hours)
        all_traces = [t for _, traces in gathered for t in traces]
        return cost_trend(all_traces, hours, buckets)

    async def highlights(
        self, slug: str | None, hours: int, backend: str = "all"
    ) -> dict[str, Any]:
        """Return dashboard highlights: top trace, session, and summary stats.

        When *backend* is not ``"all"``, traces are filtered to only those
        whose name appears in the agent-usage rows for that backend, keeping
        the highlights consistent with the backend selector.
        """
        gathered = await self._gather(slug, hours)
        all_traces = [t for _, traces in gathered for t in traces]
        if backend != "all":
            agent_rows = await self._gather_list_results(slug, hours, self._agent_usage)
            backend_names: set[str] = {
                r["name"] for r in agent_rows if r.get("backend") == backend
            }
            all_traces = [t for t in all_traces if t.name in backend_names]
        return {
            "most_expensive_trace": most_expensive_trace(all_traces),
            "most_expensive_session": most_expensive_session(all_traces),
            "session_cost_scope": backend if backend != "all" else "all",
        }

last_updated property

UTC datetime of the most recent cache refresh, or None when cold.

__init__(config, registry_client)

Initialise the service with config and a registry client.

Starts with an empty project/client map — call :meth:refresh_projects during startup to populate from the registry.

Source code in src/robotsix_cost_monitor/service/core.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def __init__(self, config: Config, registry_client: RegistryClient) -> None:
    """Initialise the service with config and a registry client.

    Starts with an empty project/client map — call :meth:`refresh_projects`
    during startup to populate from the registry.
    """
    self.config = config
    self._registry = registry_client
    self._project_map: dict[str, RegistryProject] = {}
    self._clients: dict[str, LangfuseClient] = {}
    ttl = self.config.settings.cache_ttl_seconds
    self._last_updated: datetime | None = None
    self._caches: list[TTLCache[Any, Any]] = []
    on_refresh = self._touch_last_updated

    def _mk[T](t: type[T]) -> TTLCache[Any, T]:
        c = TTLCache[Any, T](ttl, on_refresh=on_refresh)
        self._caches.append(c)
        return c

    # cache: (slug, hours) -> (traces, monotonic_deadline)
    self._cache = _mk(list[LangfuseTrace])
    # cache: (slug, hours) -> (per-model usage rows, monotonic_deadline)
    self._model_cache = _mk(list[dict[str, Any]])
    # cache: (slug, hours) -> ({time_bucket -> {backend -> cost}}, deadline)
    self._backend_cache = _mk(dict[str, dict[str, float]])
    # cache: (slug, hours) -> (per-(stage, backend) rows, monotonic_deadline)
    self._agent_usage_cache = _mk(list[dict[str, Any]])
    # cache: (slug, hours) -> (trace_count, monotonic_deadline)
    self._trace_count_cache = _mk(int)

backend_trend(slug, hours, backend) async

Return the cost trend for a backend, merged across selected projects.

Window-accurate; time-bucket granularity scales with the window.

Source code in src/robotsix_cost_monitor/service/core.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
async def backend_trend(
    self, slug: str | None, hours: int, backend: BackendKind
) -> list[dict[str, Any]]:
    """Return the cost trend for a backend, merged across selected projects.

    Window-accurate; time-bucket granularity scales with the window.
    """
    parts: list[dict[str, dict[str, float]]] = []
    for p in self._projects(slug):
        cost: dict[str, dict[str, float]] = await self._safe_project_fetch(
            p,
            lambda: self._backend_cost(p, hours),  # noqa: B023
            "backend-cost",
            {},
        )
        parts.append(cost)
    return backend_cost_series(parts, backend)

by_agent(slug, hours, backend='all') async

Cost by trace name (stage/agent), merged across selected projects.

When backend is "all" (default), uses trace-level cost (aggregate_by_name) — unchanged from the original behavior.

When a specific backend is selected, uses per-(stage, backend) observation-metrics so that each stage's cost is attributed to the backend(s) it actually used.

Source code in src/robotsix_cost_monitor/service/core.py
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
async def by_agent(
    self, slug: str | None, hours: int, backend: str = "all"
) -> list[dict[str, Any]]:
    """Cost by trace name (stage/agent), merged across selected projects.

    When ``backend`` is ``"all"`` (default), uses trace-level cost
    (``aggregate_by_name``) — unchanged from the original behavior.

    When a specific backend is selected, uses per-(stage, backend)
    observation-metrics so that each stage's cost is attributed to the
    backend(s) it actually used.
    """
    if backend == "all":
        gathered = await self._gather(slug, hours)
        all_traces = [t for _, traces in gathered for t in traces]
        return aggregate_by_name(all_traces)

    all_rows = await self._gather_list_results(slug, hours, self._agent_usage)
    return aggregate_by_name_backend(all_rows, backend)

by_model(slug, hours) async

Cost + token usage by model, merged across selected projects.

Window-accurate (see :meth:LangfuseClient.fetch_model_usage_window).

Source code in src/robotsix_cost_monitor/service/core.py
356
357
358
359
360
361
362
async def by_model(self, slug: str | None, hours: int) -> list[dict[str, Any]]:
    """Cost + token usage by model, merged across selected projects.

    Window-accurate (see :meth:`LangfuseClient.fetch_model_usage_window`).
    """
    all_rows = await self._gather_list_results(slug, hours, self._model_usage)
    return merge_model_costs([all_rows])

components()

Return discovered projects grouped by owning component.

Insertion order follows the registry, so the dashboard's component list is stable across refreshes. Projects whose component is unknown are grouped under their own slug rather than dropped.

Source code in src/robotsix_cost_monitor/service/core.py
140
141
142
143
144
145
146
147
148
149
150
def components(self) -> dict[str, list[RegistryProject]]:
    """Return discovered projects grouped by owning component.

    Insertion order follows the registry, so the dashboard's component list
    is stable across refreshes.  Projects whose component is unknown are
    grouped under their own slug rather than dropped.
    """
    out: dict[str, list[RegistryProject]] = {}
    for p in self._project_map.values():
        out.setdefault(p.component_id or p.slug, []).append(p)
    return out

highlights(slug, hours, backend='all') async

Return dashboard highlights: top trace, session, and summary stats.

When backend is not "all", traces are filtered to only those whose name appears in the agent-usage rows for that backend, keeping the highlights consistent with the backend selector.

Source code in src/robotsix_cost_monitor/service/core.py
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
async def highlights(
    self, slug: str | None, hours: int, backend: str = "all"
) -> dict[str, Any]:
    """Return dashboard highlights: top trace, session, and summary stats.

    When *backend* is not ``"all"``, traces are filtered to only those
    whose name appears in the agent-usage rows for that backend, keeping
    the highlights consistent with the backend selector.
    """
    gathered = await self._gather(slug, hours)
    all_traces = [t for _, traces in gathered for t in traces]
    if backend != "all":
        agent_rows = await self._gather_list_results(slug, hours, self._agent_usage)
        backend_names: set[str] = {
            r["name"] for r in agent_rows if r.get("backend") == backend
        }
        all_traces = [t for t in all_traces if t.name in backend_names]
    return {
        "most_expensive_trace": most_expensive_trace(all_traces),
        "most_expensive_session": most_expensive_session(all_traces),
        "session_cost_scope": backend if backend != "all" else "all",
    }

invalidate_all()

Clear every internal cache so the next request fetches fresh data.

Source code in src/robotsix_cost_monitor/service/core.py
101
102
103
104
105
def invalidate_all(self) -> None:
    """Clear every internal cache so the next request fetches fresh data."""
    for c in self._caches:
        c.invalidate()
    self._last_updated = None

projects()

Return every discovered project, in registry order.

Source code in src/robotsix_cost_monitor/service/core.py
136
137
138
def projects(self) -> list[RegistryProject]:
    """Return every discovered project, in registry order."""
    return list(self._project_map.values())

refresh_projects() async

Query the registry and rebuild the project/client map.

Best-effort: on failure the existing project list is kept unchanged.

Source code in src/robotsix_cost_monitor/service/core.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
async def refresh_projects(self) -> None:
    """Query the registry and rebuild the project/client map.

    Best-effort: on failure the existing project list is kept unchanged.
    """
    try:
        registry_projects = await self._registry.fetch_projects()
    except Exception:
        logger.warning("refresh_projects: registry fetch failed")
        return
    if not registry_projects:
        logger.warning("refresh_projects: registry returned no projects")
        return
    self._project_map = {p.slug: p for p in registry_projects}
    self._clients = {
        p.slug: LangfuseClient(
            public_key=p.langfuse_public_key,
            secret_key=p.langfuse_secret_key.get_secret_value(),
            base_url=p.langfuse_base_url,
        )
        for p in registry_projects
    }
    self.invalidate_all()
    logger.info(
        "refresh_projects: discovered %d project(s) across %d component(s)",
        len(self._project_map),
        len(self.components()),
    )

summary(slug, hours, backend='all') async

Per-project totals + the aggregate, for the window.

Cost is observation-based (the same window-accurate metrics source as the by-model / by-backend breakdowns), so the headline total, the per-model rows, and the per-backend totals all reconcile — a backend can never exceed the total. trace_count comes from a server-side view=traces count metric (not by paging every trace), so this stays fast.

When backend is not "all", only observation rows attributed to that backend are counted, so the per-component rollup and total reflect costs for the selected backend alone.

Source code in src/robotsix_cost_monitor/service/core.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
async def summary(
    self, slug: str | None, hours: int, backend: str = "all"
) -> dict[str, Any]:
    """Per-project totals + the aggregate, for the window.

    Cost is observation-based (the same window-accurate metrics source as the
    by-model / by-backend breakdowns), so the headline total, the per-model
    rows, and the per-backend totals all reconcile — a backend can never
    exceed the total. ``trace_count`` comes from a server-side ``view=traces``
    count metric (not by paging every trace), so this stays fast.

    When *backend* is not ``"all"``, only observation rows attributed to that
    backend are counted, so the per-component rollup and total reflect costs
    for the selected backend alone.
    """
    per_project: list[dict[str, Any]] = []
    total = 0.0
    for p in self._projects(slug):
        models: list[dict[str, Any]] = await self._safe_project_fetch(
            p,
            lambda: self._model_usage(p, hours),  # noqa: B023
            "model-usage",
            [],
        )
        if backend != "all":
            models = [m for m in models if m.get("backend") == backend]
        trace_count: int = await self._safe_project_fetch(
            p,
            lambda: self._trace_count(p, hours),  # noqa: B023
            "trace-count",
            0,
        )
        cost = round(sum(m["cost"] for m in models), 6)
        total += cost
        per_project.append(
            {
                "name": p.name,
                "slug": p.slug,
                "component": p.component_id,
                "cost": cost,
                "trace_count": trace_count,
            }
        )
    total = round(total, 6)
    by_component: dict[str, dict[str, Any]] = {}
    for row in per_project:
        agg = by_component.setdefault(
            str(row["component"] or row["slug"]),
            {
                "component": row["component"] or row["slug"],
                "cost": 0.0,
                "trace_count": 0,
                "projects": [],
            },
        )
        agg["cost"] = round(agg["cost"] + float(row["cost"]), 6)
        agg["trace_count"] += int(row["trace_count"])
        agg["projects"].append(row)
    components = sorted(
        by_component.values(), key=lambda c: float(c["cost"]), reverse=True
    )
    if backend != "all":
        components = [c for c in components if c["cost"] > 0]
    return {
        "window_hours": hours,
        "total_cost": total,
        "projects": per_project,
        "components": components,
    }

trend(slug, hours, buckets=48) async

Return a cost trend series across the window.

Source code in src/robotsix_cost_monitor/service/core.py
402
403
404
405
406
407
408
async def trend(
    self, slug: str | None, hours: int, buckets: int = 48
) -> list[dict[str, Any]]:
    """Return a cost trend series across the window."""
    gathered = await self._gather(slug, hours)
    all_traces = [t for _, traces in gathered for t in traces]
    return cost_trend(all_traces, hours, buckets)

RegistryClient

Discovers Langfuse-enabled components from the central-deploy registry.

The central-deploy registry exposes an authenticated GET /fleet/langfuse endpoint that returns every registered component and, for each Langfuse-enabled one, its langfuse_host and projects (each with alias, public_key, secret_key).

Source code in src/robotsix_cost_monitor/clients/registry.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
class RegistryClient:
    """Discovers Langfuse-enabled components from the central-deploy registry.

    The central-deploy registry exposes an authenticated ``GET /fleet/langfuse``
    endpoint that returns every registered component and, for each
    Langfuse-enabled one, its ``langfuse_host`` and ``projects``
    (each with ``alias``, ``public_key``, ``secret_key``).
    """

    def __init__(self, base_url: str, api_key: str, timeout: float = 30.0) -> None:
        """Initialise with the central-deploy registry URL and API key."""
        self._base_url = base_url.rstrip("/")
        self._api_key = api_key
        self._timeout = timeout

    async def fetch_projects(self) -> list[RegistryProject]:
        """Query the registry for all Langfuse-enabled components.

        Returns a (possibly empty) list of RegistryProject instances.
        Logs and returns empty on any transient failure — the service
        keeps its last-known-good project list.
        """
        url = f"{self._base_url}/fleet/langfuse"
        headers = {"X-API-Key": self._api_key}
        try:
            async with httpx.AsyncClient(timeout=self._timeout) as http_client:
                client = RetryClient(http_client)
                resp = await client.get(url, headers=headers)
            resp.raise_for_status()
            payload = resp.json()
        except Exception:
            logger.exception("registry fetch failed — keeping existing projects")
            return []

        # 7af1 schema: the response is a list of component objects, each with
        # `langfuse_host` and `projects[] = {alias, public_key, secret_key}`.
        raw_components: Any = (
            payload if isinstance(payload, list) else payload.get("components", [])
        )

        projects: list[RegistryProject] = []
        for comp in raw_components:
            langfuse_host = comp.get("langfuse_host") or "https://cloud.langfuse.com"
            component_id = comp.get("component_id") or comp.get("name") or ""
            for proj in comp.get("projects", []):
                try:
                    alias = proj["alias"]
                    projects.append(
                        RegistryProject(
                            name=alias,
                            slug=alias,
                            component_id=str(component_id),
                            langfuse_public_key=proj["public_key"],
                            langfuse_secret_key=proj["secret_key"],
                            langfuse_base_url=langfuse_host,
                            # Present when the fleet knows which provider key
                            # paid for this LLM function; enables reconciliation.
                            openrouter_key=proj.get("openrouter_key") or None,
                        )
                    )
                except KeyError, TypeError:  # PEP 758 (py3.14): KeyError OR TypeError
                    logger.warning(
                        "skipping malformed registry project: %s",
                        proj.get("alias", repr(proj)),
                    )
        return projects

__init__(base_url, api_key, timeout=30.0)

Initialise with the central-deploy registry URL and API key.

Source code in src/robotsix_cost_monitor/clients/registry.py
30
31
32
33
34
def __init__(self, base_url: str, api_key: str, timeout: float = 30.0) -> None:
    """Initialise with the central-deploy registry URL and API key."""
    self._base_url = base_url.rstrip("/")
    self._api_key = api_key
    self._timeout = timeout

fetch_projects() async

Query the registry for all Langfuse-enabled components.

Returns a (possibly empty) list of RegistryProject instances. Logs and returns empty on any transient failure — the service keeps its last-known-good project list.

Source code in src/robotsix_cost_monitor/clients/registry.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
async def fetch_projects(self) -> list[RegistryProject]:
    """Query the registry for all Langfuse-enabled components.

    Returns a (possibly empty) list of RegistryProject instances.
    Logs and returns empty on any transient failure — the service
    keeps its last-known-good project list.
    """
    url = f"{self._base_url}/fleet/langfuse"
    headers = {"X-API-Key": self._api_key}
    try:
        async with httpx.AsyncClient(timeout=self._timeout) as http_client:
            client = RetryClient(http_client)
            resp = await client.get(url, headers=headers)
        resp.raise_for_status()
        payload = resp.json()
    except Exception:
        logger.exception("registry fetch failed — keeping existing projects")
        return []

    # 7af1 schema: the response is a list of component objects, each with
    # `langfuse_host` and `projects[] = {alias, public_key, secret_key}`.
    raw_components: Any = (
        payload if isinstance(payload, list) else payload.get("components", [])
    )

    projects: list[RegistryProject] = []
    for comp in raw_components:
        langfuse_host = comp.get("langfuse_host") or "https://cloud.langfuse.com"
        component_id = comp.get("component_id") or comp.get("name") or ""
        for proj in comp.get("projects", []):
            try:
                alias = proj["alias"]
                projects.append(
                    RegistryProject(
                        name=alias,
                        slug=alias,
                        component_id=str(component_id),
                        langfuse_public_key=proj["public_key"],
                        langfuse_secret_key=proj["secret_key"],
                        langfuse_base_url=langfuse_host,
                        # Present when the fleet knows which provider key
                        # paid for this LLM function; enables reconciliation.
                        openrouter_key=proj.get("openrouter_key") or None,
                    )
                )
            except KeyError, TypeError:  # PEP 758 (py3.14): KeyError OR TypeError
                logger.warning(
                    "skipping malformed registry project: %s",
                    proj.get("alias", repr(proj)),
                )
    return projects

load_config(path=None)

Load and validate the configuration via ROBOTSIX_CONFIG_FILE.

When path is given (tests), passes it through directly to :func:robotsix_config.load_config.

Source code in src/robotsix_cost_monitor/config/__init__.py
241
242
243
244
245
246
247
248
249
def load_config(path: Path | None = None) -> Config:
    """Load and validate the configuration via ``ROBOTSIX_CONFIG_FILE``.

    When *path* is given (tests), passes it through directly to
    :func:`robotsix_config.load_config`.
    """
    if path is not None:
        return _load_config(Config, path=path)
    return _load_config(Config)

main(argv=None)

CLI entrypoint: dispatch to serve, summary, or reconcile.

Source code in src/robotsix_cost_monitor/cli.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def main(argv: list[str] | None = None) -> int:
    """CLI entrypoint: dispatch to serve, summary, or reconcile."""
    parser = argparse.ArgumentParser(prog="robotsix-cost-monitor")
    sub = parser.add_subparsers(dest="cmd")

    serve = sub.add_parser("serve", help="run the dashboard web server")
    serve.add_argument("--host", default=None)
    serve.add_argument("--port", type=int, default=None)

    summary = sub.add_parser("summary", help="print a cost summary as JSON")
    summary.add_argument("--project", default="all")
    summary.add_argument("--hours", type=int, default=0)

    recon = sub.add_parser("reconcile", help="run OpenRouter↔Langfuse reconciliation")
    recon.add_argument("--project", default="all")

    args = parser.parse_args(argv)

    if args.cmd == "serve" or args.cmd is None:
        cfg = load_config()
        host_val: str | None = getattr(args, "host", None)
        port_val: int | None = getattr(args, "port", None)
        host = host_val if host_val is not None else cfg.settings.server_host
        port = port_val if port_val is not None else cfg.settings.server_port
        uvicorn.run(
            "robotsix_cost_monitor.app:create_app",
            host=host,
            port=port,
            factory=True,
            log_config=None,  # keep structlog config from create_app
        )
        return 0

    cfg = load_config()
    registry = RegistryClient(
        base_url=cfg.settings.registry_base_url,
        api_key=resolve_registry_api_key(cfg.settings),
    )
    if args.cmd == "summary":
        svc = CostService(cfg, registry)
        if cfg.settings.registry_base_url:
            asyncio.run(svc.refresh_projects())
        h = args.hours or cfg.settings.default_window_hours
        out = asyncio.run(svc.summary(args.project, h))
        print(json.dumps(out, indent=2))
        return 0
    if args.cmd == "reconcile":
        svc = CostService(cfg, registry)
        if cfg.settings.registry_base_url:
            asyncio.run(svc.refresh_projects())
        if args.project == "all":
            out = asyncio.run(reconcile_all(cfg, svc))
            print(json.dumps(out, indent=2))
        else:
            projects = [p for p in svc._project_map.values() if p.slug == args.project]
            recon_rows = [
                asyncio.run(reconcile_project(p, cfg.settings)) for p in projects
            ]
            print(json.dumps(recon_rows, indent=2))
        return 0

    parser.print_help()
    return 1

reconcile_all(config, service) async

Reconcile every project, persist the result, and return it.

The stored last.json powers the dashboard's warning banner and the /api/reconcile/last endpoint.

Source code in src/robotsix_cost_monitor/reconcile.py
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
async def reconcile_all(config: Config, service: CostService) -> dict[str, Any]:
    """Reconcile every project, persist the result, and return it.

    The stored ``last.json`` powers the dashboard's warning banner and the
    ``/api/reconcile/last`` endpoint.
    """
    reconcile_runs.inc()
    t0 = time.monotonic()
    projects = service.projects()
    results = [await reconcile_project(p, config.settings) for p in projects]
    reconcile_duration.set(time.monotonic() - t0)
    out: dict[str, Any] = {
        "generated_at": datetime.now(UTC).isoformat(),
        "status": reconcile_status(results),
        "tolerance_usd": config.settings.reconcile_tolerance_usd,
        "results": results,
    }
    _atomic_write_text(
        _last_path(config.settings),
        json.dumps(out, indent=2),
        root=_state_dir(config.settings),
    )
    return out

reconcile_project(project, settings) async

Reconcile one project's OpenRouter spend vs Langfuse traced cost.

Snapshots the key's cumulative usage and diffs against the previous snapshot; compares the provider delta to the Langfuse traced cost over the same interval. Returns a status dict (also includes the remaining balance). The snapshot is updated on every call.

Source code in src/robotsix_cost_monitor/reconcile.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
async def reconcile_project(
    project: RegistryProject, settings: Settings
) -> dict[str, Any]:
    """Reconcile one project's OpenRouter spend vs Langfuse traced cost.

    Snapshots the key's cumulative usage and diffs against the previous
    snapshot; compares the provider delta to the Langfuse traced cost over the
    same interval. Returns a status dict (also includes the remaining
    balance). The snapshot is updated on every call.
    """
    now = datetime.now(UTC)
    result: dict[str, Any] = {
        "project": project.name,
        "slug": project.slug,
        "configured": bool(project.openrouter_key),
        "at": now.isoformat(),
    }
    if not project.openrouter_key:
        result["detail"] = "no openrouter_key configured for this project"
        return result

    try:
        from robotsix_llmio.openrouter import OpenRouterKeyCostSource
    except ImportError:
        result["error"] = "robotsix-llmio is not installed. Install it with: uv sync"
        return result

    orc = OpenRouterKeyCostSource(api_key=project.openrouter_key)

    # Per-KEY cumulative usage is the reconciliation basis (isolates this
    # consumer even when several keys share one OpenRouter account).
    async def _fetch_cumulative() -> float:
        ku = await asyncio.to_thread(orc.fetch_key_usage)
        return ku.usage

    cumulative_ = await _fetch_or_error(
        "OpenRouter", (ExternalServiceError,), _fetch_cumulative(), result
    )
    if cumulative_ is None:
        return result
    cumulative = cumulative_

    # Account-level remaining balance — informational only (shared balance pool).
    # Optional: a balance fetch failure must not fail the reconcile.
    with contextlib.suppress(Exception):
        result["balance"] = await _fetch_credits(project.openrouter_key)
        if (
            settings.low_balance_threshold_usd > 0
            and result["balance"]["remaining"] < settings.low_balance_threshold_usd
        ):
            result["low_balance"] = True
            logger.warning(
                "project %s: low balance — $%.2f remaining (threshold $%.2f)",
                project.name,
                result["balance"]["remaining"],
                settings.low_balance_threshold_usd,
            )

    prior = _load_snapshot(project.slug, settings)
    _save_snapshot(project.slug, cumulative, now, settings)

    if prior is None:
        result["detail"] = "first snapshot recorded — reconciliation on next run"
        return result

    prior_at = datetime.fromisoformat(prior["at"])
    interval_h = _hours_between(prior_at, now)
    provider_delta = round(cumulative - float(prior["cumulative"]), 6)

    lf = LangfuseClient(
        public_key=project.langfuse_public_key,
        secret_key=project.langfuse_secret_key.get_secret_value(),
        base_url=project.langfuse_base_url,
    )
    # Traced cost over the SAME interval as the provider delta (both since the
    # prior snapshot), so the two sides are comparable. Using a rounded ≥1h
    # window here made short intervals nonsensical (provider over minutes vs
    # traced over an hour).
    #
    # Compare like-for-like: OpenRouter's per-key spend only reconciles against
    # the *openrouter*-backend traced cost. Claude-SDK (level-3) traffic is
    # traced in Langfuse but billed by Anthropic, not OpenRouter — including it
    # made "traced" exceed "provider" by the Claude portion.
    by_backend_ = await _fetch_or_error(
        "Langfuse",
        (ExternalServiceError, httpx.HTTPError, json.JSONDecodeError),
        lf.fetch_cost_by_backend(interval_h),
        result,
    )
    if by_backend_ is None:
        return result
    by_backend = by_backend_

    logged = round(by_backend.get("openrouter", 0.0), 6)
    total_traced = round(sum(by_backend.values()), 6)

    drift = round(provider_delta - logged, 6)
    result.update(
        {
            "interval_hours": round(interval_h, 2),
            "provider_delta_usd": provider_delta,
            # OpenRouter-backend only — the value comparable to the provider side.
            "langfuse_cost_usd": logged,
            # All backends (incl. claude-sdk), for transparency.
            "langfuse_total_cost_usd": total_traced,
            "langfuse_cost_by_backend": {k: round(v, 6) for k, v in by_backend.items()},
            "drift_usd": drift,
            "within_tolerance": abs(drift) <= settings.reconcile_tolerance_usd,
            "tolerance_usd": settings.reconcile_tolerance_usd,
        }
    )
    return result

resolve_registry_api_key(settings)

Return the effective registry API key.

When deployed by robotsix-central-deploy with the robotsix.deploy.access: "agent" label, the deploy API key is auto-injected as the DEPLOY_API_KEY environment variable — no manual config needed. Falls back to settings.registry_api_key for local development.

Source code in src/robotsix_cost_monitor/config/__init__.py
187
188
189
190
191
192
193
194
195
196
197
198
def resolve_registry_api_key(settings: Settings) -> str:
    """Return the effective registry API key.

    When deployed by robotsix-central-deploy with the ``robotsix.deploy.access:
    "agent"`` label, the deploy API key is auto-injected as the
    ``DEPLOY_API_KEY`` environment variable — no manual config needed.  Falls
    back to ``settings.registry_api_key`` for local development.
    """
    env_val = os.environ.get("DEPLOY_API_KEY", "")
    if env_val:
        return env_val
    return settings.registry_api_key.get_secret_value()

robotsix_cost_monitor.clients

External API clients (Langfuse, Registry) for robotsix-cost-monitor.

__all__ = ['RegistryClient', 'RegistryProject'] module-attribute

RegistryClient

Discovers Langfuse-enabled components from the central-deploy registry.

The central-deploy registry exposes an authenticated GET /fleet/langfuse endpoint that returns every registered component and, for each Langfuse-enabled one, its langfuse_host and projects (each with alias, public_key, secret_key).

Source code in src/robotsix_cost_monitor/clients/registry.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
class RegistryClient:
    """Discovers Langfuse-enabled components from the central-deploy registry.

    The central-deploy registry exposes an authenticated ``GET /fleet/langfuse``
    endpoint that returns every registered component and, for each
    Langfuse-enabled one, its ``langfuse_host`` and ``projects``
    (each with ``alias``, ``public_key``, ``secret_key``).
    """

    def __init__(self, base_url: str, api_key: str, timeout: float = 30.0) -> None:
        """Initialise with the central-deploy registry URL and API key."""
        self._base_url = base_url.rstrip("/")
        self._api_key = api_key
        self._timeout = timeout

    async def fetch_projects(self) -> list[RegistryProject]:
        """Query the registry for all Langfuse-enabled components.

        Returns a (possibly empty) list of RegistryProject instances.
        Logs and returns empty on any transient failure — the service
        keeps its last-known-good project list.
        """
        url = f"{self._base_url}/fleet/langfuse"
        headers = {"X-API-Key": self._api_key}
        try:
            async with httpx.AsyncClient(timeout=self._timeout) as http_client:
                client = RetryClient(http_client)
                resp = await client.get(url, headers=headers)
            resp.raise_for_status()
            payload = resp.json()
        except Exception:
            logger.exception("registry fetch failed — keeping existing projects")
            return []

        # 7af1 schema: the response is a list of component objects, each with
        # `langfuse_host` and `projects[] = {alias, public_key, secret_key}`.
        raw_components: Any = (
            payload if isinstance(payload, list) else payload.get("components", [])
        )

        projects: list[RegistryProject] = []
        for comp in raw_components:
            langfuse_host = comp.get("langfuse_host") or "https://cloud.langfuse.com"
            component_id = comp.get("component_id") or comp.get("name") or ""
            for proj in comp.get("projects", []):
                try:
                    alias = proj["alias"]
                    projects.append(
                        RegistryProject(
                            name=alias,
                            slug=alias,
                            component_id=str(component_id),
                            langfuse_public_key=proj["public_key"],
                            langfuse_secret_key=proj["secret_key"],
                            langfuse_base_url=langfuse_host,
                            # Present when the fleet knows which provider key
                            # paid for this LLM function; enables reconciliation.
                            openrouter_key=proj.get("openrouter_key") or None,
                        )
                    )
                except KeyError, TypeError:  # PEP 758 (py3.14): KeyError OR TypeError
                    logger.warning(
                        "skipping malformed registry project: %s",
                        proj.get("alias", repr(proj)),
                    )
        return projects

__init__(base_url, api_key, timeout=30.0)

Initialise with the central-deploy registry URL and API key.

Source code in src/robotsix_cost_monitor/clients/registry.py
30
31
32
33
34
def __init__(self, base_url: str, api_key: str, timeout: float = 30.0) -> None:
    """Initialise with the central-deploy registry URL and API key."""
    self._base_url = base_url.rstrip("/")
    self._api_key = api_key
    self._timeout = timeout

fetch_projects() async

Query the registry for all Langfuse-enabled components.

Returns a (possibly empty) list of RegistryProject instances. Logs and returns empty on any transient failure — the service keeps its last-known-good project list.

Source code in src/robotsix_cost_monitor/clients/registry.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
async def fetch_projects(self) -> list[RegistryProject]:
    """Query the registry for all Langfuse-enabled components.

    Returns a (possibly empty) list of RegistryProject instances.
    Logs and returns empty on any transient failure — the service
    keeps its last-known-good project list.
    """
    url = f"{self._base_url}/fleet/langfuse"
    headers = {"X-API-Key": self._api_key}
    try:
        async with httpx.AsyncClient(timeout=self._timeout) as http_client:
            client = RetryClient(http_client)
            resp = await client.get(url, headers=headers)
        resp.raise_for_status()
        payload = resp.json()
    except Exception:
        logger.exception("registry fetch failed — keeping existing projects")
        return []

    # 7af1 schema: the response is a list of component objects, each with
    # `langfuse_host` and `projects[] = {alias, public_key, secret_key}`.
    raw_components: Any = (
        payload if isinstance(payload, list) else payload.get("components", [])
    )

    projects: list[RegistryProject] = []
    for comp in raw_components:
        langfuse_host = comp.get("langfuse_host") or "https://cloud.langfuse.com"
        component_id = comp.get("component_id") or comp.get("name") or ""
        for proj in comp.get("projects", []):
            try:
                alias = proj["alias"]
                projects.append(
                    RegistryProject(
                        name=alias,
                        slug=alias,
                        component_id=str(component_id),
                        langfuse_public_key=proj["public_key"],
                        langfuse_secret_key=proj["secret_key"],
                        langfuse_base_url=langfuse_host,
                        # Present when the fleet knows which provider key
                        # paid for this LLM function; enables reconciliation.
                        openrouter_key=proj.get("openrouter_key") or None,
                    )
                )
            except KeyError, TypeError:  # PEP 758 (py3.14): KeyError OR TypeError
                logger.warning(
                    "skipping malformed registry project: %s",
                    proj.get("alias", repr(proj)),
                )
    return projects

RegistryProject

Bases: BaseModel

One Langfuse project discovered from the central-deploy registry.

A project is a single LLM function, not a component: a component with two tracing subsystems declares two projects (e.g. robotsix-chat and robotsix-chat-cognee). :attr:component_id records which component owns it, so the dashboard can roll a component's projects up without any per-component code.

Source code in src/robotsix_cost_monitor/clients/models.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
class RegistryProject(BaseModel):
    """One Langfuse project discovered from the central-deploy registry.

    A project is a single LLM *function*, not a component: a component with
    two tracing subsystems declares two projects (e.g. ``robotsix-chat`` and
    ``robotsix-chat-cognee``).  :attr:`component_id` records which component
    owns it, so the dashboard can roll a component's projects up without any
    per-component code.
    """

    name: str
    slug: str
    component_id: str = Field(
        default="",
        description="Owning component (registry `component_id`); '' when unknown",
    )
    langfuse_public_key: str
    langfuse_secret_key: SecretStr
    langfuse_base_url: str = "https://cloud.langfuse.com"
    openrouter_key: str | None = None

robotsix_cost_monitor.config

Configuration models + loader for robotsix-cost-monitor.

Cost-monitor discovers projects at runtime from the central-deploy registry instead of carrying hardcoded Langfuse credentials. The config file only holds generic settings: the registry URL + API key, polling/window defaults, and auth/reconcile knobs.

The config is located via the ROBOTSIX_CONFIG_FILE environment variable (default config/config.json). config/config.example.json is the committed template (gitignored real keys).

_REPO_ROOT = Path(__file__).resolve().parents[3] module-attribute

AuthConfig

Bases: BaseModel

HTTP Basic auth for the dashboard.

The dashboard has no other access control, so when it is exposed through the central-deploy gateway (an unauthenticated reverse proxy) this MUST be set — otherwise the cost data is public. When either field is empty the dashboard is served open (local dev / SSH-tunnel only). /health is always exempt so the container healthcheck works.

Source code in src/robotsix_cost_monitor/config/__init__.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class AuthConfig(BaseModel):
    """HTTP Basic auth for the dashboard.

    The dashboard has no other access control, so when it is exposed through
    the central-deploy gateway (an unauthenticated reverse proxy) this MUST
    be set — otherwise the cost data is public. When either field is empty
    the dashboard is served open (local dev / SSH-tunnel only). ``/health``
    is always exempt so the container healthcheck works.
    """

    username: str = Field(
        default="",
        description=(
            "Dashboard HTTP Basic auth username. Empty means the dashboard is "
            "served open."
        ),
    )
    password: SecretStr = Field(
        default=SecretStr(""),
        description=(
            "Dashboard HTTP Basic auth password. Empty means the dashboard is "
            "served open."
        ),
    )

Config

Bases: BaseModel

Top-level config: registry-driven project discovery + global settings.

Project credentials are discovered at runtime from the central-deploy registry — there is no hardcoded project list.

Source code in src/robotsix_cost_monitor/config/__init__.py
215
216
217
218
219
220
221
222
class Config(BaseModel):
    """Top-level config: registry-driven project discovery + global settings.

    Project credentials are discovered at runtime from the central-deploy
    registry — there is no hardcoded project list.
    """

    settings: Settings = Field(default_factory=Settings)

Settings

Bases: BaseModel

Global dashboard settings — no per-project config (registry-driven).

Source code in src/robotsix_cost_monitor/config/__init__.py
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
class Settings(BaseModel):
    """Global dashboard settings — no per-project config (registry-driven)."""

    auth: AuthConfig = Field(
        default_factory=AuthConfig,
        description=(
            "HTTP Basic auth — REQUIRED when exposed via the gateway (see AuthConfig)."
        ),
    )
    # Binding every interface is deliberate: the dashboard serves from inside a
    # container behind the central-deploy gateway, and a service that binds
    # 127.0.0.1 there is unreachable through it — the container's own
    # healthcheck still passes, so it fails as a 502 rather than a crash.
    server_host: str = Field(
        default="0.0.0.0",  # noqa: S104  # nosec B104 - see above
        description="Bind address for the dashboard web server.",
    )
    server_port: int = Field(
        default=8080,
        description="Port for the dashboard web server.",
    )
    registry_base_url: str = Field(
        default="",
        description=(
            "Central-deploy registry base URL — projects are discovered at runtime."
        ),
    )
    registry_api_key: SecretStr = Field(
        default=SecretStr(""),
        description=(
            "API key for authenticating to the central-deploy registry. When "
            "deployed by robotsix-central-deploy with the robotsix.deploy.access: "
            '"agent" label, leave empty — the DEPLOY_API_KEY environment variable '
            "is injected automatically at deploy time."
        ),
    )
    registry_poll_interval_seconds: int = Field(
        default=300,
        description=(
            "Seconds between registry re-polls (0 = only at startup + manual refresh)."
        ),
    )
    default_window_hours: int = Field(
        default=168,
        description="Default cost-aggregation window in hours (e.g. 168 = 7 days).",
    )
    cache_ttl_seconds: int = Field(
        default=60,
        description=(
            "Seconds before cached Langfuse data is considered stale and re-fetched."
        ),
    )
    dashboard_refresh_interval_seconds: int = Field(
        default=120,
        description=(
            "Background cache-refresh interval — keeps dashboard aggregates "
            "precomputed so the frontend never blocks on a live Langfuse "
            "fetch. 0 disables."
        ),
    )
    reconcile_tolerance_usd: float = Field(
        default=1.0,
        description=(
            "Maximum allowed difference in USD between provider cost and traced "
            "cost before reconciliation is flagged as out of tolerance."
        ),
    )
    reconcile_schedule_hours: float = Field(
        default=24.0,
        description=(
            "Auto-run reconciliation every N hours (0 disables; default daily). "
            "The stored result drives the dashboard warning banner."
        ),
    )
    subscription_call_cap: int = Field(
        default=0,
        description=(
            "Per-day subscription call cap for volume-vs-cap monitoring; "
            "0 = disabled/unknown."
        ),
    )
    low_balance_threshold_usd: float = Field(
        default=5.0,
        description=(
            "OpenRouter account remaining-balance threshold in USD. When the "
            "remaining balance drops below this value a warning is logged and "
            "surfaced in the dashboard. Set to 0 to disable the low-balance "
            "check."
        ),
    )
    data_dir: Path = Field(
        default=Path(".data"),
        description=(
            "Runtime data directory for persistence (.data by default; /data in "
            "containers)."
        ),
    )
    log_format: str = Field(
        default="json",
        description='Structured log output format: "console" or "json".',
    )
    log_level: str = Field(
        default="INFO",
        description="Minimum log level for all loggers.",
    )
    mill_base_url: str = Field(
        default="",
        description=(
            'Base URL of the robotsix-mill board API (e.g. "http://mill:8080"). '
            "When empty, stuck-ticket detection is disabled."
        ),
    )
    mill_api_key: SecretStr = Field(
        default=SecretStr(""),
        json_schema_extra={"writeOnly": True},
        description=(
            "API key for authenticating to the mill board API. When deployed by "
            'robotsix-central-deploy with the robotsix.deploy.access: "agent" '
            "label, leave empty — the DEPLOY_API_KEY env var is used as a "
            "fallback."
        ),
    )
    stuck_ticket_threshold_hours: int = Field(
        default=48,
        description=(
            "Hours a ticket may remain in a non-terminal state before it is "
            "flagged as stuck. 0 disables stuck-ticket detection."
        ),
    )
    stuck_ticket_check_interval_seconds: int = Field(
        default=600,
        description=("Seconds between stuck-ticket checks (default 600 = 10 minutes)."),
    )

data_dir(settings=None)

Resolve the runtime-state directory for persistence.

When settings is given, the settings.data_dir field is used (relative paths are resolved against the repo root). Without settings the legacy default .data relative to the repo root is returned for backward compatibility.

Source code in src/robotsix_cost_monitor/config/__init__.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
def data_dir(settings: Settings | None = None) -> Path:
    """Resolve the runtime-state directory for persistence.

    When *settings* is given, the ``settings.data_dir`` field is used (relative
    paths are resolved against the repo root).  Without *settings* the legacy
    default ``.data`` relative to the repo root is returned for backward
    compatibility.
    """
    if settings is not None:
        path = Path(settings.data_dir)
        if not path.is_absolute():
            path = _REPO_ROOT / path
        return Path(os.path.abspath(path)).resolve()
    return Path(os.path.abspath(_REPO_ROOT / ".data")).resolve()

load_config(path=None)

Load and validate the configuration via ROBOTSIX_CONFIG_FILE.

When path is given (tests), passes it through directly to :func:robotsix_config.load_config.

Source code in src/robotsix_cost_monitor/config/__init__.py
241
242
243
244
245
246
247
248
249
def load_config(path: Path | None = None) -> Config:
    """Load and validate the configuration via ``ROBOTSIX_CONFIG_FILE``.

    When *path* is given (tests), passes it through directly to
    :func:`robotsix_config.load_config`.
    """
    if path is not None:
        return _load_config(Config, path=path)
    return _load_config(Config)

resolve_mill_api_key(settings)

Return the effective mill API key.

Follows the same convention as :func:resolve_registry_api_key: the DEPLOY_API_KEY environment variable is the default when deployed by robotsix-central-deploy. Falls back to settings.mill_api_key for local development.

Source code in src/robotsix_cost_monitor/config/__init__.py
201
202
203
204
205
206
207
208
209
210
211
212
def resolve_mill_api_key(settings: Settings) -> str:
    """Return the effective mill API key.

    Follows the same convention as :func:`resolve_registry_api_key`: the
    ``DEPLOY_API_KEY`` environment variable is the default when deployed by
    robotsix-central-deploy.  Falls back to ``settings.mill_api_key`` for
    local development.
    """
    env_val = os.environ.get("DEPLOY_API_KEY", "")
    if env_val:
        return env_val
    return settings.mill_api_key.get_secret_value()

resolve_registry_api_key(settings)

Return the effective registry API key.

When deployed by robotsix-central-deploy with the robotsix.deploy.access: "agent" label, the deploy API key is auto-injected as the DEPLOY_API_KEY environment variable — no manual config needed. Falls back to settings.registry_api_key for local development.

Source code in src/robotsix_cost_monitor/config/__init__.py
187
188
189
190
191
192
193
194
195
196
197
198
def resolve_registry_api_key(settings: Settings) -> str:
    """Return the effective registry API key.

    When deployed by robotsix-central-deploy with the ``robotsix.deploy.access:
    "agent"`` label, the deploy API key is auto-injected as the
    ``DEPLOY_API_KEY`` environment variable — no manual config needed.  Falls
    back to ``settings.registry_api_key`` for local development.
    """
    env_val = os.environ.get("DEPLOY_API_KEY", "")
    if env_val:
        return env_val
    return settings.registry_api_key.get_secret_value()

robotsix_cost_monitor.exceptions

Typed exception hierarchy for cost-monitor.

Distinguishes retriable network errors from terminal configuration errors, so catch-sites can make deliberate choices instead of blanket except Exception.

The HTTP exception classes inherit from both :class:CostMonitorError (for the FastAPI exception handler and local catch-blocks) and the corresponding :mod:robotsix_http exception classes (so the shared :class:RetryClient can raise them directly while existing except clauses still match).

CacheError

Bases: CostMonitorError

Cache corruption or deadline overflow — retriable.

Source code in src/robotsix_cost_monitor/exceptions.py
111
112
113
114
115
class CacheError(CostMonitorError):
    """Cache corruption or deadline overflow — retriable."""

    status_code = 500
    error_code = "CACHE_ERROR"

CostMonitorError

Bases: Exception

Base exception for all cost-monitor errors.

Source code in src/robotsix_cost_monitor/exceptions.py
26
27
28
29
30
31
32
33
34
35
36
37
38
class CostMonitorError(Exception):
    """Base exception for all cost-monitor errors."""

    status_code: int = 500
    error_code: str = "INTERNAL_ERROR"
    detail: str = ""

    def __init__(self, detail: str = "", *, status_code: int | None = None) -> None:
        """Initialise with an optional detail message and status code override."""
        self.detail = detail or self.detail
        if status_code is not None:
            self.status_code = status_code
        super().__init__(self.detail)

__init__(detail='', *, status_code=None)

Initialise with an optional detail message and status code override.

Source code in src/robotsix_cost_monitor/exceptions.py
33
34
35
36
37
38
def __init__(self, detail: str = "", *, status_code: int | None = None) -> None:
    """Initialise with an optional detail message and status code override."""
    self.detail = detail or self.detail
    if status_code is not None:
        self.status_code = status_code
    super().__init__(self.detail)

ExternalAuthError

Bases: ExternalServiceError, ExternalAuthError

Bad API key or credentials — NOT retriable.

Source code in src/robotsix_cost_monitor/exceptions.py
90
91
92
93
94
class ExternalAuthError(ExternalServiceError, _ExternalAuthError):
    """Bad API key or credentials — NOT retriable."""

    status_code = 502  # gateway shows as service-available-but-bad-credentials
    error_code = "EXTERNAL_AUTH_ERROR"

ExternalRateLimitError

Bases: ExternalServiceError, ExternalRateLimitError

429 rate limit — retriable with backoff.

Source code in src/robotsix_cost_monitor/exceptions.py
 97
 98
 99
100
101
class ExternalRateLimitError(ExternalServiceError, _ExternalRateLimitError):
    """429 rate limit — retriable with backoff."""

    status_code = 429
    error_code = "RATE_LIMITED"

ExternalServiceError

Bases: CostMonitorError, ExternalServiceError

An external API (Langfuse, OpenRouter) returned an error.

Transient failures (timeout, 5xx, 429) should be retried; terminal failures (401, 403, 404) should surface immediately.

Source code in src/robotsix_cost_monitor/exceptions.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
class ExternalServiceError(CostMonitorError, _ExternalServiceError):
    """An external API (Langfuse, OpenRouter) returned an error.

    Transient failures (timeout, 5xx, 429) should be retried; terminal
    failures (401, 403, 404) should surface immediately.
    """

    error_code = "EXTERNAL_SERVICE_ERROR"

    def __init__(
        self,
        detail: str = "",
        *,
        status_code: int | None = None,
        response: httpx.Response | None = None,
    ) -> None:
        """Initialise from a detail string, optionally with an HTTP response.

        When *response* is ``None`` (constructed locally), a synthetic
        :class:`httpx.Response` with the class-level ``status_code`` is
        created to satisfy :class:`ExternalHTTPError`'s required keyword
        arguments.
        """
        self.detail = detail or self.detail
        if status_code is not None:
            self.status_code = status_code
        if response is None:
            # Constructed locally without an HTTP response — use the
            # class-level status_code as the default for the robotsix-http
            # base class.  We must call both parent __init__s explicitly
            # because CostMonitorError's super().__init__ would land on
            # ExternalHTTPError which requires keyword arguments.
            Exception.__init__(self, self.detail)
            _ExternalServiceError.__init__(
                self,
                message=self.detail,
                status_code=self.status_code,
                response=httpx.Response(status_code=self.status_code),
            )
        else:
            Exception.__init__(self, self.detail)
            _ExternalServiceError.__init__(
                self,
                message=self.detail,
                status_code=status_code or self.status_code,
                response=response,
            )

__init__(detail='', *, status_code=None, response=None)

Initialise from a detail string, optionally with an HTTP response.

When response is None (constructed locally), a synthetic :class:httpx.Response with the class-level status_code is created to satisfy :class:ExternalHTTPError's required keyword arguments.

Source code in src/robotsix_cost_monitor/exceptions.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
def __init__(
    self,
    detail: str = "",
    *,
    status_code: int | None = None,
    response: httpx.Response | None = None,
) -> None:
    """Initialise from a detail string, optionally with an HTTP response.

    When *response* is ``None`` (constructed locally), a synthetic
    :class:`httpx.Response` with the class-level ``status_code`` is
    created to satisfy :class:`ExternalHTTPError`'s required keyword
    arguments.
    """
    self.detail = detail or self.detail
    if status_code is not None:
        self.status_code = status_code
    if response is None:
        # Constructed locally without an HTTP response — use the
        # class-level status_code as the default for the robotsix-http
        # base class.  We must call both parent __init__s explicitly
        # because CostMonitorError's super().__init__ would land on
        # ExternalHTTPError which requires keyword arguments.
        Exception.__init__(self, self.detail)
        _ExternalServiceError.__init__(
            self,
            message=self.detail,
            status_code=self.status_code,
            response=httpx.Response(status_code=self.status_code),
        )
    else:
        Exception.__init__(self, self.detail)
        _ExternalServiceError.__init__(
            self,
            message=self.detail,
            status_code=status_code or self.status_code,
            response=response,
        )

ProjectNotFoundError

Bases: CostMonitorError

A project slug does not match any configured project.

Source code in src/robotsix_cost_monitor/exceptions.py
104
105
106
107
108
class ProjectNotFoundError(CostMonitorError):
    """A project slug does not match any configured project."""

    status_code = 404
    error_code = "PROJECT_NOT_FOUND"

robotsix_cost_monitor.reconcile

OpenRouter ↔ Langfuse cost reconciliation via cumulative-usage snapshots.

OpenRouter exposes only cumulative key usage, so we snapshot it (under .data/reconcile/<slug>.json) and diff successive readings to get the spend in the interval, then compare that to the Langfuse traced cost over the same interval. Drift above the tolerance is flagged.

logger = structlog.get_logger(__name__) module-attribute

reconcile_duration = Gauge('robotsix_cost_monitor_reconcile_duration_seconds', 'Duration of the last reconciliation run in seconds.') module-attribute

reconcile_runs = Counter('robotsix_cost_monitor_reconcile_runs_total', 'Total number of reconciliation runs.') module-attribute

Config

Bases: BaseModel

Top-level config: registry-driven project discovery + global settings.

Project credentials are discovered at runtime from the central-deploy registry — there is no hardcoded project list.

Source code in src/robotsix_cost_monitor/config/__init__.py
215
216
217
218
219
220
221
222
class Config(BaseModel):
    """Top-level config: registry-driven project discovery + global settings.

    Project credentials are discovered at runtime from the central-deploy
    registry — there is no hardcoded project list.
    """

    settings: Settings = Field(default_factory=Settings)

CostService

Cross-project cost aggregation service with per-window TTL cache.

All five internal caches share a single :attr:last_updated timestamp (the youngest refresh across all caches) so the dashboard can display data freshness.

Source code in src/robotsix_cost_monitor/service/core.py
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
class CostService:
    """Cross-project cost aggregation service with per-window TTL cache.

    All five internal caches share a single :attr:`last_updated` timestamp
    (the youngest refresh across *all* caches) so the dashboard can display
    data freshness.
    """

    def __init__(self, config: Config, registry_client: RegistryClient) -> None:
        """Initialise the service with config and a registry client.

        Starts with an empty project/client map — call :meth:`refresh_projects`
        during startup to populate from the registry.
        """
        self.config = config
        self._registry = registry_client
        self._project_map: dict[str, RegistryProject] = {}
        self._clients: dict[str, LangfuseClient] = {}
        ttl = self.config.settings.cache_ttl_seconds
        self._last_updated: datetime | None = None
        self._caches: list[TTLCache[Any, Any]] = []
        on_refresh = self._touch_last_updated

        def _mk[T](t: type[T]) -> TTLCache[Any, T]:
            c = TTLCache[Any, T](ttl, on_refresh=on_refresh)
            self._caches.append(c)
            return c

        # cache: (slug, hours) -> (traces, monotonic_deadline)
        self._cache = _mk(list[LangfuseTrace])
        # cache: (slug, hours) -> (per-model usage rows, monotonic_deadline)
        self._model_cache = _mk(list[dict[str, Any]])
        # cache: (slug, hours) -> ({time_bucket -> {backend -> cost}}, deadline)
        self._backend_cache = _mk(dict[str, dict[str, float]])
        # cache: (slug, hours) -> (per-(stage, backend) rows, monotonic_deadline)
        self._agent_usage_cache = _mk(list[dict[str, Any]])
        # cache: (slug, hours) -> (trace_count, monotonic_deadline)
        self._trace_count_cache = _mk(int)

    def _touch_last_updated(self) -> None:
        """Record the current wall-clock time as the last cache refresh."""
        self._last_updated = datetime.now(UTC)

    @property
    def last_updated(self) -> datetime | None:
        """UTC datetime of the most recent cache refresh, or ``None`` when cold."""
        return self._last_updated

    def invalidate_all(self) -> None:
        """Clear every internal cache so the next request fetches fresh data."""
        for c in self._caches:
            c.invalidate()
        self._last_updated = None

    async def refresh_projects(self) -> None:
        """Query the registry and rebuild the project/client map.

        Best-effort: on failure the existing project list is kept unchanged.
        """
        try:
            registry_projects = await self._registry.fetch_projects()
        except Exception:
            logger.warning("refresh_projects: registry fetch failed")
            return
        if not registry_projects:
            logger.warning("refresh_projects: registry returned no projects")
            return
        self._project_map = {p.slug: p for p in registry_projects}
        self._clients = {
            p.slug: LangfuseClient(
                public_key=p.langfuse_public_key,
                secret_key=p.langfuse_secret_key.get_secret_value(),
                base_url=p.langfuse_base_url,
            )
            for p in registry_projects
        }
        self.invalidate_all()
        logger.info(
            "refresh_projects: discovered %d project(s) across %d component(s)",
            len(self._project_map),
            len(self.components()),
        )

    def projects(self) -> list[RegistryProject]:
        """Return every discovered project, in registry order."""
        return list(self._project_map.values())

    def components(self) -> dict[str, list[RegistryProject]]:
        """Return discovered projects grouped by owning component.

        Insertion order follows the registry, so the dashboard's component list
        is stable across refreshes.  Projects whose component is unknown are
        grouped under their own slug rather than dropped.
        """
        out: dict[str, list[RegistryProject]] = {}
        for p in self._project_map.values():
            out.setdefault(p.component_id or p.slug, []).append(p)
        return out

    def _projects(self, slug: str | None) -> list[RegistryProject]:
        """Resolve a selector to the projects it covers.

        Accepts ``"all"``/empty (everything), a **component id** (every project
        that component owns), or a single **project slug**.  Resolving both
        levels here is what lets every endpoint be component-aware without any
        per-endpoint or per-component code.

        Project slugs win over component ids on collision: a project is the
        more specific thing, and the single-project component case (where the
        two names coincide) resolves identically either way.
        """
        if not slug or slug == "all":
            return list(self._project_map.values())
        if (p := self._project_map.get(slug)) is not None:
            return [p]
        result = [q for q in self._project_map.values() if q.component_id == slug]
        if not result:
            raise ProjectNotFoundError(
                f"Project '{slug}' not found — no configured project or "
                f"component matches this slug."
            )
        return result

    async def _safe_project_fetch[T](
        self,
        project: RegistryProject,
        fetch_fn: Callable[[], Awaitable[T]],
        label: str,
        default: T,
    ) -> T:
        try:
            return await fetch_fn()
        except ExternalServiceError, ExternalRateLimitError, CacheError:
            logger.warning("project %s %s failed transiently", project.slug, label)
            return default
        except Exception:
            logger.exception("project %s %s failed unexpectedly", project.slug, label)
            return default

    async def _cached_fetch(
        self,
        project: RegistryProject,
        hours: int,
        cache: TTLCache[tuple[str, int], _T],
        fetch_fn: Callable[[int], Awaitable[_T]],
    ) -> _T:
        key = (project.slug, hours)
        return await cache.get_or_fetch(key, lambda: fetch_fn(hours))

    async def _traces(
        self, project: RegistryProject, hours: int
    ) -> list[LangfuseTrace]:
        return await self._cached_fetch(
            project,
            hours,
            self._cache,
            lambda h: self._clients[project.slug].fetch_traces_window(h),
        )

    async def _trace_count(self, project: RegistryProject, hours: int) -> int:
        """Trace count for the window via a server-side metrics query (cached).

        Avoids paging every raw trace just to ``len()`` them — the headline
        ``summary`` only needs the count, not the trace bodies.
        """
        return await self._cached_fetch(
            project,
            hours,
            self._trace_count_cache,
            lambda h: self._clients[project.slug].fetch_trace_count_window(h),
        )

    async def _gather(
        self, slug: str | None, hours: int
    ) -> list[tuple[RegistryProject, list[LangfuseTrace]]]:
        out: list[tuple[RegistryProject, list[LangfuseTrace]]] = []
        for p in self._projects(slug):
            traces: list[LangfuseTrace] = await self._safe_project_fetch(
                p,
                lambda: self._traces(p, hours),  # noqa: B023
                "fetch traces",
                [],
            )
            out.append((p, traces))
        return out

    async def _gather_list_results(
        self,
        slug: str | None,
        hours: int,
        fetch: Callable[[RegistryProject, int], Awaitable[list[dict[str, Any]]]],
    ) -> list[dict[str, Any]]:
        parts: list[list[dict[str, Any]]] = []
        for p in self._projects(slug):
            result: list[dict[str, Any]] = await self._safe_project_fetch(
                p,
                lambda: fetch(p, hours),  # noqa: B023
                "fetch list results",
                [],
            )
            parts.append(result)
        return [r for part in parts for r in part]

    async def summary(
        self, slug: str | None, hours: int, backend: str = "all"
    ) -> dict[str, Any]:
        """Per-project totals + the aggregate, for the window.

        Cost is observation-based (the same window-accurate metrics source as the
        by-model / by-backend breakdowns), so the headline total, the per-model
        rows, and the per-backend totals all reconcile — a backend can never
        exceed the total. ``trace_count`` comes from a server-side ``view=traces``
        count metric (not by paging every trace), so this stays fast.

        When *backend* is not ``"all"``, only observation rows attributed to that
        backend are counted, so the per-component rollup and total reflect costs
        for the selected backend alone.
        """
        per_project: list[dict[str, Any]] = []
        total = 0.0
        for p in self._projects(slug):
            models: list[dict[str, Any]] = await self._safe_project_fetch(
                p,
                lambda: self._model_usage(p, hours),  # noqa: B023
                "model-usage",
                [],
            )
            if backend != "all":
                models = [m for m in models if m.get("backend") == backend]
            trace_count: int = await self._safe_project_fetch(
                p,
                lambda: self._trace_count(p, hours),  # noqa: B023
                "trace-count",
                0,
            )
            cost = round(sum(m["cost"] for m in models), 6)
            total += cost
            per_project.append(
                {
                    "name": p.name,
                    "slug": p.slug,
                    "component": p.component_id,
                    "cost": cost,
                    "trace_count": trace_count,
                }
            )
        total = round(total, 6)
        by_component: dict[str, dict[str, Any]] = {}
        for row in per_project:
            agg = by_component.setdefault(
                str(row["component"] or row["slug"]),
                {
                    "component": row["component"] or row["slug"],
                    "cost": 0.0,
                    "trace_count": 0,
                    "projects": [],
                },
            )
            agg["cost"] = round(agg["cost"] + float(row["cost"]), 6)
            agg["trace_count"] += int(row["trace_count"])
            agg["projects"].append(row)
        components = sorted(
            by_component.values(), key=lambda c: float(c["cost"]), reverse=True
        )
        if backend != "all":
            components = [c for c in components if c["cost"] > 0]
        return {
            "window_hours": hours,
            "total_cost": total,
            "projects": per_project,
            "components": components,
        }

    async def by_agent(
        self, slug: str | None, hours: int, backend: str = "all"
    ) -> list[dict[str, Any]]:
        """Cost by trace name (stage/agent), merged across selected projects.

        When ``backend`` is ``"all"`` (default), uses trace-level cost
        (``aggregate_by_name``) — unchanged from the original behavior.

        When a specific backend is selected, uses per-(stage, backend)
        observation-metrics so that each stage's cost is attributed to the
        backend(s) it actually used.
        """
        if backend == "all":
            gathered = await self._gather(slug, hours)
            all_traces = [t for _, traces in gathered for t in traces]
            return aggregate_by_name(all_traces)

        all_rows = await self._gather_list_results(slug, hours, self._agent_usage)
        return aggregate_by_name_backend(all_rows, backend)

    async def _model_usage(
        self, project: RegistryProject, hours: int
    ) -> list[dict[str, Any]]:
        return await self._cached_fetch(
            project,
            hours,
            self._model_cache,
            lambda h: self._clients[project.slug].fetch_model_usage_window(h),
        )

    async def by_model(self, slug: str | None, hours: int) -> list[dict[str, Any]]:
        """Cost + token usage by model, merged across selected projects.

        Window-accurate (see :meth:`LangfuseClient.fetch_model_usage_window`).
        """
        all_rows = await self._gather_list_results(slug, hours, self._model_usage)
        return merge_model_costs([all_rows])

    async def _backend_cost(
        self, project: RegistryProject, hours: int
    ) -> dict[str, dict[str, float]]:
        return await self._cached_fetch(
            project,
            hours,
            self._backend_cache,
            lambda h: self._clients[project.slug].fetch_backend_cost_window(h),
        )

    async def _agent_usage(
        self, project: RegistryProject, hours: int
    ) -> list[dict[str, Any]]:
        return await self._cached_fetch(
            project,
            hours,
            self._agent_usage_cache,
            lambda h: self._clients[project.slug].fetch_agent_usage_window(h),
        )

    async def backend_trend(
        self, slug: str | None, hours: int, backend: BackendKind
    ) -> list[dict[str, Any]]:
        """Return the cost trend for a backend, merged across selected projects.

        Window-accurate; time-bucket granularity scales with the window.
        """
        parts: list[dict[str, dict[str, float]]] = []
        for p in self._projects(slug):
            cost: dict[str, dict[str, float]] = await self._safe_project_fetch(
                p,
                lambda: self._backend_cost(p, hours),  # noqa: B023
                "backend-cost",
                {},
            )
            parts.append(cost)
        return backend_cost_series(parts, backend)

    async def trend(
        self, slug: str | None, hours: int, buckets: int = 48
    ) -> list[dict[str, Any]]:
        """Return a cost trend series across the window."""
        gathered = await self._gather(slug, hours)
        all_traces = [t for _, traces in gathered for t in traces]
        return cost_trend(all_traces, hours, buckets)

    async def highlights(
        self, slug: str | None, hours: int, backend: str = "all"
    ) -> dict[str, Any]:
        """Return dashboard highlights: top trace, session, and summary stats.

        When *backend* is not ``"all"``, traces are filtered to only those
        whose name appears in the agent-usage rows for that backend, keeping
        the highlights consistent with the backend selector.
        """
        gathered = await self._gather(slug, hours)
        all_traces = [t for _, traces in gathered for t in traces]
        if backend != "all":
            agent_rows = await self._gather_list_results(slug, hours, self._agent_usage)
            backend_names: set[str] = {
                r["name"] for r in agent_rows if r.get("backend") == backend
            }
            all_traces = [t for t in all_traces if t.name in backend_names]
        return {
            "most_expensive_trace": most_expensive_trace(all_traces),
            "most_expensive_session": most_expensive_session(all_traces),
            "session_cost_scope": backend if backend != "all" else "all",
        }

last_updated property

UTC datetime of the most recent cache refresh, or None when cold.

__init__(config, registry_client)

Initialise the service with config and a registry client.

Starts with an empty project/client map — call :meth:refresh_projects during startup to populate from the registry.

Source code in src/robotsix_cost_monitor/service/core.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def __init__(self, config: Config, registry_client: RegistryClient) -> None:
    """Initialise the service with config and a registry client.

    Starts with an empty project/client map — call :meth:`refresh_projects`
    during startup to populate from the registry.
    """
    self.config = config
    self._registry = registry_client
    self._project_map: dict[str, RegistryProject] = {}
    self._clients: dict[str, LangfuseClient] = {}
    ttl = self.config.settings.cache_ttl_seconds
    self._last_updated: datetime | None = None
    self._caches: list[TTLCache[Any, Any]] = []
    on_refresh = self._touch_last_updated

    def _mk[T](t: type[T]) -> TTLCache[Any, T]:
        c = TTLCache[Any, T](ttl, on_refresh=on_refresh)
        self._caches.append(c)
        return c

    # cache: (slug, hours) -> (traces, monotonic_deadline)
    self._cache = _mk(list[LangfuseTrace])
    # cache: (slug, hours) -> (per-model usage rows, monotonic_deadline)
    self._model_cache = _mk(list[dict[str, Any]])
    # cache: (slug, hours) -> ({time_bucket -> {backend -> cost}}, deadline)
    self._backend_cache = _mk(dict[str, dict[str, float]])
    # cache: (slug, hours) -> (per-(stage, backend) rows, monotonic_deadline)
    self._agent_usage_cache = _mk(list[dict[str, Any]])
    # cache: (slug, hours) -> (trace_count, monotonic_deadline)
    self._trace_count_cache = _mk(int)

backend_trend(slug, hours, backend) async

Return the cost trend for a backend, merged across selected projects.

Window-accurate; time-bucket granularity scales with the window.

Source code in src/robotsix_cost_monitor/service/core.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
async def backend_trend(
    self, slug: str | None, hours: int, backend: BackendKind
) -> list[dict[str, Any]]:
    """Return the cost trend for a backend, merged across selected projects.

    Window-accurate; time-bucket granularity scales with the window.
    """
    parts: list[dict[str, dict[str, float]]] = []
    for p in self._projects(slug):
        cost: dict[str, dict[str, float]] = await self._safe_project_fetch(
            p,
            lambda: self._backend_cost(p, hours),  # noqa: B023
            "backend-cost",
            {},
        )
        parts.append(cost)
    return backend_cost_series(parts, backend)

by_agent(slug, hours, backend='all') async

Cost by trace name (stage/agent), merged across selected projects.

When backend is "all" (default), uses trace-level cost (aggregate_by_name) — unchanged from the original behavior.

When a specific backend is selected, uses per-(stage, backend) observation-metrics so that each stage's cost is attributed to the backend(s) it actually used.

Source code in src/robotsix_cost_monitor/service/core.py
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
async def by_agent(
    self, slug: str | None, hours: int, backend: str = "all"
) -> list[dict[str, Any]]:
    """Cost by trace name (stage/agent), merged across selected projects.

    When ``backend`` is ``"all"`` (default), uses trace-level cost
    (``aggregate_by_name``) — unchanged from the original behavior.

    When a specific backend is selected, uses per-(stage, backend)
    observation-metrics so that each stage's cost is attributed to the
    backend(s) it actually used.
    """
    if backend == "all":
        gathered = await self._gather(slug, hours)
        all_traces = [t for _, traces in gathered for t in traces]
        return aggregate_by_name(all_traces)

    all_rows = await self._gather_list_results(slug, hours, self._agent_usage)
    return aggregate_by_name_backend(all_rows, backend)

by_model(slug, hours) async

Cost + token usage by model, merged across selected projects.

Window-accurate (see :meth:LangfuseClient.fetch_model_usage_window).

Source code in src/robotsix_cost_monitor/service/core.py
356
357
358
359
360
361
362
async def by_model(self, slug: str | None, hours: int) -> list[dict[str, Any]]:
    """Cost + token usage by model, merged across selected projects.

    Window-accurate (see :meth:`LangfuseClient.fetch_model_usage_window`).
    """
    all_rows = await self._gather_list_results(slug, hours, self._model_usage)
    return merge_model_costs([all_rows])

components()

Return discovered projects grouped by owning component.

Insertion order follows the registry, so the dashboard's component list is stable across refreshes. Projects whose component is unknown are grouped under their own slug rather than dropped.

Source code in src/robotsix_cost_monitor/service/core.py
140
141
142
143
144
145
146
147
148
149
150
def components(self) -> dict[str, list[RegistryProject]]:
    """Return discovered projects grouped by owning component.

    Insertion order follows the registry, so the dashboard's component list
    is stable across refreshes.  Projects whose component is unknown are
    grouped under their own slug rather than dropped.
    """
    out: dict[str, list[RegistryProject]] = {}
    for p in self._project_map.values():
        out.setdefault(p.component_id or p.slug, []).append(p)
    return out

highlights(slug, hours, backend='all') async

Return dashboard highlights: top trace, session, and summary stats.

When backend is not "all", traces are filtered to only those whose name appears in the agent-usage rows for that backend, keeping the highlights consistent with the backend selector.

Source code in src/robotsix_cost_monitor/service/core.py
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
async def highlights(
    self, slug: str | None, hours: int, backend: str = "all"
) -> dict[str, Any]:
    """Return dashboard highlights: top trace, session, and summary stats.

    When *backend* is not ``"all"``, traces are filtered to only those
    whose name appears in the agent-usage rows for that backend, keeping
    the highlights consistent with the backend selector.
    """
    gathered = await self._gather(slug, hours)
    all_traces = [t for _, traces in gathered for t in traces]
    if backend != "all":
        agent_rows = await self._gather_list_results(slug, hours, self._agent_usage)
        backend_names: set[str] = {
            r["name"] for r in agent_rows if r.get("backend") == backend
        }
        all_traces = [t for t in all_traces if t.name in backend_names]
    return {
        "most_expensive_trace": most_expensive_trace(all_traces),
        "most_expensive_session": most_expensive_session(all_traces),
        "session_cost_scope": backend if backend != "all" else "all",
    }

invalidate_all()

Clear every internal cache so the next request fetches fresh data.

Source code in src/robotsix_cost_monitor/service/core.py
101
102
103
104
105
def invalidate_all(self) -> None:
    """Clear every internal cache so the next request fetches fresh data."""
    for c in self._caches:
        c.invalidate()
    self._last_updated = None

projects()

Return every discovered project, in registry order.

Source code in src/robotsix_cost_monitor/service/core.py
136
137
138
def projects(self) -> list[RegistryProject]:
    """Return every discovered project, in registry order."""
    return list(self._project_map.values())

refresh_projects() async

Query the registry and rebuild the project/client map.

Best-effort: on failure the existing project list is kept unchanged.

Source code in src/robotsix_cost_monitor/service/core.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
async def refresh_projects(self) -> None:
    """Query the registry and rebuild the project/client map.

    Best-effort: on failure the existing project list is kept unchanged.
    """
    try:
        registry_projects = await self._registry.fetch_projects()
    except Exception:
        logger.warning("refresh_projects: registry fetch failed")
        return
    if not registry_projects:
        logger.warning("refresh_projects: registry returned no projects")
        return
    self._project_map = {p.slug: p for p in registry_projects}
    self._clients = {
        p.slug: LangfuseClient(
            public_key=p.langfuse_public_key,
            secret_key=p.langfuse_secret_key.get_secret_value(),
            base_url=p.langfuse_base_url,
        )
        for p in registry_projects
    }
    self.invalidate_all()
    logger.info(
        "refresh_projects: discovered %d project(s) across %d component(s)",
        len(self._project_map),
        len(self.components()),
    )

summary(slug, hours, backend='all') async

Per-project totals + the aggregate, for the window.

Cost is observation-based (the same window-accurate metrics source as the by-model / by-backend breakdowns), so the headline total, the per-model rows, and the per-backend totals all reconcile — a backend can never exceed the total. trace_count comes from a server-side view=traces count metric (not by paging every trace), so this stays fast.

When backend is not "all", only observation rows attributed to that backend are counted, so the per-component rollup and total reflect costs for the selected backend alone.

Source code in src/robotsix_cost_monitor/service/core.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
async def summary(
    self, slug: str | None, hours: int, backend: str = "all"
) -> dict[str, Any]:
    """Per-project totals + the aggregate, for the window.

    Cost is observation-based (the same window-accurate metrics source as the
    by-model / by-backend breakdowns), so the headline total, the per-model
    rows, and the per-backend totals all reconcile — a backend can never
    exceed the total. ``trace_count`` comes from a server-side ``view=traces``
    count metric (not by paging every trace), so this stays fast.

    When *backend* is not ``"all"``, only observation rows attributed to that
    backend are counted, so the per-component rollup and total reflect costs
    for the selected backend alone.
    """
    per_project: list[dict[str, Any]] = []
    total = 0.0
    for p in self._projects(slug):
        models: list[dict[str, Any]] = await self._safe_project_fetch(
            p,
            lambda: self._model_usage(p, hours),  # noqa: B023
            "model-usage",
            [],
        )
        if backend != "all":
            models = [m for m in models if m.get("backend") == backend]
        trace_count: int = await self._safe_project_fetch(
            p,
            lambda: self._trace_count(p, hours),  # noqa: B023
            "trace-count",
            0,
        )
        cost = round(sum(m["cost"] for m in models), 6)
        total += cost
        per_project.append(
            {
                "name": p.name,
                "slug": p.slug,
                "component": p.component_id,
                "cost": cost,
                "trace_count": trace_count,
            }
        )
    total = round(total, 6)
    by_component: dict[str, dict[str, Any]] = {}
    for row in per_project:
        agg = by_component.setdefault(
            str(row["component"] or row["slug"]),
            {
                "component": row["component"] or row["slug"],
                "cost": 0.0,
                "trace_count": 0,
                "projects": [],
            },
        )
        agg["cost"] = round(agg["cost"] + float(row["cost"]), 6)
        agg["trace_count"] += int(row["trace_count"])
        agg["projects"].append(row)
    components = sorted(
        by_component.values(), key=lambda c: float(c["cost"]), reverse=True
    )
    if backend != "all":
        components = [c for c in components if c["cost"] > 0]
    return {
        "window_hours": hours,
        "total_cost": total,
        "projects": per_project,
        "components": components,
    }

trend(slug, hours, buckets=48) async

Return a cost trend series across the window.

Source code in src/robotsix_cost_monitor/service/core.py
402
403
404
405
406
407
408
async def trend(
    self, slug: str | None, hours: int, buckets: int = 48
) -> list[dict[str, Any]]:
    """Return a cost trend series across the window."""
    gathered = await self._gather(slug, hours)
    all_traces = [t for _, traces in gathered for t in traces]
    return cost_trend(all_traces, hours, buckets)

ExternalServiceError

Bases: CostMonitorError, ExternalServiceError

An external API (Langfuse, OpenRouter) returned an error.

Transient failures (timeout, 5xx, 429) should be retried; terminal failures (401, 403, 404) should surface immediately.

Source code in src/robotsix_cost_monitor/exceptions.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
class ExternalServiceError(CostMonitorError, _ExternalServiceError):
    """An external API (Langfuse, OpenRouter) returned an error.

    Transient failures (timeout, 5xx, 429) should be retried; terminal
    failures (401, 403, 404) should surface immediately.
    """

    error_code = "EXTERNAL_SERVICE_ERROR"

    def __init__(
        self,
        detail: str = "",
        *,
        status_code: int | None = None,
        response: httpx.Response | None = None,
    ) -> None:
        """Initialise from a detail string, optionally with an HTTP response.

        When *response* is ``None`` (constructed locally), a synthetic
        :class:`httpx.Response` with the class-level ``status_code`` is
        created to satisfy :class:`ExternalHTTPError`'s required keyword
        arguments.
        """
        self.detail = detail or self.detail
        if status_code is not None:
            self.status_code = status_code
        if response is None:
            # Constructed locally without an HTTP response — use the
            # class-level status_code as the default for the robotsix-http
            # base class.  We must call both parent __init__s explicitly
            # because CostMonitorError's super().__init__ would land on
            # ExternalHTTPError which requires keyword arguments.
            Exception.__init__(self, self.detail)
            _ExternalServiceError.__init__(
                self,
                message=self.detail,
                status_code=self.status_code,
                response=httpx.Response(status_code=self.status_code),
            )
        else:
            Exception.__init__(self, self.detail)
            _ExternalServiceError.__init__(
                self,
                message=self.detail,
                status_code=status_code or self.status_code,
                response=response,
            )

__init__(detail='', *, status_code=None, response=None)

Initialise from a detail string, optionally with an HTTP response.

When response is None (constructed locally), a synthetic :class:httpx.Response with the class-level status_code is created to satisfy :class:ExternalHTTPError's required keyword arguments.

Source code in src/robotsix_cost_monitor/exceptions.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
def __init__(
    self,
    detail: str = "",
    *,
    status_code: int | None = None,
    response: httpx.Response | None = None,
) -> None:
    """Initialise from a detail string, optionally with an HTTP response.

    When *response* is ``None`` (constructed locally), a synthetic
    :class:`httpx.Response` with the class-level ``status_code`` is
    created to satisfy :class:`ExternalHTTPError`'s required keyword
    arguments.
    """
    self.detail = detail or self.detail
    if status_code is not None:
        self.status_code = status_code
    if response is None:
        # Constructed locally without an HTTP response — use the
        # class-level status_code as the default for the robotsix-http
        # base class.  We must call both parent __init__s explicitly
        # because CostMonitorError's super().__init__ would land on
        # ExternalHTTPError which requires keyword arguments.
        Exception.__init__(self, self.detail)
        _ExternalServiceError.__init__(
            self,
            message=self.detail,
            status_code=self.status_code,
            response=httpx.Response(status_code=self.status_code),
        )
    else:
        Exception.__init__(self, self.detail)
        _ExternalServiceError.__init__(
            self,
            message=self.detail,
            status_code=status_code or self.status_code,
            response=response,
        )

LangfuseClient

Read-only cost/trace client for a single Langfuse project.

Composes :class:AsyncLangfuseReadClient for auth/URL helpers and async REST transport; owns its own domain aggregation.

Source code in src/robotsix_cost_monitor/clients/langfuse.py
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
class LangfuseClient:
    """Read-only cost/trace client for a single Langfuse project.

    Composes :class:`AsyncLangfuseReadClient` for auth/URL helpers and
    async REST transport; owns its own domain aggregation.
    """

    def __init__(
        self,
        *,
        public_key: str,
        secret_key: str,
        base_url: str,
        timeout: float = 30.0,
    ) -> None:
        """Initialise the Langfuse client with credentials and a timeout."""
        self._lf = AsyncLangfuseReadClient(
            public_key=public_key,
            secret_key=secret_key,
            base_url=base_url,
        )
        self._timeout = timeout

    async def fetch_traces_window(self, hours: float) -> list[LangfuseTrace]:
        """Return all traces with ``timestamp`` within the last *hours*.

        *hours* may be fractional (reconciliation passes the exact snapshot
        interval). Delegates to
        :meth:`AsyncLangfuseReadClient.fetch_traces_window`.
        """
        return [
            LangfuseTrace.model_validate(t)
            async for t in self._lf.fetch_traces_window(hours)
        ]

    async def _metrics(
        self,
        hours: float,
        *,
        metrics: list[dict[str, str]],
        view: str = "observations",
        dimensions: list[dict[str, str]] | None = None,
        time_dimension: dict[str, str] | None = None,
    ) -> list[LangfuseMetricsRow]:
        """Run a Langfuse metrics query and return parsed rows.

        Queries *view* (``observations`` or ``traces``) for the exact last
        *hours*, grouped by *dimensions* (``None`` → group by model; pass
        ``[]`` for an ungrouped total). Returns the raw ``data`` rows parsed
        as :class:`LangfuseMetricsRow`.

        ``/api/public/metrics`` aggregates server-side and, unlike the
        daily-metrics endpoint, honors the exact ``from``/``to`` window (the
        daily endpoint returns whole calendar days and badly over-counts sub-day
        windows). One request per query — no pagination needed.
        """
        now = _utc_now()
        query: dict[str, Any] = {
            "view": view,
            "metrics": metrics,
            "dimensions": (
                [{"field": "providedModelName"}] if dimensions is None else dimensions
            ),
            "fromTimestamp": (now - timedelta(hours=hours))
            .isoformat()
            .replace("+00:00", "Z"),
            "toTimestamp": now.isoformat().replace("+00:00", "Z"),
        }
        if time_dimension is not None:
            query["timeDimension"] = time_dimension
        import httpx

        async with httpx.AsyncClient(timeout=self._timeout) as http_client:
            client = RetryClient(http_client)
            resp = await client.get(
                self._lf.url("/api/public/metrics"),
                params={"query": json.dumps(query)},
                headers={"Authorization": self._lf.auth_header()},
            )
        data: dict[str, Any] = resp.json()
        return [
            LangfuseMetricsRow.model_validate(row) for row in (data.get("data") or [])
        ]

    async def fetch_trace_count_window(self, hours: float) -> int:
        """Count traces in the exact last *hours* via a server-side metrics query.

        Uses ``view=traces``, ungrouped ``count``. One ``/api/public/metrics``
        request — O(1), vs paging every trace just to ``len()`` them (which is
        ~27s over a week of all-project data).
        """
        rows = await self._metrics(
            hours,
            view="traces",
            metrics=[{"measure": "count", "aggregation": "count"}],
            dimensions=[],
        )
        return int(rows[0].count_count or 0) if rows else 0

    async def fetch_agent_usage_window(self, hours: int) -> list[dict[str, Any]]:
        """Per-(stage, backend) cost over the exact last *hours*.

        Groups observations by trace name AND model, then maps each model to its
        serving backend via :func:`backend_for_model`. Returns rows shaped
        ``{"name": <stage>, "backend": <backend>, "cost": <float>,
        "count": <int>}`` sorted by cost descending.

        Observations with no model name carry no cost and are skipped. Uses the
        same window-accurate metrics source as :meth:`fetch_model_usage_window`.
        """
        rows = await self._metrics(
            hours,
            metrics=[
                {"measure": "totalCost", "aggregation": "sum"},
                {"measure": "count", "aggregation": "count"},
            ],
            dimensions=[
                {"field": "traceName"},
                {"field": "providedModelName"},
            ],
        )
        acc: dict[tuple[str, str], dict[str, float]] = {}
        for row in rows:
            model = row.provided_model_name
            stage = row.trace_name
            if not model or not stage:
                continue
            backend = backend_for_model(model)
            key = (stage, backend)
            slot = acc.setdefault(key, {"cost": 0.0, "count": 0.0})
            slot["cost"] += float(row.sum_total_cost or 0.0)
            slot["count"] += float(row.count_count or 0.0)
        ordered = sorted(acc.items(), key=lambda kv: kv[1]["cost"], reverse=True)
        return [
            {
                "name": stage,
                "backend": backend,
                "cost": round(v["cost"], 6),
                "count": int(v["count"]),
            }
            for (stage, backend), v in ordered
        ]

    async def fetch_model_usage_window(self, hours: int) -> list[dict[str, Any]]:
        """Per-model cost + token usage over the exact last *hours*.

        Window-accurate (see :meth:`_metrics`). Observations with no model
        (non-generation spans) are skipped; they carry no cost.
        """
        rows = await self._metrics(
            hours,
            metrics=[
                {"measure": "totalCost", "aggregation": "sum"},
                {"measure": "inputTokens", "aggregation": "sum"},
                {"measure": "outputTokens", "aggregation": "sum"},
                {"measure": "totalTokens", "aggregation": "sum"},
                {"measure": "count", "aggregation": "count"},
            ],
        )
        acc: dict[str, dict[str, float]] = {}
        for row in rows:
            model = row.provided_model_name
            if not model:
                continue
            slot = acc.setdefault(model, _empty_model_slot())
            slot["cost"] += float(row.sum_total_cost or 0.0)
            slot["input_tokens"] += float(row.sum_input_tokens or 0.0)
            slot["output_tokens"] += float(row.sum_output_tokens or 0.0)
            slot["total_tokens"] += float(row.sum_total_tokens or 0.0)
            slot["observations"] += float(row.count_count or 0.0)
        return _model_rows(acc)

    async def fetch_cost_by_backend(self, hours: float) -> dict[str, float]:
        """Total cost per serving backend over the exact last *hours*.

        ``{backend -> cost}`` (e.g. ``{"openrouter": .., "claude-sdk": ..}``).
        Used by reconciliation to compare like-for-like: OpenRouter's per-key
        spend only reconciles against the *openrouter*-backend traced cost —
        Claude-SDK traffic is traced here but billed by Anthropic, not OpenRouter.
        """
        rows = await self._metrics(
            hours, metrics=[{"measure": "totalCost", "aggregation": "sum"}]
        )
        out: dict[str, float] = {}
        for row in rows:
            model = row.provided_model_name
            if not model:
                continue
            backend = backend_for_model(model)
            out[backend] = out.get(backend, 0.0) + float(row.sum_total_cost or 0.0)
        return out

    async def fetch_backend_cost_window(
        self, hours: int
    ) -> dict[str, dict[str, float]]:
        """``{time_bucket -> {backend -> cost}}`` over the exact last *hours*.

        Same metrics source as :meth:`fetch_model_usage_window`, bucketed over
        time (granularity scaled to the window) and folded per backend (see
        :func:`backend_for_model`) for the per-backend cost trend.
        """
        granularity = "minute" if hours <= 1 else "hour" if hours <= 72 else "day"
        rows = await self._metrics(
            hours,
            metrics=[{"measure": "totalCost", "aggregation": "sum"}],
            time_dimension={"granularity": granularity},
        )
        out: dict[str, dict[str, float]] = {}
        for row in rows:
            model = row.provided_model_name
            if not model:
                continue
            bucket = str(row.time_dimension)
            backend = backend_for_model(model)
            slot = out.setdefault(bucket, {})
            slot[backend] = slot.get(backend, 0.0) + float(row.sum_total_cost or 0.0)
        return out

__init__(*, public_key, secret_key, base_url, timeout=30.0)

Initialise the Langfuse client with credentials and a timeout.

Source code in src/robotsix_cost_monitor/clients/langfuse.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def __init__(
    self,
    *,
    public_key: str,
    secret_key: str,
    base_url: str,
    timeout: float = 30.0,
) -> None:
    """Initialise the Langfuse client with credentials and a timeout."""
    self._lf = AsyncLangfuseReadClient(
        public_key=public_key,
        secret_key=secret_key,
        base_url=base_url,
    )
    self._timeout = timeout

fetch_agent_usage_window(hours) async

Per-(stage, backend) cost over the exact last hours.

Groups observations by trace name AND model, then maps each model to its serving backend via :func:backend_for_model. Returns rows shaped {"name": <stage>, "backend": <backend>, "cost": <float>, "count": <int>} sorted by cost descending.

Observations with no model name carry no cost and are skipped. Uses the same window-accurate metrics source as :meth:fetch_model_usage_window.

Source code in src/robotsix_cost_monitor/clients/langfuse.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
async def fetch_agent_usage_window(self, hours: int) -> list[dict[str, Any]]:
    """Per-(stage, backend) cost over the exact last *hours*.

    Groups observations by trace name AND model, then maps each model to its
    serving backend via :func:`backend_for_model`. Returns rows shaped
    ``{"name": <stage>, "backend": <backend>, "cost": <float>,
    "count": <int>}`` sorted by cost descending.

    Observations with no model name carry no cost and are skipped. Uses the
    same window-accurate metrics source as :meth:`fetch_model_usage_window`.
    """
    rows = await self._metrics(
        hours,
        metrics=[
            {"measure": "totalCost", "aggregation": "sum"},
            {"measure": "count", "aggregation": "count"},
        ],
        dimensions=[
            {"field": "traceName"},
            {"field": "providedModelName"},
        ],
    )
    acc: dict[tuple[str, str], dict[str, float]] = {}
    for row in rows:
        model = row.provided_model_name
        stage = row.trace_name
        if not model or not stage:
            continue
        backend = backend_for_model(model)
        key = (stage, backend)
        slot = acc.setdefault(key, {"cost": 0.0, "count": 0.0})
        slot["cost"] += float(row.sum_total_cost or 0.0)
        slot["count"] += float(row.count_count or 0.0)
    ordered = sorted(acc.items(), key=lambda kv: kv[1]["cost"], reverse=True)
    return [
        {
            "name": stage,
            "backend": backend,
            "cost": round(v["cost"], 6),
            "count": int(v["count"]),
        }
        for (stage, backend), v in ordered
    ]

fetch_backend_cost_window(hours) async

{time_bucket -> {backend -> cost}} over the exact last hours.

Same metrics source as :meth:fetch_model_usage_window, bucketed over time (granularity scaled to the window) and folded per backend (see :func:backend_for_model) for the per-backend cost trend.

Source code in src/robotsix_cost_monitor/clients/langfuse.py
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
async def fetch_backend_cost_window(
    self, hours: int
) -> dict[str, dict[str, float]]:
    """``{time_bucket -> {backend -> cost}}`` over the exact last *hours*.

    Same metrics source as :meth:`fetch_model_usage_window`, bucketed over
    time (granularity scaled to the window) and folded per backend (see
    :func:`backend_for_model`) for the per-backend cost trend.
    """
    granularity = "minute" if hours <= 1 else "hour" if hours <= 72 else "day"
    rows = await self._metrics(
        hours,
        metrics=[{"measure": "totalCost", "aggregation": "sum"}],
        time_dimension={"granularity": granularity},
    )
    out: dict[str, dict[str, float]] = {}
    for row in rows:
        model = row.provided_model_name
        if not model:
            continue
        bucket = str(row.time_dimension)
        backend = backend_for_model(model)
        slot = out.setdefault(bucket, {})
        slot[backend] = slot.get(backend, 0.0) + float(row.sum_total_cost or 0.0)
    return out

fetch_cost_by_backend(hours) async

Total cost per serving backend over the exact last hours.

{backend -> cost} (e.g. {"openrouter": .., "claude-sdk": ..}). Used by reconciliation to compare like-for-like: OpenRouter's per-key spend only reconciles against the openrouter-backend traced cost — Claude-SDK traffic is traced here but billed by Anthropic, not OpenRouter.

Source code in src/robotsix_cost_monitor/clients/langfuse.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
async def fetch_cost_by_backend(self, hours: float) -> dict[str, float]:
    """Total cost per serving backend over the exact last *hours*.

    ``{backend -> cost}`` (e.g. ``{"openrouter": .., "claude-sdk": ..}``).
    Used by reconciliation to compare like-for-like: OpenRouter's per-key
    spend only reconciles against the *openrouter*-backend traced cost —
    Claude-SDK traffic is traced here but billed by Anthropic, not OpenRouter.
    """
    rows = await self._metrics(
        hours, metrics=[{"measure": "totalCost", "aggregation": "sum"}]
    )
    out: dict[str, float] = {}
    for row in rows:
        model = row.provided_model_name
        if not model:
            continue
        backend = backend_for_model(model)
        out[backend] = out.get(backend, 0.0) + float(row.sum_total_cost or 0.0)
    return out

fetch_model_usage_window(hours) async

Per-model cost + token usage over the exact last hours.

Window-accurate (see :meth:_metrics). Observations with no model (non-generation spans) are skipped; they carry no cost.

Source code in src/robotsix_cost_monitor/clients/langfuse.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
async def fetch_model_usage_window(self, hours: int) -> list[dict[str, Any]]:
    """Per-model cost + token usage over the exact last *hours*.

    Window-accurate (see :meth:`_metrics`). Observations with no model
    (non-generation spans) are skipped; they carry no cost.
    """
    rows = await self._metrics(
        hours,
        metrics=[
            {"measure": "totalCost", "aggregation": "sum"},
            {"measure": "inputTokens", "aggregation": "sum"},
            {"measure": "outputTokens", "aggregation": "sum"},
            {"measure": "totalTokens", "aggregation": "sum"},
            {"measure": "count", "aggregation": "count"},
        ],
    )
    acc: dict[str, dict[str, float]] = {}
    for row in rows:
        model = row.provided_model_name
        if not model:
            continue
        slot = acc.setdefault(model, _empty_model_slot())
        slot["cost"] += float(row.sum_total_cost or 0.0)
        slot["input_tokens"] += float(row.sum_input_tokens or 0.0)
        slot["output_tokens"] += float(row.sum_output_tokens or 0.0)
        slot["total_tokens"] += float(row.sum_total_tokens or 0.0)
        slot["observations"] += float(row.count_count or 0.0)
    return _model_rows(acc)

fetch_trace_count_window(hours) async

Count traces in the exact last hours via a server-side metrics query.

Uses view=traces, ungrouped count. One /api/public/metrics request — O(1), vs paging every trace just to len() them (which is ~27s over a week of all-project data).

Source code in src/robotsix_cost_monitor/clients/langfuse.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
async def fetch_trace_count_window(self, hours: float) -> int:
    """Count traces in the exact last *hours* via a server-side metrics query.

    Uses ``view=traces``, ungrouped ``count``. One ``/api/public/metrics``
    request — O(1), vs paging every trace just to ``len()`` them (which is
    ~27s over a week of all-project data).
    """
    rows = await self._metrics(
        hours,
        view="traces",
        metrics=[{"measure": "count", "aggregation": "count"}],
        dimensions=[],
    )
    return int(rows[0].count_count or 0) if rows else 0

fetch_traces_window(hours) async

Return all traces with timestamp within the last hours.

hours may be fractional (reconciliation passes the exact snapshot interval). Delegates to :meth:AsyncLangfuseReadClient.fetch_traces_window.

Source code in src/robotsix_cost_monitor/clients/langfuse.py
57
58
59
60
61
62
63
64
65
66
67
async def fetch_traces_window(self, hours: float) -> list[LangfuseTrace]:
    """Return all traces with ``timestamp`` within the last *hours*.

    *hours* may be fractional (reconciliation passes the exact snapshot
    interval). Delegates to
    :meth:`AsyncLangfuseReadClient.fetch_traces_window`.
    """
    return [
        LangfuseTrace.model_validate(t)
        async for t in self._lf.fetch_traces_window(hours)
    ]

RegistryProject

Bases: BaseModel

One Langfuse project discovered from the central-deploy registry.

A project is a single LLM function, not a component: a component with two tracing subsystems declares two projects (e.g. robotsix-chat and robotsix-chat-cognee). :attr:component_id records which component owns it, so the dashboard can roll a component's projects up without any per-component code.

Source code in src/robotsix_cost_monitor/clients/models.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
class RegistryProject(BaseModel):
    """One Langfuse project discovered from the central-deploy registry.

    A project is a single LLM *function*, not a component: a component with
    two tracing subsystems declares two projects (e.g. ``robotsix-chat`` and
    ``robotsix-chat-cognee``).  :attr:`component_id` records which component
    owns it, so the dashboard can roll a component's projects up without any
    per-component code.
    """

    name: str
    slug: str
    component_id: str = Field(
        default="",
        description="Owning component (registry `component_id`); '' when unknown",
    )
    langfuse_public_key: str
    langfuse_secret_key: SecretStr
    langfuse_base_url: str = "https://cloud.langfuse.com"
    openrouter_key: str | None = None

Settings

Bases: BaseModel

Global dashboard settings — no per-project config (registry-driven).

Source code in src/robotsix_cost_monitor/config/__init__.py
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
class Settings(BaseModel):
    """Global dashboard settings — no per-project config (registry-driven)."""

    auth: AuthConfig = Field(
        default_factory=AuthConfig,
        description=(
            "HTTP Basic auth — REQUIRED when exposed via the gateway (see AuthConfig)."
        ),
    )
    # Binding every interface is deliberate: the dashboard serves from inside a
    # container behind the central-deploy gateway, and a service that binds
    # 127.0.0.1 there is unreachable through it — the container's own
    # healthcheck still passes, so it fails as a 502 rather than a crash.
    server_host: str = Field(
        default="0.0.0.0",  # noqa: S104  # nosec B104 - see above
        description="Bind address for the dashboard web server.",
    )
    server_port: int = Field(
        default=8080,
        description="Port for the dashboard web server.",
    )
    registry_base_url: str = Field(
        default="",
        description=(
            "Central-deploy registry base URL — projects are discovered at runtime."
        ),
    )
    registry_api_key: SecretStr = Field(
        default=SecretStr(""),
        description=(
            "API key for authenticating to the central-deploy registry. When "
            "deployed by robotsix-central-deploy with the robotsix.deploy.access: "
            '"agent" label, leave empty — the DEPLOY_API_KEY environment variable '
            "is injected automatically at deploy time."
        ),
    )
    registry_poll_interval_seconds: int = Field(
        default=300,
        description=(
            "Seconds between registry re-polls (0 = only at startup + manual refresh)."
        ),
    )
    default_window_hours: int = Field(
        default=168,
        description="Default cost-aggregation window in hours (e.g. 168 = 7 days).",
    )
    cache_ttl_seconds: int = Field(
        default=60,
        description=(
            "Seconds before cached Langfuse data is considered stale and re-fetched."
        ),
    )
    dashboard_refresh_interval_seconds: int = Field(
        default=120,
        description=(
            "Background cache-refresh interval — keeps dashboard aggregates "
            "precomputed so the frontend never blocks on a live Langfuse "
            "fetch. 0 disables."
        ),
    )
    reconcile_tolerance_usd: float = Field(
        default=1.0,
        description=(
            "Maximum allowed difference in USD between provider cost and traced "
            "cost before reconciliation is flagged as out of tolerance."
        ),
    )
    reconcile_schedule_hours: float = Field(
        default=24.0,
        description=(
            "Auto-run reconciliation every N hours (0 disables; default daily). "
            "The stored result drives the dashboard warning banner."
        ),
    )
    subscription_call_cap: int = Field(
        default=0,
        description=(
            "Per-day subscription call cap for volume-vs-cap monitoring; "
            "0 = disabled/unknown."
        ),
    )
    low_balance_threshold_usd: float = Field(
        default=5.0,
        description=(
            "OpenRouter account remaining-balance threshold in USD. When the "
            "remaining balance drops below this value a warning is logged and "
            "surfaced in the dashboard. Set to 0 to disable the low-balance "
            "check."
        ),
    )
    data_dir: Path = Field(
        default=Path(".data"),
        description=(
            "Runtime data directory for persistence (.data by default; /data in "
            "containers)."
        ),
    )
    log_format: str = Field(
        default="json",
        description='Structured log output format: "console" or "json".',
    )
    log_level: str = Field(
        default="INFO",
        description="Minimum log level for all loggers.",
    )
    mill_base_url: str = Field(
        default="",
        description=(
            'Base URL of the robotsix-mill board API (e.g. "http://mill:8080"). '
            "When empty, stuck-ticket detection is disabled."
        ),
    )
    mill_api_key: SecretStr = Field(
        default=SecretStr(""),
        json_schema_extra={"writeOnly": True},
        description=(
            "API key for authenticating to the mill board API. When deployed by "
            'robotsix-central-deploy with the robotsix.deploy.access: "agent" '
            "label, leave empty — the DEPLOY_API_KEY env var is used as a "
            "fallback."
        ),
    )
    stuck_ticket_threshold_hours: int = Field(
        default=48,
        description=(
            "Hours a ticket may remain in a non-terminal state before it is "
            "flagged as stuck. 0 disables stuck-ticket detection."
        ),
    )
    stuck_ticket_check_interval_seconds: int = Field(
        default=600,
        description=("Seconds between stuck-ticket checks (default 600 = 10 minutes)."),
    )

_atomic_write_text(path, text, root=None)

Write text to path atomically (temp file + fsync + os.replace).

A crash mid-write leaves the previous file content intact instead of a truncated file. The temp file lives in the same directory so os.replace stays on one filesystem (atomic on POSIX).

path must resolve inside root (default: its own parent directory); otherwise ValueError is raised so a crafted slug such as ../x cannot escape the state directory.

Source code in src/robotsix_cost_monitor/reconcile.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def _atomic_write_text(path: Path, text: str, root: Path | None = None) -> None:
    """Write *text* to *path* atomically (temp file + fsync + ``os.replace``).

    A crash mid-write leaves the previous file content intact instead of a
    truncated file. The temp file lives in the same directory so
    ``os.replace`` stays on one filesystem (atomic on POSIX).

    *path* must resolve inside *root* (default: its own parent directory);
    otherwise ``ValueError`` is raised so a crafted slug such as ``../x``
    cannot escape the state directory.
    """
    base = os.path.realpath(root if root is not None else path.parent)
    target = os.path.realpath(path)
    if not target.startswith(base + os.sep):
        raise ValueError(f"refusing to write outside {base!r}")
    fd, tmp = tempfile.mkstemp(
        dir=os.path.dirname(target), prefix=os.path.basename(target), suffix=".tmp"
    )
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as fh:
            fh.write(text)
            fh.flush()
            os.fsync(fh.fileno())
        os.replace(tmp, target)
    except BaseException:
        with contextlib.suppress(OSError):
            os.unlink(tmp)
        raise

_fetch_credits(api_key) async

Fetch account-level credit balance from OpenRouter (informational).

Source code in src/robotsix_cost_monitor/reconcile.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
async def _fetch_credits(api_key: str) -> dict[str, float]:
    """Fetch account-level credit balance from OpenRouter (informational)."""
    from robotsix_http import RetryClient

    url = "https://openrouter.ai/api/v1/credits"
    headers = {"Authorization": f"Bearer {api_key}"}
    async with httpx.AsyncClient(timeout=20.0) as http_client:
        client = RetryClient(http_client)
        resp = await client.get(url, headers=headers)
    data = resp.json().get("data") or {}
    total_credits = float(data.get("total_credits", 0) or 0)
    total_usage = float(data.get("total_usage", 0) or 0)
    # OpenRouter's /credits payload carries only the two totals — there is no
    # `remaining` field, so reading one yielded 0.0 for every account and
    # tripped the low-balance warning on every project, every run.
    return {
        "total_credits": total_credits,
        "total_usage": total_usage,
        "remaining": total_credits - total_usage,
    }

_fetch_or_error(label, transient, coro, result) async

Await coro, catching transient and unexpected exceptions uniformly.

On failure, records result["error"] and returns None so the caller can return the result dict immediately.

Source code in src/robotsix_cost_monitor/reconcile.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
async def _fetch_or_error[T](
    label: str,
    transient: tuple[type[Exception], ...],
    coro: Awaitable[T],
    result: dict[str, Any],
) -> T | None:
    """Await *coro*, catching transient and unexpected exceptions uniformly.

    On failure, records ``result["error"]`` and returns ``None`` so the
    caller can return the result dict immediately.
    """
    try:
        return await coro
    except transient as exc:
        logger.warning("%s fetch transient failure: %s", label, exc)
        result["error"] = f"{label} fetch failed: {exc}"
        return None
    except Exception as exc:
        logger.exception("%s fetch unexpected failure: %s", label, exc)
        result["error"] = f"{label} fetch failed: {exc}"
        return None

_hours_between(a, b)

Source code in src/robotsix_cost_monitor/reconcile.py
92
93
def _hours_between(a: datetime, b: datetime) -> float:
    return max(0.0, (b - a).total_seconds() / 3600.0)

_last_path(settings=None)

Source code in src/robotsix_cost_monitor/reconcile.py
255
256
def _last_path(settings: Settings | None = None) -> Path:
    return _state_dir(settings) / "last.json"

_load_snapshot(slug, settings=None)

Source code in src/robotsix_cost_monitor/reconcile.py
76
77
78
79
def _load_snapshot(
    slug: str, settings: Settings | None = None
) -> dict[str, Any] | None:
    return safe_load_json(_snapshot_path(slug, settings), None)

_save_snapshot(slug, cumulative, at, settings=None)

Source code in src/robotsix_cost_monitor/reconcile.py
82
83
84
85
86
87
88
89
def _save_snapshot(
    slug: str, cumulative: float, at: datetime, settings: Settings | None = None
) -> None:
    _atomic_write_text(
        _snapshot_path(slug, settings),
        json.dumps({"cumulative": cumulative, "at": at.isoformat()}),
        root=_state_dir(settings),
    )

_snapshot_path(slug, settings=None)

Source code in src/robotsix_cost_monitor/reconcile.py
42
43
def _snapshot_path(slug: str, settings: Settings | None = None) -> Path:
    return _state_dir(settings) / f"{slug}.json"

_state_dir(settings=None)

Source code in src/robotsix_cost_monitor/reconcile.py
36
37
38
39
def _state_dir(settings: Settings | None = None) -> Path:
    d = data_dir(settings) / "reconcile"
    d.mkdir(parents=True, exist_ok=True)
    return d

data_dir(settings=None)

Resolve the runtime-state directory for persistence.

When settings is given, the settings.data_dir field is used (relative paths are resolved against the repo root). Without settings the legacy default .data relative to the repo root is returned for backward compatibility.

Source code in src/robotsix_cost_monitor/config/__init__.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
def data_dir(settings: Settings | None = None) -> Path:
    """Resolve the runtime-state directory for persistence.

    When *settings* is given, the ``settings.data_dir`` field is used (relative
    paths are resolved against the repo root).  Without *settings* the legacy
    default ``.data`` relative to the repo root is returned for backward
    compatibility.
    """
    if settings is not None:
        path = Path(settings.data_dir)
        if not path.is_absolute():
            path = _REPO_ROOT / path
        return Path(os.path.abspath(path)).resolve()
    return Path(os.path.abspath(_REPO_ROOT / ".data")).resolve()

load_last_reconcile(settings=None)

Return the last stored reconcile result (for the banner); empty when none yet.

Source code in src/robotsix_cost_monitor/reconcile.py
302
303
304
305
306
307
def load_last_reconcile(settings: Settings | None = None) -> dict[str, Any]:
    """Return the last stored reconcile result (for the banner); empty when none yet."""
    return safe_load_json(
        _last_path(settings),
        {"generated_at": None, "status": "unknown", "results": []},
    )

reconcile_all(config, service) async

Reconcile every project, persist the result, and return it.

The stored last.json powers the dashboard's warning banner and the /api/reconcile/last endpoint.

Source code in src/robotsix_cost_monitor/reconcile.py
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
async def reconcile_all(config: Config, service: CostService) -> dict[str, Any]:
    """Reconcile every project, persist the result, and return it.

    The stored ``last.json`` powers the dashboard's warning banner and the
    ``/api/reconcile/last`` endpoint.
    """
    reconcile_runs.inc()
    t0 = time.monotonic()
    projects = service.projects()
    results = [await reconcile_project(p, config.settings) for p in projects]
    reconcile_duration.set(time.monotonic() - t0)
    out: dict[str, Any] = {
        "generated_at": datetime.now(UTC).isoformat(),
        "status": reconcile_status(results),
        "tolerance_usd": config.settings.reconcile_tolerance_usd,
        "results": results,
    }
    _atomic_write_text(
        _last_path(config.settings),
        json.dumps(out, indent=2),
        root=_state_dir(config.settings),
    )
    return out

reconcile_project(project, settings) async

Reconcile one project's OpenRouter spend vs Langfuse traced cost.

Snapshots the key's cumulative usage and diffs against the previous snapshot; compares the provider delta to the Langfuse traced cost over the same interval. Returns a status dict (also includes the remaining balance). The snapshot is updated on every call.

Source code in src/robotsix_cost_monitor/reconcile.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
async def reconcile_project(
    project: RegistryProject, settings: Settings
) -> dict[str, Any]:
    """Reconcile one project's OpenRouter spend vs Langfuse traced cost.

    Snapshots the key's cumulative usage and diffs against the previous
    snapshot; compares the provider delta to the Langfuse traced cost over the
    same interval. Returns a status dict (also includes the remaining
    balance). The snapshot is updated on every call.
    """
    now = datetime.now(UTC)
    result: dict[str, Any] = {
        "project": project.name,
        "slug": project.slug,
        "configured": bool(project.openrouter_key),
        "at": now.isoformat(),
    }
    if not project.openrouter_key:
        result["detail"] = "no openrouter_key configured for this project"
        return result

    try:
        from robotsix_llmio.openrouter import OpenRouterKeyCostSource
    except ImportError:
        result["error"] = "robotsix-llmio is not installed. Install it with: uv sync"
        return result

    orc = OpenRouterKeyCostSource(api_key=project.openrouter_key)

    # Per-KEY cumulative usage is the reconciliation basis (isolates this
    # consumer even when several keys share one OpenRouter account).
    async def _fetch_cumulative() -> float:
        ku = await asyncio.to_thread(orc.fetch_key_usage)
        return ku.usage

    cumulative_ = await _fetch_or_error(
        "OpenRouter", (ExternalServiceError,), _fetch_cumulative(), result
    )
    if cumulative_ is None:
        return result
    cumulative = cumulative_

    # Account-level remaining balance — informational only (shared balance pool).
    # Optional: a balance fetch failure must not fail the reconcile.
    with contextlib.suppress(Exception):
        result["balance"] = await _fetch_credits(project.openrouter_key)
        if (
            settings.low_balance_threshold_usd > 0
            and result["balance"]["remaining"] < settings.low_balance_threshold_usd
        ):
            result["low_balance"] = True
            logger.warning(
                "project %s: low balance — $%.2f remaining (threshold $%.2f)",
                project.name,
                result["balance"]["remaining"],
                settings.low_balance_threshold_usd,
            )

    prior = _load_snapshot(project.slug, settings)
    _save_snapshot(project.slug, cumulative, now, settings)

    if prior is None:
        result["detail"] = "first snapshot recorded — reconciliation on next run"
        return result

    prior_at = datetime.fromisoformat(prior["at"])
    interval_h = _hours_between(prior_at, now)
    provider_delta = round(cumulative - float(prior["cumulative"]), 6)

    lf = LangfuseClient(
        public_key=project.langfuse_public_key,
        secret_key=project.langfuse_secret_key.get_secret_value(),
        base_url=project.langfuse_base_url,
    )
    # Traced cost over the SAME interval as the provider delta (both since the
    # prior snapshot), so the two sides are comparable. Using a rounded ≥1h
    # window here made short intervals nonsensical (provider over minutes vs
    # traced over an hour).
    #
    # Compare like-for-like: OpenRouter's per-key spend only reconciles against
    # the *openrouter*-backend traced cost. Claude-SDK (level-3) traffic is
    # traced in Langfuse but billed by Anthropic, not OpenRouter — including it
    # made "traced" exceed "provider" by the Claude portion.
    by_backend_ = await _fetch_or_error(
        "Langfuse",
        (ExternalServiceError, httpx.HTTPError, json.JSONDecodeError),
        lf.fetch_cost_by_backend(interval_h),
        result,
    )
    if by_backend_ is None:
        return result
    by_backend = by_backend_

    logged = round(by_backend.get("openrouter", 0.0), 6)
    total_traced = round(sum(by_backend.values()), 6)

    drift = round(provider_delta - logged, 6)
    result.update(
        {
            "interval_hours": round(interval_h, 2),
            "provider_delta_usd": provider_delta,
            # OpenRouter-backend only — the value comparable to the provider side.
            "langfuse_cost_usd": logged,
            # All backends (incl. claude-sdk), for transparency.
            "langfuse_total_cost_usd": total_traced,
            "langfuse_cost_by_backend": {k: round(v, 6) for k, v in by_backend.items()},
            "drift_usd": drift,
            "within_tolerance": abs(drift) <= settings.reconcile_tolerance_usd,
            "tolerance_usd": settings.reconcile_tolerance_usd,
        }
    )
    return result

reconcile_status(results)

Overall status across per-project reconcile results.

warning if any configured project errored or drifted beyond tolerance; pending while every configured project is still on its first snapshot; ok otherwise. Unconfigured projects are ignored.

Source code in src/robotsix_cost_monitor/reconcile.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
def reconcile_status(results: list[dict[str, Any]]) -> str:
    """Overall status across per-project reconcile results.

    ``warning`` if any configured project errored or drifted beyond tolerance;
    ``pending`` while every configured project is still on its first snapshot;
    ``ok`` otherwise. Unconfigured projects are ignored.
    """
    comparable = [r for r in results if r.get("configured", True)]
    if any(
        r.get("error") or r.get("within_tolerance") is False or r.get("low_balance")
        for r in comparable
    ):
        return "warning"
    if comparable and all("within_tolerance" not in r for r in comparable):
        return "pending"
    return "ok"

safe_load_json(path, default)

Load and parse path as JSON, returning default on any error.

Catches FileNotFoundError (via .exists() returning False), json.JSONDecodeError, and most OSError subclasses during the read. PermissionError raised by .exists() itself is NOT caught — it propagates to the caller.

Source code in src/robotsix_cost_monitor/_utils.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def safe_load_json[T](path: Path, default: T) -> T:
    """Load and parse ``path`` as JSON, returning *default* on any error.

    Catches ``FileNotFoundError`` (via ``.exists()`` returning ``False``),
    ``json.JSONDecodeError``, and most ``OSError`` subclasses during the
    read.  ``PermissionError`` raised by ``.exists()`` itself is NOT caught
    — it propagates to the caller.
    """
    if not path.exists():
        return default
    try:
        return cast(T, json.loads(path.read_text()))
    except json.JSONDecodeError, OSError:  # PEP 758 (py3.14): JSONDecodeError/OSError
        return default

robotsix_cost_monitor.routes

HTTP route handlers (APIRouter).

All route handlers that were previously inline inside create_app now live here, using FastAPI dependency injection to obtain Config and CostService from app.state.

Exception handling and the /health, /health/live and /readyz probe routes are provided by the shared :mod:robotsix_http.fastapi bootstrap and wired up in :mod:.app.

BackendKind = Literal['openrouter', 'claude-sdk', 'all'] module-attribute

MAX_WINDOW_HOURS = 168 module-attribute

_CHAT_SKILL = '# robotsix-cost-monitor — Chat Agent Skill\n\n## Base URL\n\n```\nhttp://cost-monitor:8080\n```\n\n## Authentication\n\nHTTP Basic auth **may** be required (configured at deploy time — ask the\noperator for credentials). All endpoints return 401 when auth is enabled\nand no valid credentials are supplied. The probes (`/health`,\n`/health/live`, `/readyz`) are always exempt.\n\n## Read endpoints\n\nAll read endpoints accept an optional `?project=<scope>` query parameter\n(default `all`) and an optional `?hours=<n>` time window (see\n[Time window](#time-window) below).\n\n`<scope>` resolves at either level:\n\n- a **component id** (e.g. `chat`) — every Langfuse project that component\n owns, aggregated;\n- a **project slug** (e.g. `robotsix-chat-cognee`) — that one LLM function.\n\nA component owns one project per LLM function, so `chat` covers both\n`robotsix-chat` and `robotsix-chat-cognee`. Components and their projects\nare discovered from the central-deploy registry — anything with a Langfuse\nconfig is monitored automatically, so do not assume a fixed list; call\n`GET /api/components` to see what exists right now.\n\nAn unmatched `<scope>` (stale or mistyped slug) returns `404` with error\ncode `PROJECT_NOT_FOUND` — distinct from a valid-but-empty project and from\n`?project=all` which always returns `200`.\n\n## Time window\n\nEvery windowed endpoint accepts `?hours=<n>`, the number of hours of history\nto report on:\n\n- **Default (omitted or `hours=0`)** — the server\'s configured default\n window is used (currently **168 h** = 7 days).\n- **Ceiling** — the maximum accepted window is **168 h**. A request for\n `hours` **greater than 168** is *rejected*, not silently clamped: the\n response is `422` with error code `validation_error` and a field-level\n message naming the limit. `hours` below `0` is rejected the same way.\n- **Config-default clamping** — only the *server-side* default is clamped to\n the 168 h ceiling if an operator misconfigures it; a client-supplied value\n is always either honoured (0-168) or rejected.\n\nTo remove any ambiguity about which window was applied, every windowed\nresponse advertises the resolved value:\n\n- **`X-Effective-Hours`** response header — present on *all* windowed\n endpoints (including the list-shaped breakdowns and trends).\n- **`effective_hours`** JSON field — additionally included in the body of\n the object-shaped endpoints (`GET /api/summary`, `GET /api/highlights`).\n\nRead the effective window from either place rather than inferring it from\ntrend bucket sizes.\n\n### Pagination\n\nList-shaped endpoints (`GET /api/components`, `GET /api/projects`,\n`GET /api/by-agent`, `GET /api/by-model`) accept `?offset=` & `?limit=`.\n\n### Cost summaries\n\n| Endpoint | Description |\n|---|---|\n| `GET /api/summary` | Cost summary by project & component. Optional `?backend=`. |\n| `GET /api/components` | Components + owning projects. Paged `?offset=`/`?limit=`. |\n| `GET /api/projects` | Discovered projects. Paged `?offset=`/`?limit=`. |\n\n### Per-agent / per-model breakdowns\n\n| Endpoint | Description |\n|---|---|\n| `GET /api/by-agent` | By agent. Optional `?backend=`. Paged `?offset=`/`?limit=`. |\n| `GET /api/by-model` | By model. Paged `?offset=`/`?limit=`. |\n\n### Trends\n\n| Endpoint | Description |\n|---|---|\n| `GET /api/trend` | Cost trend series bucketed by time. Optional `?buckets=`. |\n| `GET /api/backend-trend` | Cost trend per backend. Optional `?backend=`. |\n\n### Highlights & reconciliation\n\n| Endpoint | Description |\n|---|---|\n| `GET /api/highlights` | Most expensive trace and session. Optional `?backend=`. |\n| `GET /api/reconcile` | Run reconciliation now (writes snapshots — see Safety). |\n| `GET /api/reconcile/last` | Most recent reconciliation result. |\n\n### Stuck tickets\n\n| Endpoint | Description |\n|---|---|\n| `GET /api/stuck-tickets` | Mill tickets stuck in non-terminal states. 503 = unknown. |\n\n`GET /api/stuck-tickets` queries the mill board live on every call. An\nempty list means no stuck tickets (or detection is disabled). A `503`\nmeans the mill board is unreachable: the stuck-ticket state is\n**unknown, not zero** — never report it as "no stuck tickets".\n\n### Health\n\n| Endpoint | Description |\n|---|---|\n| `GET /health` | Health check (`{"status": "ok"}`). Always unauthenticated. |\n| `GET /health/live` | Liveness probe (no dependency checks). Always unauthenticated. |\n| `GET /readyz` | Readiness probe (`projects`, `data_dir` checks); 503 if any fail. |\n\n## Safety\n\n**Mutating endpoints** — these change server state (invalidate caches,\npersist reconciliation snapshots, call the OpenRouter API). The chat\nagent MUST ask for explicit operator confirmation before calling any of\nthem:\n\n| Endpoint | What it does |\n|---|---|\n| `POST /api/refresh` | Invalidate all caches; next request fetches fresh data. |\n| `GET /api/reconcile` | Fetch OpenRouter usage; overwrite reconciliation snapshots. |\n\nEvery other read endpoint (`GET`) is safe and requires no confirmation.\nTo inspect reconciliation without side effects, use\n`GET /api/reconcile/last`.\n\nThere is no `POST /api/reconcile/run` endpoint; reconciliation runs on\nthe server\'s schedule or via `GET /api/reconcile` above.\n\n`GET /metrics` (Prometheus scrape) and the HTML pages (`/`, `/settings`)\nare operator/browser-facing and intentionally not part of this skill.\n' module-attribute

_WEB = Path(__file__).resolve().parent.parent / 'web' module-attribute

router = APIRouter() module-attribute

Config

Bases: BaseModel

Top-level config: registry-driven project discovery + global settings.

Project credentials are discovered at runtime from the central-deploy registry — there is no hardcoded project list.

Source code in src/robotsix_cost_monitor/config/__init__.py
215
216
217
218
219
220
221
222
class Config(BaseModel):
    """Top-level config: registry-driven project discovery + global settings.

    Project credentials are discovered at runtime from the central-deploy
    registry — there is no hardcoded project list.
    """

    settings: Settings = Field(default_factory=Settings)

CostService

Cross-project cost aggregation service with per-window TTL cache.

All five internal caches share a single :attr:last_updated timestamp (the youngest refresh across all caches) so the dashboard can display data freshness.

Source code in src/robotsix_cost_monitor/service/core.py
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
class CostService:
    """Cross-project cost aggregation service with per-window TTL cache.

    All five internal caches share a single :attr:`last_updated` timestamp
    (the youngest refresh across *all* caches) so the dashboard can display
    data freshness.
    """

    def __init__(self, config: Config, registry_client: RegistryClient) -> None:
        """Initialise the service with config and a registry client.

        Starts with an empty project/client map — call :meth:`refresh_projects`
        during startup to populate from the registry.
        """
        self.config = config
        self._registry = registry_client
        self._project_map: dict[str, RegistryProject] = {}
        self._clients: dict[str, LangfuseClient] = {}
        ttl = self.config.settings.cache_ttl_seconds
        self._last_updated: datetime | None = None
        self._caches: list[TTLCache[Any, Any]] = []
        on_refresh = self._touch_last_updated

        def _mk[T](t: type[T]) -> TTLCache[Any, T]:
            c = TTLCache[Any, T](ttl, on_refresh=on_refresh)
            self._caches.append(c)
            return c

        # cache: (slug, hours) -> (traces, monotonic_deadline)
        self._cache = _mk(list[LangfuseTrace])
        # cache: (slug, hours) -> (per-model usage rows, monotonic_deadline)
        self._model_cache = _mk(list[dict[str, Any]])
        # cache: (slug, hours) -> ({time_bucket -> {backend -> cost}}, deadline)
        self._backend_cache = _mk(dict[str, dict[str, float]])
        # cache: (slug, hours) -> (per-(stage, backend) rows, monotonic_deadline)
        self._agent_usage_cache = _mk(list[dict[str, Any]])
        # cache: (slug, hours) -> (trace_count, monotonic_deadline)
        self._trace_count_cache = _mk(int)

    def _touch_last_updated(self) -> None:
        """Record the current wall-clock time as the last cache refresh."""
        self._last_updated = datetime.now(UTC)

    @property
    def last_updated(self) -> datetime | None:
        """UTC datetime of the most recent cache refresh, or ``None`` when cold."""
        return self._last_updated

    def invalidate_all(self) -> None:
        """Clear every internal cache so the next request fetches fresh data."""
        for c in self._caches:
            c.invalidate()
        self._last_updated = None

    async def refresh_projects(self) -> None:
        """Query the registry and rebuild the project/client map.

        Best-effort: on failure the existing project list is kept unchanged.
        """
        try:
            registry_projects = await self._registry.fetch_projects()
        except Exception:
            logger.warning("refresh_projects: registry fetch failed")
            return
        if not registry_projects:
            logger.warning("refresh_projects: registry returned no projects")
            return
        self._project_map = {p.slug: p for p in registry_projects}
        self._clients = {
            p.slug: LangfuseClient(
                public_key=p.langfuse_public_key,
                secret_key=p.langfuse_secret_key.get_secret_value(),
                base_url=p.langfuse_base_url,
            )
            for p in registry_projects
        }
        self.invalidate_all()
        logger.info(
            "refresh_projects: discovered %d project(s) across %d component(s)",
            len(self._project_map),
            len(self.components()),
        )

    def projects(self) -> list[RegistryProject]:
        """Return every discovered project, in registry order."""
        return list(self._project_map.values())

    def components(self) -> dict[str, list[RegistryProject]]:
        """Return discovered projects grouped by owning component.

        Insertion order follows the registry, so the dashboard's component list
        is stable across refreshes.  Projects whose component is unknown are
        grouped under their own slug rather than dropped.
        """
        out: dict[str, list[RegistryProject]] = {}
        for p in self._project_map.values():
            out.setdefault(p.component_id or p.slug, []).append(p)
        return out

    def _projects(self, slug: str | None) -> list[RegistryProject]:
        """Resolve a selector to the projects it covers.

        Accepts ``"all"``/empty (everything), a **component id** (every project
        that component owns), or a single **project slug**.  Resolving both
        levels here is what lets every endpoint be component-aware without any
        per-endpoint or per-component code.

        Project slugs win over component ids on collision: a project is the
        more specific thing, and the single-project component case (where the
        two names coincide) resolves identically either way.
        """
        if not slug or slug == "all":
            return list(self._project_map.values())
        if (p := self._project_map.get(slug)) is not None:
            return [p]
        result = [q for q in self._project_map.values() if q.component_id == slug]
        if not result:
            raise ProjectNotFoundError(
                f"Project '{slug}' not found — no configured project or "
                f"component matches this slug."
            )
        return result

    async def _safe_project_fetch[T](
        self,
        project: RegistryProject,
        fetch_fn: Callable[[], Awaitable[T]],
        label: str,
        default: T,
    ) -> T:
        try:
            return await fetch_fn()
        except ExternalServiceError, ExternalRateLimitError, CacheError:
            logger.warning("project %s %s failed transiently", project.slug, label)
            return default
        except Exception:
            logger.exception("project %s %s failed unexpectedly", project.slug, label)
            return default

    async def _cached_fetch(
        self,
        project: RegistryProject,
        hours: int,
        cache: TTLCache[tuple[str, int], _T],
        fetch_fn: Callable[[int], Awaitable[_T]],
    ) -> _T:
        key = (project.slug, hours)
        return await cache.get_or_fetch(key, lambda: fetch_fn(hours))

    async def _traces(
        self, project: RegistryProject, hours: int
    ) -> list[LangfuseTrace]:
        return await self._cached_fetch(
            project,
            hours,
            self._cache,
            lambda h: self._clients[project.slug].fetch_traces_window(h),
        )

    async def _trace_count(self, project: RegistryProject, hours: int) -> int:
        """Trace count for the window via a server-side metrics query (cached).

        Avoids paging every raw trace just to ``len()`` them — the headline
        ``summary`` only needs the count, not the trace bodies.
        """
        return await self._cached_fetch(
            project,
            hours,
            self._trace_count_cache,
            lambda h: self._clients[project.slug].fetch_trace_count_window(h),
        )

    async def _gather(
        self, slug: str | None, hours: int
    ) -> list[tuple[RegistryProject, list[LangfuseTrace]]]:
        out: list[tuple[RegistryProject, list[LangfuseTrace]]] = []
        for p in self._projects(slug):
            traces: list[LangfuseTrace] = await self._safe_project_fetch(
                p,
                lambda: self._traces(p, hours),  # noqa: B023
                "fetch traces",
                [],
            )
            out.append((p, traces))
        return out

    async def _gather_list_results(
        self,
        slug: str | None,
        hours: int,
        fetch: Callable[[RegistryProject, int], Awaitable[list[dict[str, Any]]]],
    ) -> list[dict[str, Any]]:
        parts: list[list[dict[str, Any]]] = []
        for p in self._projects(slug):
            result: list[dict[str, Any]] = await self._safe_project_fetch(
                p,
                lambda: fetch(p, hours),  # noqa: B023
                "fetch list results",
                [],
            )
            parts.append(result)
        return [r for part in parts for r in part]

    async def summary(
        self, slug: str | None, hours: int, backend: str = "all"
    ) -> dict[str, Any]:
        """Per-project totals + the aggregate, for the window.

        Cost is observation-based (the same window-accurate metrics source as the
        by-model / by-backend breakdowns), so the headline total, the per-model
        rows, and the per-backend totals all reconcile — a backend can never
        exceed the total. ``trace_count`` comes from a server-side ``view=traces``
        count metric (not by paging every trace), so this stays fast.

        When *backend* is not ``"all"``, only observation rows attributed to that
        backend are counted, so the per-component rollup and total reflect costs
        for the selected backend alone.
        """
        per_project: list[dict[str, Any]] = []
        total = 0.0
        for p in self._projects(slug):
            models: list[dict[str, Any]] = await self._safe_project_fetch(
                p,
                lambda: self._model_usage(p, hours),  # noqa: B023
                "model-usage",
                [],
            )
            if backend != "all":
                models = [m for m in models if m.get("backend") == backend]
            trace_count: int = await self._safe_project_fetch(
                p,
                lambda: self._trace_count(p, hours),  # noqa: B023
                "trace-count",
                0,
            )
            cost = round(sum(m["cost"] for m in models), 6)
            total += cost
            per_project.append(
                {
                    "name": p.name,
                    "slug": p.slug,
                    "component": p.component_id,
                    "cost": cost,
                    "trace_count": trace_count,
                }
            )
        total = round(total, 6)
        by_component: dict[str, dict[str, Any]] = {}
        for row in per_project:
            agg = by_component.setdefault(
                str(row["component"] or row["slug"]),
                {
                    "component": row["component"] or row["slug"],
                    "cost": 0.0,
                    "trace_count": 0,
                    "projects": [],
                },
            )
            agg["cost"] = round(agg["cost"] + float(row["cost"]), 6)
            agg["trace_count"] += int(row["trace_count"])
            agg["projects"].append(row)
        components = sorted(
            by_component.values(), key=lambda c: float(c["cost"]), reverse=True
        )
        if backend != "all":
            components = [c for c in components if c["cost"] > 0]
        return {
            "window_hours": hours,
            "total_cost": total,
            "projects": per_project,
            "components": components,
        }

    async def by_agent(
        self, slug: str | None, hours: int, backend: str = "all"
    ) -> list[dict[str, Any]]:
        """Cost by trace name (stage/agent), merged across selected projects.

        When ``backend`` is ``"all"`` (default), uses trace-level cost
        (``aggregate_by_name``) — unchanged from the original behavior.

        When a specific backend is selected, uses per-(stage, backend)
        observation-metrics so that each stage's cost is attributed to the
        backend(s) it actually used.
        """
        if backend == "all":
            gathered = await self._gather(slug, hours)
            all_traces = [t for _, traces in gathered for t in traces]
            return aggregate_by_name(all_traces)

        all_rows = await self._gather_list_results(slug, hours, self._agent_usage)
        return aggregate_by_name_backend(all_rows, backend)

    async def _model_usage(
        self, project: RegistryProject, hours: int
    ) -> list[dict[str, Any]]:
        return await self._cached_fetch(
            project,
            hours,
            self._model_cache,
            lambda h: self._clients[project.slug].fetch_model_usage_window(h),
        )

    async def by_model(self, slug: str | None, hours: int) -> list[dict[str, Any]]:
        """Cost + token usage by model, merged across selected projects.

        Window-accurate (see :meth:`LangfuseClient.fetch_model_usage_window`).
        """
        all_rows = await self._gather_list_results(slug, hours, self._model_usage)
        return merge_model_costs([all_rows])

    async def _backend_cost(
        self, project: RegistryProject, hours: int
    ) -> dict[str, dict[str, float]]:
        return await self._cached_fetch(
            project,
            hours,
            self._backend_cache,
            lambda h: self._clients[project.slug].fetch_backend_cost_window(h),
        )

    async def _agent_usage(
        self, project: RegistryProject, hours: int
    ) -> list[dict[str, Any]]:
        return await self._cached_fetch(
            project,
            hours,
            self._agent_usage_cache,
            lambda h: self._clients[project.slug].fetch_agent_usage_window(h),
        )

    async def backend_trend(
        self, slug: str | None, hours: int, backend: BackendKind
    ) -> list[dict[str, Any]]:
        """Return the cost trend for a backend, merged across selected projects.

        Window-accurate; time-bucket granularity scales with the window.
        """
        parts: list[dict[str, dict[str, float]]] = []
        for p in self._projects(slug):
            cost: dict[str, dict[str, float]] = await self._safe_project_fetch(
                p,
                lambda: self._backend_cost(p, hours),  # noqa: B023
                "backend-cost",
                {},
            )
            parts.append(cost)
        return backend_cost_series(parts, backend)

    async def trend(
        self, slug: str | None, hours: int, buckets: int = 48
    ) -> list[dict[str, Any]]:
        """Return a cost trend series across the window."""
        gathered = await self._gather(slug, hours)
        all_traces = [t for _, traces in gathered for t in traces]
        return cost_trend(all_traces, hours, buckets)

    async def highlights(
        self, slug: str | None, hours: int, backend: str = "all"
    ) -> dict[str, Any]:
        """Return dashboard highlights: top trace, session, and summary stats.

        When *backend* is not ``"all"``, traces are filtered to only those
        whose name appears in the agent-usage rows for that backend, keeping
        the highlights consistent with the backend selector.
        """
        gathered = await self._gather(slug, hours)
        all_traces = [t for _, traces in gathered for t in traces]
        if backend != "all":
            agent_rows = await self._gather_list_results(slug, hours, self._agent_usage)
            backend_names: set[str] = {
                r["name"] for r in agent_rows if r.get("backend") == backend
            }
            all_traces = [t for t in all_traces if t.name in backend_names]
        return {
            "most_expensive_trace": most_expensive_trace(all_traces),
            "most_expensive_session": most_expensive_session(all_traces),
            "session_cost_scope": backend if backend != "all" else "all",
        }

last_updated property

UTC datetime of the most recent cache refresh, or None when cold.

__init__(config, registry_client)

Initialise the service with config and a registry client.

Starts with an empty project/client map — call :meth:refresh_projects during startup to populate from the registry.

Source code in src/robotsix_cost_monitor/service/core.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def __init__(self, config: Config, registry_client: RegistryClient) -> None:
    """Initialise the service with config and a registry client.

    Starts with an empty project/client map — call :meth:`refresh_projects`
    during startup to populate from the registry.
    """
    self.config = config
    self._registry = registry_client
    self._project_map: dict[str, RegistryProject] = {}
    self._clients: dict[str, LangfuseClient] = {}
    ttl = self.config.settings.cache_ttl_seconds
    self._last_updated: datetime | None = None
    self._caches: list[TTLCache[Any, Any]] = []
    on_refresh = self._touch_last_updated

    def _mk[T](t: type[T]) -> TTLCache[Any, T]:
        c = TTLCache[Any, T](ttl, on_refresh=on_refresh)
        self._caches.append(c)
        return c

    # cache: (slug, hours) -> (traces, monotonic_deadline)
    self._cache = _mk(list[LangfuseTrace])
    # cache: (slug, hours) -> (per-model usage rows, monotonic_deadline)
    self._model_cache = _mk(list[dict[str, Any]])
    # cache: (slug, hours) -> ({time_bucket -> {backend -> cost}}, deadline)
    self._backend_cache = _mk(dict[str, dict[str, float]])
    # cache: (slug, hours) -> (per-(stage, backend) rows, monotonic_deadline)
    self._agent_usage_cache = _mk(list[dict[str, Any]])
    # cache: (slug, hours) -> (trace_count, monotonic_deadline)
    self._trace_count_cache = _mk(int)

backend_trend(slug, hours, backend) async

Return the cost trend for a backend, merged across selected projects.

Window-accurate; time-bucket granularity scales with the window.

Source code in src/robotsix_cost_monitor/service/core.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
async def backend_trend(
    self, slug: str | None, hours: int, backend: BackendKind
) -> list[dict[str, Any]]:
    """Return the cost trend for a backend, merged across selected projects.

    Window-accurate; time-bucket granularity scales with the window.
    """
    parts: list[dict[str, dict[str, float]]] = []
    for p in self._projects(slug):
        cost: dict[str, dict[str, float]] = await self._safe_project_fetch(
            p,
            lambda: self._backend_cost(p, hours),  # noqa: B023
            "backend-cost",
            {},
        )
        parts.append(cost)
    return backend_cost_series(parts, backend)

by_agent(slug, hours, backend='all') async

Cost by trace name (stage/agent), merged across selected projects.

When backend is "all" (default), uses trace-level cost (aggregate_by_name) — unchanged from the original behavior.

When a specific backend is selected, uses per-(stage, backend) observation-metrics so that each stage's cost is attributed to the backend(s) it actually used.

Source code in src/robotsix_cost_monitor/service/core.py
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
async def by_agent(
    self, slug: str | None, hours: int, backend: str = "all"
) -> list[dict[str, Any]]:
    """Cost by trace name (stage/agent), merged across selected projects.

    When ``backend`` is ``"all"`` (default), uses trace-level cost
    (``aggregate_by_name``) — unchanged from the original behavior.

    When a specific backend is selected, uses per-(stage, backend)
    observation-metrics so that each stage's cost is attributed to the
    backend(s) it actually used.
    """
    if backend == "all":
        gathered = await self._gather(slug, hours)
        all_traces = [t for _, traces in gathered for t in traces]
        return aggregate_by_name(all_traces)

    all_rows = await self._gather_list_results(slug, hours, self._agent_usage)
    return aggregate_by_name_backend(all_rows, backend)

by_model(slug, hours) async

Cost + token usage by model, merged across selected projects.

Window-accurate (see :meth:LangfuseClient.fetch_model_usage_window).

Source code in src/robotsix_cost_monitor/service/core.py
356
357
358
359
360
361
362
async def by_model(self, slug: str | None, hours: int) -> list[dict[str, Any]]:
    """Cost + token usage by model, merged across selected projects.

    Window-accurate (see :meth:`LangfuseClient.fetch_model_usage_window`).
    """
    all_rows = await self._gather_list_results(slug, hours, self._model_usage)
    return merge_model_costs([all_rows])

components()

Return discovered projects grouped by owning component.

Insertion order follows the registry, so the dashboard's component list is stable across refreshes. Projects whose component is unknown are grouped under their own slug rather than dropped.

Source code in src/robotsix_cost_monitor/service/core.py
140
141
142
143
144
145
146
147
148
149
150
def components(self) -> dict[str, list[RegistryProject]]:
    """Return discovered projects grouped by owning component.

    Insertion order follows the registry, so the dashboard's component list
    is stable across refreshes.  Projects whose component is unknown are
    grouped under their own slug rather than dropped.
    """
    out: dict[str, list[RegistryProject]] = {}
    for p in self._project_map.values():
        out.setdefault(p.component_id or p.slug, []).append(p)
    return out

highlights(slug, hours, backend='all') async

Return dashboard highlights: top trace, session, and summary stats.

When backend is not "all", traces are filtered to only those whose name appears in the agent-usage rows for that backend, keeping the highlights consistent with the backend selector.

Source code in src/robotsix_cost_monitor/service/core.py
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
async def highlights(
    self, slug: str | None, hours: int, backend: str = "all"
) -> dict[str, Any]:
    """Return dashboard highlights: top trace, session, and summary stats.

    When *backend* is not ``"all"``, traces are filtered to only those
    whose name appears in the agent-usage rows for that backend, keeping
    the highlights consistent with the backend selector.
    """
    gathered = await self._gather(slug, hours)
    all_traces = [t for _, traces in gathered for t in traces]
    if backend != "all":
        agent_rows = await self._gather_list_results(slug, hours, self._agent_usage)
        backend_names: set[str] = {
            r["name"] for r in agent_rows if r.get("backend") == backend
        }
        all_traces = [t for t in all_traces if t.name in backend_names]
    return {
        "most_expensive_trace": most_expensive_trace(all_traces),
        "most_expensive_session": most_expensive_session(all_traces),
        "session_cost_scope": backend if backend != "all" else "all",
    }

invalidate_all()

Clear every internal cache so the next request fetches fresh data.

Source code in src/robotsix_cost_monitor/service/core.py
101
102
103
104
105
def invalidate_all(self) -> None:
    """Clear every internal cache so the next request fetches fresh data."""
    for c in self._caches:
        c.invalidate()
    self._last_updated = None

projects()

Return every discovered project, in registry order.

Source code in src/robotsix_cost_monitor/service/core.py
136
137
138
def projects(self) -> list[RegistryProject]:
    """Return every discovered project, in registry order."""
    return list(self._project_map.values())

refresh_projects() async

Query the registry and rebuild the project/client map.

Best-effort: on failure the existing project list is kept unchanged.

Source code in src/robotsix_cost_monitor/service/core.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
async def refresh_projects(self) -> None:
    """Query the registry and rebuild the project/client map.

    Best-effort: on failure the existing project list is kept unchanged.
    """
    try:
        registry_projects = await self._registry.fetch_projects()
    except Exception:
        logger.warning("refresh_projects: registry fetch failed")
        return
    if not registry_projects:
        logger.warning("refresh_projects: registry returned no projects")
        return
    self._project_map = {p.slug: p for p in registry_projects}
    self._clients = {
        p.slug: LangfuseClient(
            public_key=p.langfuse_public_key,
            secret_key=p.langfuse_secret_key.get_secret_value(),
            base_url=p.langfuse_base_url,
        )
        for p in registry_projects
    }
    self.invalidate_all()
    logger.info(
        "refresh_projects: discovered %d project(s) across %d component(s)",
        len(self._project_map),
        len(self.components()),
    )

summary(slug, hours, backend='all') async

Per-project totals + the aggregate, for the window.

Cost is observation-based (the same window-accurate metrics source as the by-model / by-backend breakdowns), so the headline total, the per-model rows, and the per-backend totals all reconcile — a backend can never exceed the total. trace_count comes from a server-side view=traces count metric (not by paging every trace), so this stays fast.

When backend is not "all", only observation rows attributed to that backend are counted, so the per-component rollup and total reflect costs for the selected backend alone.

Source code in src/robotsix_cost_monitor/service/core.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
async def summary(
    self, slug: str | None, hours: int, backend: str = "all"
) -> dict[str, Any]:
    """Per-project totals + the aggregate, for the window.

    Cost is observation-based (the same window-accurate metrics source as the
    by-model / by-backend breakdowns), so the headline total, the per-model
    rows, and the per-backend totals all reconcile — a backend can never
    exceed the total. ``trace_count`` comes from a server-side ``view=traces``
    count metric (not by paging every trace), so this stays fast.

    When *backend* is not ``"all"``, only observation rows attributed to that
    backend are counted, so the per-component rollup and total reflect costs
    for the selected backend alone.
    """
    per_project: list[dict[str, Any]] = []
    total = 0.0
    for p in self._projects(slug):
        models: list[dict[str, Any]] = await self._safe_project_fetch(
            p,
            lambda: self._model_usage(p, hours),  # noqa: B023
            "model-usage",
            [],
        )
        if backend != "all":
            models = [m for m in models if m.get("backend") == backend]
        trace_count: int = await self._safe_project_fetch(
            p,
            lambda: self._trace_count(p, hours),  # noqa: B023
            "trace-count",
            0,
        )
        cost = round(sum(m["cost"] for m in models), 6)
        total += cost
        per_project.append(
            {
                "name": p.name,
                "slug": p.slug,
                "component": p.component_id,
                "cost": cost,
                "trace_count": trace_count,
            }
        )
    total = round(total, 6)
    by_component: dict[str, dict[str, Any]] = {}
    for row in per_project:
        agg = by_component.setdefault(
            str(row["component"] or row["slug"]),
            {
                "component": row["component"] or row["slug"],
                "cost": 0.0,
                "trace_count": 0,
                "projects": [],
            },
        )
        agg["cost"] = round(agg["cost"] + float(row["cost"]), 6)
        agg["trace_count"] += int(row["trace_count"])
        agg["projects"].append(row)
    components = sorted(
        by_component.values(), key=lambda c: float(c["cost"]), reverse=True
    )
    if backend != "all":
        components = [c for c in components if c["cost"] > 0]
    return {
        "window_hours": hours,
        "total_cost": total,
        "projects": per_project,
        "components": components,
    }

trend(slug, hours, buckets=48) async

Return a cost trend series across the window.

Source code in src/robotsix_cost_monitor/service/core.py
402
403
404
405
406
407
408
async def trend(
    self, slug: str | None, hours: int, buckets: int = 48
) -> list[dict[str, Any]]:
    """Return a cost trend series across the window."""
    gathered = await self._gather(slug, hours)
    all_traces = [t for _, traces in gathered for t in traces]
    return cost_trend(all_traces, hours, buckets)

MillAPIError

Bases: RuntimeError

The mill board API could not be queried (network or HTTP error).

Raised instead of returning an empty result so callers can tell a failed check apart from a successful check that found nothing. Callers must treat this as "unknown": preserve the last known stuck-ticket state rather than overwriting it with an empty list.

Source code in src/robotsix_cost_monitor/clients/mill.py
22
23
24
25
26
27
28
29
class MillAPIError(RuntimeError):
    """The mill board API could not be queried (network or HTTP error).

    Raised instead of returning an empty result so callers can tell a
    *failed* check apart from a successful check that found nothing.
    Callers must treat this as "unknown": preserve the last known
    stuck-ticket state rather than overwriting it with an empty list.
    """

MillClient dataclass

HTTP client for the robotsix-mill board API.

Used by the stuck-ticket background loop to periodically query the mill's GET /tickets endpoint and identify tickets that have been in a non-terminal state longer than the configured threshold.

Source code in src/robotsix_cost_monitor/clients/mill.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
@dataclass
class MillClient:
    """HTTP client for the robotsix-mill board API.

    Used by the stuck-ticket background loop to periodically query the
    mill's ``GET /tickets`` endpoint and identify tickets that have been
    in a non-terminal state longer than the configured threshold.
    """

    settings: Settings
    _http: httpx.AsyncClient | None = field(default=None, repr=False, init=False)

    def __post_init__(self) -> None:
        """Initialise lazy HTTP client holder to None."""
        self._http = None

    @property
    def base_url(self) -> str:
        """Return the mill API base URL with trailing slash stripped."""
        return self.settings.mill_base_url.rstrip("/")

    @property
    def _api_key(self) -> str:
        """Return the effective mill API key (env var or config)."""
        return resolve_mill_api_key(self.settings)

    @property
    def _threshold_hours(self) -> int:
        """Return the stuck-ticket threshold in hours."""
        return self.settings.stuck_ticket_threshold_hours

    @property
    def _enabled(self) -> bool:
        """Return True when stuck-ticket detection is configured and active."""
        return bool(self.base_url) and self._threshold_hours > 0

    async def _client(self) -> httpx.AsyncClient:
        """Lazy-init the HTTP client so it's not created at import time."""
        if self._http is None:
            self._http = httpx.AsyncClient(timeout=30.0)
        return self._http

    async def fetch_stuck_tickets(self) -> list[StuckTicket]:
        """Query the mill for tickets stuck in non-terminal states.

        Calls ``GET /tickets`` (``include_closed=false`` is the default,
        so terminal states are already excluded).  Each returned ticket
        whose ``updated_at`` is older than the configured threshold is
        flagged as stuck.

        Returns an empty list when detection is disabled.  Raises
        :class:`MillAPIError` when the mill API is unreachable, returns
        an error status, or returns an unexpected payload — the caller
        must then keep the previous results instead of treating the
        check as a clean empty result.
        """
        if not self._enabled:
            return []

        threshold = timedelta(hours=self._threshold_hours)
        cutoff = datetime.now(UTC) - threshold

        url = f"{self.base_url}/tickets"
        headers = {"X-API-Key": self._api_key} if self._api_key else {}
        try:
            client = await self._client()
            retry = RetryClient(client)
            resp = await retry.get(url, headers=headers)
            resp.raise_for_status()
            tickets = resp.json()
        except Exception as exc:
            logger.exception(
                "mill stuck-ticket check failed — keeping previous results"
            )
            raise MillAPIError(
                "mill board API unavailable — previous stuck-ticket results kept"
            ) from exc

        stuck: list[StuckTicket] = []
        if not isinstance(tickets, list):
            logger.warning("mill /tickets returned non-list payload: %s", type(tickets))
            raise MillAPIError(
                "mill board API returned an unexpected payload — "
                "previous stuck-ticket results kept"
            )

        for raw in tickets:
            if not isinstance(raw, dict):
                continue
            state = raw.get("state", "")
            if state not in NON_TERMINAL_STATES:
                continue
            updated_raw = raw.get("updated_at", "")
            try:
                updated = datetime.fromisoformat(updated_raw.replace("Z", "+00:00"))
            except ValueError, TypeError:
                continue
            if updated > cutoff:
                continue
            stuck_for = (datetime.now(UTC) - updated).total_seconds() / 3600.0
            stuck.append(
                StuckTicket(
                    ticket_id=raw.get("id", ""),
                    title=raw.get("title", ""),
                    state=state,
                    kind=raw.get("kind", ""),
                    source=raw.get("source", ""),
                    created_at=raw.get("created_at", ""),
                    updated_at=updated_raw,
                    stuck_for_hours=round(stuck_for, 1),
                )
            )
        return stuck

    async def close(self) -> None:
        """Release the underlying HTTP client."""
        if self._http is not None:
            await self._http.aclose()
            self._http = None

base_url property

Return the mill API base URL with trailing slash stripped.

__post_init__()

Initialise lazy HTTP client holder to None.

Source code in src/robotsix_cost_monitor/clients/mill.py
84
85
86
def __post_init__(self) -> None:
    """Initialise lazy HTTP client holder to None."""
    self._http = None

close() async

Release the underlying HTTP client.

Source code in src/robotsix_cost_monitor/clients/mill.py
186
187
188
189
190
async def close(self) -> None:
    """Release the underlying HTTP client."""
    if self._http is not None:
        await self._http.aclose()
        self._http = None

fetch_stuck_tickets() async

Query the mill for tickets stuck in non-terminal states.

Calls GET /tickets (include_closed=false is the default, so terminal states are already excluded). Each returned ticket whose updated_at is older than the configured threshold is flagged as stuck.

Returns an empty list when detection is disabled. Raises :class:MillAPIError when the mill API is unreachable, returns an error status, or returns an unexpected payload — the caller must then keep the previous results instead of treating the check as a clean empty result.

Source code in src/robotsix_cost_monitor/clients/mill.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
async def fetch_stuck_tickets(self) -> list[StuckTicket]:
    """Query the mill for tickets stuck in non-terminal states.

    Calls ``GET /tickets`` (``include_closed=false`` is the default,
    so terminal states are already excluded).  Each returned ticket
    whose ``updated_at`` is older than the configured threshold is
    flagged as stuck.

    Returns an empty list when detection is disabled.  Raises
    :class:`MillAPIError` when the mill API is unreachable, returns
    an error status, or returns an unexpected payload — the caller
    must then keep the previous results instead of treating the
    check as a clean empty result.
    """
    if not self._enabled:
        return []

    threshold = timedelta(hours=self._threshold_hours)
    cutoff = datetime.now(UTC) - threshold

    url = f"{self.base_url}/tickets"
    headers = {"X-API-Key": self._api_key} if self._api_key else {}
    try:
        client = await self._client()
        retry = RetryClient(client)
        resp = await retry.get(url, headers=headers)
        resp.raise_for_status()
        tickets = resp.json()
    except Exception as exc:
        logger.exception(
            "mill stuck-ticket check failed — keeping previous results"
        )
        raise MillAPIError(
            "mill board API unavailable — previous stuck-ticket results kept"
        ) from exc

    stuck: list[StuckTicket] = []
    if not isinstance(tickets, list):
        logger.warning("mill /tickets returned non-list payload: %s", type(tickets))
        raise MillAPIError(
            "mill board API returned an unexpected payload — "
            "previous stuck-ticket results kept"
        )

    for raw in tickets:
        if not isinstance(raw, dict):
            continue
        state = raw.get("state", "")
        if state not in NON_TERMINAL_STATES:
            continue
        updated_raw = raw.get("updated_at", "")
        try:
            updated = datetime.fromisoformat(updated_raw.replace("Z", "+00:00"))
        except ValueError, TypeError:
            continue
        if updated > cutoff:
            continue
        stuck_for = (datetime.now(UTC) - updated).total_seconds() / 3600.0
        stuck.append(
            StuckTicket(
                ticket_id=raw.get("id", ""),
                title=raw.get("title", ""),
                state=state,
                kind=raw.get("kind", ""),
                source=raw.get("source", ""),
                created_at=raw.get("created_at", ""),
                updated_at=updated_raw,
                stuck_for_hours=round(stuck_for, 1),
            )
        )
    return stuck

ProjectWindow

Bases: NamedTuple

Resolved project slug and effective window hours for a request.

Source code in src/robotsix_cost_monitor/routes/__init__.py
50
51
52
53
54
class ProjectWindow(NamedTuple):
    """Resolved project slug and effective window hours for a request."""

    project: str
    hours: int

_paginate(items, offset, limit)

Wrap a full result set in a standard offset/limit pagination envelope.

Source code in src/robotsix_cost_monitor/routes/__init__.py
258
259
260
261
262
263
264
265
266
267
def _paginate(items: list[dict[str, Any]], offset: int, limit: int) -> dict[str, Any]:
    """Wrap a full result set in a standard offset/limit pagination envelope."""
    total = len(items)
    return {
        "items": items[offset : offset + limit],
        "total": total,
        "offset": offset,
        "limit": limit,
        "has_more": offset + limit < total,
    }

_window(hours, config)

Resolve the effective window: fall back to the default, clamp to the max.

Source code in src/robotsix_cost_monitor/routes/__init__.py
64
65
66
def _window(hours: int, config: Config) -> int:
    """Resolve the effective window: fall back to the default, clamp to the max."""
    return min(hours or config.settings.default_window_hours, MAX_WINDOW_HOURS)

backend_trend(backend=Query('all'), pw=Depends(project_window), service=Depends(get_service)) async

GET /api/backend-trend — cost trend per backend for a project and window.

Source code in src/robotsix_cost_monitor/routes/__init__.py
370
371
372
373
374
375
376
377
@router.get("/api/backend-trend")
async def backend_trend(
    backend: str = Query("all"),
    pw: ProjectWindow = Depends(project_window),
    service: CostService = Depends(get_service),
) -> list[dict[str, Any]]:
    """GET /api/backend-trend — cost trend per backend for a project and window."""
    return await service.backend_trend(pw.project, pw.hours, cast(BackendKind, backend))

by_agent(backend=Query('all'), offset=Query(0, ge=0), limit=Query(100, ge=1, le=1000), pw=Depends(project_window), service=Depends(get_service)) async

GET /api/by-agent — cost breakdown by agent name (paginated).

Source code in src/robotsix_cost_monitor/routes/__init__.py
345
346
347
348
349
350
351
352
353
354
355
@router.get("/api/by-agent")
async def by_agent(
    backend: str = Query("all"),
    offset: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=1000),
    pw: ProjectWindow = Depends(project_window),
    service: CostService = Depends(get_service),
) -> dict[str, Any]:
    """GET /api/by-agent — cost breakdown by agent name (paginated)."""
    results = await service.by_agent(pw.project, pw.hours, backend)
    return _paginate(results, offset, limit)

by_model(offset=Query(0, ge=0), limit=Query(100, ge=1, le=1000), pw=Depends(project_window), service=Depends(get_service)) async

GET /api/by-model — cost breakdown by model (paginated).

Source code in src/robotsix_cost_monitor/routes/__init__.py
358
359
360
361
362
363
364
365
366
367
@router.get("/api/by-model")
async def by_model(
    offset: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=1000),
    pw: ProjectWindow = Depends(project_window),
    service: CostService = Depends(get_service),
) -> dict[str, Any]:
    """GET /api/by-model — cost breakdown by model (paginated)."""
    results = await service.by_model(pw.project, pw.hours)
    return _paginate(results, offset, limit)

chat_skill()

GET /chat-skill — robotsix-chat agent skill document (Markdown).

Source code in src/robotsix_cost_monitor/routes/__init__.py
252
253
254
255
@router.get("/chat-skill", response_class=PlainTextResponse)
def chat_skill() -> str:
    """GET /chat-skill — robotsix-chat agent skill document (Markdown)."""
    return _CHAT_SKILL

components(offset=Query(0, ge=0), limit=Query(100, ge=1, le=1000), service=Depends(get_service)) async

GET /api/components — components and the projects they own (paginated).

Drives the dashboard's selector. Everything here comes from registry discovery, so a newly onboarded component with a Langfuse config appears without any change to this service.

Source code in src/robotsix_cost_monitor/routes/__init__.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
@router.get("/api/components")
async def components(
    offset: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=1000),
    service: CostService = Depends(get_service),
) -> dict[str, Any]:
    """GET /api/components — components and the projects they own (paginated).

    Drives the dashboard's selector.  Everything here comes from registry
    discovery, so a newly onboarded component with a Langfuse config appears
    without any change to this service.
    """
    results = [
        {
            "component": component_id,
            "projects": [
                {
                    "name": p.name,
                    "slug": p.slug,
                    "reconcilable": bool(p.openrouter_key),
                }
                for p in projects_
            ],
        }
        for component_id, projects_ in service.components().items()
    ]
    return _paginate(results, offset, limit)

get_config(request)

Return the :class:Config stored on app.state during startup.

Source code in src/robotsix_cost_monitor/routes/__init__.py
35
36
37
def get_config(request: Request) -> Config:
    """Return the :class:`Config` stored on ``app.state`` during startup."""
    return request.app.state.config  # type: ignore[no-any-return]

get_service(request)

Return the :class:CostService stored on app.state during startup.

Source code in src/robotsix_cost_monitor/routes/__init__.py
40
41
42
def get_service(request: Request) -> CostService:
    """Return the :class:`CostService` stored on ``app.state`` during startup."""
    return request.app.state.service  # type: ignore[no-any-return]

highlights(backend=Query('all'), pw=Depends(project_window), service=Depends(get_service)) async

GET /api/highlights — most expensive trace and session for the window.

Accepts an optional backend query parameter to filter results to a specific backend (e.g. openrouter). Defaults to all.

Source code in src/robotsix_cost_monitor/routes/__init__.py
390
391
392
393
394
395
396
397
398
399
400
401
402
403
@router.get("/api/highlights")
async def highlights(
    backend: str = Query("all"),
    pw: ProjectWindow = Depends(project_window),
    service: CostService = Depends(get_service),
) -> dict[str, Any]:
    """GET /api/highlights — most expensive trace and session for the window.

    Accepts an optional ``backend`` query parameter to filter results to
    a specific backend (e.g. ``openrouter``).  Defaults to ``all``.
    """
    result = await service.highlights(pw.project, pw.hours, backend)
    result["effective_hours"] = pw.hours
    return result

index()

GET / — serve the main dashboard HTML page.

Source code in src/robotsix_cost_monitor/routes/__init__.py
459
460
461
462
@router.get("/", response_class=HTMLResponse)
def index() -> str:
    """GET / — serve the main dashboard HTML page."""
    return (_WEB / "index.html").read_text()

load_last_reconcile(settings=None)

Return the last stored reconcile result (for the banner); empty when none yet.

Source code in src/robotsix_cost_monitor/reconcile.py
302
303
304
305
306
307
def load_last_reconcile(settings: Settings | None = None) -> dict[str, Any]:
    """Return the last stored reconcile result (for the banner); empty when none yet."""
    return safe_load_json(
        _last_path(settings),
        {"generated_at": None, "status": "unknown", "results": []},
    )

project_window(response, project=Depends(resolve_project), hours=Depends(resolve_hours))

Composite dependency: validated project slug + resolved window hours.

Advertises the resolved window on every windowed endpoint via the X-Effective-Hours response header, so a caller can always tell which window was actually used — the requested value, the config default (when hours is omitted), or the clamped ceiling — without inferring it from the payload. Dict-shaped endpoints additionally echo it in-body as effective_hours.

Source code in src/robotsix_cost_monitor/routes/__init__.py
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def project_window(
    response: Response,
    project: str = Depends(resolve_project),
    hours: int = Depends(resolve_hours),
) -> ProjectWindow:
    """Composite dependency: validated project slug + resolved window hours.

    Advertises the resolved window on every windowed endpoint via the
    ``X-Effective-Hours`` response header, so a caller can always tell which
    window was actually used — the requested value, the config default (when
    ``hours`` is omitted), or the clamped ceiling — without inferring it from
    the payload.  Dict-shaped endpoints additionally echo it in-body as
    ``effective_hours``.
    """
    response.headers["X-Effective-Hours"] = str(hours)
    return ProjectWindow(project=project, hours=hours)

projects(offset=Query(0, ge=0), limit=Query(100, ge=1, le=1000), service=Depends(get_service)) async

GET /api/projects — discovered projects with name and slug (paginated).

Source code in src/robotsix_cost_monitor/routes/__init__.py
270
271
272
273
274
275
276
277
278
279
280
281
@router.get("/api/projects")
async def projects(
    offset: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=1000),
    service: CostService = Depends(get_service),
) -> dict[str, Any]:
    """GET /api/projects — discovered projects with name and slug (paginated)."""
    results = [
        {"name": p.name, "slug": p.slug, "component": p.component_id}
        for p in service.projects()
    ]
    return _paginate(results, offset, limit)

reconcile(project=Query('all'), cfg=Depends(get_config), service=Depends(get_service)) async

GET /api/reconcile — reconcile OpenRouter usage against Langfuse traced costs.

Source code in src/robotsix_cost_monitor/routes/__init__.py
406
407
408
409
410
411
412
413
414
415
416
417
@router.get("/api/reconcile")
async def reconcile(
    project: str = Query("all"),
    cfg: Config = Depends(get_config),
    service: CostService = Depends(get_service),
) -> list[dict[str, Any]]:
    """GET /api/reconcile — reconcile OpenRouter usage against Langfuse traced costs."""
    if project == "all":
        out = await reconcile_all(cfg, service)
        return cast("list[dict[str, Any]]", out["results"])
    targets = service._projects(project)
    return [await reconcile_project(p, cfg.settings) for p in targets]

reconcile_all(config, service) async

Reconcile every project, persist the result, and return it.

The stored last.json powers the dashboard's warning banner and the /api/reconcile/last endpoint.

Source code in src/robotsix_cost_monitor/reconcile.py
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
async def reconcile_all(config: Config, service: CostService) -> dict[str, Any]:
    """Reconcile every project, persist the result, and return it.

    The stored ``last.json`` powers the dashboard's warning banner and the
    ``/api/reconcile/last`` endpoint.
    """
    reconcile_runs.inc()
    t0 = time.monotonic()
    projects = service.projects()
    results = [await reconcile_project(p, config.settings) for p in projects]
    reconcile_duration.set(time.monotonic() - t0)
    out: dict[str, Any] = {
        "generated_at": datetime.now(UTC).isoformat(),
        "status": reconcile_status(results),
        "tolerance_usd": config.settings.reconcile_tolerance_usd,
        "results": results,
    }
    _atomic_write_text(
        _last_path(config.settings),
        json.dumps(out, indent=2),
        root=_state_dir(config.settings),
    )
    return out

reconcile_last(cfg=Depends(get_config))

GET /api/reconcile/last — return the most recent reconciliation result.

Source code in src/robotsix_cost_monitor/routes/__init__.py
420
421
422
423
@router.get("/api/reconcile/last")
def reconcile_last(cfg: Config = Depends(get_config)) -> dict[str, Any]:
    """GET /api/reconcile/last — return the most recent reconciliation result."""
    return load_last_reconcile(cfg.settings)

reconcile_project(project, settings) async

Reconcile one project's OpenRouter spend vs Langfuse traced cost.

Snapshots the key's cumulative usage and diffs against the previous snapshot; compares the provider delta to the Langfuse traced cost over the same interval. Returns a status dict (also includes the remaining balance). The snapshot is updated on every call.

Source code in src/robotsix_cost_monitor/reconcile.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
async def reconcile_project(
    project: RegistryProject, settings: Settings
) -> dict[str, Any]:
    """Reconcile one project's OpenRouter spend vs Langfuse traced cost.

    Snapshots the key's cumulative usage and diffs against the previous
    snapshot; compares the provider delta to the Langfuse traced cost over the
    same interval. Returns a status dict (also includes the remaining
    balance). The snapshot is updated on every call.
    """
    now = datetime.now(UTC)
    result: dict[str, Any] = {
        "project": project.name,
        "slug": project.slug,
        "configured": bool(project.openrouter_key),
        "at": now.isoformat(),
    }
    if not project.openrouter_key:
        result["detail"] = "no openrouter_key configured for this project"
        return result

    try:
        from robotsix_llmio.openrouter import OpenRouterKeyCostSource
    except ImportError:
        result["error"] = "robotsix-llmio is not installed. Install it with: uv sync"
        return result

    orc = OpenRouterKeyCostSource(api_key=project.openrouter_key)

    # Per-KEY cumulative usage is the reconciliation basis (isolates this
    # consumer even when several keys share one OpenRouter account).
    async def _fetch_cumulative() -> float:
        ku = await asyncio.to_thread(orc.fetch_key_usage)
        return ku.usage

    cumulative_ = await _fetch_or_error(
        "OpenRouter", (ExternalServiceError,), _fetch_cumulative(), result
    )
    if cumulative_ is None:
        return result
    cumulative = cumulative_

    # Account-level remaining balance — informational only (shared balance pool).
    # Optional: a balance fetch failure must not fail the reconcile.
    with contextlib.suppress(Exception):
        result["balance"] = await _fetch_credits(project.openrouter_key)
        if (
            settings.low_balance_threshold_usd > 0
            and result["balance"]["remaining"] < settings.low_balance_threshold_usd
        ):
            result["low_balance"] = True
            logger.warning(
                "project %s: low balance — $%.2f remaining (threshold $%.2f)",
                project.name,
                result["balance"]["remaining"],
                settings.low_balance_threshold_usd,
            )

    prior = _load_snapshot(project.slug, settings)
    _save_snapshot(project.slug, cumulative, now, settings)

    if prior is None:
        result["detail"] = "first snapshot recorded — reconciliation on next run"
        return result

    prior_at = datetime.fromisoformat(prior["at"])
    interval_h = _hours_between(prior_at, now)
    provider_delta = round(cumulative - float(prior["cumulative"]), 6)

    lf = LangfuseClient(
        public_key=project.langfuse_public_key,
        secret_key=project.langfuse_secret_key.get_secret_value(),
        base_url=project.langfuse_base_url,
    )
    # Traced cost over the SAME interval as the provider delta (both since the
    # prior snapshot), so the two sides are comparable. Using a rounded ≥1h
    # window here made short intervals nonsensical (provider over minutes vs
    # traced over an hour).
    #
    # Compare like-for-like: OpenRouter's per-key spend only reconciles against
    # the *openrouter*-backend traced cost. Claude-SDK (level-3) traffic is
    # traced in Langfuse but billed by Anthropic, not OpenRouter — including it
    # made "traced" exceed "provider" by the Claude portion.
    by_backend_ = await _fetch_or_error(
        "Langfuse",
        (ExternalServiceError, httpx.HTTPError, json.JSONDecodeError),
        lf.fetch_cost_by_backend(interval_h),
        result,
    )
    if by_backend_ is None:
        return result
    by_backend = by_backend_

    logged = round(by_backend.get("openrouter", 0.0), 6)
    total_traced = round(sum(by_backend.values()), 6)

    drift = round(provider_delta - logged, 6)
    result.update(
        {
            "interval_hours": round(interval_h, 2),
            "provider_delta_usd": provider_delta,
            # OpenRouter-backend only — the value comparable to the provider side.
            "langfuse_cost_usd": logged,
            # All backends (incl. claude-sdk), for transparency.
            "langfuse_total_cost_usd": total_traced,
            "langfuse_cost_by_backend": {k: round(v, 6) for k, v in by_backend.items()},
            "drift_usd": drift,
            "within_tolerance": abs(drift) <= settings.reconcile_tolerance_usd,
            "tolerance_usd": settings.reconcile_tolerance_usd,
        }
    )
    return result

refresh_cache(service=Depends(get_service)) async

POST /api/refresh — invalidate all caches and force a fresh fetch.

The next dashboard request will block on a fresh Langfuse fetch (cold start), then subsequent requests within the TTL will be served from cache with stale-while-revalidate background refresh.

Source code in src/robotsix_cost_monitor/routes/__init__.py
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
@router.post("/api/refresh")
async def refresh_cache(
    service: CostService = Depends(get_service),
) -> dict[str, Any]:
    """POST /api/refresh — invalidate all caches and force a fresh fetch.

    The next dashboard request will block on a fresh Langfuse fetch (cold
    start), then subsequent requests within the TTL will be served from
    cache with stale-while-revalidate background refresh.
    """
    service.invalidate_all()
    return {
        "status": "ok",
        "message": "Cache invalidated — next request will fetch fresh data.",
    }

resolve_hours(hours=Query(0, ge=0, le=MAX_WINDOW_HOURS), cfg=Depends(get_config))

Return hours (clamped to :data:MAX_WINDOW_HOURS), or the config default.

Source code in src/robotsix_cost_monitor/routes/__init__.py
76
77
78
79
80
def resolve_hours(
    hours: int = Query(0, ge=0, le=MAX_WINDOW_HOURS), cfg: Config = Depends(get_config)
) -> int:
    """Return *hours* (clamped to :data:`MAX_WINDOW_HOURS`), or the config default."""
    return _window(hours, cfg)

resolve_project(project=Query('all'), cfg=Depends(get_config))

Validate and return the project slug query parameter.

Source code in src/robotsix_cost_monitor/routes/__init__.py
69
70
71
72
73
def resolve_project(
    project: str = Query("all"), cfg: Config = Depends(get_config)
) -> str:
    """Validate and return the project slug query parameter."""
    return project

settings_page()

GET /settings — serve the settings page (shared config panel).

Source code in src/robotsix_cost_monitor/routes/__init__.py
465
466
467
468
@router.get("/settings", response_class=HTMLResponse)
def settings_page() -> str:
    """GET /settings — serve the settings page (shared config panel)."""
    return (_WEB / "settings.html").read_text()

stuck_tickets(request) async

GET /api/stuck-tickets — return tickets stuck in non-terminal states.

Fetches fresh results from the mill board on every call. Returns an empty list when stuck-ticket detection is disabled (no mill_base_url or stuck_ticket_threshold_hours = 0). Returns 503 when the mill board API is unreachable — the caller must not treat that as "no stuck tickets".

Source code in src/robotsix_cost_monitor/routes/__init__.py
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
@router.get("/api/stuck-tickets")
async def stuck_tickets(request: Request) -> list[dict[str, Any]]:
    """GET /api/stuck-tickets — return tickets stuck in non-terminal states.

    Fetches fresh results from the mill board on every call.  Returns an
    empty list when stuck-ticket detection is disabled (no mill_base_url
    or stuck_ticket_threshold_hours = 0).  Returns 503 when the mill
    board API is unreachable — the caller must not treat that as "no
    stuck tickets".
    """
    mill: MillClient = request.app.state.mill
    try:
        stuck = await mill.fetch_stuck_tickets()
    except MillAPIError:
        raise HTTPException(
            status_code=503,
            detail="mill board API unavailable; stuck-ticket state unknown",
        ) from None
    return [
        {
            "ticket_id": t.ticket_id,
            "title": t.title,
            "state": t.state,
            "kind": t.kind,
            "source": t.source,
            "created_at": t.created_at,
            "updated_at": t.updated_at,
            "stuck_for_hours": t.stuck_for_hours,
        }
        for t in stuck
    ]

summary(backend=Query('all'), pw=Depends(project_window), service=Depends(get_service)) async

GET /api/summary — total cost and per-project totals for the window.

Source code in src/robotsix_cost_monitor/routes/__init__.py
313
314
315
316
317
318
319
320
321
322
323
324
325
@router.get("/api/summary")
async def summary(
    backend: str = Query("all"),
    pw: ProjectWindow = Depends(project_window),
    service: CostService = Depends(get_service),
) -> dict[str, Any]:
    """GET /api/summary — total cost and per-project totals for the window."""
    result = await service.summary(pw.project, pw.hours, backend)
    result["effective_hours"] = pw.hours
    lu = service.last_updated
    if lu is not None:
        result["last_updated"] = lu.isoformat()
    return result

trend(buckets=Query(48, ge=1, le=200), pw=Depends(project_window), service=Depends(get_service)) async

GET /api/trend — cost trend series bucketed by time for a project and window.

Source code in src/robotsix_cost_monitor/routes/__init__.py
380
381
382
383
384
385
386
387
@router.get("/api/trend")
async def trend(
    buckets: int = Query(48, ge=1, le=200),
    pw: ProjectWindow = Depends(project_window),
    service: CostService = Depends(get_service),
) -> list[dict[str, Any]]:
    """GET /api/trend — cost trend series bucketed by time for a project and window."""
    return await service.trend(pw.project, pw.hours, buckets)

robotsix_cost_monitor.service

Service layer: cross-project cost aggregation with a small TTL cache.

The implementation lives in :mod:robotsix_cost_monitor.service.core; this package re-exports its public names so from robotsix_cost_monitor.service import CostService keeps working.

DASHBOARD_WINDOW_PRESETS = (1, 6, 24, 168) module-attribute

__all__ = ['DASHBOARD_WINDOW_PRESETS', 'CostService'] module-attribute

CostService

Cross-project cost aggregation service with per-window TTL cache.

All five internal caches share a single :attr:last_updated timestamp (the youngest refresh across all caches) so the dashboard can display data freshness.

Source code in src/robotsix_cost_monitor/service/core.py
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
class CostService:
    """Cross-project cost aggregation service with per-window TTL cache.

    All five internal caches share a single :attr:`last_updated` timestamp
    (the youngest refresh across *all* caches) so the dashboard can display
    data freshness.
    """

    def __init__(self, config: Config, registry_client: RegistryClient) -> None:
        """Initialise the service with config and a registry client.

        Starts with an empty project/client map — call :meth:`refresh_projects`
        during startup to populate from the registry.
        """
        self.config = config
        self._registry = registry_client
        self._project_map: dict[str, RegistryProject] = {}
        self._clients: dict[str, LangfuseClient] = {}
        ttl = self.config.settings.cache_ttl_seconds
        self._last_updated: datetime | None = None
        self._caches: list[TTLCache[Any, Any]] = []
        on_refresh = self._touch_last_updated

        def _mk[T](t: type[T]) -> TTLCache[Any, T]:
            c = TTLCache[Any, T](ttl, on_refresh=on_refresh)
            self._caches.append(c)
            return c

        # cache: (slug, hours) -> (traces, monotonic_deadline)
        self._cache = _mk(list[LangfuseTrace])
        # cache: (slug, hours) -> (per-model usage rows, monotonic_deadline)
        self._model_cache = _mk(list[dict[str, Any]])
        # cache: (slug, hours) -> ({time_bucket -> {backend -> cost}}, deadline)
        self._backend_cache = _mk(dict[str, dict[str, float]])
        # cache: (slug, hours) -> (per-(stage, backend) rows, monotonic_deadline)
        self._agent_usage_cache = _mk(list[dict[str, Any]])
        # cache: (slug, hours) -> (trace_count, monotonic_deadline)
        self._trace_count_cache = _mk(int)

    def _touch_last_updated(self) -> None:
        """Record the current wall-clock time as the last cache refresh."""
        self._last_updated = datetime.now(UTC)

    @property
    def last_updated(self) -> datetime | None:
        """UTC datetime of the most recent cache refresh, or ``None`` when cold."""
        return self._last_updated

    def invalidate_all(self) -> None:
        """Clear every internal cache so the next request fetches fresh data."""
        for c in self._caches:
            c.invalidate()
        self._last_updated = None

    async def refresh_projects(self) -> None:
        """Query the registry and rebuild the project/client map.

        Best-effort: on failure the existing project list is kept unchanged.
        """
        try:
            registry_projects = await self._registry.fetch_projects()
        except Exception:
            logger.warning("refresh_projects: registry fetch failed")
            return
        if not registry_projects:
            logger.warning("refresh_projects: registry returned no projects")
            return
        self._project_map = {p.slug: p for p in registry_projects}
        self._clients = {
            p.slug: LangfuseClient(
                public_key=p.langfuse_public_key,
                secret_key=p.langfuse_secret_key.get_secret_value(),
                base_url=p.langfuse_base_url,
            )
            for p in registry_projects
        }
        self.invalidate_all()
        logger.info(
            "refresh_projects: discovered %d project(s) across %d component(s)",
            len(self._project_map),
            len(self.components()),
        )

    def projects(self) -> list[RegistryProject]:
        """Return every discovered project, in registry order."""
        return list(self._project_map.values())

    def components(self) -> dict[str, list[RegistryProject]]:
        """Return discovered projects grouped by owning component.

        Insertion order follows the registry, so the dashboard's component list
        is stable across refreshes.  Projects whose component is unknown are
        grouped under their own slug rather than dropped.
        """
        out: dict[str, list[RegistryProject]] = {}
        for p in self._project_map.values():
            out.setdefault(p.component_id or p.slug, []).append(p)
        return out

    def _projects(self, slug: str | None) -> list[RegistryProject]:
        """Resolve a selector to the projects it covers.

        Accepts ``"all"``/empty (everything), a **component id** (every project
        that component owns), or a single **project slug**.  Resolving both
        levels here is what lets every endpoint be component-aware without any
        per-endpoint or per-component code.

        Project slugs win over component ids on collision: a project is the
        more specific thing, and the single-project component case (where the
        two names coincide) resolves identically either way.
        """
        if not slug or slug == "all":
            return list(self._project_map.values())
        if (p := self._project_map.get(slug)) is not None:
            return [p]
        result = [q for q in self._project_map.values() if q.component_id == slug]
        if not result:
            raise ProjectNotFoundError(
                f"Project '{slug}' not found — no configured project or "
                f"component matches this slug."
            )
        return result

    async def _safe_project_fetch[T](
        self,
        project: RegistryProject,
        fetch_fn: Callable[[], Awaitable[T]],
        label: str,
        default: T,
    ) -> T:
        try:
            return await fetch_fn()
        except ExternalServiceError, ExternalRateLimitError, CacheError:
            logger.warning("project %s %s failed transiently", project.slug, label)
            return default
        except Exception:
            logger.exception("project %s %s failed unexpectedly", project.slug, label)
            return default

    async def _cached_fetch(
        self,
        project: RegistryProject,
        hours: int,
        cache: TTLCache[tuple[str, int], _T],
        fetch_fn: Callable[[int], Awaitable[_T]],
    ) -> _T:
        key = (project.slug, hours)
        return await cache.get_or_fetch(key, lambda: fetch_fn(hours))

    async def _traces(
        self, project: RegistryProject, hours: int
    ) -> list[LangfuseTrace]:
        return await self._cached_fetch(
            project,
            hours,
            self._cache,
            lambda h: self._clients[project.slug].fetch_traces_window(h),
        )

    async def _trace_count(self, project: RegistryProject, hours: int) -> int:
        """Trace count for the window via a server-side metrics query (cached).

        Avoids paging every raw trace just to ``len()`` them — the headline
        ``summary`` only needs the count, not the trace bodies.
        """
        return await self._cached_fetch(
            project,
            hours,
            self._trace_count_cache,
            lambda h: self._clients[project.slug].fetch_trace_count_window(h),
        )

    async def _gather(
        self, slug: str | None, hours: int
    ) -> list[tuple[RegistryProject, list[LangfuseTrace]]]:
        out: list[tuple[RegistryProject, list[LangfuseTrace]]] = []
        for p in self._projects(slug):
            traces: list[LangfuseTrace] = await self._safe_project_fetch(
                p,
                lambda: self._traces(p, hours),  # noqa: B023
                "fetch traces",
                [],
            )
            out.append((p, traces))
        return out

    async def _gather_list_results(
        self,
        slug: str | None,
        hours: int,
        fetch: Callable[[RegistryProject, int], Awaitable[list[dict[str, Any]]]],
    ) -> list[dict[str, Any]]:
        parts: list[list[dict[str, Any]]] = []
        for p in self._projects(slug):
            result: list[dict[str, Any]] = await self._safe_project_fetch(
                p,
                lambda: fetch(p, hours),  # noqa: B023
                "fetch list results",
                [],
            )
            parts.append(result)
        return [r for part in parts for r in part]

    async def summary(
        self, slug: str | None, hours: int, backend: str = "all"
    ) -> dict[str, Any]:
        """Per-project totals + the aggregate, for the window.

        Cost is observation-based (the same window-accurate metrics source as the
        by-model / by-backend breakdowns), so the headline total, the per-model
        rows, and the per-backend totals all reconcile — a backend can never
        exceed the total. ``trace_count`` comes from a server-side ``view=traces``
        count metric (not by paging every trace), so this stays fast.

        When *backend* is not ``"all"``, only observation rows attributed to that
        backend are counted, so the per-component rollup and total reflect costs
        for the selected backend alone.
        """
        per_project: list[dict[str, Any]] = []
        total = 0.0
        for p in self._projects(slug):
            models: list[dict[str, Any]] = await self._safe_project_fetch(
                p,
                lambda: self._model_usage(p, hours),  # noqa: B023
                "model-usage",
                [],
            )
            if backend != "all":
                models = [m for m in models if m.get("backend") == backend]
            trace_count: int = await self._safe_project_fetch(
                p,
                lambda: self._trace_count(p, hours),  # noqa: B023
                "trace-count",
                0,
            )
            cost = round(sum(m["cost"] for m in models), 6)
            total += cost
            per_project.append(
                {
                    "name": p.name,
                    "slug": p.slug,
                    "component": p.component_id,
                    "cost": cost,
                    "trace_count": trace_count,
                }
            )
        total = round(total, 6)
        by_component: dict[str, dict[str, Any]] = {}
        for row in per_project:
            agg = by_component.setdefault(
                str(row["component"] or row["slug"]),
                {
                    "component": row["component"] or row["slug"],
                    "cost": 0.0,
                    "trace_count": 0,
                    "projects": [],
                },
            )
            agg["cost"] = round(agg["cost"] + float(row["cost"]), 6)
            agg["trace_count"] += int(row["trace_count"])
            agg["projects"].append(row)
        components = sorted(
            by_component.values(), key=lambda c: float(c["cost"]), reverse=True
        )
        if backend != "all":
            components = [c for c in components if c["cost"] > 0]
        return {
            "window_hours": hours,
            "total_cost": total,
            "projects": per_project,
            "components": components,
        }

    async def by_agent(
        self, slug: str | None, hours: int, backend: str = "all"
    ) -> list[dict[str, Any]]:
        """Cost by trace name (stage/agent), merged across selected projects.

        When ``backend`` is ``"all"`` (default), uses trace-level cost
        (``aggregate_by_name``) — unchanged from the original behavior.

        When a specific backend is selected, uses per-(stage, backend)
        observation-metrics so that each stage's cost is attributed to the
        backend(s) it actually used.
        """
        if backend == "all":
            gathered = await self._gather(slug, hours)
            all_traces = [t for _, traces in gathered for t in traces]
            return aggregate_by_name(all_traces)

        all_rows = await self._gather_list_results(slug, hours, self._agent_usage)
        return aggregate_by_name_backend(all_rows, backend)

    async def _model_usage(
        self, project: RegistryProject, hours: int
    ) -> list[dict[str, Any]]:
        return await self._cached_fetch(
            project,
            hours,
            self._model_cache,
            lambda h: self._clients[project.slug].fetch_model_usage_window(h),
        )

    async def by_model(self, slug: str | None, hours: int) -> list[dict[str, Any]]:
        """Cost + token usage by model, merged across selected projects.

        Window-accurate (see :meth:`LangfuseClient.fetch_model_usage_window`).
        """
        all_rows = await self._gather_list_results(slug, hours, self._model_usage)
        return merge_model_costs([all_rows])

    async def _backend_cost(
        self, project: RegistryProject, hours: int
    ) -> dict[str, dict[str, float]]:
        return await self._cached_fetch(
            project,
            hours,
            self._backend_cache,
            lambda h: self._clients[project.slug].fetch_backend_cost_window(h),
        )

    async def _agent_usage(
        self, project: RegistryProject, hours: int
    ) -> list[dict[str, Any]]:
        return await self._cached_fetch(
            project,
            hours,
            self._agent_usage_cache,
            lambda h: self._clients[project.slug].fetch_agent_usage_window(h),
        )

    async def backend_trend(
        self, slug: str | None, hours: int, backend: BackendKind
    ) -> list[dict[str, Any]]:
        """Return the cost trend for a backend, merged across selected projects.

        Window-accurate; time-bucket granularity scales with the window.
        """
        parts: list[dict[str, dict[str, float]]] = []
        for p in self._projects(slug):
            cost: dict[str, dict[str, float]] = await self._safe_project_fetch(
                p,
                lambda: self._backend_cost(p, hours),  # noqa: B023
                "backend-cost",
                {},
            )
            parts.append(cost)
        return backend_cost_series(parts, backend)

    async def trend(
        self, slug: str | None, hours: int, buckets: int = 48
    ) -> list[dict[str, Any]]:
        """Return a cost trend series across the window."""
        gathered = await self._gather(slug, hours)
        all_traces = [t for _, traces in gathered for t in traces]
        return cost_trend(all_traces, hours, buckets)

    async def highlights(
        self, slug: str | None, hours: int, backend: str = "all"
    ) -> dict[str, Any]:
        """Return dashboard highlights: top trace, session, and summary stats.

        When *backend* is not ``"all"``, traces are filtered to only those
        whose name appears in the agent-usage rows for that backend, keeping
        the highlights consistent with the backend selector.
        """
        gathered = await self._gather(slug, hours)
        all_traces = [t for _, traces in gathered for t in traces]
        if backend != "all":
            agent_rows = await self._gather_list_results(slug, hours, self._agent_usage)
            backend_names: set[str] = {
                r["name"] for r in agent_rows if r.get("backend") == backend
            }
            all_traces = [t for t in all_traces if t.name in backend_names]
        return {
            "most_expensive_trace": most_expensive_trace(all_traces),
            "most_expensive_session": most_expensive_session(all_traces),
            "session_cost_scope": backend if backend != "all" else "all",
        }

last_updated property

UTC datetime of the most recent cache refresh, or None when cold.

__init__(config, registry_client)

Initialise the service with config and a registry client.

Starts with an empty project/client map — call :meth:refresh_projects during startup to populate from the registry.

Source code in src/robotsix_cost_monitor/service/core.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def __init__(self, config: Config, registry_client: RegistryClient) -> None:
    """Initialise the service with config and a registry client.

    Starts with an empty project/client map — call :meth:`refresh_projects`
    during startup to populate from the registry.
    """
    self.config = config
    self._registry = registry_client
    self._project_map: dict[str, RegistryProject] = {}
    self._clients: dict[str, LangfuseClient] = {}
    ttl = self.config.settings.cache_ttl_seconds
    self._last_updated: datetime | None = None
    self._caches: list[TTLCache[Any, Any]] = []
    on_refresh = self._touch_last_updated

    def _mk[T](t: type[T]) -> TTLCache[Any, T]:
        c = TTLCache[Any, T](ttl, on_refresh=on_refresh)
        self._caches.append(c)
        return c

    # cache: (slug, hours) -> (traces, monotonic_deadline)
    self._cache = _mk(list[LangfuseTrace])
    # cache: (slug, hours) -> (per-model usage rows, monotonic_deadline)
    self._model_cache = _mk(list[dict[str, Any]])
    # cache: (slug, hours) -> ({time_bucket -> {backend -> cost}}, deadline)
    self._backend_cache = _mk(dict[str, dict[str, float]])
    # cache: (slug, hours) -> (per-(stage, backend) rows, monotonic_deadline)
    self._agent_usage_cache = _mk(list[dict[str, Any]])
    # cache: (slug, hours) -> (trace_count, monotonic_deadline)
    self._trace_count_cache = _mk(int)

backend_trend(slug, hours, backend) async

Return the cost trend for a backend, merged across selected projects.

Window-accurate; time-bucket granularity scales with the window.

Source code in src/robotsix_cost_monitor/service/core.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
async def backend_trend(
    self, slug: str | None, hours: int, backend: BackendKind
) -> list[dict[str, Any]]:
    """Return the cost trend for a backend, merged across selected projects.

    Window-accurate; time-bucket granularity scales with the window.
    """
    parts: list[dict[str, dict[str, float]]] = []
    for p in self._projects(slug):
        cost: dict[str, dict[str, float]] = await self._safe_project_fetch(
            p,
            lambda: self._backend_cost(p, hours),  # noqa: B023
            "backend-cost",
            {},
        )
        parts.append(cost)
    return backend_cost_series(parts, backend)

by_agent(slug, hours, backend='all') async

Cost by trace name (stage/agent), merged across selected projects.

When backend is "all" (default), uses trace-level cost (aggregate_by_name) — unchanged from the original behavior.

When a specific backend is selected, uses per-(stage, backend) observation-metrics so that each stage's cost is attributed to the backend(s) it actually used.

Source code in src/robotsix_cost_monitor/service/core.py
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
async def by_agent(
    self, slug: str | None, hours: int, backend: str = "all"
) -> list[dict[str, Any]]:
    """Cost by trace name (stage/agent), merged across selected projects.

    When ``backend`` is ``"all"`` (default), uses trace-level cost
    (``aggregate_by_name``) — unchanged from the original behavior.

    When a specific backend is selected, uses per-(stage, backend)
    observation-metrics so that each stage's cost is attributed to the
    backend(s) it actually used.
    """
    if backend == "all":
        gathered = await self._gather(slug, hours)
        all_traces = [t for _, traces in gathered for t in traces]
        return aggregate_by_name(all_traces)

    all_rows = await self._gather_list_results(slug, hours, self._agent_usage)
    return aggregate_by_name_backend(all_rows, backend)

by_model(slug, hours) async

Cost + token usage by model, merged across selected projects.

Window-accurate (see :meth:LangfuseClient.fetch_model_usage_window).

Source code in src/robotsix_cost_monitor/service/core.py
356
357
358
359
360
361
362
async def by_model(self, slug: str | None, hours: int) -> list[dict[str, Any]]:
    """Cost + token usage by model, merged across selected projects.

    Window-accurate (see :meth:`LangfuseClient.fetch_model_usage_window`).
    """
    all_rows = await self._gather_list_results(slug, hours, self._model_usage)
    return merge_model_costs([all_rows])

components()

Return discovered projects grouped by owning component.

Insertion order follows the registry, so the dashboard's component list is stable across refreshes. Projects whose component is unknown are grouped under their own slug rather than dropped.

Source code in src/robotsix_cost_monitor/service/core.py
140
141
142
143
144
145
146
147
148
149
150
def components(self) -> dict[str, list[RegistryProject]]:
    """Return discovered projects grouped by owning component.

    Insertion order follows the registry, so the dashboard's component list
    is stable across refreshes.  Projects whose component is unknown are
    grouped under their own slug rather than dropped.
    """
    out: dict[str, list[RegistryProject]] = {}
    for p in self._project_map.values():
        out.setdefault(p.component_id or p.slug, []).append(p)
    return out

highlights(slug, hours, backend='all') async

Return dashboard highlights: top trace, session, and summary stats.

When backend is not "all", traces are filtered to only those whose name appears in the agent-usage rows for that backend, keeping the highlights consistent with the backend selector.

Source code in src/robotsix_cost_monitor/service/core.py
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
async def highlights(
    self, slug: str | None, hours: int, backend: str = "all"
) -> dict[str, Any]:
    """Return dashboard highlights: top trace, session, and summary stats.

    When *backend* is not ``"all"``, traces are filtered to only those
    whose name appears in the agent-usage rows for that backend, keeping
    the highlights consistent with the backend selector.
    """
    gathered = await self._gather(slug, hours)
    all_traces = [t for _, traces in gathered for t in traces]
    if backend != "all":
        agent_rows = await self._gather_list_results(slug, hours, self._agent_usage)
        backend_names: set[str] = {
            r["name"] for r in agent_rows if r.get("backend") == backend
        }
        all_traces = [t for t in all_traces if t.name in backend_names]
    return {
        "most_expensive_trace": most_expensive_trace(all_traces),
        "most_expensive_session": most_expensive_session(all_traces),
        "session_cost_scope": backend if backend != "all" else "all",
    }

invalidate_all()

Clear every internal cache so the next request fetches fresh data.

Source code in src/robotsix_cost_monitor/service/core.py
101
102
103
104
105
def invalidate_all(self) -> None:
    """Clear every internal cache so the next request fetches fresh data."""
    for c in self._caches:
        c.invalidate()
    self._last_updated = None

projects()

Return every discovered project, in registry order.

Source code in src/robotsix_cost_monitor/service/core.py
136
137
138
def projects(self) -> list[RegistryProject]:
    """Return every discovered project, in registry order."""
    return list(self._project_map.values())

refresh_projects() async

Query the registry and rebuild the project/client map.

Best-effort: on failure the existing project list is kept unchanged.

Source code in src/robotsix_cost_monitor/service/core.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
async def refresh_projects(self) -> None:
    """Query the registry and rebuild the project/client map.

    Best-effort: on failure the existing project list is kept unchanged.
    """
    try:
        registry_projects = await self._registry.fetch_projects()
    except Exception:
        logger.warning("refresh_projects: registry fetch failed")
        return
    if not registry_projects:
        logger.warning("refresh_projects: registry returned no projects")
        return
    self._project_map = {p.slug: p for p in registry_projects}
    self._clients = {
        p.slug: LangfuseClient(
            public_key=p.langfuse_public_key,
            secret_key=p.langfuse_secret_key.get_secret_value(),
            base_url=p.langfuse_base_url,
        )
        for p in registry_projects
    }
    self.invalidate_all()
    logger.info(
        "refresh_projects: discovered %d project(s) across %d component(s)",
        len(self._project_map),
        len(self.components()),
    )

summary(slug, hours, backend='all') async

Per-project totals + the aggregate, for the window.

Cost is observation-based (the same window-accurate metrics source as the by-model / by-backend breakdowns), so the headline total, the per-model rows, and the per-backend totals all reconcile — a backend can never exceed the total. trace_count comes from a server-side view=traces count metric (not by paging every trace), so this stays fast.

When backend is not "all", only observation rows attributed to that backend are counted, so the per-component rollup and total reflect costs for the selected backend alone.

Source code in src/robotsix_cost_monitor/service/core.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
async def summary(
    self, slug: str | None, hours: int, backend: str = "all"
) -> dict[str, Any]:
    """Per-project totals + the aggregate, for the window.

    Cost is observation-based (the same window-accurate metrics source as the
    by-model / by-backend breakdowns), so the headline total, the per-model
    rows, and the per-backend totals all reconcile — a backend can never
    exceed the total. ``trace_count`` comes from a server-side ``view=traces``
    count metric (not by paging every trace), so this stays fast.

    When *backend* is not ``"all"``, only observation rows attributed to that
    backend are counted, so the per-component rollup and total reflect costs
    for the selected backend alone.
    """
    per_project: list[dict[str, Any]] = []
    total = 0.0
    for p in self._projects(slug):
        models: list[dict[str, Any]] = await self._safe_project_fetch(
            p,
            lambda: self._model_usage(p, hours),  # noqa: B023
            "model-usage",
            [],
        )
        if backend != "all":
            models = [m for m in models if m.get("backend") == backend]
        trace_count: int = await self._safe_project_fetch(
            p,
            lambda: self._trace_count(p, hours),  # noqa: B023
            "trace-count",
            0,
        )
        cost = round(sum(m["cost"] for m in models), 6)
        total += cost
        per_project.append(
            {
                "name": p.name,
                "slug": p.slug,
                "component": p.component_id,
                "cost": cost,
                "trace_count": trace_count,
            }
        )
    total = round(total, 6)
    by_component: dict[str, dict[str, Any]] = {}
    for row in per_project:
        agg = by_component.setdefault(
            str(row["component"] or row["slug"]),
            {
                "component": row["component"] or row["slug"],
                "cost": 0.0,
                "trace_count": 0,
                "projects": [],
            },
        )
        agg["cost"] = round(agg["cost"] + float(row["cost"]), 6)
        agg["trace_count"] += int(row["trace_count"])
        agg["projects"].append(row)
    components = sorted(
        by_component.values(), key=lambda c: float(c["cost"]), reverse=True
    )
    if backend != "all":
        components = [c for c in components if c["cost"] > 0]
    return {
        "window_hours": hours,
        "total_cost": total,
        "projects": per_project,
        "components": components,
    }

trend(slug, hours, buckets=48) async

Return a cost trend series across the window.

Source code in src/robotsix_cost_monitor/service/core.py
402
403
404
405
406
407
408
async def trend(
    self, slug: str | None, hours: int, buckets: int = 48
) -> list[dict[str, Any]]:
    """Return a cost trend series across the window."""
    gathered = await self._gather(slug, hours)
    all_traces = [t for _, traces in gathered for t in traces]
    return cost_trend(all_traces, hours, buckets)