draco-harness 0.1.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 (63) hide show
  1. draco/__init__.py +18 -0
  2. draco/adapters/__init__.py +6 -0
  3. draco/adapters/ingestion.py +35 -0
  4. draco/adapters/langgraph.py +57 -0
  5. draco/adapters/langgraph_checkpoint.py +133 -0
  6. draco/adapters/model_provider.py +44 -0
  7. draco/adapters/providers/__init__.py +1 -0
  8. draco/adapters/providers/_http.py +29 -0
  9. draco/adapters/providers/anthropic.py +50 -0
  10. draco/adapters/providers/openai_compat.py +46 -0
  11. draco/adapters/retrieval.py +97 -0
  12. draco/agents/__init__.py +10 -0
  13. draco/agents/registry.py +51 -0
  14. draco/agents/router.py +155 -0
  15. draco/core/__init__.py +25 -0
  16. draco/core/budget.py +75 -0
  17. draco/core/config.py +68 -0
  18. draco/core/context.py +125 -0
  19. draco/core/errors.py +86 -0
  20. draco/core/events.py +74 -0
  21. draco/core/identity.py +35 -0
  22. draco/core/policy.py +57 -0
  23. draco/core/protocols.py +10 -0
  24. draco/core/results.py +138 -0
  25. draco/harness/__init__.py +3 -0
  26. draco/harness/instrument.py +95 -0
  27. draco/harness/persistence.py +34 -0
  28. draco/harness/runner.py +426 -0
  29. draco/observability/__init__.py +2 -0
  30. draco/observability/otel.py +47 -0
  31. draco/observability/redaction.py +35 -0
  32. draco/observability/trace.py +72 -0
  33. draco/plugins/__init__.py +2 -0
  34. draco/plugins/registry.py +198 -0
  35. draco/plugins/services.py +60 -0
  36. draco/policies/__init__.py +3 -0
  37. draco/policies/guardrails.py +31 -0
  38. draco/policies/ratelimit.py +76 -0
  39. draco/py.typed +0 -0
  40. draco/security/__init__.py +5 -0
  41. draco/security/audit.py +29 -0
  42. draco/security/authorization.py +90 -0
  43. draco/security/crypto.py +58 -0
  44. draco/security/secrets.py +48 -0
  45. draco/state/__init__.py +16 -0
  46. draco/state/_sql.py +226 -0
  47. draco/state/memory.py +93 -0
  48. draco/state/postgres.py +125 -0
  49. draco/state/retention.py +33 -0
  50. draco/state/sqlite.py +99 -0
  51. draco/state/stores.py +101 -0
  52. draco/tools/__init__.py +17 -0
  53. draco/tools/contracts.py +120 -0
  54. draco/tools/execution.py +181 -0
  55. draco/tools/mcp.py +109 -0
  56. draco/tools/native.py +45 -0
  57. draco/tools/registry.py +27 -0
  58. draco/tools/safety.py +14 -0
  59. draco_harness-0.1.0.dist-info/METADATA +194 -0
  60. draco_harness-0.1.0.dist-info/RECORD +63 -0
  61. draco_harness-0.1.0.dist-info/WHEEL +5 -0
  62. draco_harness-0.1.0.dist-info/licenses/LICENSE +21 -0
  63. draco_harness-0.1.0.dist-info/top_level.txt +1 -0
