agent2dashboard 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. agent2dashboard/__init__.py +593 -0
  2. agent2dashboard/__main__.py +3 -0
  3. agent2dashboard/_env.py +79 -0
  4. agent2dashboard/a2ui/__init__.py +1 -0
  5. agent2dashboard/a2ui/catalogs/dashboard/v1/catalog.json +496 -0
  6. agent2dashboard/a2ui/checks.py +656 -0
  7. agent2dashboard/a2ui/express.py +349 -0
  8. agent2dashboard/a2ui/layout_actions.py +409 -0
  9. agent2dashboard/a2ui/render.py +252 -0
  10. agent2dashboard/a2ui/state.py +600 -0
  11. agent2dashboard/a2ui/surfaces.py +23 -0
  12. agent2dashboard/agent/__init__.py +83 -0
  13. agent2dashboard/agent/builtin_tools.py +258 -0
  14. agent2dashboard/agent/history.py +218 -0
  15. agent2dashboard/agent/loop.py +341 -0
  16. agent2dashboard/agent/prompt.py +66 -0
  17. agent2dashboard/agent/tools.py +162 -0
  18. agent2dashboard/agent/turn.py +201 -0
  19. agent2dashboard/auth.py +350 -0
  20. agent2dashboard/cli/__init__.py +50 -0
  21. agent2dashboard/errors.py +18 -0
  22. agent2dashboard/http/__init__.py +40 -0
  23. agent2dashboard/http/dashboards.py +100 -0
  24. agent2dashboard/http/functions.py +462 -0
  25. agent2dashboard/http/queries.py +168 -0
  26. agent2dashboard/http/revisions.py +126 -0
  27. agent2dashboard/http/router.py +353 -0
  28. agent2dashboard/http/schemas.py +102 -0
  29. agent2dashboard/llm/__init__.py +7 -0
  30. agent2dashboard/llm/_messages_api.py +123 -0
  31. agent2dashboard/llm/bedrock.py +96 -0
  32. agent2dashboard/llm/direct.py +40 -0
  33. agent2dashboard/llm/messages.py +45 -0
  34. agent2dashboard/migrations/__init__.py +383 -0
  35. agent2dashboard/migrations/versions/0001_initial.py +228 -0
  36. agent2dashboard/ports.py +538 -0
  37. agent2dashboard/py.typed +0 -0
  38. agent2dashboard/query/__init__.py +65 -0
  39. agent2dashboard/query/errors.py +39 -0
  40. agent2dashboard/query/executor.py +203 -0
  41. agent2dashboard/query/filters.py +446 -0
  42. agent2dashboard/query/governed.py +155 -0
  43. agent2dashboard/query/readonly.py +166 -0
  44. agent2dashboard/query/registry.py +213 -0
  45. agent2dashboard/query/row_filter.py +135 -0
  46. agent2dashboard/query/service.py +93 -0
  47. agent2dashboard/query/sql_guard.py +219 -0
  48. agent2dashboard/runs/__init__.py +87 -0
  49. agent2dashboard/runs/errors.py +65 -0
  50. agent2dashboard/runs/events.py +147 -0
  51. agent2dashboard/runs/hooks.py +135 -0
  52. agent2dashboard/runs/http.py +169 -0
  53. agent2dashboard/runs/memory.py +148 -0
  54. agent2dashboard/runs/redis_bus.py +219 -0
  55. agent2dashboard/runs/service.py +728 -0
  56. agent2dashboard/runs/writer.py +95 -0
  57. agent2dashboard/semantic/__init__.py +6 -0
  58. agent2dashboard/semantic/cube.py +39 -0
  59. agent2dashboard/semantic/static.py +81 -0
  60. agent2dashboard/storage/__init__.py +60 -0
  61. agent2dashboard/storage/lifecycle.py +105 -0
  62. agent2dashboard/storage/memory.py +488 -0
  63. agent2dashboard/storage/records.py +219 -0
  64. agent2dashboard/storage/sql.py +666 -0
  65. agent2dashboard/storage/tables.py +387 -0
  66. agent2dashboard/testing/__init__.py +20 -0
  67. agent2dashboard/testing/event_bus.py +10 -0
  68. agent2dashboard/testing/fake_llm.py +129 -0
  69. agent2dashboard/testing/host.py +191 -0
  70. agent2dashboard/tracing/__init__.py +36 -0
  71. agent2dashboard/tracing/db.py +143 -0
  72. agent2dashboard/tracing/fanout.py +153 -0
  73. agent2dashboard/tracing/langfuse.py +339 -0
  74. agent2dashboard/tracing/masking.py +26 -0
  75. agent2dashboard-0.2.0.dist-info/METADATA +81 -0
  76. agent2dashboard-0.2.0.dist-info/RECORD +79 -0
  77. agent2dashboard-0.2.0.dist-info/WHEEL +4 -0
  78. agent2dashboard-0.2.0.dist-info/entry_points.txt +3 -0
  79. agent2dashboard-0.2.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,201 @@
