opshield 0.2.0__tar.gz

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 (55) hide show
  1. opshield-0.2.0/.gitignore +21 -0
  2. opshield-0.2.0/CHANGELOG.md +67 -0
  3. opshield-0.2.0/LICENSE +21 -0
  4. opshield-0.2.0/PKG-INFO +469 -0
  5. opshield-0.2.0/README.md +422 -0
  6. opshield-0.2.0/examples/demo.py +136 -0
  7. opshield-0.2.0/examples/demo_full.py +259 -0
  8. opshield-0.2.0/examples/demo_multiagent.py +101 -0
  9. opshield-0.2.0/examples/demo_openai.py +185 -0
  10. opshield-0.2.0/examples/policy.json +50 -0
  11. opshield-0.2.0/pyproject.toml +67 -0
  12. opshield-0.2.0/site/index.html +302 -0
  13. opshield-0.2.0/src/opshield/__init__.py +53 -0
  14. opshield-0.2.0/src/opshield/__main__.py +3 -0
  15. opshield-0.2.0/src/opshield/action.py +50 -0
  16. opshield-0.2.0/src/opshield/approval.py +275 -0
  17. opshield-0.2.0/src/opshield/async_shield.py +195 -0
  18. opshield-0.2.0/src/opshield/budget.py +76 -0
  19. opshield-0.2.0/src/opshield/capabilities.py +211 -0
  20. opshield-0.2.0/src/opshield/chaos.py +193 -0
  21. opshield-0.2.0/src/opshield/circuitbreaker.py +150 -0
  22. opshield-0.2.0/src/opshield/cli.py +117 -0
  23. opshield-0.2.0/src/opshield/compliance.py +306 -0
  24. opshield-0.2.0/src/opshield/config.py +91 -0
  25. opshield-0.2.0/src/opshield/dashboard.py +212 -0
  26. opshield-0.2.0/src/opshield/forecast.py +174 -0
  27. opshield-0.2.0/src/opshield/integrations/__init__.py +1 -0
  28. opshield-0.2.0/src/opshield/integrations/anthropic_sdk.py +119 -0
  29. opshield-0.2.0/src/opshield/integrations/autogen.py +116 -0
  30. opshield-0.2.0/src/opshield/integrations/crewai.py +115 -0
  31. opshield-0.2.0/src/opshield/integrations/langchain.py +127 -0
  32. opshield-0.2.0/src/opshield/integrations/openai_agents.py +138 -0
  33. opshield-0.2.0/src/opshield/logger.py +112 -0
  34. opshield-0.2.0/src/opshield/masking.py +185 -0
  35. opshield-0.2.0/src/opshield/metrics.py +159 -0
  36. opshield-0.2.0/src/opshield/multiagent.py +160 -0
  37. opshield-0.2.0/src/opshield/policy.py +126 -0
  38. opshield-0.2.0/src/opshield/ratelimit.py +109 -0
  39. opshield-0.2.0/src/opshield/replay.py +187 -0
  40. opshield-0.2.0/src/opshield/retry.py +106 -0
  41. opshield-0.2.0/src/opshield/rules.py +116 -0
  42. opshield-0.2.0/src/opshield/scoring.py +229 -0
  43. opshield-0.2.0/src/opshield/shield.py +474 -0
  44. opshield-0.2.0/src/opshield/snapshot.py +67 -0
  45. opshield-0.2.0/src/opshield/tracing.py +256 -0
  46. opshield-0.2.0/src/opshield/webhooks.py +113 -0
  47. opshield-0.2.0/tests/__init__.py +0 -0
  48. opshield-0.2.0/tests/test_config_and_logger.py +103 -0
  49. opshield-0.2.0/tests/test_phase3.py +228 -0
  50. opshield-0.2.0/tests/test_phase4.py +249 -0
  51. opshield-0.2.0/tests/test_phase5.py +223 -0
  52. opshield-0.2.0/tests/test_phase6.py +229 -0
  53. opshield-0.2.0/tests/test_phase7.py +467 -0
  54. opshield-0.2.0/tests/test_phase8.py +460 -0
  55. opshield-0.2.0/tests/test_shield.py +138 -0
