verilink-sdk 3.7.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.
- verilink_sdk/__init__.py +27 -0
- verilink_sdk/_check_schemas.py +108 -0
- verilink_sdk/_enums.py +146 -0
- verilink_sdk/_version.py +7 -0
- verilink_sdk/adapters/__init__.py +5 -0
- verilink_sdk/adapters/autogen.py +63 -0
- verilink_sdk/adapters/crewai.py +45 -0
- verilink_sdk/adapters/guardian.py +237 -0
- verilink_sdk/adapters/langchain.py +48 -0
- verilink_sdk/adapters/openclaw.py +56 -0
- verilink_sdk/canonical.py +190 -0
- verilink_sdk/client.py +957 -0
- verilink_sdk/mcp/__init__.py +3 -0
- verilink_sdk/mcp/adapters.py +120 -0
- verilink_sdk/mcp/app_views.py +63 -0
- verilink_sdk/mcp/cli.py +5 -0
- verilink_sdk/mcp/client.py +298 -0
- verilink_sdk/mcp/server.py +201 -0
- verilink_sdk/mcp/tasks.py +156 -0
- verilink_sdk/schemas.py +387 -0
- verilink_sdk-3.7.0.dist-info/METADATA +185 -0
- verilink_sdk-3.7.0.dist-info/RECORD +25 -0
- verilink_sdk-3.7.0.dist-info/WHEEL +5 -0
- verilink_sdk-3.7.0.dist-info/entry_points.txt +2 -0
- verilink_sdk-3.7.0.dist-info/top_level.txt +1 -0
verilink_sdk/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
from .client import VeriLinkClient, VAPReceiptBuilder
|
|
2
|
+
from .schemas import *
|
|
3
|
+
from .adapters.guardian import (
|
|
4
|
+
enforce,
|
|
5
|
+
preflight,
|
|
6
|
+
PreflightBlocked,
|
|
7
|
+
set_active_client,
|
|
8
|
+
get_active_client,
|
|
9
|
+
set_client,
|
|
10
|
+
get_client,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
# Backward compatibility alias
|
|
14
|
+
VeriLinkSDKClient = VeriLinkClient
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"VeriLinkClient",
|
|
18
|
+
"VeriLinkSDKClient",
|
|
19
|
+
"VAPReceiptBuilder",
|
|
20
|
+
"enforce",
|
|
21
|
+
"preflight",
|
|
22
|
+
"PreflightBlocked",
|
|
23
|
+
"set_active_client",
|
|
24
|
+
"get_active_client",
|
|
25
|
+
"set_client",
|
|
26
|
+
"get_client"
|
|
27
|
+
]
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Pre-flight check schemas, vendored from verilink.schemas.core.
|
|
2
|
+
|
|
3
|
+
Kept in the SDK so the published wheel has no dependency on the server package.
|
|
4
|
+
"""
|
|
5
|
+
from typing import Any, Dict, List, Optional
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from enum import Enum
|
|
8
|
+
from pydantic import BaseModel, Field, ConfigDict
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class CheckActionabilityOptions(BaseModel):
|
|
12
|
+
"""Optional flags controlling check_actionability behavior."""
|
|
13
|
+
explain: bool = True
|
|
14
|
+
check_claims: bool = True
|
|
15
|
+
estimate_cost: bool = True
|
|
16
|
+
return_receipt: bool = True
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class CheckActionabilityRequest(BaseModel):
|
|
20
|
+
"""Input for the public pre-flight check."""
|
|
21
|
+
action: Dict[str, Any] = Field(..., description="Full action: type + inputs")
|
|
22
|
+
agent: Optional[Dict[str, Any]] = Field(None, description="Agent DID + capabilities")
|
|
23
|
+
organization: Optional[Dict[str, Any]] = Field(None, description="Org id + policy_version")
|
|
24
|
+
options: Optional[CheckActionabilityOptions] = Field(
|
|
25
|
+
default_factory=CheckActionabilityOptions,
|
|
26
|
+
description="Optional behavior flags",
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class MissingClaim(BaseModel):
|
|
31
|
+
"""A claim the agent must satisfy to make the action actionable."""
|
|
32
|
+
claim_id: str = Field(..., description="Stable identifier for the claim")
|
|
33
|
+
type: str = Field(..., description="human_approval | regulatory | technical | evidence | delegation")
|
|
34
|
+
description: str = Field(..., description="Human-readable description of what's required")
|
|
35
|
+
how_to_satisfy: str = Field(..., description="Specific action the agent can take")
|
|
36
|
+
priority: str = Field(..., description="blocking | warning")
|
|
37
|
+
endpoint: Optional[str] = Field(None, description="API endpoint or CLI command to satisfy")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class EstimatedCost(BaseModel):
|
|
41
|
+
"""Estimated cost of executing (or attempting) the action."""
|
|
42
|
+
tokens: int = Field(0, ge=0, description="Estimated token consumption")
|
|
43
|
+
rep_impact: float = Field(0.0, description="Estimated reputation change (negative = loss)")
|
|
44
|
+
rep_impact_reason: Optional[str] = Field(None, description="Why the reputation moves")
|
|
45
|
+
api_cost_usd: float = Field(0.0, ge=0.0, description="Estimated API cost in USD")
|
|
46
|
+
est_execution_time_ms: int = Field(0, ge=0, description="Estimated execution time")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class ReasoningStep(BaseModel):
|
|
50
|
+
"""One step in the decision reasoning path."""
|
|
51
|
+
step: int = Field(..., ge=1)
|
|
52
|
+
check: str = Field(..., description="e.g. agent_revocation | delegation_scope | policy_evaluation")
|
|
53
|
+
result: str = Field(..., description="clean | valid | blocked | escalated | unknown")
|
|
54
|
+
note: Optional[str] = None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class NextStep(BaseModel):
|
|
58
|
+
"""A concrete next step the agent can take."""
|
|
59
|
+
action: str = Field(..., description="reduce_amount | request_extension | escalate_hitl | wait_until | ...")
|
|
60
|
+
description: str = Field(..., description="Human-readable description of the option")
|
|
61
|
+
endpoint: Optional[str] = Field(None, description="API endpoint for this option")
|
|
62
|
+
example: Optional[Dict[str, Any]] = Field(None, description="Example payload")
|
|
63
|
+
retry_after: Optional[datetime] = Field(None, description="When to retry (time-based blocks)")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class CheckActionabilityVerdict(BaseModel):
|
|
67
|
+
"""The verdict — multiple views for different consumers."""
|
|
68
|
+
is_actionable: bool = Field(..., description="Headline answer: is this actionable?")
|
|
69
|
+
allowed: bool = Field(..., description="Would enforce() permit this?")
|
|
70
|
+
block_risk: bool = Field(..., description="Is there a risk of block?")
|
|
71
|
+
requires_hitl: bool = Field(False, description="Would this require human approval?")
|
|
72
|
+
execution_status: str = Field(..., description="allowed | blocked | pending")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class CheckActionabilityResponse(BaseModel):
|
|
76
|
+
"""Output for the public pre-flight check."""
|
|
77
|
+
# Identification
|
|
78
|
+
check_id: str = Field(..., description="Unique ID for this check")
|
|
79
|
+
receipt_id: Optional[str] = Field(None, description="ID of the self-contained signed receipt for this check (not persisted)")
|
|
80
|
+
receipt_url: Optional[str] = Field(None, description="Always null: the zero-side-effect check does not persist a retrievable receipt")
|
|
81
|
+
checked_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
|
82
|
+
latency_ms: float = Field(0.0, ge=0.0, description="Server-side evaluation latency")
|
|
83
|
+
|
|
84
|
+
# Verdict (nested)
|
|
85
|
+
verdict: CheckActionabilityVerdict
|
|
86
|
+
|
|
87
|
+
# Reason
|
|
88
|
+
block_reason: Optional[str] = Field(None, description="Short reason if blocked")
|
|
89
|
+
counterfactual: Optional[str] = Field(None, description="What would have made this actionable")
|
|
90
|
+
rule_id: Optional[str] = Field(None, description="The rule that blocked, if any")
|
|
91
|
+
|
|
92
|
+
# Roadmap to success
|
|
93
|
+
missing_claims: List[MissingClaim] = Field(default_factory=list)
|
|
94
|
+
next_steps: List[NextStep] = Field(default_factory=list)
|
|
95
|
+
|
|
96
|
+
# Cost
|
|
97
|
+
estimated_cost: Optional[EstimatedCost] = None
|
|
98
|
+
|
|
99
|
+
# Legibility
|
|
100
|
+
reasoning_path: List[ReasoningStep] = Field(default_factory=list)
|
|
101
|
+
constraints_checked: List[Dict[str, Any]] = Field(default_factory=list)
|
|
102
|
+
|
|
103
|
+
# Proof
|
|
104
|
+
receipt: Optional[Dict[str, Any]] = Field(None, description="Full Ed25519-signed VAP receipt for the check itself, returned inline; not persisted")
|
|
105
|
+
|
|
106
|
+
# Risk & applicability
|
|
107
|
+
risk_tier: int = Field(1, ge=1, le=5)
|
|
108
|
+
applicability_domain: Optional[Dict[str, Any]] = None
|
verilink_sdk/_enums.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Enums needed by SDK schemas, vendored from verilink.enums.
|
|
2
|
+
|
|
3
|
+
Kept in the SDK so the published wheel has no dependency on the server package.
|
|
4
|
+
Regenerate from verilink/enums.py when the wire contract changes; the parity test
|
|
5
|
+
in tests/test_sdk_packaging.py guards the critical values.
|
|
6
|
+
"""
|
|
7
|
+
from enum import Enum
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class VAPActionType(str, Enum):
|
|
11
|
+
link_check = "link_check"
|
|
12
|
+
message_forward = "message_forward"
|
|
13
|
+
ai_decision = "ai_decision"
|
|
14
|
+
datacenter_attestation = "datacenter_attestation"
|
|
15
|
+
custom_action = "custom_action"
|
|
16
|
+
custom = "custom"
|
|
17
|
+
contract_created = "contract_created"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
# Asset Protection
|
|
21
|
+
identity_registered = "identity_registered"
|
|
22
|
+
emblem_issued = "emblem_issued"
|
|
23
|
+
authority_endorsed = "authority_endorsed"
|
|
24
|
+
integrity_verified = "integrity_verified"
|
|
25
|
+
incident_reported = "incident_reported"
|
|
26
|
+
forensic_package_generated = "forensic_package_generated"
|
|
27
|
+
protection_renewed = "protection_renewed"
|
|
28
|
+
configuration_published = "configuration_published"
|
|
29
|
+
protection_revoked = "protection_revoked"
|
|
30
|
+
agent_bound = "agent_bound"
|
|
31
|
+
|
|
32
|
+
# Bootstrap / Common
|
|
33
|
+
monitoring = "monitoring"
|
|
34
|
+
financial = "financial"
|
|
35
|
+
data_access = "data_access"
|
|
36
|
+
|
|
37
|
+
# Agent-native action types (added for policy simulation)
|
|
38
|
+
financial_transfer = "financial_transfer"
|
|
39
|
+
read = "read"
|
|
40
|
+
memory_write = "memory_write"
|
|
41
|
+
|
|
42
|
+
# Platform
|
|
43
|
+
agent_disposition = "agent_disposition" # Internal platform decision receipt
|
|
44
|
+
credential_finding = "credential_finding"
|
|
45
|
+
code_leak_finding = "code_leak_finding"
|
|
46
|
+
|
|
47
|
+
# High-risk actions requiring HITL
|
|
48
|
+
wire_transfer = "wire_transfer"
|
|
49
|
+
data_export = "data_export"
|
|
50
|
+
delete_db = "delete_db"
|
|
51
|
+
agent_handoff = "agent_handoff"
|
|
52
|
+
parametric_claim = "parametric_claim"
|
|
53
|
+
payment_settlement = "payment_settlement"
|
|
54
|
+
mcp_invoke = "mcp_invoke"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class VAPDecisionVerdict(str, Enum):
|
|
58
|
+
allow = "allow"
|
|
59
|
+
block = "block"
|
|
60
|
+
warn = "warn"
|
|
61
|
+
defer = "defer"
|
|
62
|
+
attest_pass = "attest_pass"
|
|
63
|
+
attest_fail = "attest_fail"
|
|
64
|
+
custom = "custom"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class VAPActorType(str, Enum):
|
|
68
|
+
agent = "agent"
|
|
69
|
+
user = "user"
|
|
70
|
+
system = "system"
|
|
71
|
+
unknown = "unknown"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class VAPSector(str, Enum):
|
|
75
|
+
finance = "finance"
|
|
76
|
+
healthcare = "healthcare"
|
|
77
|
+
information = "information"
|
|
78
|
+
national_security = "national_security"
|
|
79
|
+
it = "it"
|
|
80
|
+
other = "other"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class AIBOMStatus(str, Enum):
|
|
84
|
+
DRAFT = "draft"
|
|
85
|
+
SIGNED = "signed"
|
|
86
|
+
VERIFIED = "verified"
|
|
87
|
+
COMPROMISED = "compromised"
|
|
88
|
+
EXPIRED = "expired"
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class IncidentSeverity(str, Enum):
|
|
92
|
+
CRITICAL = "critical"
|
|
93
|
+
HIGH = "high"
|
|
94
|
+
MEDIUM = "medium"
|
|
95
|
+
LOW = "low"
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class AssetType(str, Enum):
|
|
99
|
+
"""NEW: Types of digital assets that can be protected."""
|
|
100
|
+
URL = "url"
|
|
101
|
+
DOMAIN = "domain"
|
|
102
|
+
IP = "ip"
|
|
103
|
+
WILDCARD = "wildcard"
|
|
104
|
+
QR_CODE = "qr_code"
|
|
105
|
+
INFRASTRUCTURE = "infrastructure"
|
|
106
|
+
SERVER = "server"
|
|
107
|
+
NETWORK = "network"
|
|
108
|
+
AI_MODEL = "ai_model"
|
|
109
|
+
CULTURAL_HERITAGE = "cultural_heritage"
|
|
110
|
+
TREATY = "treaty"
|
|
111
|
+
LEGAL_DOCUMENT = "legal_document"
|
|
112
|
+
CONTRACT = "contract"
|
|
113
|
+
WALLET = "wallet"
|
|
114
|
+
TRANSACTION = "transaction"
|
|
115
|
+
INSURANCE_POLICY = "insurance_policy"
|
|
116
|
+
PATIENT_RECORD = "patient_record"
|
|
117
|
+
PRESCRIPTION = "prescription"
|
|
118
|
+
CONSENT = "consent"
|
|
119
|
+
IDENTITY = "identity"
|
|
120
|
+
CREDENTIAL = "credential"
|
|
121
|
+
DIGITAL_ART = "digital_art"
|
|
122
|
+
PHYSICAL_ASSET = "physical_asset"
|
|
123
|
+
CUSTOM = "custom"
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class DiscoveryPath(str, Enum):
|
|
127
|
+
"""NEW: Discovery paths for asset attestations."""
|
|
128
|
+
DNS_TXT = "dns_txt"
|
|
129
|
+
WELL_KNOWN = "well_known"
|
|
130
|
+
HTTP_HEADER = "header"
|
|
131
|
+
TLSA = "tlsa"
|
|
132
|
+
HTTPS = "https"
|
|
133
|
+
UDP = "udp"
|
|
134
|
+
TLS = "tls"
|
|
135
|
+
QR = "qr"
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class ReceiptStatus(str, Enum):
|
|
139
|
+
"""MGF Alignment: Formal lifecycle of a VAP action from permit to settlement."""
|
|
140
|
+
PENDING = "pending"
|
|
141
|
+
PERMIT_GRANTED = "permit_granted"
|
|
142
|
+
EXECUTING = "executing"
|
|
143
|
+
SETTLEMENT_COMPLETE = "settlement_complete"
|
|
144
|
+
SETTLEMENT_FAILED = "settlement_failed"
|
|
145
|
+
BLOCKED = "blocked"
|
|
146
|
+
AUTOMATED = "automated"
|
verilink_sdk/_version.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""SDK release version.
|
|
2
|
+
|
|
3
|
+
Baked into the package so `python -m build` works in PyPI's isolated build
|
|
4
|
+
environment, where the server repository is not present. tests/test_sdk_packaging.py
|
|
5
|
+
asserts this matches the server's verilink.__version__; bump both together.
|
|
6
|
+
"""
|
|
7
|
+
__version__ = "3.7.0"
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from typing import Any, Dict, List, Optional, Union, Callable
|
|
3
|
+
import asyncio
|
|
4
|
+
|
|
5
|
+
logger = logging.getLogger(__name__)
|
|
6
|
+
|
|
7
|
+
class VeriLinkAutoGenAdapter:
|
|
8
|
+
"""
|
|
9
|
+
Adapter for Microsoft AutoGen governance.
|
|
10
|
+
Intercepts message exchanges and tool calls between agents.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
def __init__(self, verilink_client: Any):
|
|
14
|
+
self.client = verilink_client
|
|
15
|
+
|
|
16
|
+
def govern_agent(self, agent: Any):
|
|
17
|
+
"""Wraps an AutoGen agent with VeriLinkOS governance."""
|
|
18
|
+
# AutoGen uses receive/send methods
|
|
19
|
+
original_receive = agent.receive
|
|
20
|
+
|
|
21
|
+
async def governed_receive(message: Union[Dict, str], sender: Any, request_reply: Optional[bool] = None, silent: Optional[bool] = False):
|
|
22
|
+
# 1. Enforce message safety
|
|
23
|
+
input_data = {
|
|
24
|
+
"message": str(message),
|
|
25
|
+
"sender_name": sender.name if hasattr(sender, "name") else "unknown",
|
|
26
|
+
"receiver_name": agent.name
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
try:
|
|
30
|
+
result = await self.client.enforce_action("autogen_message_receive", input_data)
|
|
31
|
+
if not result.get("allowed", True):
|
|
32
|
+
logger.warning(f"VeriLink: Blocked AutoGen message to {agent.name}")
|
|
33
|
+
# In AutoGen, we might want to return an error message or halt
|
|
34
|
+
return
|
|
35
|
+
except Exception as e:
|
|
36
|
+
logger.error(f"VeriLink: Error enforcing AutoGen message: {e}")
|
|
37
|
+
|
|
38
|
+
# 2. Call original receive
|
|
39
|
+
if asyncio.iscoroutinefunction(original_receive):
|
|
40
|
+
return await original_receive(message, sender, request_reply, silent)
|
|
41
|
+
else:
|
|
42
|
+
return original_receive(message, sender, request_reply, silent)
|
|
43
|
+
|
|
44
|
+
agent.receive = governed_receive
|
|
45
|
+
return agent
|
|
46
|
+
|
|
47
|
+
def wrap_tool(self, tool_func: Callable, action_type: str = "autogen_tool_call"):
|
|
48
|
+
"""Wraps an AutoGen tool function with governance."""
|
|
49
|
+
@asyncio.coroutine
|
|
50
|
+
async def wrapped_tool(*args, **kwargs):
|
|
51
|
+
input_data = {
|
|
52
|
+
"tool_name": tool_func.__name__,
|
|
53
|
+
"args": [str(a) for a in args],
|
|
54
|
+
"kwargs": {k: str(v) for k, v in kwargs.items()}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
result = await self.client.enforce_action(action_type, input_data)
|
|
58
|
+
if not result.get("allowed", True):
|
|
59
|
+
raise PermissionError(f"VeriLink: AutoGen tool '{tool_func.__name__}' blocked: {result.get('recommendation')}")
|
|
60
|
+
|
|
61
|
+
return tool_func(*args, **kwargs)
|
|
62
|
+
|
|
63
|
+
return wrapped_tool
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import logging
|
|
3
|
+
from typing import Any, Dict, List, Optional
|
|
4
|
+
|
|
5
|
+
logger = logging.getLogger(__name__)
|
|
6
|
+
|
|
7
|
+
class VeriLinkCrewAIGovernor:
|
|
8
|
+
"""
|
|
9
|
+
Governor for CrewAI teams.
|
|
10
|
+
Intercepts task executions and agent interactions to ensure compliance.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
def __init__(self, verilink_client: Any, agent_id: str):
|
|
14
|
+
self.client = verilink_client
|
|
15
|
+
self.agent_id = agent_id
|
|
16
|
+
|
|
17
|
+
def task_callback(self, task: Any, result: Any, **kwargs: Any) -> Any:
|
|
18
|
+
"""Callback for task execution compliance verification."""
|
|
19
|
+
async def _govern():
|
|
20
|
+
input_data = {
|
|
21
|
+
"agent_id": self.agent_id,
|
|
22
|
+
"task_name": getattr(task, "name", "unknown"),
|
|
23
|
+
"task_description": getattr(task, "description", ""),
|
|
24
|
+
"result_preview": str(result)[:1000] # Truncate for safety
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
resp = await self.client.enforce_action(
|
|
28
|
+
action_type=f"crewai_task_{getattr(task, 'name', 'execution')}",
|
|
29
|
+
input_data=input_data
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
if not resp.get("allowed", True):
|
|
33
|
+
raise PermissionError(
|
|
34
|
+
f"VeriLinkOS Blocked Task: {resp.get('recommendation', 'Policy violation')}"
|
|
35
|
+
)
|
|
36
|
+
return result
|
|
37
|
+
|
|
38
|
+
try:
|
|
39
|
+
loop = asyncio.get_event_loop()
|
|
40
|
+
if loop.is_running():
|
|
41
|
+
return asyncio.run_coroutine_threadsafe(_govern(), loop).result()
|
|
42
|
+
else:
|
|
43
|
+
return loop.run_until_complete(_govern())
|
|
44
|
+
except RuntimeError:
|
|
45
|
+
return asyncio.run(_govern())
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import functools
|
|
3
|
+
import logging
|
|
4
|
+
import inspect
|
|
5
|
+
from typing import Callable, Any, Dict, Optional, List
|
|
6
|
+
from contextvars import ContextVar
|
|
7
|
+
from ..client import VeriLinkClient
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger(__name__)
|
|
10
|
+
|
|
11
|
+
# Context variable to store the active VeriLink client for the current thread/task
|
|
12
|
+
active_client: ContextVar[Optional[VeriLinkClient]] = ContextVar("verilink_active_client", default=None)
|
|
13
|
+
|
|
14
|
+
def set_active_client(client: Optional[VeriLinkClient]):
|
|
15
|
+
"""Sets the VeriLink client for the current context."""
|
|
16
|
+
active_client.set(client)
|
|
17
|
+
|
|
18
|
+
def get_active_client() -> Optional[VeriLinkClient]:
|
|
19
|
+
"""Retrieves the VeriLink client from the current context."""
|
|
20
|
+
return active_client.get()
|
|
21
|
+
|
|
22
|
+
# Aliases for backward compatibility or different naming conventions
|
|
23
|
+
set_client = set_active_client
|
|
24
|
+
get_client = get_active_client
|
|
25
|
+
|
|
26
|
+
def enforce(
|
|
27
|
+
action_type: str,
|
|
28
|
+
risk_threshold: int = 1,
|
|
29
|
+
require_hitl: bool = False,
|
|
30
|
+
fallback_policy: str = "block",
|
|
31
|
+
metadata: Optional[Dict[str, Any]] = None,
|
|
32
|
+
custom_input: Optional[Callable[[Dict[str, Any]], Dict[str, Any]]] = None
|
|
33
|
+
):
|
|
34
|
+
"""
|
|
35
|
+
Universal Python decorator for agent action governance.
|
|
36
|
+
Intercepts function calls and enforces policy via VeriLinkOS Guardian.
|
|
37
|
+
|
|
38
|
+
Usage:
|
|
39
|
+
@enforce(action_type="financial_transaction", risk_threshold=2)
|
|
40
|
+
async def execute_payment(amount: float, recipient: str):
|
|
41
|
+
return await payment_gateway.send(amount, recipient)
|
|
42
|
+
"""
|
|
43
|
+
def decorator(func: Callable) -> Callable:
|
|
44
|
+
@functools.wraps(func)
|
|
45
|
+
async def async_wrapper(*args, **kwargs):
|
|
46
|
+
client = get_active_client()
|
|
47
|
+
if not client:
|
|
48
|
+
if fallback_policy == "block":
|
|
49
|
+
raise RuntimeError(
|
|
50
|
+
"VeriLinkClient not found in context. Use 'async with VeriLinkClient(...) as client:'"
|
|
51
|
+
)
|
|
52
|
+
logger.warning("VeriLink: No active client found. Skipping enforcement.")
|
|
53
|
+
return await func(*args, **kwargs)
|
|
54
|
+
|
|
55
|
+
# Build action context from function call
|
|
56
|
+
input_data = {
|
|
57
|
+
"function": func.__name__,
|
|
58
|
+
"module": func.__module__,
|
|
59
|
+
"args": [str(a) for a in args],
|
|
60
|
+
"kwargs": {k: str(v) for k, v in kwargs.items()},
|
|
61
|
+
"risk_threshold": risk_threshold,
|
|
62
|
+
"require_hitl": require_hitl,
|
|
63
|
+
"metadata": metadata or {}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if custom_input:
|
|
67
|
+
input_data = custom_input(input_data)
|
|
68
|
+
|
|
69
|
+
# Enforce via Guardian
|
|
70
|
+
result = await client.enforce_action(action_type, input_data)
|
|
71
|
+
|
|
72
|
+
if not result.get("allowed", True):
|
|
73
|
+
block_reason = result.get("recommendation", "Policy violation")
|
|
74
|
+
logger.error(f"VeriLink: Action '{func.__name__}' blocked: {block_reason}")
|
|
75
|
+
raise PermissionError(
|
|
76
|
+
f"Action '{func.__name__}' blocked by VeriLink Guardian: {block_reason}"
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
# Execute the actual function
|
|
80
|
+
return await func(*args, **kwargs)
|
|
81
|
+
|
|
82
|
+
@functools.wraps(func)
|
|
83
|
+
def sync_wrapper(*args, **kwargs):
|
|
84
|
+
# For sync functions, we use the event loop
|
|
85
|
+
try:
|
|
86
|
+
loop = asyncio.get_event_loop()
|
|
87
|
+
if loop.is_running():
|
|
88
|
+
return asyncio.run_coroutine_threadsafe(async_wrapper(*args, **kwargs), loop).result()
|
|
89
|
+
else:
|
|
90
|
+
return loop.run_until_complete(async_wrapper(*args, **kwargs))
|
|
91
|
+
except RuntimeError:
|
|
92
|
+
return asyncio.run(async_wrapper(*args, **kwargs))
|
|
93
|
+
|
|
94
|
+
return async_wrapper if asyncio.iscoroutinefunction(func) else sync_wrapper
|
|
95
|
+
|
|
96
|
+
return decorator
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def preflight(
|
|
100
|
+
action_type: str,
|
|
101
|
+
metadata: Optional[Dict[str, Any]] = None,
|
|
102
|
+
custom_input: Optional[Callable[[Dict[str, Any]], Dict[str, Any]]] = None,
|
|
103
|
+
raise_on_block: bool = True,
|
|
104
|
+
):
|
|
105
|
+
"""
|
|
106
|
+
Universal Python decorator for pre-flight actionability checks.
|
|
107
|
+
|
|
108
|
+
Sibling to @enforce. Where @enforce checks policy *when the function
|
|
109
|
+
is called* (post-commitment, with side-effects), @preflight checks
|
|
110
|
+
policy *before the function's body executes* (pre-commitment, zero
|
|
111
|
+
side-effects).
|
|
112
|
+
|
|
113
|
+
Zero side-effects. Pure evaluation. Signed receipt.
|
|
114
|
+
|
|
115
|
+
Usage:
|
|
116
|
+
@preflight(action_type="financial_transfer")
|
|
117
|
+
async def plan_transfer(amount: float):
|
|
118
|
+
# This body only runs if the action is actionable
|
|
119
|
+
return await do_transfer(amount)
|
|
120
|
+
|
|
121
|
+
Args:
|
|
122
|
+
action_type: The action type (e.g. "financial_transfer").
|
|
123
|
+
metadata: Optional static metadata merged into the action.
|
|
124
|
+
custom_input: Optional function to build the action payload
|
|
125
|
+
from the call arguments (overrides default).
|
|
126
|
+
raise_on_block: If True (default), raise PreflightBlocked on
|
|
127
|
+
non-actionable. If False, log and proceed.
|
|
128
|
+
|
|
129
|
+
Raises:
|
|
130
|
+
PreflightBlocked: When the action is not actionable and
|
|
131
|
+
raise_on_block is True.
|
|
132
|
+
RuntimeError: When no active client is set and
|
|
133
|
+
raise_on_block is True.
|
|
134
|
+
"""
|
|
135
|
+
def decorator(func: Callable) -> Callable:
|
|
136
|
+
@functools.wraps(func)
|
|
137
|
+
async def async_wrapper(*args, **kwargs):
|
|
138
|
+
client = get_active_client()
|
|
139
|
+
if not client:
|
|
140
|
+
if raise_on_block:
|
|
141
|
+
raise RuntimeError(
|
|
142
|
+
"VeriLinkClient not found in context. "
|
|
143
|
+
"Use 'async with VeriLinkClient(...) as client:'"
|
|
144
|
+
)
|
|
145
|
+
logger.warning("VeriLink: No active client. Skipping preflight.")
|
|
146
|
+
return await func(*args, **kwargs)
|
|
147
|
+
|
|
148
|
+
action: Dict[str, Any] = {
|
|
149
|
+
"type": action_type,
|
|
150
|
+
"function": func.__name__,
|
|
151
|
+
"module": func.__module__,
|
|
152
|
+
"args": [str(a) for a in args],
|
|
153
|
+
"kwargs": {k: str(v) for k, v in kwargs.items()},
|
|
154
|
+
}
|
|
155
|
+
if metadata:
|
|
156
|
+
action["metadata"] = dict(metadata)
|
|
157
|
+
if custom_input:
|
|
158
|
+
action = custom_input(action)
|
|
159
|
+
|
|
160
|
+
result = await client.check_actionability(action=action)
|
|
161
|
+
|
|
162
|
+
if not result.verdict.is_actionable:
|
|
163
|
+
manifest = {
|
|
164
|
+
"block_reason": result.block_reason,
|
|
165
|
+
"counterfactual": result.counterfactual,
|
|
166
|
+
"missing_claims": [
|
|
167
|
+
{
|
|
168
|
+
"claim_id": c.claim_id,
|
|
169
|
+
"type": c.type,
|
|
170
|
+
"how_to_satisfy": c.how_to_satisfy,
|
|
171
|
+
"priority": c.priority,
|
|
172
|
+
}
|
|
173
|
+
for c in result.missing_claims
|
|
174
|
+
],
|
|
175
|
+
"next_steps": [
|
|
176
|
+
{
|
|
177
|
+
"action": s.action,
|
|
178
|
+
"description": s.description,
|
|
179
|
+
"endpoint": s.endpoint,
|
|
180
|
+
}
|
|
181
|
+
for s in result.next_steps
|
|
182
|
+
],
|
|
183
|
+
"estimated_cost": (
|
|
184
|
+
result.estimated_cost.model_dump()
|
|
185
|
+
if result.estimated_cost
|
|
186
|
+
else None
|
|
187
|
+
),
|
|
188
|
+
"check_id": result.check_id,
|
|
189
|
+
"receipt_id": result.receipt_id,
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
if raise_on_block:
|
|
193
|
+
logger.error(
|
|
194
|
+
f"VeriLink: Preflight blocked '{func.__name__}': "
|
|
195
|
+
f"{result.block_reason}"
|
|
196
|
+
)
|
|
197
|
+
raise PreflightBlocked(
|
|
198
|
+
f"Action '{func.__name__}' blocked by pre-flight check: "
|
|
199
|
+
f"{result.block_reason}",
|
|
200
|
+
manifest=manifest,
|
|
201
|
+
)
|
|
202
|
+
else:
|
|
203
|
+
logger.warning(
|
|
204
|
+
f"VeriLink: Preflight blocked '{func.__name__}' "
|
|
205
|
+
f"but raise_on_block=False. Proceeding."
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
return await func(*args, **kwargs)
|
|
209
|
+
|
|
210
|
+
@functools.wraps(func)
|
|
211
|
+
def sync_wrapper(*args, **kwargs):
|
|
212
|
+
try:
|
|
213
|
+
loop = asyncio.get_event_loop()
|
|
214
|
+
if loop.is_running():
|
|
215
|
+
return asyncio.run_coroutine_threadsafe(
|
|
216
|
+
async_wrapper(*args, **kwargs), loop
|
|
217
|
+
).result()
|
|
218
|
+
else:
|
|
219
|
+
return loop.run_until_complete(async_wrapper(*args, **kwargs))
|
|
220
|
+
except RuntimeError:
|
|
221
|
+
return asyncio.run(async_wrapper(*args, **kwargs))
|
|
222
|
+
|
|
223
|
+
return async_wrapper if asyncio.iscoroutinefunction(func) else sync_wrapper
|
|
224
|
+
|
|
225
|
+
return decorator
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
class PreflightBlocked(PermissionError):
|
|
229
|
+
"""
|
|
230
|
+
Raised by @preflight when an action is not actionable.
|
|
231
|
+
|
|
232
|
+
Carries a structured manifest (block_reason, counterfactual,
|
|
233
|
+
missing_claims, next_steps, estimated_cost, check_id, receipt_id).
|
|
234
|
+
"""
|
|
235
|
+
def __init__(self, message: str, manifest: Optional[Dict[str, Any]] = None):
|
|
236
|
+
super().__init__(message)
|
|
237
|
+
self.manifest: Dict[str, Any] = manifest or {}
|