1
+ """One agent turn of a run: run -> agent loop -> tools -> dashboard (design §1.10, §3.2, §5.1,
2
+ §6.4).
3
+
4
+ `build_turn_function(dashboard)` returns the `TurnFunction` the run service calls once per
5
+ run (`agent2dashboard.runs.hooks` picks it up). Per run it:
6
+
7
+ 1. checks the query connection once (`dashboard.startup()`, §7);
8
+ 2. works out which capabilities the principal holds (QUERY decides which tools are offered);
9
+ 3. loads the conversation's `DashboardSession` (its `RendererState` and query registry) and
10
+ replays the stored history up to the run's user message;
11
+ 4. builds the system prompt: the SDK default, the Express contract for the dashboard catalog
12
+ (when the principal may build), the host addendum, the semantic index, the locale line,
13
+ then the per-turn "[Host] on screen" section with the surface id;
14
+ 5. runs `run_agent_loop` with the dashboard's `LLMProvider`, the offered tools, the run's
15
+ cancel check and `TurnState`, and a trace from every configured sink (the DB sink writes
16
+ one `llm_call` row per model round);
17
+ 6. passes every loop item through: the run service maps text to `message.delta`, tool
18
+ progress to `tool.started` / `tool.finished`, and the `render_dashboard` emit to
19
+ `canvas.a2ui`;
20
+ 7. sets `ctx.message_fields` from `session.message_fields()` (`a2ui`, `revision`), so the
21
+ run service stores them on the assistant message with the text and tool trail.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import contextlib
27
+ import logging
28
+ from collections.abc import AsyncIterator, Iterable
29
+ from typing import TYPE_CHECKING, Any
30
+
31
+ from agent2dashboard.a2ui.render import render_dashboard_tool
32
+ from agent2dashboard.a2ui.state import DASHBOARD_SESSION, DashboardSession
33
+ from agent2dashboard.agent.builtin_tools import define_query_tool, lookup_tools
34
+ from agent2dashboard.agent.history import replay_history
35
+ from agent2dashboard.agent.loop import CANCELLED, TurnResult, run_agent_loop
36
+ from agent2dashboard.agent.prompt import DEFAULT_SYSTEM_PROMPT, build_system_prompt
37
+ from agent2dashboard.agent.tools import ToolContext, ToolEmit, ToolRegistry
38
+ from agent2dashboard.ports import Capability, Principal, RunInfo, RunStatus, TraceSink
39
+ from agent2dashboard.tracing.fanout import TraceFanout
40
+
41
+ if TYPE_CHECKING:
42
+ from agent2dashboard import AgentDashboard
43
+ from agent2dashboard.runs.service import RunContext, TurnFunction
44
+
45
+ __all__ = ["DASHBOARD_PROMPT_HEADER", "build_tool_registry", "build_turn_function"]
46
+
47
+ logger = logging.getLogger(__name__)
48
+
49
+ DASHBOARD_PROMPT_HEADER = (
50
+ "Dashboards are written in A2UI Express against the dashboard catalog below, through "
51
+ "the `render_dashboard` tool."
52
+ )
53
+
54
+
55
+ def build_tool_registry(dashboard: AgentDashboard) -> ToolRegistry:
56
+ """Every tool the SDK offers for this dashboard, each gated by its capability: the
57
+ lookups (CHAT), `define_query` and `render_dashboard` (QUERY)."""
58
+ service = dashboard.query_service
59
+ tools = ToolRegistry(lookup_tools(dashboard.data.governed, dashboard.semantic))
60
+ tools.register(define_query_tool(service))
61
+ tools.register(
62
+ render_dashboard_tool(
63
+ storage=dashboard.resolve_storage(),
64
+ processor=dashboard.processor,
65
+ query_service=service,
66
+ )
67
+ )
68
+ return tools
69
+
70
+
71
+ async def _capabilities(dashboard: AgentDashboard, principal: Principal) -> frozenset[Capability]:
72
+ held = set()
73
+ for capability in (Capability.CHAT, Capability.QUERY):
74
+ if await dashboard.auth.can(principal, capability):
75
+ held.add(capability)
76
+ return frozenset(held)
77
+
78
+
79
+ def _sinks(dashboard: AgentDashboard) -> Iterable[TraceSink]:
80
+ return dashboard.trace_sinks()
81
+
82
+
83
+ async def _flush(sinks: Iterable[TraceSink]) -> None:
84
+ """Wait for sinks that write in the background (the DB sink), so a finished run's
85
+ `llm_call` rows are stored by the time its terminal event is sent."""
86
+ for sink in sinks:
87
+ flush = getattr(sink, "flush", None)
88
+ if flush is None:
89
+ continue
90
+ try:
91
+ result = flush()
92
+ if hasattr(result, "__await__"):
93
+ await result
94
+ except Exception:
95
+ logger.warning(
96
+ "agent2dashboard.trace_sink.flush_failed",
97
+ extra={"sink": type(sink).__name__},
98
+ exc_info=True,
99
+ )
100
+
101
+
102
+ def build_turn_function(dashboard: AgentDashboard) -> TurnFunction:
103
+ """The `TurnFunction` for runs of `dashboard` (see the module docstring)."""
104
+ storage = dashboard.resolve_storage()
105
+ processor = dashboard.processor
106
+ registry = build_tool_registry(dashboard)
107
+ sinks = tuple(_sinks(dashboard))
108
+ fanout = TraceFanout(sinks)
109
+ config = dashboard.config
110
+ base_build = "\n\n".join(
111
+ [DEFAULT_SYSTEM_PROMPT, DASHBOARD_PROMPT_HEADER, processor.prompt_snippet]
112
+ )
113
+
114
+ async def turn(ctx: RunContext) -> AsyncIterator[Any]:
115
+ await dashboard.startup()
116
+ principal = ctx.principal
117
+ conversation_id = ctx.run.conversation_id
118
+ capabilities = await _capabilities(dashboard, principal)
119
+ can_build = Capability.QUERY in capabilities
120
+
121
+ session = await DashboardSession.load(
122
+ storage, conversation_id, processor, run_id=ctx.run.id
123
+ )
124
+ stored = await storage.messages.list(conversation_id, up_to_message_id=ctx.user_message.id)
125
+ revisions = await storage.dashboards.list_revisions(conversation_id)
126
+ history = replay_history(stored, revisions=revisions)
127
+
128
+ system = await build_system_prompt(
129
+ principal=principal,
130
+ default_locale=config.default_locale,
131
+ semantic=dashboard.semantic,
132
+ addendum=dashboard.system_prompt_addendum,
133
+ locale_addenda=dashboard.locale_addenda,
134
+ base=base_build if can_build else DEFAULT_SYSTEM_PROMPT,
135
+ )
136
+ if can_build:
137
+ system = f"{system}\n\n{session.on_screen()}"
138
+
139
+ context = ToolContext(
140
+ principal=principal,
141
+ conversation_id=conversation_id,
142
+ run_id=ctx.run.id,
143
+ capabilities=capabilities,
144
+ locale=principal.locale or config.default_locale,
145
+ extras={DASHBOARD_SESSION: session},
146
+ )
147
+ trace = fanout.start_run(
148
+ RunInfo(
149
+ run_id=ctx.run.id,
150
+ conversation_id=conversation_id,
151
+ principal_id=principal.id,
152
+ model_id=dashboard.llm.model_id,
153
+ input=ctx.user_message.content,
154
+ )
155
+ )
156
+
157
+ def keep_fields() -> None:
158
+ fields = session.message_fields()
159
+ if fields.get("revision") is not None:
160
+ ctx.message_fields.update(fields)
161
+
162
+ result: TurnResult | None = None
163
+ status, error = RunStatus.FAILED, None
164
+ try:
165
+ async for item in run_agent_loop(
166
+ llm=dashboard.llm,
167
+ system=system,
168
+ messages=history,
169
+ tools=registry.offered(capabilities),
170
+ context=context,
171
+ trace=trace,
172
+ max_tool_rounds=config.limits.max_tool_rounds,
173
+ should_cancel=ctx.should_cancel,
174
+ state=ctx.state,
175
+ ):
176
+ if isinstance(item, ToolEmit):
177
+ keep_fields()
178
+ if isinstance(item, TurnResult):
179
+ result = item
180
+ keep_fields()
181
+ yield item
182
+ status = (
183
+ RunStatus.CANCELLED
184
+ if result is not None and result.stop_reason == CANCELLED
185
+ else RunStatus.SUCCEEDED
186
+ )
187
+ except BaseException as exc:
188
+ status = RunStatus.FAILED if isinstance(exc, Exception) else RunStatus.INTERRUPTED
189
+ error = type(exc).__name__
190
+ raise
191
+ finally:
192
+ keep_fields()
193
+ with contextlib.suppress(Exception):
194
+ trace.end(
195
+ status=status,
196
+ output=ctx.state.text if result is None else result.text,
197
+ error=error,
198
+ )
199
+ await _flush(sinks)
200
+
201
+ return turn
@@ -0,0 +1,350 @@
1
+ """Ready-made `AuthProvider`s (design §3.3), so a host doesn't have to write one.
2
+
3
+ - `FunctionAuth(authenticate, can=None)`: a plain async function `(request) -> Principal`
4
+ (raise `Unauthenticated` to refuse) becomes a provider. `AgentDashboard(auth=...)` and
5
+ `AgentDashboard.from_env(auth=...)` wrap a function for you.
6
+ - `CapabilityRule(query_group=None)`: the default capability rule. Everyone authenticated
7
+ may `CHAT`; `QUERY` is for everyone, or only for members of `query_group` when it is set;
8
+ `TRACE_VIEW` is for nobody.
9
+ - `OIDCAuth(issuer, ...)` / `OIDCAuth.from_env()`: verifies the request's bearer JWT against
10
+ the issuer's JWKS (extra `[oidc]`, PyJWT).
11
+ - `bearer_token(request)`: the `Authorization: Bearer <token>` value, or None.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import asyncio
17
+ import inspect
18
+ import json
19
+ import threading
20
+ import time
21
+ import urllib.request
22
+ from collections.abc import Awaitable, Callable, Mapping, Sequence
23
+ from dataclasses import dataclass
24
+ from typing import Any
25
+ from urllib.parse import urlparse
26
+
27
+ from starlette.requests import Request
28
+
29
+ from agent2dashboard.errors import ConfigurationError, Unauthenticated
30
+ from agent2dashboard.ports import AuthProvider, Capability, Principal
31
+
32
+ __all__ = [
33
+ "AuthFunction",
34
+ "CapabilityRule",
35
+ "FunctionAuth",
36
+ "OIDCAuth",
37
+ "as_auth_provider",
38
+ "bearer_token",
39
+ ]
40
+
41
+ AuthFunction = Callable[[Request], Awaitable[Principal]]
42
+ CanFunction = Callable[[Principal, Capability], bool | Awaitable[bool]]
43
+ FetchJson = Callable[[str], Mapping[str, Any]]
44
+
45
+
46
+ def bearer_token(request: Request) -> str | None:
47
+ """The token of `Authorization: Bearer <token>` (scheme in any case), or None."""
48
+ header = request.headers.get("authorization", "")
49
+ scheme, _, token = header.partition(" ")
50
+ if scheme.lower() != "bearer" or not token.strip():
51
+ return None
52
+ return token.strip()
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class CapabilityRule:
57
+ """Everyone authenticated may `CHAT`. `QUERY` (define queries, build dashboards) is for
58
+ everyone, or only for principals in `query_group` when it is set. `TRACE_VIEW`: nobody."""
59
+
60
+ query_group: str | None = None
61
+
62
+ def __call__(self, principal: Principal, capability: Capability) -> bool:
63
+ if capability is Capability.CHAT:
64
+ return True
65
+ if capability is Capability.QUERY:
66
+ return self.query_group is None or self.query_group in principal.groups
67
+ return False
68
+
69
+
70
+ async def _decide(can: CanFunction, principal: Principal, capability: Capability) -> bool:
71
+ result = can(principal, capability)
72
+ if inspect.isawaitable(result):
73
+ result = await result
74
+ return bool(result)
75
+
76
+
77
+ class FunctionAuth:
78
+ """An `AuthProvider` from an async `authenticate(request) -> Principal` (raise
79
+ `Unauthenticated` to refuse) and an optional `can(principal, capability)`, sync or
80
+ async, which defaults to `CapabilityRule()`."""
81
+
82
+ def __init__(self, authenticate: AuthFunction, can: CanFunction | None = None) -> None:
83
+ if not callable(authenticate):
84
+ raise TypeError("FunctionAuth needs an async function (request) -> Principal")
85
+ self._authenticate = authenticate
86
+ self._can: CanFunction = can if can is not None else CapabilityRule()
87
+
88
+ async def authenticate(self, request: Request) -> Principal:
89
+ principal = await self._authenticate(request)
90
+ if not isinstance(principal, Principal):
91
+ raise TypeError("the auth function must return a Principal")
92
+ return principal
93
+
94
+ async def can(self, principal: Principal, capability: Capability) -> bool:
95
+ return await _decide(self._can, principal, capability)
96
+
97
+ def __repr__(self) -> str:
98
+ name = getattr(self._authenticate, "__qualname__", type(self._authenticate).__name__)
99
+ return f"FunctionAuth({name}, can={self._can!r})"
100
+
101
+
102
+ def as_auth_provider(auth: AuthProvider | AuthFunction) -> AuthProvider:
103
+ """A plain function (no `authenticate` method) is wrapped in `FunctionAuth`; anything
104
+ else is returned as is (an `AuthProvider`)."""
105
+ if callable(auth) and not hasattr(auth, "authenticate"):
106
+ return FunctionAuth(auth) # type: ignore[arg-type]
107
+ return auth # type: ignore[return-value]
108
+
109
+
110
+ # --- OIDC --------------------------------------------------------------------------------------
111
+
112
+ DEFAULT_ALGORITHMS = ("RS256", "ES256")
113
+ _ALLOWED_ALGORITHMS = frozenset(DEFAULT_ALGORITHMS)
114
+
115
+
116
+ def _fetch_json(url: str, *, timeout: float = 10.0) -> Mapping[str, Any]:
117
+ """GET `url` as JSON (http/https only). Blocking: called off the event loop."""
118
+ if urlparse(url).scheme.lower() not in ("http", "https"):
119
+ raise ValueError("only http(s) URLs are fetched")
120
+ request = urllib.request.Request(url, headers={"Accept": "application/json"})
121
+ with urllib.request.urlopen(request, timeout=timeout) as response:
122
+ data = json.load(response)
123
+ if not isinstance(data, dict):
124
+ raise ValueError("expected a JSON object")
125
+ return data
126
+
127
+
128
+ def _import_jwt() -> Any:
129
+ try:
130
+ import jwt
131
+ except ImportError as exc: # pragma: no cover - depends on the install
132
+ raise RuntimeError(
133
+ "OIDCAuth needs the oidc extra: pip install 'agent2dashboard[oidc]'"
134
+ ) from exc
135
+ return jwt
136
+
137
+
138
+ def _claim(claims: Mapping[str, Any], path: str) -> Any:
139
+ """`claims[path]`, or a dotted path into nested objects (`realm_access.roles`)."""
140
+ if path in claims:
141
+ return claims[path]
142
+ value: Any = claims
143
+ for part in path.split("."):
144
+ if not isinstance(value, Mapping) or part not in value:
145
+ return None
146
+ value = value[part]
147
+ return value
148
+
149
+
150
+ def _groups(value: Any) -> frozenset[str]:
151
+ if isinstance(value, str):
152
+ return frozenset({value})
153
+ if isinstance(value, list | tuple | set | frozenset):
154
+ return frozenset(str(v) for v in value if isinstance(v, str | int))
155
+ return frozenset()
156
+
157
+
158
+ class OIDCAuth:
159
+ """Verifies `Authorization: Bearer <JWT>` against an OpenID Connect issuer.
160
+
161
+ The signature is checked with the issuer's JWKS (RS256/ES256 only), and so are `iss`,
162
+ `exp`, `nbf` (with `leeway_s`) and, when `audience` is given, `aud`. Without `jwks_url`
163
+ the JWKS location is discovered from `<issuer>/.well-known/openid-configuration`. Keys are
164
+ cached; an unknown key id refetches the JWKS at most once per `refresh_cooldown_s`. All
165
+ fetches run in a worker thread (`asyncio.to_thread`), never on the event loop.
166
+
167
+ The principal: `id` from `id_claim`, `display_name` from `name` (else
168
+ `preferred_username`), `email` from `email`, `groups` from `groups_claim` (a list, or a
169
+ dotted path such as `realm_access.roles`), `locale` from `locale`. Capabilities follow
170
+ `can`, by default `CapabilityRule(query_group)`. Any failure is `Unauthenticated` (401).
171
+
172
+ `fetch_json(url) -> dict` replaces the HTTP fetch (tests serve a JWKS from memory)."""
173
+
174
+ def __init__(
175
+ self,
176
+ issuer: str,
177
+ *,
178
+ audience: str | Sequence[str] | None = None,
179
+ jwks_url: str | None = None,
180
+ groups_claim: str = "groups",
181
+ id_claim: str = "sub",
182
+ query_group: str | None = None,
183
+ leeway_s: float = 30,
184
+ algorithms: Sequence[str] = DEFAULT_ALGORITHMS,
185
+ can: CanFunction | None = None,
186
+ fetch_json: FetchJson | None = None,
187
+ jwks_cache_s: float = 3600,
188
+ refresh_cooldown_s: float = 30,
189
+ ) -> None:
190
+ if not issuer:
191
+ raise ConfigurationError("OIDCAuth needs an issuer")
192
+ unknown = set(algorithms) - _ALLOWED_ALGORITHMS
193
+ if unknown or not algorithms:
194
+ raise ConfigurationError("OIDCAuth accepts only RS256 and ES256")
195
+ self.issuer = issuer
196
+ self.audience = audience
197
+ self.jwks_url = jwks_url
198
+ self.groups_claim = groups_claim
199
+ self.id_claim = id_claim
200
+ self.query_group = query_group
201
+ self.leeway_s = leeway_s
202
+ self.algorithms = tuple(algorithms)
203
+ self._can: CanFunction = can if can is not None else CapabilityRule(query_group)
204
+ self._fetch: FetchJson = fetch_json or _fetch_json
205
+ self._jwks_cache_s = jwks_cache_s
206
+ self._refresh_cooldown_s = refresh_cooldown_s
207
+ self._lock = threading.Lock()
208
+ self._keys: dict[str, Any] = {} # kid -> PyJWK
209
+ self._fetched_at: float | None = None
210
+ # Set by `from_env` when a required variable is missing while the SDK is off: the
211
+ # provider then refuses every request, and `AgentDashboard.mount` refuses to mount.
212
+ self.config_problems: tuple[str, ...] = ()
213
+
214
+ @classmethod
215
+ def from_env(
216
+ cls,
217
+ environ: Mapping[str, str] | None = None,
218
+ *,
219
+ env_prefix: str = "AGENT2DASHBOARD_",
220
+ **overrides: Any,
221
+ ) -> OIDCAuth:
222
+ """`<prefix>OIDC_ISSUER` (required), `_OIDC_AUDIENCE`, `_OIDC_JWKS_URL`,
223
+ `_OIDC_GROUPS_CLAIM`, `_OIDC_QUERY_GROUP`, `_OIDC_ID_CLAIM`; a keyword argument wins
224
+ over its variable.
225
+
226
+ Without an issuer it raises `ConfigurationError`, unless `<prefix>ENABLED` is off:
227
+ then it returns a provider that refuses every request, so a host with the SDK
228
+ switched off needs no OIDC settings (`AgentDashboard.mount` won't mount it)."""
229
+ from agent2dashboard._env import Env
230
+
231
+ env = Env(environ, env_prefix)
232
+ settings: dict[str, Any] = {
233
+ "audience": env.get("OIDC_AUDIENCE"),
234
+ "jwks_url": env.get("OIDC_JWKS_URL"),
235
+ "groups_claim": env.get("OIDC_GROUPS_CLAIM") or "groups",
236
+ "id_claim": env.get("OIDC_ID_CLAIM") or "sub",
237
+ "query_group": env.get("OIDC_QUERY_GROUP"),
238
+ }
239
+ settings.update(overrides)
240
+ issuer = settings.pop("issuer", None) or env.get("OIDC_ISSUER")
241
+ if not issuer:
242
+ problem = f"{env.name('OIDC_ISSUER')} is not set"
243
+ if env.enabled():
244
+ raise ConfigurationError(problem)
245
+ unconfigured = cls("unconfigured:", **settings)
246
+ unconfigured.config_problems = (problem,)
247
+ return unconfigured
248
+ return cls(issuer, **settings)
249
+
250
+ # --- keys -------------------------------------------------------------------------------
251
+
252
+ def _discover_jwks_url(self) -> str:
253
+ if self.jwks_url is None:
254
+ config = self._fetch(self.issuer.rstrip("/") + "/.well-known/openid-configuration")
255
+ if str(config.get("issuer", "")).rstrip("/") != self.issuer.rstrip("/"):
256
+ raise ValueError("the discovery document names another issuer")
257
+ jwks_uri = config.get("jwks_uri")
258
+ if not isinstance(jwks_uri, str) or not jwks_uri:
259
+ raise ValueError("the discovery document has no jwks_uri")
260
+ self.jwks_url = jwks_uri
261
+ return self.jwks_url
262
+
263
+ def _load_keys(self) -> None:
264
+ jwt = _import_jwt()
265
+ jwk_set = jwt.PyJWKSet.from_dict(dict(self._fetch(self._discover_jwks_url())))
266
+ keys: dict[str, Any] = {}
267
+ for index, key in enumerate(jwk_set.keys):
268
+ if getattr(key, "public_key_use", None) in (None, "sig"):
269
+ keys[key.key_id or f"#{index}"] = key
270
+ self._keys = keys
271
+ self._fetched_at = time.monotonic()
272
+
273
+ def _signing_key(self, kid: str | None) -> Any:
274
+ """The key for `kid` (or the only key, for a token without one). Blocking."""
275
+ with self._lock:
276
+ now = time.monotonic()
277
+ expired = self._fetched_at is None or now - self._fetched_at > self._jwks_cache_s
278
+ if expired:
279
+ self._load_keys()
280
+ key = self._find(kid)
281
+ if key is None and not expired:
282
+ assert self._fetched_at is not None
283
+ if now - self._fetched_at >= self._refresh_cooldown_s: # rotated keys
284
+ self._load_keys()
285
+ key = self._find(kid)
286
+ if key is None:
287
+ raise LookupError("no signing key for the token")
288
+ return key
289
+
290
+ def _find(self, kid: str | None) -> Any:
291
+ if kid is not None:
292
+ return self._keys.get(kid)
293
+ return next(iter(self._keys.values())) if len(self._keys) == 1 else None
294
+
295
+ # --- verification -----------------------------------------------------------------------
296
+
297
+ def verify(self, token: str) -> dict[str, Any]:
298
+ """The token's verified claims. Blocking (it may fetch keys); raises on any failure."""
299
+ jwt = _import_jwt()
300
+ header = jwt.get_unverified_header(token)
301
+ if header.get("alg") not in self.algorithms:
302
+ raise ValueError("token algorithm not allowed")
303
+ key = self._signing_key(header.get("kid"))
304
+ return jwt.decode(
305
+ token,
306
+ key,
307
+ algorithms=list(self.algorithms),
308
+ audience=self.audience,
309
+ issuer=self.issuer,
310
+ leeway=self.leeway_s,
311
+ options={"require": ["exp", "iss"], "verify_aud": self.audience is not None},
312
+ )
313
+
314
+ def principal(self, claims: Mapping[str, Any]) -> Principal:
315
+ subject = _claim(claims, self.id_claim)
316
+ if subject is None or str(subject) == "":
317
+ raise Unauthenticated(f"access token has no {self.id_claim} claim")
318
+ name = claims.get("name") or claims.get("preferred_username")
319
+ email = claims.get("email")
320
+ locale = claims.get("locale")
321
+ return Principal(
322
+ id=str(subject),
323
+ display_name=str(name) if name else None,
324
+ email=str(email) if email else None,
325
+ groups=_groups(_claim(claims, self.groups_claim)),
326
+ attributes={},
327
+ locale=str(locale) if isinstance(locale, str) and locale else None,
328
+ )
329
+
330
+ async def authenticate(self, request: Request) -> Principal:
331
+ if self.config_problems:
332
+ raise Unauthenticated("authentication is not configured")
333
+ token = bearer_token(request)
334
+ if token is None:
335
+ raise Unauthenticated("missing bearer token")
336
+ try:
337
+ claims = await asyncio.to_thread(self.verify, token)
338
+ except Exception:
339
+ # Never echo the token or the reason's details to the caller.
340
+ raise Unauthenticated("invalid or expired access token") from None
341
+ return self.principal(claims)
342
+
343
+ async def can(self, principal: Principal, capability: Capability) -> bool:
344
+ return await _decide(self._can, principal, capability)
345
+
346
+ def __repr__(self) -> str:
347
+ return (
348
+ f"OIDCAuth(issuer={self.issuer!r}, audience={self.audience!r}, "
349
+ f"groups_claim={self.groups_claim!r}, query_group={self.query_group!r})"
350
+ )
@@ -0,0 +1,50 @@
1
+ """`agent2dashboard` command line (also `python -m agent2dashboard`).
2
+
3
+ agent2dashboard migrate --database-url postgresql+psycopg://user:pw@host/db
4
+ [--schema agent2dashboard] [--table-prefix ""]
5
+
6
+ The URL may come from `AGENT2DASHBOARD_DATABASE_URL` instead, so it stays out of the process
7
+ list. A sync driver URL (`postgresql://`, `postgresql+psycopg2://`) is used as psycopg async.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import asyncio
14
+ import os
15
+ import sys
16
+ from collections.abc import Sequence
17
+
18
+ from agent2dashboard._env import async_database_url
19
+ from agent2dashboard.errors import ConfigurationError
20
+ from agent2dashboard.migrations import DEFAULT_SCHEMA, migrate_url
21
+ from agent2dashboard.storage import TableNames
22
+
23
+ URL_ENV = "AGENT2DASHBOARD_DATABASE_URL"
24
+
25
+
26
+ def main(argv: Sequence[str] | None = None) -> int:
27
+ parser = argparse.ArgumentParser(prog="agent2dashboard")
28
+ commands = parser.add_subparsers(dest="command", required=True)
29
+ m = commands.add_parser("migrate", help="create or upgrade the SDK's tables")
30
+ m.add_argument("--database-url", default=os.environ.get(URL_ENV), help=f"default: ${URL_ENV}")
31
+ m.add_argument("--schema", default=DEFAULT_SCHEMA, help=f"default: {DEFAULT_SCHEMA}")
32
+ m.add_argument("--table-prefix", default="", help="default: none")
33
+ args = parser.parse_args(argv)
34
+
35
+ if not args.database_url:
36
+ parser.error(f"--database-url or ${URL_ENV} is required")
37
+ try:
38
+ url = async_database_url(args.database_url, name="the database URL")
39
+ except ConfigurationError as exc:
40
+ parser.error(str(exc))
41
+ asyncio.run(
42
+ migrate_url(
43
+ url,
44
+ schema=args.schema or None,
45
+ tables=TableNames.prefixed(args.table_prefix),
46
+ )
47
+ )
48
+ where = f"schema {args.schema}" if args.schema else "the default schema"
49
+ print(f"agent2dashboard: tables up to date in {where}", file=sys.stderr)
50
+ return 0
@@ -0,0 +1,18 @@
1
+ """Exceptions the SDK raises and hosts may raise from their port implementations."""
2
+
3
+
4
+ class AgentDashboardError(Exception):
5
+ """Base class for every error the SDK defines."""
6
+
7
+
8
+ class Unauthenticated(AgentDashboardError):
9
+ """Raised by `AuthProvider.authenticate` when the request carries no valid identity."""
10
+
11
+
12
+ class RowFilterDenied(AgentDashboardError):
13
+ """Raised by `RowFilter.scopes` to refuse a query outright for this principal."""
14
+
15
+
16
+ class ConfigurationError(AgentDashboardError):
17
+ """The SDK was set up in a way it refuses to run: a required setting is missing or
18
+ invalid, or a combination it refuses (e.g. an in-memory bus with multi-instance)."""
@@ -0,0 +1,40 @@
1
+ """The SDK's HTTP layer (design §5.1, §7): `AgentDashboard.router()` builds it.
2
+
3
+ Mount points for the runs package: `agent2dashboard.runs.build_runs_router(dashboard)` returns
4
+ the run routes (`POST /conversations/{cid}/runs`, `GET /runs/{id}/events`,
5
+ `POST /runs/{id}/cancel`), and `agent2dashboard.runs.build_action_handler(dashboard)` returns
6
+ the `ActionHandler` behind `POST /surfaces/{sid}/actions`. Until they exist, the router has no
7
+ run routes and actions answer 501.
8
+ """
9
+
10
+ from agent2dashboard.http.dashboards import (
11
+ create_surface_messages,
12
+ dashboard_summary,
13
+ surface_parts,
14
+ )
15
+ from agent2dashboard.http.functions import (
16
+ FunctionError,
17
+ FunctionRateLimiter,
18
+ InMemoryRateLimiter,
19
+ ResultCache,
20
+ SurfaceFunctions,
21
+ agent_function_error,
22
+ agent_function_value,
23
+ )
24
+ from agent2dashboard.http.router import ActionHandler, PrincipalDependency, build_router
25
+
26
+ __all__ = [
27
+ "ActionHandler",
28
+ "FunctionError",
29
+ "FunctionRateLimiter",
30
+ "InMemoryRateLimiter",
31
+ "PrincipalDependency",
32
+ "ResultCache",
33
+ "SurfaceFunctions",
34
+ "agent_function_error",
35
+ "agent_function_value",
36
+ "build_router",
37
+ "create_surface_messages",
38
+ "dashboard_summary",
39
+ "surface_parts",
40
+ ]