"""The current run, as a context variable (Phase 15). ``AgentRuntime`` sets a ``RunContext`` around every graph invocation. Everything below it in the same asyncio task tree (graph nodes, the quarantine extractor, LLM wrappers) can then attribute work to the run without threading ids through every signature: * LLM spans and token costs (``core.agent.models.InstrumentedLLM``); * the tenant's non-secret config snapshot (time zone, safety profile) for prompts (ADR-0009 G5/G6). Outside a run (API helpers, NL rule compilation) ``current_run()`` is None and callers fall back to their defaults. """ from __future__ import annotations import uuid from collections.abc import Awaitable, Callable, Iterator, Mapping from contextlib import contextmanager from contextvars import ContextVar from dataclasses import dataclass, field from typing import Any CostSink = Callable[[uuid.UUID, uuid.UUID, float], Awaitable[None]] @dataclass class RunContext: tenant_id: uuid.UUID run_id: uuid.UUID thread_id: str tenant_config: Mapping[str, Any] = field(default_factory=dict) # Persists a cost increment (tenant, run, usd); set by the runtime. None: count only. cost_sink: CostSink | None = None cost_usd: float = 0.0 # LLM cost attributed in this process during this invocation input_tokens: int = 0 output_tokens: int = 0 llm_calls: int = 0 async def add_usage(self, input_tokens: int, output_tokens: int, usd: float) -> None: self.llm_calls += 1 self.input_tokens += input_tokens self.output_tokens += output_tokens self.cost_usd += usd if usd > 0 and self.cost_sink is not None: await self.cost_sink(self.tenant_id, self.run_id, usd) _current: ContextVar[RunContext | None] = ContextVar("workpilot_run", default=None) def current_run() -> RunContext | None: return _current.get() @contextmanager def run_context(ctx: RunContext) -> Iterator[RunContext]: token = _current.set(ctx) try: yield ctx finally: _current.reset(token)