draco/__init__.py ADDED
@@ -0,0 +1,18 @@
1
+ """Draco: execution harness and extension layer for RAG and agentic apps."""
2
+ from draco.core import (
3
+ BudgetLimits,
4
+ DracoError,
5
+ DracoSettings,
6
+ ExecutionContext,
7
+ ExecutionResult,
8
+ Handoff,
9
+ Identity,
10
+ Policy,
11
+ Status,
12
+ Waiting,
13
+ )
14
+ from draco.harness import Harness, call_model, call_with_retry, step
15
+
16
+ __version__ = "0.1.0"
17
+ __all__ = ["BudgetLimits", "DracoError", "DracoSettings", "ExecutionContext", "ExecutionResult", "Handoff", "Harness", "Identity",
18
+ "Policy", "Status", "Waiting", "call_model", "call_with_retry", "step"]
@@ -0,0 +1,6 @@
1
+ """Adapters translate external components into Draco contracts.
2
+
3
+ Each adapter is its own module and pulls in its optional dependency only when imported:
4
+ `retrieval`, `ingestion`, `model_provider`, `providers`, `langgraph`, `langgraph_checkpoint`.
5
+ Application-specific adapters live with the application (for example `app.draco_adapters` in draco-rag).
6
+ """
@@ -0,0 +1,35 @@
1
+ """Generic ingestion workload: the harness runs whatever callable the application injects. Parsing,
2
+ chunking, embedding and storage stay in that callable; nothing here knows about them."""
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import inspect
7
+ from collections.abc import Callable
8
+ from typing import Any
9
+
10
+ from draco.core.context import ExecutionContext
11
+ from draco.core.errors import ContractError
12
+ from draco.core.protocols import Workload
13
+ from draco.security.audit import authorize
14
+ from draco.security.authorization import Resource
15
+
16
+
17
+ def ingest_workload(ingest: Callable[..., Any], *, resource_for: Callable[[str], Resource] | None = None) -> Workload:
18
+ """input {'document_id': str, 'file_path': str}. `ingest(document_id, file_path)` may be sync (run in a
19
+ thread) or async. With `resource_for`, `document.ingest` is authorized on the target document before the
20
+ callable runs. Re-running is only safe if `ingest` is idempotent (e.g. deterministic chunk ids)."""
21
+ async def run(ctx: ExecutionContext, inp: Any) -> dict[str, Any]:
22
+ if not isinstance(inp, dict) or not {"document_id", "file_path"} <= inp.keys():
23
+ raise ContractError("input must contain document_id and file_path")
24
+ ctx.check()
25
+ doc = str(inp["document_id"])
26
+ if resource_for is not None:
27
+ await authorize(ctx, "document.ingest", resource_for(doc))
28
+ elif ctx.identity is not None:
29
+ await authorize(ctx, "document.ingest", Resource("document", doc, tenant_id=ctx.tenant_id))
30
+ if inspect.iscoroutinefunction(ingest):
31
+ await ingest(doc, inp["file_path"])
32
+ else:
33
+ await asyncio.to_thread(ingest, doc, inp["file_path"])
34
+ return {"document_id": doc, "status": "processed"}
35
+ return run
@@ -0,0 +1,57 @@
1
+ """Run any compiled LangGraph graph as a Draco workload. LangGraph stays the graph engine; install with
2
+ `pip install draco-harness[agents]` (this module itself imports nothing from langgraph).
3
+
4
+ Semantics:
5
+ - thread id: the Draco execution id, so a checkpointer's state is keyed to the execution. `Harness.resume`
6
+ keeps the execution id, so a resumed run continues the same LangGraph thread.
7
+ - identity: tenant, user, session and correlation ids are passed as run metadata (for tracing only; they
8
+ are never read back from graph state).
9
+ - recursion: `recursion_limit` bounds graph supersteps; exceeding it is reported as `BudgetExhausted`.
10
+ - interrupts: a result containing LangGraph's `__interrupt__` is returned as `Waiting`; continue with
11
+ `harness.resume(id, input=Command(resume=...))`.
12
+ - cancellation/deadline: enforced by the harness around the `ainvoke` task (cooperative at awaits).
13
+ - budgets: model calls made *inside* the graph are only counted if the graph's nodes call
14
+ `draco.harness.call_model`; the adapter cannot see them otherwise."""
15
+
16
+ from __future__ import annotations
17
+
18
+ from collections.abc import Callable
19
+ from typing import Any
20
+
21
+ from draco.adapters.langgraph_checkpoint import checkpoint_config
22
+ from draco.core.context import ExecutionContext
23
+ from draco.core.errors import BudgetExhausted
24
+ from draco.core.protocols import Workload
25
+ from draco.core.results import Waiting
26
+
27
+
28
+ def graph_workload(
29
+ graph: Any,
30
+ *,
31
+ to_state: Callable[[Any], Any] = lambda x: x,
32
+ from_state: Callable[[Any], Any] = lambda s: s,
33
+ recursion_limit: int = 25,
34
+ ) -> Workload:
35
+ """`graph` is a compiled graph with `ainvoke`."""
36
+
37
+ async def run(ctx: ExecutionContext, inp: Any) -> Any:
38
+ ctx.check()
39
+ cfg = checkpoint_config(
40
+ ctx.execution_id,
41
+ tenant_id=ctx.tenant_id,
42
+ user_id=ctx.user_id,
43
+ session_id=ctx.session_id,
44
+ correlation_id=ctx.correlation_id,
45
+ recursion_limit=recursion_limit,
46
+ )
47
+ try:
48
+ out = await graph.ainvoke(to_state(inp), cfg)
49
+ except Exception as exc:
50
+ if type(exc).__name__ == "GraphRecursionError":
51
+ raise BudgetExhausted("graph_steps", recursion_limit) from exc
52
+ raise
53
+ if isinstance(out, dict) and out.get("__interrupt__"):
54
+ return Waiting("graph interrupted", [getattr(i, "value", i) for i in out["__interrupt__"]])
55
+ return from_state(out)
56
+
57
+ return run
@@ -0,0 +1,133 @@
1
+ """Optional LangGraph checkpoint configuration and SQLite saver helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sqlite3
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class CheckpointConfig:
13
+ """Canonical LangGraph thread identity for a Draco execution."""
14
+
15
+ execution_id: str
16
+ tenant_id: str | None = None
17
+ user_id: str | None = None
18
+ session_id: str | None = None
19
+ correlation_id: str | None = None
20
+ checkpoint_ns: str = ""
21
+ recursion_limit: int = 25
22
+
23
+ def __post_init__(self) -> None:
24
+ if not self.execution_id:
25
+ raise ValueError("execution_id must not be empty")
26
+ if self.recursion_limit < 1:
27
+ raise ValueError("recursion_limit must be positive")
28
+
29
+ def to_runnable_config(self) -> dict[str, Any]:
30
+ metadata = {
31
+ key: value
32
+ for key, value in {
33
+ "draco_tenant_id": self.tenant_id,
34
+ "draco_user_id": self.user_id,
35
+ "draco_session_id": self.session_id,
36
+ "draco_correlation_id": self.correlation_id,
37
+ }.items()
38
+ if value is not None
39
+ }
40
+ return {
41
+ "configurable": {
42
+ "thread_id": self.execution_id,
43
+ "checkpoint_ns": self.checkpoint_ns,
44
+ },
45
+ "recursion_limit": self.recursion_limit,
46
+ "metadata": metadata,
47
+ }
48
+
49
+ @classmethod
50
+ def from_execution_context(cls, ctx: Any, *, recursion_limit: int = 25) -> CheckpointConfig:
51
+ """Build from a trusted Draco ExecutionContext."""
52
+ return cls(
53
+ execution_id=ctx.execution_id,
54
+ tenant_id=ctx.tenant_id,
55
+ user_id=ctx.user_id,
56
+ session_id=ctx.session_id,
57
+ correlation_id=ctx.correlation_id,
58
+ recursion_limit=recursion_limit,
59
+ )
60
+
61
+
62
+ def checkpoint_config(
63
+ execution_id: str,
64
+ *,
65
+ tenant_id: str | None = None,
66
+ user_id: str | None = None,
67
+ session_id: str | None = None,
68
+ correlation_id: str | None = None,
69
+ checkpoint_ns: str = "",
70
+ recursion_limit: int = 25,
71
+ ) -> dict[str, Any]:
72
+ """Create a LangGraph RunnableConfig with stable execution and identity metadata."""
73
+ return CheckpointConfig(
74
+ execution_id=execution_id,
75
+ tenant_id=tenant_id,
76
+ user_id=user_id,
77
+ session_id=session_id,
78
+ correlation_id=correlation_id,
79
+ checkpoint_ns=checkpoint_ns,
80
+ recursion_limit=recursion_limit,
81
+ ).to_runnable_config()
82
+
83
+
84
+ def build_sqlite_checkpointer(path: str | Path) -> Any:
85
+ """Create LangGraph's optional SQLite saver for durable graph state.
86
+
87
+ The returned saver owns its SQLite connection; close ``saver.conn`` when
88
+ its lifecycle ends. Install ``draco-harness[agents]`` to enable this helper.
89
+ """
90
+ try:
91
+ from langgraph.checkpoint.sqlite import SqliteSaver
92
+ except ImportError as exc:
93
+ raise ImportError(
94
+ "SQLite checkpointing requires the optional agents dependencies; "
95
+ "install with: pip install 'draco-harness[agents]'"
96
+ ) from exc
97
+
98
+ db_path = str(path)
99
+ if db_path != ":memory:":
100
+ Path(db_path).parent.mkdir(parents=True, exist_ok=True)
101
+ conn = sqlite3.connect(db_path, check_same_thread=False)
102
+ try:
103
+ saver = SqliteSaver(conn)
104
+ saver.setup()
105
+ except Exception:
106
+ conn.close()
107
+ raise
108
+ return saver
109
+
110
+
111
+ def resume_command(decision: str) -> Any:
112
+ """Create the validated resume payload used by the approval interrupt contract."""
113
+ if decision not in ("approve", "reject"):
114
+ raise ValueError("decision must be 'approve' or 'reject'")
115
+ try:
116
+ from langgraph.types import Command
117
+ except ImportError as exc:
118
+ raise ImportError(
119
+ "LangGraph is required for resume_command; install with: pip install 'draco-harness[agents]'"
120
+ ) from exc
121
+ return Command(resume={"decision": decision})
122
+
123
+
124
+ def is_interrupted(result: Any) -> bool:
125
+ """Return whether a LangGraph result carries at least one interrupt."""
126
+ return isinstance(result, dict) and bool(result.get("__interrupt__"))
127
+
128
+
129
+ def extract_interrupts(result: Any) -> list[Any]:
130
+ """Return interrupt values, not LangGraph's wrapper objects."""
131
+ if not is_interrupted(result):
132
+ return []
133
+ return [getattr(item, "value", item) for item in result["__interrupt__"]]
@@ -0,0 +1,44 @@
1
+ """Provider-neutral model call contract. Concrete providers (vLLM, OpenAI-compatible, Anthropic ...) live
2
+ in optional integration modules and only need to satisfy `ModelProvider`."""
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Protocol, runtime_checkable
7
+
8
+ from draco.core.context import ExecutionContext
9
+ from draco.harness.instrument import call_model
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class ModelRequest:
14
+ messages: list[dict[str, Any]]
15
+ model: str | None = None
16
+ params: dict[str, Any] = field(default_factory=dict) # temperature, max_tokens ... provider-interpreted
17
+
18
+
19
+ @dataclass
20
+ class ModelResponse:
21
+ text: str
22
+ model: str = ""
23
+ input_tokens: int = 0
24
+ output_tokens: int = 0
25
+ raw: Any = None # provider payload; never exported to traces
26
+
27
+ @property
28
+ def total_tokens(self) -> int:
29
+ return self.input_tokens + self.output_tokens
30
+
31
+
32
+ @runtime_checkable
33
+ class ModelProvider(Protocol):
34
+ name: str
35
+
36
+ async def generate(self, request: ModelRequest) -> ModelResponse: ...
37
+
38
+
39
+ async def generate(ctx: ExecutionContext, provider: ModelProvider, request: ModelRequest) -> ModelResponse:
40
+ """Run a provider call as a budget-charged, cancellable, evented model call with token accounting.
41
+ Provider exceptions propagate unchanged: have providers raise `ProviderError` with `retryable` set,
42
+ then wrap with `draco.harness.call_with_retry` if the call is safe to repeat."""
43
+ return await call_model(ctx, provider.generate, request, provider=provider.name, model=request.model or "",
44
+ usage_of=lambda r: r.total_tokens or None)
@@ -0,0 +1 @@
1
+ """Concrete `ModelProvider` implementations. Optional: `pip install draco-harness[providers]` (httpx)."""
@@ -0,0 +1,29 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ from draco.core.errors import ProviderError
6
+
7
+ _RETRYABLE = {408, 409, 425, 429, 500, 502, 503, 504, 529}
8
+
9
+
10
+ async def post_json(client: Any, url: str, *, headers: dict[str, str], body: dict[str, Any], provider: str) -> dict[str, Any]:
11
+ """POST and decode JSON, mapping every failure to ProviderError. Response bodies and headers are never put
12
+ in the error (they can echo prompts or credentials); only the status code is."""
13
+ import httpx
14
+ try:
15
+ resp = await client.post(url, headers=headers, json=body)
16
+ except httpx.TimeoutException as exc:
17
+ raise ProviderError(f"{provider} request timed out", retryable=True) from exc
18
+ except httpx.HTTPError as exc:
19
+ raise ProviderError(f"{provider} request failed ({type(exc).__name__})", retryable=True) from exc
20
+ if resp.status_code >= 400:
21
+ raise ProviderError(f"{provider} returned HTTP {resp.status_code}", retryable=resp.status_code in _RETRYABLE,
22
+ details={"status_code": resp.status_code})
23
+ try:
24
+ data = resp.json()
25
+ except ValueError as exc:
26
+ raise ProviderError(f"{provider} returned invalid JSON") from exc
27
+ if not isinstance(data, dict):
28
+ raise ProviderError(f"{provider} returned an unexpected payload")
29
+ return data
@@ -0,0 +1,50 @@
1
+ """Anthropic Messages API over httpx (no SDK dependency)."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any
5
+
6
+ from draco.adapters.model_provider import ModelRequest, ModelResponse
7
+ from draco.adapters.providers._http import post_json
8
+ from draco.core.errors import ConfigurationError, ProviderError
9
+ from draco.security.secrets import Secret
10
+
11
+ API_VERSION = "2023-06-01"
12
+
13
+
14
+ class AnthropicProvider:
15
+ name = "anthropic"
16
+
17
+ def __init__(self, api_key: Secret, *, model: str | None = None, base_url: str = "https://api.anthropic.com",
18
+ client: Any = None, timeout_s: float = 60.0, default_max_tokens: int = 1024):
19
+ self._key, self.model, self.base_url = api_key, model, base_url.rstrip("/")
20
+ self._client, self._timeout, self.default_max_tokens = client, timeout_s, default_max_tokens
21
+
22
+ def _http(self) -> Any:
23
+ if self._client is None:
24
+ import httpx
25
+ self._client = httpx.AsyncClient(timeout=self._timeout)
26
+ return self._client
27
+
28
+ async def aclose(self) -> None:
29
+ if self._client is not None:
30
+ await self._client.aclose()
31
+
32
+ async def generate(self, request: ModelRequest) -> ModelResponse:
33
+ model = request.model or self.model
34
+ if not model:
35
+ raise ConfigurationError("no model configured for this request")
36
+ system = "\n\n".join(str(m["content"]) for m in request.messages if m.get("role") == "system")
37
+ messages = [m for m in request.messages if m.get("role") != "system"]
38
+ body: dict[str, Any] = {"model": model, "max_tokens": self.default_max_tokens, "messages": messages,
39
+ **request.params}
40
+ if system:
41
+ body["system"] = system
42
+ headers = {"x-api-key": self._key.reveal(), "anthropic-version": API_VERSION, "content-type": "application/json"}
43
+ data = await post_json(self._http(), f"{self.base_url}/v1/messages", headers=headers, body=body, provider=self.name)
44
+ try:
45
+ text = "".join(b.get("text", "") for b in data["content"] if b.get("type") == "text")
46
+ except (KeyError, TypeError, AttributeError) as exc:
47
+ raise ProviderError("anthropic returned an unexpected payload") from exc
48
+ usage = data.get("usage") or {}
49
+ return ModelResponse(text, str(data.get("model") or model), int(usage.get("input_tokens") or 0),
50
+ int(usage.get("output_tokens") or 0), raw=data)
@@ -0,0 +1,46 @@
1
+ """OpenAI-compatible chat completions (OpenAI, vLLM, llama.cpp server, ...)."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any
5
+
6
+ from draco.adapters.model_provider import ModelRequest, ModelResponse
7
+ from draco.adapters.providers._http import post_json
8
+ from draco.core.errors import ConfigurationError, ProviderError
9
+ from draco.security.secrets import Secret
10
+
11
+
12
+ class OpenAICompatProvider:
13
+ def __init__(self, base_url: str, *, api_key: Secret | None = None, model: str | None = None,
14
+ client: Any = None, timeout_s: float = 60.0, name: str = "openai_compat"):
15
+ """`base_url` includes the version prefix, e.g. https://host/v1. Pass `client` (httpx.AsyncClient)
16
+ to control transport, proxies or testing; otherwise one is created lazily and owned by the provider."""
17
+ self.name, self.base_url, self.model, self._key, self._timeout = name, base_url.rstrip("/"), model, api_key, timeout_s
18
+ self._client = client
19
+
20
+ def _http(self) -> Any:
21
+ if self._client is None:
22
+ import httpx
23
+ self._client = httpx.AsyncClient(timeout=self._timeout)
24
+ return self._client
25
+
26
+ async def aclose(self) -> None:
27
+ if self._client is not None:
28
+ await self._client.aclose()
29
+
30
+ async def generate(self, request: ModelRequest) -> ModelResponse:
31
+ model = request.model or self.model
32
+ if not model:
33
+ raise ConfigurationError("no model configured for this request")
34
+ headers = {"content-type": "application/json"}
35
+ if self._key is not None:
36
+ headers["authorization"] = f"Bearer {self._key.reveal()}"
37
+ body: dict[str, Any] = {"model": model, "messages": request.messages, **request.params}
38
+ data = await post_json(self._http(), f"{self.base_url}/chat/completions", headers=headers, body=body,
39
+ provider=self.name)
40
+ try:
41
+ text = data["choices"][0]["message"]["content"] or ""
42
+ except (KeyError, IndexError, TypeError) as exc:
43
+ raise ProviderError(f"{self.name} returned an unexpected payload") from exc
44
+ usage = data.get("usage") or {}
45
+ return ModelResponse(text, str(data.get("model") or model), int(usage.get("prompt_tokens") or 0),
46
+ int(usage.get("completion_tokens") or 0), raw=data)
@@ -0,0 +1,97 @@
1
+ """Provider-neutral retrieval contract with authorization applied before and after the backend call.
2
+
3
+ Retrieval is optional: nothing in the core imports this module. A backend implements `Retriever`; the
4
+ An application's own retrieval service is adapted on the application side (see draco-rag's `app.draco_adapters.retrieval`)."""
5
+ from __future__ import annotations
6
+
7
+ from collections.abc import Callable
8
+ from dataclasses import asdict, dataclass, field
9
+ from typing import Any, Protocol, runtime_checkable
10
+
11
+ from draco.core.context import ExecutionContext
12
+ from draco.core.errors import ContractError, PolicyViolation
13
+ from draco.core.protocols import Workload
14
+ from draco.harness.instrument import emit
15
+ from draco.security.audit import audit, authorize
16
+ from draco.security.authorization import Decision, Resource, decide
17
+
18
+
19
+ @dataclass
20
+ class Evidence:
21
+ document_id: str
22
+ text: str
23
+ chunk_id: str = ""
24
+ score: float | None = None
25
+ source: str = ""
26
+ locator: dict[str, Any] = field(default_factory=dict) # page range, offsets ...
27
+
28
+
29
+ @dataclass
30
+ class RetrievalResult:
31
+ query: str
32
+ evidence: list[Evidence]
33
+ degraded: list[str] = field(default_factory=list)
34
+ meta: dict[str, Any] = field(default_factory=dict)
35
+
36
+
37
+ @runtime_checkable
38
+ class Retriever(Protocol):
39
+ async def retrieve(self, ctx: ExecutionContext, query: str, document_ids: list[str] | None) -> RetrievalResult: ...
40
+
41
+
42
+ DocumentResource = Callable[[str], Resource] # document id -> Resource carrying the owning tenant/ACL attributes
43
+
44
+
45
+ async def authorize_request(ctx: ExecutionContext, document_ids: list[str] | None,
46
+ document_resource: DocumentResource | None) -> None:
47
+ """Before the backend runs. Fails closed in identity-aware (multi-tenant) mode: if documents are
48
+ requested but the application gave no way to resolve their owners, the request is denied."""
49
+ await authorize(ctx, "retrieval.query", Resource("retrieval", tenant_id=ctx.tenant_id))
50
+ for doc in document_ids or []:
51
+ if document_resource is None:
52
+ if ctx.identity is not None:
53
+ raise PolicyViolation("document access cannot be verified: no document_resource configured")
54
+ continue
55
+ await authorize(ctx, "document.read", document_resource(doc))
56
+
57
+
58
+ async def authorize_evidence(ctx: ExecutionContext, evidence: list[Evidence],
59
+ document_resource: DocumentResource | None) -> list[Evidence]:
60
+ """After the backend ran: drop (and audit) evidence the caller may not read. Backends may over-return
61
+ (shared index), so the result is never trusted to be pre-filtered."""
62
+ if document_resource is None:
63
+ if ctx.identity is not None and evidence:
64
+ raise PolicyViolation("document access cannot be verified: no document_resource configured")
65
+ return evidence
66
+ cache: dict[str, Decision] = {}
67
+ kept = []
68
+ for e in evidence:
69
+ res = document_resource(e.document_id)
70
+ if e.document_id not in cache:
71
+ authorizer = ctx.services.get("authorizer")
72
+ cache[e.document_id] = await decide(authorizer, ctx.identity, "document.read", res)
73
+ await audit(ctx, "document.read", res, cache[e.document_id], stage="post_retrieval")
74
+ if cache[e.document_id].allowed:
75
+ kept.append(e)
76
+ return kept
77
+
78
+
79
+ def retrieval_workload(retriever: Retriever, *, document_resource: DocumentResource | None = None) -> Workload:
80
+ """query string or {'query': str, 'document_ids': [...]} -> {'query', 'evidence', 'degraded'}."""
81
+ async def run(ctx: ExecutionContext, inp: Any) -> dict[str, Any]:
82
+ if isinstance(inp, str):
83
+ query, docs = inp, None
84
+ elif isinstance(inp, dict) and isinstance(inp.get("query"), str):
85
+ query, docs = inp["query"], inp.get("document_ids")
86
+ else:
87
+ raise ContractError("input must be a query string or {'query': str, 'document_ids': [...]}")
88
+ if docs is not None and not (isinstance(docs, list) and all(isinstance(d, str) for d in docs)):
89
+ raise ContractError("document_ids must be a list of strings")
90
+ ctx.check()
91
+ await authorize_request(ctx, docs, document_resource)
92
+ res = await retriever.retrieve(ctx, query, docs)
93
+ evidence = await authorize_evidence(ctx, res.evidence, document_resource)
94
+ await emit(ctx, "retrieval.after", selected=len(evidence), withheld=len(res.evidence) - len(evidence),
95
+ degraded=list(res.degraded))
96
+ return {"query": res.query, "evidence": [asdict(e) for e in evidence], "degraded": list(res.degraded)}
97
+ return run
@@ -0,0 +1,10 @@
1
+ from draco.agents.registry import AgentRegistry, AgentSpec
2
+ from draco.agents.router import (
3
+ Router,
4
+ RouteRequest,
5
+ RoutingDecision,
6
+ by_capability,
7
+ explicit,
8
+ llm_proposal,
9
+ rules,
10
+ )
@@ -0,0 +1,51 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import Any
5
+
6
+ from draco.core.errors import ContractError, RoutingError
7
+ from draco.core.protocols import Workload
8
+ from draco.harness.runner import Harness
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class AgentSpec:
13
+ name: str
14
+ description: str = ""
15
+ capabilities: frozenset[str] = frozenset()
16
+ meta: dict[str, Any] = field(default_factory=dict)
17
+
18
+
19
+ class AgentRegistry:
20
+ """Agents are harness workloads plus routing metadata. Provider-independent: an agent is any
21
+ async callable (a LangGraph graph, a RAG pipeline, a plain function)."""
22
+
23
+ def __init__(self, harness: Harness):
24
+ self.harness = harness
25
+ self._agents: dict[str, AgentSpec] = {}
26
+
27
+ def register(self, name: str, fn: Workload, *, description: str = "",
28
+ capabilities: set[str] | frozenset[str] = frozenset(), **meta: Any) -> AgentSpec:
29
+ if not name or name == "router":
30
+ raise ContractError(f"invalid agent name '{name}'")
31
+ if name in self._agents:
32
+ raise ContractError(f"agent '{name}' already registered")
33
+ self.harness.register(name, fn, description=description, capabilities=capabilities, **meta)
34
+ spec = AgentSpec(name, description, frozenset(capabilities), meta)
35
+ self._agents[name] = spec
36
+ return spec
37
+
38
+ def get(self, name: str) -> AgentSpec:
39
+ try:
40
+ return self._agents[name]
41
+ except KeyError:
42
+ raise RoutingError(f"unknown agent '{name}'", details={"known": sorted(self._agents)}) from None
43
+
44
+ def has(self, name: str) -> bool:
45
+ return name in self._agents
46
+
47
+ def all(self) -> list[AgentSpec]:
48
+ return [self._agents[k] for k in sorted(self._agents)]
49
+
50
+ def with_capabilities(self, required: set[str] | frozenset[str]) -> list[AgentSpec]:
51
+ return [a for a in self.all() if frozenset(required) <= a.capabilities]