Spaces:
Running

File size: 2,783 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
"""Tool contracts: every action the agent can take is a ``ToolSpec`` plus an async handler."""

from __future__ import annotations

import enum
import uuid
from collections.abc import Awaitable, Callable, Mapping
from dataclasses import dataclass, field
from typing import Any

from pydantic import BaseModel, ConfigDict
from sqlalchemy.ext.asyncio import AsyncSession


class RiskTier(enum.IntEnum):
    T0_READ = 0  # read-only
    T1_INTERNAL = 1  # reversible internal write
    T2_EXTERNAL = 2  # external but bounded (quota + undo window)
    T3_CRITICAL = 3  # financial / irreversible / out-of-policy: human approval


class ToolSpec(BaseModel):
    model_config = ConfigDict(arbitrary_types_allowed=True, frozen=True)

    name: str  # "<pack>.<verb>_<noun>", e.g. "ecommerce.refund_order"
    description: str
    input_model: type[BaseModel]
    output_model: type[BaseModel] | None = None
    risk_tier: RiskTier = RiskTier.T3_CRITICAL  # deny-by-default posture
    sensitive_args: tuple[str, ...] = ()  # sinks that reject tainted values
    supports_dry_run: bool = True
    pack: str | None = None
    always_loaded: bool = False  # else discovered via tool search
    tags: tuple[str, ...] = ()

    def json_schema(self) -> dict[str, Any]:
        return self.input_model.model_json_schema()


class ToolResult(BaseModel):
    ok: bool
    data: dict[str, Any] | None = None
    error: str | None = None
    dry_run: bool = False
    preview_hash: str | None = None  # hash of the would-be effect (see core.tools.preview)


@dataclass(frozen=True)
class ToolContext:
    """What a handler receives besides its arguments. Never shown to the LLM."""

    tenant_id: uuid.UUID
    actor: str
    run_id: uuid.UUID | None
    session: AsyncSession  # tenant-bound, inside the gateway's transaction
    dry_run: bool
    credentials: Mapping[str, str] = field(default_factory=dict)


ToolHandler = Callable[[BaseModel, ToolContext], Awaitable[ToolResult]]

# Deterministic check run when a sensitive argument is tainted. Returns True if the value
# is confirmed against trusted data (e.g. the recipient equals the customer on file).
TaintValidator = Callable[[Any, dict[str, Any], ToolContext], Awaitable[bool]]

# Adds trusted facts (read from the system of record) to the Cedar policy context,
# e.g. {"order_total": 25000} so a policy can compare it with the requested amount.
PolicyContextProvider = Callable[[dict[str, Any], ToolContext], Awaitable[dict[str, Any]]]


@dataclass(frozen=True)
class RegisteredTool:
    spec: ToolSpec
    handler: ToolHandler
    validators: Mapping[str, TaintValidator] = field(default_factory=dict)
    policy_context: PolicyContextProvider | None = None