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,341 @@
1
+ """The agent loop: model rounds and tool calls (copied from XoraOps' `llm/client.py` `stream_llm`).
2
+
3
+ One call of `run_agent_loop` is one assistant turn. It streams the model's text, answers every
4
+ tool call of a round in one batch, and calls the model again, up to `max_tool_rounds` times
5
+ after the first round. The last round sends `tool_choice: none`, so the model must answer
6
+ instead of asking again. The loop lives in the SDK, not in the provider (§3.5).
7
+
8
+ Yields, in order of occurrence:
9
+ - `str`: a text delta (rounds after the first are separated by a blank line);
10
+ - `ToolProgress`: a tool call starting, then finishing;
11
+ - `ToolEmit`: a tool result the user must see;
12
+ - `TurnResult`: once, last, unless the loop raised.
13
+
14
+ Cancel (§5.3): `should_cancel` is checked before every round, after every streamed chunk and
15
+ before every tool call; a cancelled turn ends with a `TurnResult` whose `stop_reason` is
16
+ `"cancelled"`. If the task is cancelled or the consumer closes the generator instead, the
17
+ loop records `"interrupted"` on the `TurnState` (which the caller can still read, with the
18
+ partial text and trail) and re-raises. A model error is traced and re-raised. A tool error
19
+ never ends the turn: it goes back to the model as an `is_error` result.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import asyncio
25
+ import contextlib
26
+ import logging
27
+ import time
28
+ from collections import Counter
29
+ from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
30
+ from dataclasses import dataclass, field
31
+ from typing import Any, Literal
32
+
33
+ from agent2dashboard.agent.history import TOOL_TRAIL_MAX_CALLS, trail_entry
34
+ from agent2dashboard.agent.tools import (
35
+ ToolContext,
36
+ ToolEmit,
37
+ ToolError,
38
+ ToolProgress,
39
+ ToolRegistry,
40
+ ToolResult,
41
+ )
42
+ from agent2dashboard.llm.messages import message_dicts, text_digest, tool_use_dict
43
+ from agent2dashboard.ports import (
44
+ ChatMessage,
45
+ LLMProvider,
46
+ ModelResult,
47
+ ModelTurn,
48
+ RunTrace,
49
+ ToolUse,
50
+ Usage,
51
+ )
52
+
53
+ __all__ = [
54
+ "CANCELLED",
55
+ "DEFAULT_MAX_TOKENS",
56
+ "INTERRUPTED",
57
+ "MAX_TOOL_ROUNDS",
58
+ "MAX_TOOL_ROUNDS_REACHED",
59
+ "ROUND_SEPARATOR",
60
+ "CancelCheck",
61
+ "TurnEvent",
62
+ "TurnResult",
63
+ "TurnState",
64
+ "run_agent_loop",
65
+ ]
66
+
67
+ logger = logging.getLogger(__name__)
68
+
69
+ # Model round trips allowed after the first, each answering a batch of tool calls. Building a
70
+ # dashboard takes lookups, a query per widget, a render and sometimes a retry.
71
+ MAX_TOOL_ROUNDS = 15
72
+ DEFAULT_MAX_TOKENS = 8192
73
+ ROUND_SEPARATOR = "\n\n"
74
+
75
+ CANCELLED = "cancelled" # the user pressed Stop; the turn ended cleanly
76
+ INTERRUPTED = "interrupted" # the task was cancelled or the consumer went away
77
+ MAX_TOOL_ROUNDS_REACHED = "max_tool_rounds"
78
+
79
+ CancelCheck = Callable[[], Awaitable[bool]]
80
+
81
+
82
+ @dataclass
83
+ class TurnState:
84
+ """What the turn has produced so far. Pass one in to read it even when the loop raises."""
85
+
86
+ parts: list[str] = field(default_factory=list)
87
+ trail: list[dict[str, Any]] = field(default_factory=list)
88
+ emits: list[ToolEmit] = field(default_factory=list)
89
+ input_tokens: int = 0
90
+ output_tokens: int = 0
91
+ rounds: int = 0
92
+ stop_reason: str | None = None
93
+
94
+ @property
95
+ def text(self) -> str:
96
+ return "".join(self.parts)
97
+
98
+ @property
99
+ def usage(self) -> Usage:
100
+ return Usage(input_tokens=self.input_tokens, output_tokens=self.output_tokens)
101
+
102
+
103
+ @dataclass(frozen=True)
104
+ class TurnResult:
105
+ text: str
106
+ stop_reason: str | None
107
+ usage: Usage
108
+ rounds: int
109
+ tool_trail: tuple[Mapping[str, Any], ...]
110
+ emits: tuple[ToolEmit, ...]
111
+
112
+ @property
113
+ def cancelled(self) -> bool:
114
+ return self.stop_reason == CANCELLED
115
+
116
+
117
+ TurnEvent = str | ToolProgress | ToolEmit | TurnResult
118
+
119
+
120
+ class _Cancelled(Exception):
121
+ """Internal: `should_cancel` said stop."""
122
+
123
+
124
+ def _elapsed_ms(started: float) -> int:
125
+ return round((time.monotonic() - started) * 1000)
126
+
127
+
128
+ def _assistant_turn(result: ModelResult) -> ChatMessage:
129
+ """The model's reply as a request message, so the next round sees its own tool calls."""
130
+ content: list[Mapping[str, Any]] = []
131
+ if result.text:
132
+ content.append({"type": "text", "text": result.text})
133
+ content.extend(tool_use_dict(t) for t in result.tool_uses)
134
+ return ChatMessage(role="assistant", content=content)
135
+
136
+
137
+ def _generation_output(result: ModelResult) -> dict[str, Any]:
138
+ return {
139
+ "text": result.text,
140
+ "tool_uses": [tool_use_dict(t) for t in result.tool_uses],
141
+ "stop_reason": result.stop_reason,
142
+ }
143
+
144
+
145
+ async def _run_tool(tools: ToolRegistry, call: ToolUse, context: ToolContext) -> ToolResult:
146
+ tool = tools.get(call.name)
147
+ if tool is None:
148
+ known = ", ".join(tools.names) or "none"
149
+ return ToolResult(f"Unknown tool `{call.name}`. Available tools: {known}.", is_error=True)
150
+ try:
151
+ return await tool.handler(call.input, context)
152
+ except ToolError as exc:
153
+ return ToolResult(str(exc) or f"`{call.name}` failed.", is_error=True)
154
+ except Exception as exc:
155
+ logger.exception("agent2dashboard.tool.failed", extra={"tool": call.name})
156
+ return ToolResult(
157
+ f"`{call.name}` failed with an internal error. Try a different approach.",
158
+ is_error=True,
159
+ trace_metadata={"exception": type(exc).__name__},
160
+ )
161
+
162
+
163
+ async def _close_turn(turn: ModelTurn | None) -> None:
164
+ aclose = getattr(turn.text_deltas, "aclose", None) if turn is not None else None
165
+ if aclose is not None:
166
+ with contextlib.suppress(Exception):
167
+ await aclose()
168
+
169
+
170
+ async def run_agent_loop(
171
+ *,
172
+ llm: LLMProvider,
173
+ system: str,
174
+ messages: list[ChatMessage],
175
+ tools: ToolRegistry,
176
+ context: ToolContext,
177
+ trace: RunTrace | None = None,
178
+ max_tool_rounds: int = MAX_TOOL_ROUNDS,
179
+ max_tokens: int = DEFAULT_MAX_TOKENS,
180
+ should_cancel: CancelCheck | None = None,
181
+ state: TurnState | None = None,
182
+ ) -> AsyncIterator[TurnEvent]:
183
+ state = state if state is not None else TurnState()
184
+ messages = list(messages)
185
+ definitions = tools.definitions()
186
+ system_sha = text_digest(system)
187
+
188
+ async def check_cancel() -> None:
189
+ if should_cancel is not None and await should_cancel():
190
+ raise _Cancelled
191
+
192
+ # What is in flight, so an interruption can be traced against it.
193
+ turn: ModelTurn | None = None
194
+ gen_round: int | None = None
195
+ gen_input: Any = None
196
+ gen_started = 0.0
197
+ round_parts: list[str] = []
198
+
199
+ def trace_generation(output: Any, usage: Usage, error: str | None) -> None:
200
+ nonlocal gen_round
201
+ if trace is not None and gen_round is not None:
202
+ trace.generation(
203
+ round=gen_round,
204
+ input=gen_input,
205
+ output=output,
206
+ usage=usage,
207
+ latency_ms=_elapsed_ms(gen_started),
208
+ error=error,
209
+ )
210
+ gen_round = None
211
+
212
+ try:
213
+ for round_number in range(max_tool_rounds + 1):
214
+ await check_cancel()
215
+ state.rounds = round_number + 1
216
+ forced_final = bool(definitions) and round_number == max_tool_rounds
217
+ tool_choice: Literal["auto", "none"] = "none" if forced_final else "auto"
218
+ gen_round, gen_started, round_parts = round_number, time.monotonic(), []
219
+ gen_input = {
220
+ "messages": message_dicts(messages),
221
+ "tool_choice": tool_choice,
222
+ "max_tokens": max_tokens,
223
+ "model": llm.model_id,
224
+ "system_sha256": system_sha,
225
+ **({"system": system} if round_number == 0 else {}),
226
+ }
227
+ turn = await llm.stream(
228
+ system=system,
229
+ messages=messages,
230
+ tools=definitions,
231
+ max_tokens=max_tokens,
232
+ tool_choice=tool_choice,
233
+ )
234
+ separator = ROUND_SEPARATOR if state.parts else ""
235
+ async for delta in turn.text_deltas:
236
+ if not delta:
237
+ continue
238
+ chunk, separator = separator + delta, ""
239
+ state.parts.append(chunk)
240
+ round_parts.append(delta)
241
+ yield chunk
242
+ await check_cancel()
243
+ result = await turn.result()
244
+ turn = None
245
+ state.input_tokens += result.usage.input_tokens
246
+ state.output_tokens += result.usage.output_tokens
247
+ state.stop_reason = result.stop_reason
248
+ trace_generation(_generation_output(result), result.usage, None)
249
+
250
+ if result.stop_reason != "tool_use" or not result.tool_uses:
251
+ break
252
+ if forced_final: # the model ignored `tool_choice: none`; its calls are not run
253
+ state.stop_reason = MAX_TOOL_ROUNDS_REACHED
254
+ break
255
+ messages.append(_assistant_turn(result))
256
+
257
+ answers: list[Mapping[str, Any]] = []
258
+ totals = Counter(call.name for call in result.tool_uses)
259
+ seen: Counter[str] = Counter()
260
+ for call in result.tool_uses:
261
+ await check_cancel()
262
+ seen[call.name] += 1
263
+ position = {"index": seen[call.name], "count": totals[call.name]}
264
+ yield ToolProgress(
265
+ call.name, "started", call.input, **position, tool_use_id=call.id
266
+ )
267
+ started = time.monotonic()
268
+ try:
269
+ answer = await _run_tool(tools, call, context)
270
+ except BaseException:
271
+ if trace is not None:
272
+ trace.tool(
273
+ name=call.name,
274
+ input=call.input,
275
+ result_summary=INTERRUPTED,
276
+ is_error=True,
277
+ metadata={"tool_use_id": call.id, "round": round_number},
278
+ latency_ms=_elapsed_ms(started),
279
+ )
280
+ raise
281
+ progress = ToolProgress(
282
+ call.name,
283
+ "finished",
284
+ call.input,
285
+ **position,
286
+ is_error=answer.is_error,
287
+ result=answer.content,
288
+ tool_use_id=call.id,
289
+ )
290
+ if len(state.trail) < TOOL_TRAIL_MAX_CALLS:
291
+ state.trail.append(trail_entry(progress))
292
+ if trace is not None:
293
+ trace.tool(
294
+ name=call.name,
295
+ input=call.input,
296
+ result_summary=answer.content,
297
+ is_error=answer.is_error,
298
+ metadata={
299
+ "tool_use_id": call.id,
300
+ "round": round_number,
301
+ **(answer.trace_metadata or {}),
302
+ },
303
+ latency_ms=_elapsed_ms(started),
304
+ )
305
+ yield progress
306
+ if answer.emit is not None:
307
+ emit = ToolEmit(name=call.name, payload=answer.emit)
308
+ state.emits.append(emit)
309
+ yield emit
310
+ answers.append(
311
+ {
312
+ "type": "tool_result",
313
+ "tool_use_id": call.id,
314
+ "content": answer.content,
315
+ "is_error": answer.is_error,
316
+ }
317
+ )
318
+ messages.append(ChatMessage(role="user", content=answers))
319
+ except _Cancelled:
320
+ await _close_turn(turn)
321
+ state.stop_reason = CANCELLED
322
+ trace_generation({"text": "".join(round_parts)}, Usage(), CANCELLED)
323
+ except (asyncio.CancelledError, GeneratorExit):
324
+ state.stop_reason = INTERRUPTED
325
+ await _close_turn(turn)
326
+ trace_generation({"text": "".join(round_parts)}, Usage(), INTERRUPTED)
327
+ raise
328
+ except Exception as exc:
329
+ state.stop_reason = "error"
330
+ await _close_turn(turn)
331
+ trace_generation({"text": "".join(round_parts)}, Usage(), str(exc) or type(exc).__name__)
332
+ raise
333
+
334
+ yield TurnResult(
335
+ text=state.text,
336
+ stop_reason=state.stop_reason,
337
+ usage=state.usage,
338
+ rounds=state.rounds,
339
+ tool_trail=tuple(state.trail),
340
+ emits=tuple(state.emits),
341
+ )
@@ -0,0 +1,66 @@
1
+ """The system prompt: SDK default + host addendum + semantic index + locale line (§3.5, §3.9).
2
+
3
+ The parts that are the same for every turn of a host come first and the per-principal parts
4
+ last, so prompt caching can apply to the fixed prefix (§1.10 *Prompt budget*).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Mapping
10
+
11
+ from agent2dashboard.ports import Principal, SemanticProvider
12
+
13
+ __all__ = ["DEFAULT_SYSTEM_PROMPT", "LOCALE_NAMES", "build_system_prompt", "locale_line"]
14
+
15
+ DEFAULT_SYSTEM_PROMPT = """\
16
+ You are a data analyst inside a business application. You answer questions about the \
17
+ application's governed data and build live dashboards inside this conversation.
18
+
19
+ How you work:
20
+ - Look up structure before you write SQL: list the tables, describe the ones you need, and \
21
+ search the metric definitions. Use a metric's own SQL when one fits the question.
22
+ - You never see row values. Tools answer with structure only: table columns, and for a \
23
+ query its result columns, their kinds and the row count.
24
+ - Register every query with `define_query` before a dashboard uses it. A dashboard refers to \
25
+ a query by its id; SQL never goes into the dashboard.
26
+ - Build or change the dashboard with `render_dashboard`. When a tool answers with an error, \
27
+ read it, fix the call and try again.
28
+ - The conversation has one dashboard. To change it, send only the components that change.
29
+ - Keep replies short: say what you built or found, and what the user can ask next. Do not \
30
+ repeat numbers you have not seen.
31
+ - If a question cannot be answered from the governed data, say so plainly."""
32
+
33
+ # Names the model is told, by locale code (the SDK's defaults are en + vi, §10 #9).
34
+ LOCALE_NAMES: Mapping[str, str] = {"en": "English", "vi": "Vietnamese (Tiếng Việt)"}
35
+
36
+
37
+ def locale_line(locale: str) -> str:
38
+ name = LOCALE_NAMES.get(locale) or LOCALE_NAMES.get(locale.split("-", 1)[0]) or locale
39
+ return (
40
+ f"The user's interface language is {name} (`{locale}`). Answer in it, unless the "
41
+ "user writes to you in another language."
42
+ )
43
+
44
+
45
+ async def build_system_prompt(
46
+ *,
47
+ principal: Principal,
48
+ default_locale: str = "en",
49
+ semantic: SemanticProvider | None = None,
50
+ addendum: str | None = None,
51
+ locale_addenda: Mapping[str, str] | None = None,
52
+ base: str = DEFAULT_SYSTEM_PROMPT,
53
+ ) -> str:
54
+ """`base` (the SDK default), then the host's `addendum`, then the semantic provider's
55
+ `context_index` for this principal, then the locale line and the host's addendum for that
56
+ locale, if any. Empty parts are left out."""
57
+ locale = principal.locale or default_locale
58
+ context = await semantic.context_index(principal) if semantic is not None else None
59
+ parts = [
60
+ base,
61
+ addendum,
62
+ context,
63
+ locale_line(locale),
64
+ (locale_addenda or {}).get(locale),
65
+ ]
66
+ return "\n\n".join(part.strip() for part in parts if part and part.strip())
@@ -0,0 +1,162 @@
1
+ """Tools the agent loop offers the model, registered by name (design §1.10 *Agent tools*).
2
+
3
+ Copied from XoraOps' `llm/client.py` (`ToolResult`, `ToolEmit`, `ToolProgress`) and generalised:
4
+ a tool is a `ToolDef` plus an async handler, kept in a `ToolRegistry`. Other SDK modules plug
5
+ their tools in by name (`define_query`, `render_dashboard`, `describe_table`, ...); the loop
6
+ only knows the registry. A tool's answer to the model is structure only, never row values.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Awaitable, Callable, Iterable, Mapping
12
+ from dataclasses import dataclass, field
13
+ from typing import Any, Literal
14
+
15
+ from agent2dashboard.ports import Capability, Principal, ToolDef
16
+
17
+ __all__ = [
18
+ "DEFINE_QUERY",
19
+ "DESCRIBE_TABLE",
20
+ "GET_METRIC",
21
+ "LIST_TABLES",
22
+ "RENDER_DASHBOARD",
23
+ "SEARCH_METRICS",
24
+ "Tool",
25
+ "ToolContext",
26
+ "ToolEmit",
27
+ "ToolError",
28
+ "ToolHandler",
29
+ "ToolProgress",
30
+ "ToolRegistry",
31
+ "ToolResult",
32
+ ]
33
+
34
+ # Names of the SDK's own tools (§1.10). Their handlers live with the module that owns them.
35
+ LIST_TABLES = "list_tables"
36
+ DESCRIBE_TABLE = "describe_table"
37
+ SEARCH_METRICS = "search_metrics"
38
+ GET_METRIC = "get_metric"
39
+ DEFINE_QUERY = "define_query"
40
+ RENDER_DASHBOARD = "render_dashboard"
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class ToolResult:
45
+ """What a tool answers the model. `is_error` tells the model the call failed and why, so
46
+ it can fix the call; the run carries on."""
47
+
48
+ content: str
49
+ is_error: bool = False
50
+ # Sent to the caller as a `ToolEmit` as well, for results the user must see (e.g. the
51
+ # compiled A2UI messages of an accepted `render_dashboard`), not only the model.
52
+ emit: Mapping[str, Any] | None = None
53
+ # Extra facts about the call for its trace (never row values).
54
+ trace_metadata: Mapping[str, Any] | None = None
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class ToolEmit:
59
+ name: str
60
+ payload: Mapping[str, Any]
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class ToolProgress:
65
+ """A tool call starting or finishing, so a caller can show what the agent is doing while
66
+ no text streams. `index` and `count` place it among the calls of the same tool in its
67
+ round (1-based), e.g. query 3 of 9."""
68
+
69
+ name: str
70
+ status: Literal["started", "finished"]
71
+ tool_input: Mapping[str, Any]
72
+ index: int = 1
73
+ count: int = 1
74
+ is_error: bool = False
75
+ # On `finished`: what the tool answered the model (structure only, never row values).
76
+ result: str | None = None
77
+ tool_use_id: str | None = None
78
+
79
+
80
+ class ToolError(Exception):
81
+ """Raised by a handler to answer the model with an error result. The message is sent to
82
+ the model as is, so it must be safe and actionable ("unknown table 'x'; known: ...")."""
83
+
84
+
85
+ @dataclass(frozen=True)
86
+ class ToolContext:
87
+ """What a handler may know about the call it serves."""
88
+
89
+ principal: Principal
90
+ conversation_id: str
91
+ run_id: str
92
+ capabilities: frozenset[Capability] = frozenset()
93
+ locale: str | None = None
94
+ # Room for the module that owns a tool (query registry, surface state, ...).
95
+ extras: Mapping[str, Any] = field(default_factory=dict)
96
+
97
+
98
+ ToolHandler = Callable[[Mapping[str, Any], ToolContext], Awaitable[ToolResult]]
99
+
100
+
101
+ @dataclass(frozen=True)
102
+ class Tool:
103
+ definition: ToolDef
104
+ handler: ToolHandler
105
+ # Offered only to principals with this capability (§3.3: QUERY decides which tools).
106
+ capability: Capability = Capability.CHAT
107
+
108
+ @property
109
+ def name(self) -> str:
110
+ return self.definition.name
111
+
112
+
113
+ class ToolRegistry:
114
+ """Tools by name, in registration order (the order the model sees them)."""
115
+
116
+ def __init__(self, tools: Iterable[Tool] = ()) -> None:
117
+ self._tools: dict[str, Tool] = {}
118
+ for tool in tools:
119
+ self.register(tool)
120
+
121
+ def register(self, tool: Tool, *, replace: bool = False) -> None:
122
+ if tool.name in self._tools and not replace:
123
+ raise ValueError(f"tool {tool.name!r} is already registered")
124
+ self._tools[tool.name] = tool
125
+
126
+ def add(
127
+ self,
128
+ name: str,
129
+ description: str,
130
+ input_schema: Mapping[str, Any],
131
+ handler: ToolHandler,
132
+ *,
133
+ capability: Capability = Capability.CHAT,
134
+ replace: bool = False,
135
+ ) -> Tool:
136
+ tool = Tool(ToolDef(name, description, input_schema), handler, capability)
137
+ self.register(tool, replace=replace)
138
+ return tool
139
+
140
+ def unregister(self, name: str) -> None:
141
+ self._tools.pop(name, None)
142
+
143
+ def get(self, name: str) -> Tool | None:
144
+ return self._tools.get(name)
145
+
146
+ def __contains__(self, name: object) -> bool:
147
+ return name in self._tools
148
+
149
+ def __len__(self) -> int:
150
+ return len(self._tools)
151
+
152
+ @property
153
+ def names(self) -> list[str]:
154
+ return list(self._tools)
155
+
156
+ def offered(self, capabilities: Iterable[Capability]) -> ToolRegistry:
157
+ """The tools a principal holding `capabilities` may call, as a new registry."""
158
+ held = set(capabilities)
159
+ return ToolRegistry(t for t in self._tools.values() if t.capability in held)
160
+
161
+ def definitions(self) -> list[ToolDef]:
162
+ return [tool.definition for tool in self._tools.values()]