@@ -0,0 +1,21 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ *.egg-info/
5
+ dist/
6
+ build/
7
+ *.egg
8
+ .eggs/
9
+ venv/
10
+ .venv/
11
+ env/
12
+ .env
13
+ *.db
14
+ *.sqlite3
15
+ logs/
16
+ .pytest_cache/
17
+ .mypy_cache/
18
+ .ruff_cache/
19
+ *.whl
20
+ *.tar.gz
21
+ .DS_Store
@@ -0,0 +1,67 @@
1
+ # Changelog
2
+
3
+ All notable changes to OpShield are documented here.
4
+
5
+ ## [0.2.0] - 2026-10-08
6
+
7
+ ### Added — Phase 7: Enterprise Safety
8
+ - **Circuit Breaker** (`circuitbreaker.py`): CLOSED/OPEN/HALF_OPEN states, configurable failure threshold, reset timeout, success threshold for recovery, on_open/on_close callbacks
9
+ - **Approval Workflows** (`approval.py`): Human-in-the-loop with configurable timeout, auto-deny, callback-based approve/deny, risk-based approval, escalation chains
10
+ - **Agent Capabilities** (`capabilities.py`): Per-agent allowlist/denylist, argument constraints (args_deny/args_require), max cost per tool, max calls per hour, time-based schedules
11
+ - **Compliance Reports** (`compliance.py`): Structured audit reports from SQLite logs, anomaly detection (high block/error rate, CRITICAL attempts), risk breakdown, JSON/HTML export
12
+
13
+ ### Added — Phase 8: Observability & Resilience
14
+ - **Distributed Tracing** (`tracing.py`): OpenTelemetry-compatible spans with trace/span IDs, nested spans via context manager, JSON and OTLP export, trace grouping
15
+ - **Chaos Engineering** (`chaos.py`): Fault injection (ERROR, LATENCY, TIMEOUT, CORRUPT_OUTPUT), probability control, conditional triggers, wildcard rules, max injection limits
16
+ - **Cost Forecasting** (`forecast.py`): Burn rate analysis (per minute/hour), budget exhaustion prediction, trend detection (increasing/decreasing/stable), cost-by-tool breakdown
17
+ - **Agent Scoring** (`scoring.py`): Safety/reliability/efficiency/risk dimensions (0-100), A-F grading, configurable weights, multi-agent pool ranking via PoolScorer
18
+
19
+ ### Added — Phase 9: Polish & Market Readiness
20
+ - Full README rewrite covering all 32+ modules
21
+ - Landing page (`site/index.html`) with feature showcase and market data
22
+ - Comprehensive end-to-end demo (`examples/demo_full.py`)
23
+ - This CHANGELOG
24
+
25
+ ### Changed
26
+ - `shield.py`: Integrated circuit breaker, capabilities, chaos, and tracing into execution pipeline
27
+ - `__init__.py`: Added exports for all new modules (ApprovalManager, CapabilityManager, CircuitBreaker, ChaosEngine, ComplianceReporter, CostForecaster, AgentScorer, PoolScorer, Tracer, FaultType, CircuitState)
28
+
29
+ ## [0.1.0] - 2026-10-08
30
+
31
+ ### Added — Phase 1: Core
32
+ - `OpShield` main class with tool decorator
33
+ - Risk classification engine (LOW/MEDIUM/HIGH/CRITICAL)
34
+ - Budget tracking with per-action cost
35
+ - State snapshots and rollback
36
+ - Test/simulation mode
37
+
38
+ ### Added — Phase 2: Infrastructure
39
+ - Dict-based configuration system
40
+ - SQLite-backed action logging
41
+ - OpenAI Agents SDK integration
42
+ - LangChain integration
43
+ - CLI tool (stats, logs, export, validate, dashboard)
44
+ - pip install support via pyproject.toml
45
+
46
+ ### Added — Phase 3: Rate Limiting & Events
47
+ - Sliding-window rate limiter (global RPM/RPH, per-tool limits)
48
+ - Webhook/event notification system (HTTP + callbacks)
49
+ - Anthropic Claude SDK integration
50
+ - AsyncOpShield with async_tool decorator
51
+
52
+ ### Added — Phase 4: Policy & Dashboard
53
+ - Policy-as-code (JSON/YAML files)
54
+ - Retry with exponential backoff and conditional retry
55
+ - CrewAI integration
56
+ - Web dashboard (dark theme, auto-refresh, stats cards)
57
+
58
+ ### Added — Phase 5: Multi-Agent & Metrics
59
+ - AgentPool for multi-agent management with isolated budgets
60
+ - Microsoft AutoGen integration
61
+ - Prometheus-compatible metrics export (OpenMetrics text format)
62
+
63
+ ### Added — Phase 6: Privacy & Debug
64
+ - DataMasker with 10 built-in PII/secret patterns
65
+ - Custom masking patterns support
66
+ - ActionReplayer for debugging/audit from SQLite logs
67
+ - Dry-run and single-action replay
opshield-0.2.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ali Çelik
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,469 @@
1
+ Metadata-Version: 2.5
2
+ Name: opshield
3
+ Version: 0.2.0
4
+ Summary: AI agent safety platform: rollback, cost control, circuit breakers, tracing, compliance, and chaos testing.
5
+ Project-URL: Homepage, https://github.com/alicelik-games/opshield
6
+ Project-URL: Documentation, https://github.com/alicelik-games/opshield#readme
7
+ Project-URL: Issues, https://github.com/alicelik-games/opshield/issues
8
+ Project-URL: Changelog, https://github.com/alicelik-games/opshield/blob/main/CHANGELOG.md
9
+ Author-email: Ali Çelik <alicelik1980@gmail.com>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: agent,ai,chaos-engineering,circuit-breaker,compliance,cost-control,guardrails,multi-agent,observability,rate-limiting,rollback,safety,testing,tracing
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Topic :: Security
22
+ Classifier: Topic :: Software Development :: Libraries
23
+ Requires-Python: >=3.11
24
+ Provides-Extra: all
25
+ Requires-Dist: anthropic>=0.18; extra == 'all'
26
+ Requires-Dist: crewai>=0.1; extra == 'all'
27
+ Requires-Dist: langchain-core>=0.1; extra == 'all'
28
+ Requires-Dist: openai>=1.0; extra == 'all'
29
+ Requires-Dist: pyautogen>=0.2; extra == 'all'
30
+ Requires-Dist: pyyaml>=6.0; extra == 'all'
31
+ Provides-Extra: anthropic
32
+ Requires-Dist: anthropic>=0.18; extra == 'anthropic'
33
+ Provides-Extra: autogen
34
+ Requires-Dist: pyautogen>=0.2; extra == 'autogen'
35
+ Provides-Extra: crewai
36
+ Requires-Dist: crewai>=0.1; extra == 'crewai'
37
+ Provides-Extra: dev
38
+ Requires-Dist: pytest>=7.0; extra == 'dev'
39
+ Requires-Dist: ruff>=0.1; extra == 'dev'
40
+ Provides-Extra: langchain
41
+ Requires-Dist: langchain-core>=0.1; extra == 'langchain'
42
+ Provides-Extra: openai
43
+ Requires-Dist: openai>=1.0; extra == 'openai'
44
+ Provides-Extra: yaml
45
+ Requires-Dist: pyyaml>=6.0; extra == 'yaml'
46
+ Description-Content-Type: text/markdown
47
+
48
+ # OpShield
49
+
50
+ **The safety layer between AI agents and the real world.**
51
+
52
+ OpShield intercepts every tool call your AI agent makes and provides rollback, cost control, rate limiting, circuit breakers, approval workflows, distributed tracing, chaos testing, and compliance reporting — so agents can work autonomously without causing damage.
53
+
54
+ **Zero mandatory dependencies. One `pip install`. Works with every major agent framework.**
55
+
56
+ > **Market context:** With Guardrails AI acquired by Harvey (Sept 2026) and the AI agent safety market projected to grow from $610M to $6.85B at 41% CAGR, OpShield fills the gap as a comprehensive, framework-agnostic agent operations platform.
57
+
58
+ ## Why OpShield?
59
+
60
+ | Problem | OpShield Solution |
61
+ |---------|---------------------|
62
+ | Agent runs `DROP TABLE` | Auto-blocked by risk classification |
63
+ | Agent overspends API budget | Budget limits + cost forecasting |
64
+ | Want to test without side effects | Test mode simulates everything |
65
+ | Agent made a mistake | One-call rollback via state snapshots |
66
+ | Agent spams an API | Rate limiting (RPM/RPH per tool) |
67
+ | Tool keeps failing | Circuit breaker auto-disables it |
68
+ | Need human approval | Approval workflows with timeout/escalation |
69
+ | Different agents, different rules | AgentPool with isolated budgets + capabilities |
70
+ | Sensitive data in logs | Automatic PII/secret masking |
71
+ | Need audit trail | SQLite logging + Prometheus + compliance reports |
72
+ | Test agent resilience | Chaos engineering with fault injection |
73
+ | Track every action | OpenTelemetry-compatible distributed tracing |
74
+ | Evaluate agent quality | Safety/performance scoring (A-F grades) |
75
+
76
+ ## Install
77
+
78
+ ```bash
79
+ pip install opshield
80
+ ```
81
+
82
+ With framework integrations:
83
+
84
+ ```bash
85
+ pip install opshield[openai] # OpenAI Agents SDK
86
+ pip install opshield[anthropic] # Anthropic Claude SDK
87
+ pip install opshield[langchain] # LangChain
88
+ pip install opshield[crewai] # CrewAI
89
+ pip install opshield[autogen] # Microsoft AutoGen
90
+ pip install opshield[yaml] # YAML policy files
91
+ pip install opshield[all] # Everything
92
+ ```
93
+
94
+ ## Quick Start
95
+
96
+ ```python
97
+ from opshield import OpShield
98
+
99
+ shield = OpShield(budget=5.00, auto_snapshot=True)
100
+
101
+ @shield.tool(cost=0.03)
102
+ def query_db(sql: str) -> str:
103
+ return db.execute(sql)
104
+
105
+ # Normal execution
106
+ result = query_db(sql="SELECT * FROM users")
107
+ print(result.output) # Works fine
108
+
109
+ # Destructive SQL is auto-blocked
110
+ result = query_db(sql="DROP TABLE users")
111
+ print(result.blocked) # True
112
+ print(result.block_reason) # "CRITICAL risk blocked: Destructive SQL detected"
113
+
114
+ # Undo the last action
115
+ shield.rollback()
116
+ ```
117
+
118
+ ## Core Features
119
+
120
+ ### Policy-as-Code
121
+
122
+ Define rules in JSON or YAML files:
123
+
124
+ ```json
125
+ {
126
+ "budget": 25.00,
127
+ "mode": "production",
128
+ "global_rpm": 120,
129
+ "tool_limits": {"send_email": {"rpm": 10, "rph": 100}},
130
+ "rules": [
131
+ {
132
+ "name": "no_prod_access",
133
+ "match": {"args_regex": "production|prod-db"},
134
+ "risk": "critical",
135
+ "reason": "Production database access blocked"
136
+ }
137
+ ],
138
+ "webhooks": [
139
+ {"url": "https://hooks.slack.com/...", "events": ["action_blocked"]}
140
+ ]
141
+ }
142
+ ```
143
+
144
+ ```python
145
+ from opshield import load_policy
146
+ shield = load_policy("policy.json")
147
+ ```
148
+
149
+ ### Multi-Agent Support
150
+
151
+ ```python
152
+ from opshield import AgentPool
153
+
154
+ pool = AgentPool(default_budget=5.00)
155
+ researcher = pool.register("researcher", budget=3.00)
156
+ coder = pool.register("coder", budget=10.00)
157
+ reviewer = pool.register("reviewer", budget=1.00, mode="test")
158
+
159
+ pool.stats() # Aggregated view across all agents
160
+ pool.over_budget() # ["researcher"] if over budget
161
+ ```
162
+
163
+ ### Rate Limiting
164
+
165
+ ```python
166
+ from opshield import OpShield, ToolLimit
167
+
168
+ shield = OpShield(
169
+ budget=10.00,
170
+ global_rpm=60, # 60 calls/min globally
171
+ tool_limits={"send_email": ToolLimit(rpm=5)}, # 5 emails/min
172
+ )
173
+ ```
174
+
175
+ ### Retry with Backoff
176
+
177
+ ```python
178
+ from opshield import RetryPolicy
179
+
180
+ policy = RetryPolicy(max_retries=3, backoff_base=1.0, jitter=0.5)
181
+
182
+ @shield.tool(cost=0.05, retry=policy)
183
+ def flaky_api(query: str) -> str:
184
+ return requests.get(f"https://api.example.com?q={query}").text
185
+ ```
186
+
187
+ ### Sensitive Data Masking
188
+
189
+ ```python
190
+ from opshield import DataMasker
191
+
192
+ masker = DataMasker()
193
+ shield.set_masker(masker)
194
+
195
+ # Emails, API keys, credit cards, SSNs, JWTs are auto-masked in logs
196
+ masker.add_pattern("project_id", r"PROJ-\d{6}", "PROJ-******")
197
+ ```
198
+
199
+ ## Enterprise Safety
200
+
201
+ ### Circuit Breaker
202
+
203
+ Auto-disable tools that fail repeatedly (CLOSED → OPEN → HALF_OPEN):
204
+
205
+ ```python
206
+ from opshield import CircuitBreaker
207
+
208
+ cb = CircuitBreaker(failure_threshold=5, reset_timeout=60.0)
209
+ shield.set_circuit_breaker(cb)
210
+ # After 5 consecutive failures, the tool is auto-disabled for 60s
211
+ # Then one probe call is allowed (HALF_OPEN) to test recovery
212
+ ```
213
+
214
+ ### Human-in-the-Loop Approval
215
+
216
+ ```python
217
+ from opshield import ApprovalManager
218
+
219
+ approver = ApprovalManager(default_timeout=30.0)
220
+ approver.require_approval("send_email", timeout=60.0)
221
+ approver.require_approval_for_risk("HIGH")
222
+ shield.set_approval(approver)
223
+
224
+ # From another thread or webhook handler:
225
+ approver.approve(request_id, approver="admin@company.com")
226
+ ```
227
+
228
+ ### Agent Capabilities / Permissions
229
+
230
+ Fine-grained tool access control per agent:
231
+
232
+ ```python
233
+ from opshield import CapabilityManager
234
+
235
+ caps = CapabilityManager()
236
+ caps.grant("researcher", allow=["search", "read_file"])
237
+ caps.grant("intern_bot", deny=["delete_record", "send_email"])
238
+ caps.add_constraint("coder", "run_sql", args_deny=["DROP", "TRUNCATE"])
239
+ shield.set_capabilities(caps)
240
+ ```
241
+
242
+ ### Compliance & Audit Reports
243
+
244
+ ```python
245
+ from opshield import ComplianceReporter
246
+
247
+ reporter = ComplianceReporter(db_path="audit.db")
248
+ report = reporter.generate_report(start="2026-01-01", end="2026-12-31")
249
+ print(report.summary) # Text summary with anomaly detection
250
+ reporter.export_json("audit.json")
251
+ html = reporter.to_html() # Full HTML report
252
+ ```
253
+
254
+ ## Observability
255
+
256
+ ### Distributed Tracing
257
+
258
+ OpenTelemetry-compatible span system:
259
+
260
+ ```python
261
+ from opshield import Tracer
262
+
263
+ tracer = Tracer(service_name="my-agent")
264
+ shield.set_tracer(tracer)
265
+
266
+ # Every tool call automatically generates spans
267
+ # Nested spans for complex workflows:
268
+ with tracer.span("data_pipeline") as parent:
269
+ with tracer.span("extract", parent=parent):
270
+ extract_data()
271
+ with tracer.span("transform", parent=parent):
272
+ transform_data()
273
+
274
+ tracer.export_json("traces.json") # JSON export
275
+ tracer.export_otlp() # OTLP-compatible dict
276
+ ```
277
+
278
+ ### Cost Forecasting
279
+
280
+ ```python
281
+ from opshield import CostForecaster
282
+
283
+ forecaster = CostForecaster(shield)
284
+ report = forecaster.forecast()
285
+ print(report.burn_rate_per_hour) # $/hour
286
+ print(report.estimated_exhaustion) # datetime
287
+ print(report.estimated_actions_remaining)
288
+ print(report.trend) # "increasing" / "stable" / "decreasing"
289
+ ```
290
+
291
+ ### Agent Scoring & Benchmarking
292
+
293
+ ```python
294
+ from opshield import AgentScorer, PoolScorer
295
+
296
+ scorer = AgentScorer(shield, agent_name="my-bot")
297
+ report = scorer.score()
298
+ print(report.overall_score) # 0-100
299
+ print(report.grade) # A/B/C/D/F
300
+ print(report.safety_score) # Safety dimension
301
+ print(report.reliability_score)
302
+
303
+ # Rank all agents in a pool
304
+ pool_scorer = PoolScorer(pool)
305
+ print(pool_scorer.summary()) # Ranked leaderboard
306
+ ```
307
+
308
+ ### Web Dashboard
309
+
310
+ ```bash
311
+ opshield --db audit.db dashboard --port 8080
312
+ ```
313
+
314
+ Real-time web UI showing actions, blocks, budget, and rate limits.
315
+
316
+ ### Prometheus Metrics
317
+
318
+ ```python
319
+ from opshield.metrics import start_metrics_server
320
+ start_metrics_server(shield, port=9090)
321
+ # Scrape http://localhost:9090/metrics
322
+ ```
323
+
324
+ Exports: `opshield_actions_total`, `opshield_actions_blocked_total`, `opshield_budget_spent_dollars`, per-tool and per-agent labels.
325
+
326
+ ### Webhook Notifications
327
+
328
+ ```python
329
+ shield.notifier.add_webhook(
330
+ url="https://hooks.slack.com/services/xxx",
331
+ events={"action_blocked", "budget_exceeded"},
332
+ )
333
+
334
+ shield.notifier.on("action_blocked", lambda event, data: print(f"Alert: {data}"))
335
+ ```
336
+
337
+ ## Resilience Testing
338
+
339
+ ### Chaos Engineering
340
+
341
+ Test agent resilience with controlled fault injection:
342
+
343
+ ```python
344
+ from opshield import ChaosEngine, FaultType
345
+
346
+ chaos = ChaosEngine()
347
+ shield.set_chaos(chaos)
348
+
349
+ # Random failures (20% of calls)
350
+ chaos.add_fault("search_api", FaultType.ERROR, probability=0.2)
351
+
352
+ # Latency injection
353
+ chaos.add_fault("slow_api", FaultType.LATENCY, latency_ms=2000)
354
+
355
+ # Conditional faults
356
+ chaos.add_fault("db_query", FaultType.ERROR,
357
+ condition=lambda args: "prod" in str(args))
358
+
359
+ # Wildcard — affect all tools
360
+ chaos.add_fault("*", FaultType.LATENCY, latency_ms=500, probability=0.1)
361
+ ```
362
+
363
+ ### Action Replay
364
+
365
+ ```python
366
+ from opshield.replay import ActionReplayer
367
+
368
+ replayer = ActionReplayer(db_path="audit.db", executors={"run_sql": my_fn})
369
+ report = replayer.replay_all(shield)
370
+ print(f"Match rate: {report.success_rate:.0%}")
371
+ ```
372
+
373
+ ### Async Support
374
+
375
+ ```python
376
+ from opshield import AsyncOpShield
377
+
378
+ shield = AsyncOpShield(budget=5.00)
379
+
380
+ @shield.async_tool(cost=0.05)
381
+ async def async_query(sql: str) -> str:
382
+ return await db.execute(sql)
383
+ ```
384
+
385
+ ## Framework Integrations
386
+
387
+ | Framework | Module | Pattern |
388
+ |-----------|--------|---------|
389
+ | OpenAI Agents SDK | `integrations.openai_agents` | Middleware |
390
+ | Anthropic Claude | `integrations.anthropic_sdk` | Middleware |
391
+ | LangChain | `integrations.langchain` | Tool wrapper |
392
+ | CrewAI | `integrations.crewai` | Tool wrapper |
393
+ | Microsoft AutoGen | `integrations.autogen` | Function wrapper |
394
+
395
+ ```python
396
+ # OpenAI
397
+ from opshield.integrations.openai_agents import OpenAIShieldMiddleware
398
+ middleware = OpenAIShieldMiddleware(shield=shield, executors={...})
399
+
400
+ # Anthropic
401
+ from opshield.integrations.anthropic_sdk import AnthropicShieldMiddleware
402
+ middleware = AnthropicShieldMiddleware(shield=shield, executors={...})
403
+
404
+ # LangChain
405
+ from opshield.integrations.langchain import shield_langchain_tools
406
+
407
+ # CrewAI
408
+ from opshield.integrations.crewai import shield_crewai_tools
409
+
410
+ # AutoGen
411
+ from opshield.integrations.autogen import shield_autogen_functions
412
+ ```
413
+
414
+ ## CLI
415
+
416
+ ```bash
417
+ opshield stats # Action statistics
418
+ opshield logs # View action log
419
+ opshield logs --blocked # Only blocked actions
420
+ opshield export audit.json # Export to JSON
421
+ opshield validate policy.json # Validate a policy file
422
+ opshield dashboard --port 8080 # Start web dashboard
423
+ ```
424
+
425
+ ## Risk Levels
426
+
427
+ | Level | Behavior | Examples |
428
+ |-------|----------|----------|
429
+ | LOW | Execute normally | SELECT queries, file reads |
430
+ | MEDIUM | Execute with logging | Outbound messages, moderate operations |
431
+ | HIGH | Ask user for approval | Bulk operations (>100 items) |
432
+ | CRITICAL | Auto-block | DROP TABLE, TRUNCATE, DELETE FROM |
433
+
434
+ ## Architecture
435
+
436
+ ```
437
+ Agent → OpShield → Tool
438
+ ├── Capability Check (permissions)
439
+ ├── Circuit Breaker (fail-fast)
440
+ ├── Risk Classification (rules engine)
441
+ ├── Approval Workflow (human-in-the-loop)
442
+ ├── Budget Check + Forecast
443
+ ├── Rate Limit Check
444
+ ├── Snapshot (for rollback)
445
+ ├── Chaos Injection (testing)
446
+ ├── Execute (or simulate in test mode)
447
+ ├── Retry (on failure, with backoff)
448
+ ├── Data Masking (for logs)
449
+ ├── Log to SQLite
450
+ ├── Emit webhook/callback events
451
+ ├── Record span (distributed tracing)
452
+ ├── Agent Scoring
453
+ └── Prometheus metrics
454
+ ```
455
+
456
+ ## Stats
457
+
458
+ - **32+ Python modules**, 107+ tests
459
+ - **Zero mandatory dependencies**
460
+ - **5 framework integrations**
461
+ - Works with Python 3.11+
462
+
463
+ ## Author
464
+
465
+ **Ali Çelik** — [LinkedIn](https://linkedin.com/in/alicelik1980) · [Email](mailto:alicelik1980@gmail.com)
466
+
467
+ ## License
468
+
469
+ MIT — see [LICENSE](LICENSE) for details.