web3-systemic-agent 1.0.2__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.
src/report.py ADDED
@@ -0,0 +1,142 @@
1
+ """
2
+ Report and Diagnostics CLI for Web3 Condition-Action Trigger Agent.
3
+ Queries SQLite operational ledger to generate human-readable metrics summaries,
4
+ Stage 1 filter rate performance, LLM token/cost telemetry, and error distributions.
5
+
6
+ Usage:
7
+ python -m src.report [--db PATH] [--price USD]
8
+ python src/report.py [--db PATH] [--price USD]
9
+ """
10
+
11
+ import argparse
12
+ import asyncio
13
+ import os
14
+ import sys
15
+ from typing import Dict, Any, Optional
16
+
17
+ # Ensure module search paths support running directly or as a package
18
+ _CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
19
+ _ROOT_DIR = os.path.abspath(os.path.join(_CURRENT_DIR, "..")) if os.path.basename(_CURRENT_DIR) == "src" else _CURRENT_DIR
20
+ _SRC_DIR = os.path.join(_ROOT_DIR, "src")
21
+ for _p in (_ROOT_DIR, _SRC_DIR):
22
+ if _p not in sys.path:
23
+ sys.path.insert(0, _p)
24
+
25
+ try:
26
+ from src.storage import AgentStorage, get_default_db_path
27
+ except ImportError:
28
+ from storage import AgentStorage, get_default_db_path
29
+
30
+
31
+ async def generate_report(
32
+ db_path: Optional[str] = None, target_price_usd: float = 0.015
33
+ ) -> Dict[str, Any]:
34
+ """
35
+ Connects to the AgentStorage database and computes summary metrics.
36
+ """
37
+ storage = AgentStorage(db_path=db_path)
38
+ return await storage.get_summary_metrics(target_price_usd=target_price_usd)
39
+
40
+
41
+ def format_report_text(metrics: Dict[str, Any]) -> str:
42
+ """
43
+ Formats the summary metrics dictionary into a clean, human-readable terminal report.
44
+ """
45
+ total_evals = metrics.get("total_evaluations", 0)
46
+ stage1_halted = metrics.get("stage1_halted_count", 0)
47
+ filter_rate = metrics.get("stage1_filter_rate_pct", metrics.get("stage1_Filter_rate_pct", 0.0))
48
+ llm_invoked = metrics.get("llm_invoked_count", 0)
49
+
50
+ total_in_tok = metrics.get("total_input_tokens", 0)
51
+ total_out_tok = metrics.get("total_output_tokens", 0)
52
+ total_tokens = total_in_tok + total_out_tok
53
+ total_cost = metrics.get("total_cost_usd", 0.0)
54
+ avg_cost_eval = metrics.get("avg_cost_per_eval_usd", 0.0)
55
+ avg_cost_llm = metrics.get("avg_cost_per_llm_call_usd", 0.0)
56
+ max_cost = metrics.get("max_cost_usd", 0.0)
57
+ p95_cost = metrics.get("p95_cost_usd", 0.0)
58
+
59
+ target_price = metrics.get("target_price_usd", 0.015)
60
+ covers_max = metrics.get("price_covers_max_cost", True)
61
+ margin_status = "PASS (Covers Max Cost)" if covers_max else "FAIL (Exceeds Target Price)"
62
+
63
+ total_payments = metrics.get("total_payments_settled")
64
+ total_rev = metrics.get("total_revenue_usdc")
65
+ net_profit = metrics.get("net_profit_usd")
66
+
67
+ total_errors = metrics.get("total_errors", 0)
68
+ errors_by_stage = metrics.get("errors_by_stage", {})
69
+
70
+ lines = [
71
+ "=" * 64,
72
+ " Web3 Condition-Action Trigger Agent: Operational Report ",
73
+ "=" * 64,
74
+ f"Total Evaluations Processed : {total_evals}",
75
+ f"Stage 1 Halted (Filtered) : {stage1_halted}",
76
+ f"Stage 1 Filter Efficiency : {filter_rate:.2f}%",
77
+ f"Stage 2 LLM Calls Invoked : {llm_invoked}",
78
+ "-" * 64,
79
+ "LLM Token & Cost Telemetry:",
80
+ f" Input Tokens Consumed : {total_in_tok:,}",
81
+ f" Output Tokens Generated : {total_out_tok:,}",
82
+ f" Total Tokens : {total_tokens:,}",
83
+ f" Total Estimated Cost (USD): ${total_cost:.6f}",
84
+ f" Avg Cost per Evaluation : ${avg_cost_eval:.6f}",
85
+ f" Avg Cost per LLM Call : ${avg_cost_llm:.6f}",
86
+ f" P95 Evaluation Cost (USD) : ${p95_cost:.6f}",
87
+ f" Max Evaluation Cost (USD) : ${max_cost:.6f}",
88
+ "-" * 64,
89
+ "Commercial Margin Feasibility:",
90
+ f" Target Price per Eval : ${target_price:.4f}",
91
+ f" Margin Status : {margin_status}",
92
+ ]
93
+
94
+ if total_payments is not None or total_rev is not None:
95
+ lines.extend([
96
+ "-" * 64,
97
+ "x402 Micropayment Telemetry:",
98
+ f" Total Payments Settled : {int(total_payments or 0)}",
99
+ f" Total Settled Revenue : ${float(total_rev or 0.0):.6f} USDC",
100
+ f" Net Profit (Revenue-Cost) : ${float(net_profit or 0.0):.6f} USD",
101
+ ])
102
+
103
+ lines.extend([
104
+ "-" * 64,
105
+ f"Operational Error Log (Total: {total_errors}):",
106
+ ])
107
+
108
+ if not errors_by_stage:
109
+ lines.append(" No operational errors recorded.")
110
+ else:
111
+ for stage, count in sorted(errors_by_stage.items()):
112
+ lines.append(f" Stage '{stage}': {count} error(s)")
113
+
114
+ lines.append("=" * 64)
115
+ return "\n".join(lines)
116
+
117
+
118
+ def main() -> None:
119
+ parser = argparse.ArgumentParser(
120
+ description="Web3 Condition-Action Trigger Agent Ledger Reporting CLI"
121
+ )
122
+ parser.add_argument(
123
+ "--db",
124
+ type=str,
125
+ default=None,
126
+ help="Path to SQLite ledger database (defaults to LEDGER_DB_PATH or data/agent.db)",
127
+ )
128
+ parser.add_argument(
129
+ "--price",
130
+ type=float,
131
+ default=0.015,
132
+ help="Target commercial price per evaluation in USD (default: 0.015)",
133
+ )
134
+
135
+ args = parser.parse_args()
136
+ metrics = asyncio.run(generate_report(db_path=args.db, target_price_usd=args.price))
137
+ report_text = format_report_text(metrics)
138
+ print(report_text)
139
+
140
+
141
+ if __name__ == "__main__":
142
+ main()
src/schemas.py ADDED
@@ -0,0 +1,330 @@
1
+ """
2
+ Pydantic schemas and data models for Web3 Condition-Action Trigger Agent.
3
+ Defines schemas for deterministic conditions, semantic evaluations, payloads, and results.
4
+ """
5
+
6
+ from enum import Enum
7
+ import re
8
+ from typing import Dict, Any, Optional, List, Literal, Union
9
+ from pydantic import BaseModel, Field, field_validator, model_validator
10
+ from web3 import Web3
11
+
12
+
13
+ class ChainId(int, Enum):
14
+ BASE_MAINNET = 8453
15
+ BASE_SEPOLIA = 84532
16
+ ARBITRUM_ONE = 42161
17
+
18
+
19
+ class DeterministicCondition(BaseModel):
20
+ target_address: str = Field(..., description="Contract or wallet address to monitor")
21
+ min_value_wei: int = Field(default=0, ge=0, description="Minimum transaction or balance value in Wei")
22
+ required_function_selectors: Optional[List[str]] = Field(
23
+ default=None, description="List of 4-byte hex function selectors (e.g., ['0xa9059cbb'])"
24
+ )
25
+ check_native_balance: bool = Field(default=False, description="Whether to check native ETH balance of target")
26
+
27
+ @field_validator("target_address")
28
+ @classmethod
29
+ def validate_checksum_address(cls, v: str) -> str:
30
+ if not Web3.is_address(v):
31
+ raise ValueError(f"Invalid Ethereum address: {v}")
32
+ return Web3.to_checksum_address(v)
33
+
34
+ @field_validator("required_function_selectors")
35
+ @classmethod
36
+ def validate_function_selectors(cls, v: Optional[List[str]]) -> Optional[List[str]]:
37
+ if v is None:
38
+ return v
39
+ selector_regex = re.compile(r"^0x[0-9a-fA-F]{8}$")
40
+ normalized = []
41
+ for selector in v:
42
+ if not isinstance(selector, str) or not selector_regex.match(selector):
43
+ raise ValueError(
44
+ f"Invalid function selector format '{selector}'. "
45
+ f"Must be a 10-character hex string starting with '0x' (e.g., '0xa9059cbb')."
46
+ )
47
+ normalized.append(selector.lower())
48
+ return normalized
49
+
50
+
51
+ class SemanticCondition(BaseModel):
52
+ enabled: bool = Field(default=True, description="Whether LLM evaluation is required after deterministic match")
53
+ policy_prompt: str = Field(
54
+ ..., description="Natural language rule to verify against the transaction/proposal context"
55
+ )
56
+ risk_threshold: float = Field(default=7.0, ge=0.0, le=10.0, description="Minimum risk score to flag")
57
+
58
+
59
+ class ConditionRulePayload(BaseModel):
60
+ rule_id: str = Field(..., description="Unique identifier for the monitoring rule")
61
+ chain_id: ChainId = Field(default=ChainId.BASE_SEPOLIA)
62
+ deterministic: DeterministicCondition
63
+ semantic: SemanticCondition
64
+ context_metadata: Dict[str, Any] = Field(
65
+ default_factory=dict, description="Proposal text, calldata, or extra metadata to inspect"
66
+ )
67
+
68
+
69
+ class DeterministicResult(BaseModel):
70
+ passed: bool
71
+ reason: str
72
+ observed_data: Dict[str, Any] = Field(default_factory=dict)
73
+ error: Optional[str] = None
74
+
75
+
76
+ class JobStatus(str, Enum):
77
+ QUEUED = "QUEUED"
78
+ PROCESSING = "PROCESSING"
79
+ COMPLETED = "COMPLETED"
80
+ FAILED = "FAILED"
81
+ CANCELLED = "CANCELLED"
82
+
83
+
84
+ class LLMAuditOutput(BaseModel):
85
+ conditions_met: bool = Field(..., description="Whether the semantic policy condition was triggered")
86
+ risk_score: float = Field(..., ge=0.0, le=10.0, description="Calculated risk score from 0.0 to 10.0")
87
+ flagged_issues: List[str] = Field(..., description="Specific technical or governance issues found")
88
+ summary: str = Field(..., description="Concise technical justification of the evaluation")
89
+ recommended_action: Literal["APPROVE", "REJECT", "MANUAL_REVIEW"] = Field(
90
+ ..., description="Actionable recommendation: APPROVE, REJECT, or MANUAL_REVIEW"
91
+ )
92
+
93
+ @field_validator("recommended_action", mode="before")
94
+ @classmethod
95
+ def normalize_recommended_action(cls, v: Any) -> Any:
96
+ if isinstance(v, str):
97
+ v = v.strip().upper()
98
+ return v
99
+
100
+
101
+ class SemanticAuditResult(BaseModel):
102
+ conditions_met: bool = Field(..., description="Whether the semantic policy condition was triggered")
103
+ risk_score: float = Field(..., ge=0.0, le=10.0, description="Calculated risk score from 0.0 to 10.0")
104
+ flagged_issues: List[str] = Field(default_factory=list, description="Specific technical or governance issues found")
105
+ summary: str = Field(..., description="Concise technical justification of the evaluation")
106
+ recommended_action: Literal["APPROVE", "REJECT", "MANUAL_REVIEW"] = Field(
107
+ ..., description="Actionable recommendation: APPROVE, REJECT, or MANUAL_REVIEW"
108
+ )
109
+ cached: Optional[bool] = Field(default=False, description="Whether this result was served from semantic cache")
110
+ provider: Optional[str] = Field(default=None, description="LLM provider identifier ('gemini', 'openai', or 'mock')")
111
+ model: Optional[str] = Field(default=None, description="Model name used for evaluation")
112
+ input_tokens: int = Field(default=0, ge=0, description="Input prompt token count")
113
+ output_tokens: int = Field(default=0, ge=0, description="Output completion token count")
114
+ estimated_cost_usd: float = Field(default=0.0, ge=0.0, description="Estimated USD cost of LLM call")
115
+ latency_ms: float = Field(default=0.0, ge=0.0, description="Evaluation latency in milliseconds")
116
+
117
+ def __eq__(self, other: Any) -> bool:
118
+ if not isinstance(other, SemanticAuditResult):
119
+ return False
120
+ # Core audit fields must match
121
+ if (
122
+ self.conditions_met != other.conditions_met
123
+ or self.risk_score != other.risk_score
124
+ or self.flagged_issues != other.flagged_issues
125
+ or self.summary != other.summary
126
+ or self.recommended_action != other.recommended_action
127
+ or (self.cached or False) != (other.cached or False)
128
+ ):
129
+ return False
130
+ # Telemetry fields: if specified on both, they must match
131
+ for field in ("provider", "model"):
132
+ v1, v2 = getattr(self, field), getattr(other, field)
133
+ if v1 is not None and v2 is not None and v1 != v2:
134
+ return False
135
+ for field in ("input_tokens", "output_tokens"):
136
+ v1, v2 = getattr(self, field, 0), getattr(other, field, 0)
137
+ if v1 != 0 and v2 != 0 and v1 != v2:
138
+ return False
139
+ if (
140
+ getattr(self, "estimated_cost_usd", 0.0) != 0.0
141
+ and getattr(other, "estimated_cost_usd", 0.0) != 0.0
142
+ and self.estimated_cost_usd != other.estimated_cost_usd
143
+ ):
144
+ return False
145
+ if (
146
+ getattr(self, "latency_ms", 0.0) != 0.0
147
+ and getattr(other, "latency_ms", 0.0) != 0.0
148
+ and self.latency_ms != other.latency_ms
149
+ ):
150
+ return False
151
+ return True
152
+
153
+ @field_validator("recommended_action", mode="before")
154
+ @classmethod
155
+ def normalize_recommended_action(cls, v: Any) -> Any:
156
+ if isinstance(v, str):
157
+ v = v.strip().upper()
158
+ return v
159
+
160
+
161
+ class PaymentReceipt(BaseModel):
162
+ payment_id: str = Field(..., description="Unique payment identifier or EIP-3009 nonce")
163
+ payer_address: str = Field(..., description="Checksummed EVM address of the paying agent")
164
+ pay_to_address: str = Field(..., description="Checksummed EVM address receiving the payment")
165
+ amount_usdc: float = Field(..., ge=0.0, description="Settled amount in USDC (e.g. 0.01)")
166
+ amount_atomic: int = Field(..., ge=0, description="Settled amount in USDC atomic units (6 decimals, e.g. 10000)")
167
+ network: str = Field(default="eip155:84532", description="CAIP-2 network identifier")
168
+ asset: str = Field(default="USDC", description="Payment token symbol or contract address")
169
+ tx_hash: str = Field(..., description="On-chain settlement transaction hash")
170
+ endpoint: str = Field(..., description="API endpoint paid for")
171
+ settled_at: str = Field(..., description="ISO 8601 UTC timestamp of settlement")
172
+
173
+ @field_validator("payer_address", "pay_to_address")
174
+ @classmethod
175
+ def normalize_addresses(cls, v: str) -> str:
176
+ if Web3.is_address(v):
177
+ return Web3.to_checksum_address(v)
178
+ return v
179
+
180
+
181
+ class FinalAgentResponse(BaseModel):
182
+ rule_id: str
183
+ chain_id: int
184
+ deterministic_check: DeterministicResult
185
+ llm_invoked: bool
186
+ semantic_Evaluation: Optional[SemanticAuditResult] = None
187
+ payment: Optional[PaymentReceipt] = Field(
188
+ default=None, description="x402 payment receipt when paid mode is active"
189
+ )
190
+
191
+
192
+ class PreflightSimulationResult(BaseModel):
193
+ executed: bool = Field(default=False, description="Whether eth_call simulation was executed")
194
+ success: Optional[bool] = Field(default=None, description="True if eth_call succeeded without reverting")
195
+ return_data: Optional[str] = Field(default=None, description="Hex return data from eth_call")
196
+ revert_reason: Optional[str] = Field(default=None, description="Decoded or raw revert reason if transaction reverted")
197
+ rpc_error: Optional[str] = Field(default=None, description="Infrastructure RPC error if all RPC nodes failed")
198
+
199
+
200
+ class PreflightRequest(BaseModel):
201
+ chain_id: ChainId = Field(default=ChainId.BASE_MAINNET, description="EVM Chain ID")
202
+ from_address: Optional[str] = Field(default=None, description="Optional sender EVM address")
203
+ to_address: Optional[str] = Field(default=None, description="Target contract or recipient EVM address")
204
+ target_address: Optional[str] = Field(default=None, description="Alias for to_address")
205
+ calldata: str = Field(default="0x", description="Hex transaction calldata")
206
+ value_wei: int = Field(default=0, ge=0, description="Transaction value in Wei")
207
+ eip712_typed_data: Optional[Dict[str, Any]] = Field(
208
+ default=None, description="Optional EIP-712 typed data payload to inspect before signing"
209
+ )
210
+ untrusted_text: Optional[str] = Field(
211
+ default=None,
212
+ description="Optional untrusted token metadata, router text, or proposal description to scan for Indirect Prompt Injection",
213
+ )
214
+ run_simulation: bool = Field(default=True, description="Whether to run eth_call simulation on chain")
215
+
216
+ @field_validator("from_address", "to_address", "target_address")
217
+ @classmethod
218
+ def validate_and_normalize_address(cls, v: Optional[str]) -> Optional[str]:
219
+ if v is None or v == "":
220
+ return None
221
+ if not Web3.is_address(v):
222
+ raise ValueError(f"Invalid Ethereum address: {v}")
223
+ return Web3.to_checksum_address(v)
224
+
225
+ @model_validator(mode="after")
226
+ def harmonize_target_address(self) -> "PreflightRequest":
227
+ if not self.to_address and self.target_address:
228
+ self.to_address = self.target_address
229
+ elif not self.target_address and self.to_address:
230
+ self.target_address = self.to_address
231
+ return self
232
+
233
+
234
+ class PreflightVerdict(BaseModel):
235
+ verdict: Literal["ALLOW", "BLOCK", "MANUAL_REVIEW"] = Field(
236
+ ..., description="Pre-sign firewall verdict"
237
+ )
238
+ risk_score: float = Field(..., ge=0.0, le=10.0, description="Calculated risk score from 0.0 to 10.0")
239
+ chain_id: int = Field(default=8453)
240
+ target_address: Optional[str] = Field(default=None)
241
+ decoded_action: Dict[str, Any] = Field(
242
+ default_factory=dict, description="Decoded function selector, signature, and arguments"
243
+ )
244
+ approval_risks: List[str] = Field(
245
+ default_factory=list, description="Detected unlimited approvals, Permit2, or setApprovalForAll risks"
246
+ )
247
+ eip712_findings: List[str] = Field(
248
+ default_factory=list, description="Risks detected in EIP-712 typed data"
249
+ )
250
+ prompt_injection_detected: bool = Field(
251
+ default=False, description="Whether Indirect Prompt Injection patterns were found"
252
+ )
253
+ prompt_injection_signals: List[str] = Field(
254
+ default_factory=list, description="Matched prompt injection indicators"
255
+ )
256
+ simulation: PreflightSimulationResult = Field(default_factory=PreflightSimulationResult)
257
+ flagged_issues: List[str] = Field(default_factory=list)
258
+ summary: str = Field(default="", description="Concise technical justification of the preflight verdict")
259
+ llm_invoked: bool = Field(default=False)
260
+ payment: Optional[PaymentReceipt] = Field(default=None)
261
+
262
+
263
+ class DeepAuditRequest(BaseModel):
264
+ target_address: Optional[str] = Field(default=None, description="Hex EVM smart contract address to audit")
265
+ address: Optional[str] = Field(default=None, description="Alias for target_address")
266
+ contract_address: Optional[str] = Field(default=None, description="Alias for target_address")
267
+ chain_id: int = Field(default=8453, description="EVM Chain ID")
268
+ proposal_description: str = Field(
269
+ default="Deep security audit of smart contract source code, proxy implementation, and administrative privileges.",
270
+ description="Audit context or proposal claim",
271
+ )
272
+ policy_prompt: str = Field(
273
+ default="Audit verified Solidity source code, proxy implementation storage, and privileged roles for backdoors, reentrancy, arbitrary tax manipulation, or fund drainage.",
274
+ description="Security policy prompt",
275
+ )
276
+ calldata: str = Field(default="0x", description="Optional transaction hex calldata")
277
+ risk_threshold: float = Field(default=7.0, ge=0.0, le=10.0, description="Risk score threshold")
278
+ resolve_proxy: bool = Field(
279
+ default=True, description="Whether to resolve EIP-1967/Beacon proxy implementation slots on-chain"
280
+ )
281
+ fetch_verified_source: bool = Field(
282
+ default=True, description="Whether to fetch verified Solidity source code from Sourcify/Etherscan"
283
+ )
284
+
285
+ @field_validator("target_address", "address", "contract_address")
286
+ @classmethod
287
+ def validate_and_normalize_addr(cls, v: Optional[str]) -> Optional[str]:
288
+ if v is None or v == "":
289
+ return None
290
+ if not Web3.is_address(v):
291
+ raise ValueError(f"Invalid Ethereum address: {v}")
292
+ return Web3.to_checksum_address(v)
293
+
294
+ @model_validator(mode="after")
295
+ def harmonize_addresses(self) -> "DeepAuditRequest":
296
+ resolved = self.target_address or self.address or self.contract_address
297
+ if resolved:
298
+ self.target_address = resolved
299
+ if not self.address:
300
+ self.address = resolved
301
+ if not self.contract_address:
302
+ self.contract_address = resolved
303
+ return self
304
+
305
+
306
+ class TokenCheckResponse(BaseModel):
307
+ address: str
308
+ chain_id: int = 8453
309
+ is_contract: bool
310
+ bytecode_size_bytes: int = 0
311
+ verdict: Literal["SAFE", "CAUTION", "DANGEROUS", "EOA"]
312
+ risk_score: float = Field(..., ge=0.0, le=10.0)
313
+ is_honeypot_suspect: bool = False
314
+ threat_categories: List[str] = Field(default_factory=list)
315
+ honeypot_flags: List[str] = Field(default_factory=list)
316
+ selectors_found: List[Dict[str, Any]] = Field(default_factory=list)
317
+ high_risk_selectors: List[str] = Field(default_factory=list)
318
+ is_proxy: bool = False
319
+ implementation_address: Optional[str] = None
320
+ source_verified: bool = False
321
+ source_provider: Optional[str] = None
322
+ security_warnings: List[str] = Field(default_factory=list)
323
+ summary: str = ""
324
+ deep_audit_url: str = ""
325
+ report_url: str = ""
326
+ llm_invoked: bool = False
327
+ payment: Optional[PaymentReceipt] = None
328
+
329
+
330
+