aizee 6.8.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 (322) hide show
  1. aizee-6.8.0.dist-info/METADATA +617 -0
  2. aizee-6.8.0.dist-info/RECORD +322 -0
  3. aizee-6.8.0.dist-info/WHEEL +5 -0
  4. aizee-6.8.0.dist-info/entry_points.txt +2 -0
  5. aizee-6.8.0.dist-info/licenses/LICENSE +21 -0
  6. aizee-6.8.0.dist-info/licenses/NOTICE +33 -0
  7. aizee-6.8.0.dist-info/top_level.txt +7 -0
  8. aizee_cli.py +2907 -0
  9. aizee_mcp/API.md +353 -0
  10. aizee_mcp/__init__.py +3 -0
  11. aizee_mcp/_compat.py +50 -0
  12. aizee_mcp/adapters.py +555 -0
  13. aizee_mcp/agent.py +208 -0
  14. aizee_mcp/aizee_server.py +501 -0
  15. aizee_mcp/config.json +29 -0
  16. aizee_mcp/rbac.py +109 -0
  17. aizee_mcp/rbac.yaml +25 -0
  18. aizee_mcp/schema_profile.py +74 -0
  19. aizee_mcp/tools/__init__.py +94 -0
  20. aizee_mcp/tools/ads_tools.py +285 -0
  21. aizee_mcp/tools/analytics_tools.py +408 -0
  22. aizee_mcp/tools/common.py +103 -0
  23. aizee_mcp/tools/context_tools.py +140 -0
  24. aizee_mcp/tools/cro_tools.py +295 -0
  25. aizee_mcp/tools/doctor_tools.py +69 -0
  26. aizee_mcp/tools/email_tools.py +555 -0
  27. aizee_mcp/tools/freelance_tools.py +300 -0
  28. aizee_mcp/tools/intel_tools.py +114 -0
  29. aizee_mcp/tools/memory_tools.py +236 -0
  30. aizee_mcp/tools/policy_tools.py +135 -0
  31. aizee_mcp/tools/schemas.py +296 -0
  32. aizee_mcp/tools/seo_page_reporters.py +181 -0
  33. aizee_mcp/tools/seo_tools.py +1047 -0
  34. aizee_mcp/tools/social_tools.py +358 -0
  35. aizee_mcp/tools/task_tools.py +135 -0
  36. aizee_mcp/tools/workflow_tools.py +209 -0
  37. config.py +64 -0
  38. eval/__init__.py +0 -0
  39. eval/agent_benchmark.py +268 -0
  40. eval/chaos.py +296 -0
  41. eval/harness.py +234 -0
  42. eval/pipeline.py +460 -0
  43. eval/prompt_injection_suite.py +385 -0
  44. eval/redteam.py +284 -0
  45. eval/release_gate.py +157 -0
  46. eval/reliability.py +510 -0
  47. eval/rubric.py +263 -0
  48. eval/scenarios/goldfish-review.yaml +61 -0
  49. eval/scenarios/persona.yaml +22 -0
  50. eval/scenarios/security.yaml +43 -0
  51. eval/skill_scenarios.py +235 -0
  52. eval/stages.py +135 -0
  53. eval/trigger_cases.json +118 -0
  54. eval/vibe.py +234 -0
  55. memory/__init__.py +22 -0
  56. memory/archive/Memory-202610.md +604 -0
  57. memory/checkpoint.py +331 -0
  58. memory/compactor.py +196 -0
  59. memory/consolidation.py +140 -0
  60. memory/decay_scheduler.py +119 -0
  61. memory/git_memory.py +360 -0
  62. memory/graph.py +156 -0
  63. memory/handoff.py +144 -0
  64. memory/heat.py +131 -0
  65. memory/hybrid.py +236 -0
  66. memory/ingest.py +244 -0
  67. memory/instincts.py +128 -0
  68. memory/observations.py +439 -0
  69. memory/schema_contract.py +361 -0
  70. memory/sectors.py +165 -0
  71. memory/simhash.py +164 -0
  72. memory/store.py +1383 -0
  73. memory/temporal.py +173 -0
  74. memory/vector.py +458 -0
  75. plugins/__init__.py +0 -0
  76. plugins/automatisch/__init__.py +5 -0
  77. plugins/automatisch/automatisch_plugin.py +78 -0
  78. plugins/brevo/__init__.py +5 -0
  79. plugins/brevo/brevo_plugin.py +78 -0
  80. plugins/chatwoot/__init__.py +5 -0
  81. plugins/chatwoot/chatwoot_plugin.py +78 -0
  82. plugins/code2video/README.md +87 -0
  83. plugins/code2video/__init__.py +3 -0
  84. plugins/code2video/code2video_plugin.py +229 -0
  85. plugins/code2video/entrypoint.py +166 -0
  86. plugins/code2video/litellm-c2v.yaml +30 -0
  87. plugins/context7/__init__.py +5 -0
  88. plugins/context7/context7_plugin.py +57 -0
  89. plugins/documenso/__init__.py +5 -0
  90. plugins/documenso/documenso_plugin.py +78 -0
  91. plugins/erpnext/__init__.py +5 -0
  92. plugins/erpnext/erpnext_plugin.py +78 -0
  93. plugins/fiverr/__init__.py +5 -0
  94. plugins/fiverr/fiverr_plugin.py +82 -0
  95. plugins/flagsmith/__init__.py +5 -0
  96. plugins/flagsmith/flagsmith_plugin.py +78 -0
  97. plugins/formbricks/__init__.py +5 -0
  98. plugins/formbricks/formbricks_plugin.py +78 -0
  99. plugins/freelancer/__init__.py +5 -0
  100. plugins/freelancer/freelancer_plugin.py +106 -0
  101. plugins/google_ads/__init__.py +5 -0
  102. plugins/google_ads/google_ads_plugin.py +78 -0
  103. plugins/graphify/__init__.py +3 -0
  104. plugins/graphify/graph_plugin.py +168 -0
  105. plugins/growthbook/__init__.py +5 -0
  106. plugins/growthbook/growthbook_plugin.py +78 -0
  107. plugins/hubspot/__init__.py +5 -0
  108. plugins/hubspot/hubspot_plugin.py +78 -0
  109. plugins/khamsat/__init__.py +5 -0
  110. plugins/khamsat/khamsat_plugin.py +80 -0
  111. plugins/kit/__init__.py +5 -0
  112. plugins/kit/kit_plugin.py +78 -0
  113. plugins/klaviyo/__init__.py +5 -0
  114. plugins/klaviyo/klaviyo_plugin.py +78 -0
  115. plugins/lago/__init__.py +5 -0
  116. plugins/lago/lago_plugin.py +78 -0
  117. plugins/linkedin/__init__.py +5 -0
  118. plugins/linkedin/linkedin_plugin.py +188 -0
  119. plugins/linkedin_ads/__init__.py +5 -0
  120. plugins/linkedin_ads/linkedin_ads_plugin.py +78 -0
  121. plugins/listmonk/__init__.py +5 -0
  122. plugins/listmonk/listmonk_plugin.py +78 -0
  123. plugins/meta_ads/__init__.py +5 -0
  124. plugins/meta_ads/meta_ads_plugin.py +78 -0
  125. plugins/mostaql/__init__.py +5 -0
  126. plugins/mostaql/mostaql_plugin.py +80 -0
  127. plugins/n8n/__init__.py +5 -0
  128. plugins/n8n/n8n_plugin.py +78 -0
  129. plugins/openreplay/__init__.py +5 -0
  130. plugins/openreplay/openreplay_plugin.py +78 -0
  131. plugins/posthog/__init__.py +5 -0
  132. plugins/posthog/posthog_plugin.py +78 -0
  133. plugins/postiz/__init__.py +5 -0
  134. plugins/postiz/postiz_plugin.py +78 -0
  135. plugins/sendgrid/__init__.py +5 -0
  136. plugins/sendgrid/sendgrid_plugin.py +78 -0
  137. plugins/tiktok_ads/__init__.py +5 -0
  138. plugins/tiktok_ads/tiktok_ads_plugin.py +78 -0
  139. plugins/twenty/__init__.py +5 -0
  140. plugins/twenty/twenty_plugin.py +78 -0
  141. plugins/twitter/__init__.py +5 -0
  142. plugins/twitter/twitter_plugin.py +78 -0
  143. plugins/upwork/__init__.py +5 -0
  144. plugins/upwork/upwork_plugin.py +90 -0
  145. plugins/youtube/__init__.py +5 -0
  146. plugins/youtube/youtube_plugin.py +78 -0
  147. runtime/__init__.py +694 -0
  148. runtime/_osroot.tar.gz +0 -0
  149. runtime/abstracts.py +159 -0
  150. runtime/agent_baseline.py +350 -0
  151. runtime/agent_circuit_breaker.py +305 -0
  152. runtime/agent_discovery.py +320 -0
  153. runtime/agent_gateway.py +448 -0
  154. runtime/agent_sli.py +435 -0
  155. runtime/api_session.py +229 -0
  156. runtime/approval_cache.py +61 -0
  157. runtime/approval_service.py +352 -0
  158. runtime/approval_sla.py +341 -0
  159. runtime/astryx.py +111 -0
  160. runtime/attribution_model.py +76 -0
  161. runtime/audit.py +641 -0
  162. runtime/audit_signing.py +346 -0
  163. runtime/billing_ledger.py +209 -0
  164. runtime/blade_template_linter.py +239 -0
  165. runtime/blast_radius.py +526 -0
  166. runtime/bootstrap.py +233 -0
  167. runtime/budget.py +800 -0
  168. runtime/budget_advanced.py +799 -0
  169. runtime/budget_escalation.py +220 -0
  170. runtime/c4_docs.py +200 -0
  171. runtime/call_plan.py +798 -0
  172. runtime/chat.py +63 -0
  173. runtime/ci.py +70 -0
  174. runtime/codemode/__init__.py +14 -0
  175. runtime/codemode/_child.py +123 -0
  176. runtime/codemode/executor.py +311 -0
  177. runtime/config_ops.py +116 -0
  178. runtime/context_composition.py +149 -0
  179. runtime/crm_manager.py +164 -0
  180. runtime/cross_tool_taint.py +529 -0
  181. runtime/crypto.py +195 -0
  182. runtime/curriculum.py +113 -0
  183. runtime/daemon.py +719 -0
  184. runtime/db_migration_safety.py +251 -0
  185. runtime/defensive_injection.py +472 -0
  186. runtime/deps.py +461 -0
  187. runtime/design_db.py +505 -0
  188. runtime/design_library.py +467 -0
  189. runtime/design_slop_verifier.py +540 -0
  190. runtime/dns_wire.py +200 -0
  191. runtime/doc_links.py +151 -0
  192. runtime/doctor.py +312 -0
  193. runtime/domain_intel.py +342 -0
  194. runtime/drip_engine.py +162 -0
  195. runtime/durable.py +443 -0
  196. runtime/enforcement.py +282 -0
  197. runtime/enums.py +67 -0
  198. runtime/evidence.py +97 -0
  199. runtime/experiment_tracker.py +184 -0
  200. runtime/fairness_detector.py +404 -0
  201. runtime/feature_flags.py +97 -0
  202. runtime/filament_access_auditor.py +232 -0
  203. runtime/find.py +150 -0
  204. runtime/funnel_tracker.py +128 -0
  205. runtime/gateway_proxy.py +335 -0
  206. runtime/governance.py +71 -0
  207. runtime/guardian.py +531 -0
  208. runtime/guardrails/__init__.py +11 -0
  209. runtime/guardrails/prompt_injection.py +143 -0
  210. runtime/hallucination_detector.py +398 -0
  211. runtime/harness_exporter.py +179 -0
  212. runtime/heal.py +316 -0
  213. runtime/hook_lifecycle.py +162 -0
  214. runtime/hooks.py +183 -0
  215. runtime/ingest_rules.py +106 -0
  216. runtime/injection_detector.py +794 -0
  217. runtime/inventory_note.py +165 -0
  218. runtime/kernel.py +1299 -0
  219. runtime/laravel_policy_linter.py +247 -0
  220. runtime/lead_scorer.py +86 -0
  221. runtime/lifecycle.py +158 -0
  222. runtime/llm_attestation.py +511 -0
  223. runtime/local_responder.py +133 -0
  224. runtime/loop_detector.py +394 -0
  225. runtime/managers/__init__.py +15 -0
  226. runtime/managers/agent_manager.py +106 -0
  227. runtime/managers/chat_manager.py +93 -0
  228. runtime/managers/policy_manager.py +353 -0
  229. runtime/managers/workflow_manager.py +136 -0
  230. runtime/marketing_compliance.py +74 -0
  231. runtime/mcp_auditor.py +701 -0
  232. runtime/mcp_client.py +743 -0
  233. runtime/mcp_firewall.py +381 -0
  234. runtime/mcp_freeze.py +114 -0
  235. runtime/mcp_manifest_lock.py +327 -0
  236. runtime/mcp_orchestrator.py +224 -0
  237. runtime/mcp_protocol.py +203 -0
  238. runtime/metrics.py +566 -0
  239. runtime/middleware.py +157 -0
  240. runtime/migrations.py +305 -0
  241. runtime/model_router.py +314 -0
  242. runtime/models_catalog.py +92 -0
  243. runtime/orchestrator.py +109 -0
  244. runtime/output_filter.py +87 -0
  245. runtime/overengineering.py +181 -0
  246. runtime/persona.py +524 -0
  247. runtime/personas.yaml +2130 -0
  248. runtime/pipeline_analytics.py +91 -0
  249. runtime/pipeline_catalog.py +263 -0
  250. runtime/plan_diff_validator.py +357 -0
  251. runtime/plugin.py +409 -0
  252. runtime/plugin_packager.py +158 -0
  253. runtime/plugin_transactions.py +151 -0
  254. runtime/policies/agentic-owasp.yaml +76 -0
  255. runtime/policies/consequence-tiers.yaml +92 -0
  256. runtime/policies/default.yaml +48 -0
  257. runtime/policies/examples/api-rate-limits.yaml +13 -0
  258. runtime/policies/examples/data-exfiltration.yaml +13 -0
  259. runtime/policies/examples/time-based-access.yaml +13 -0
  260. runtime/policies/guardian.yaml +101 -0
  261. runtime/policies/mcp_firewall.yaml +49 -0
  262. runtime/policies/probity.yaml +74 -0
  263. runtime/policy.py +558 -0
  264. runtime/policy_lint.py +255 -0
  265. runtime/post_queue.py +93 -0
  266. runtime/preloop.py +65 -0
  267. runtime/pricing_calculator.py +87 -0
  268. runtime/probity.py +211 -0
  269. runtime/project_config.py +111 -0
  270. runtime/prompt_gate.py +545 -0
  271. runtime/prompt_injection_detector.py +322 -0
  272. runtime/repository.py +113 -0
  273. runtime/rule_compiler.py +180 -0
  274. runtime/rule_frontmatter.py +180 -0
  275. runtime/rules_materializer.py +373 -0
  276. runtime/saga.py +213 -0
  277. runtime/schemas.py +299 -0
  278. runtime/secret_scrub.py +101 -0
  279. runtime/security_scanner.py +612 -0
  280. runtime/self_healing.py +116 -0
  281. runtime/sensitive.py +63 -0
  282. runtime/seo_issue_registry.py +349 -0
  283. runtime/service_catalog.py +476 -0
  284. runtime/settings.py +887 -0
  285. runtime/skill_lifecycle.py +352 -0
  286. runtime/skill_lint.py +344 -0
  287. runtime/skill_lock.py +213 -0
  288. runtime/skill_resolver.py +111 -0
  289. runtime/skill_scan.py +155 -0
  290. runtime/skill_validator.py +195 -0
  291. runtime/sovereign.py +80 -0
  292. runtime/spec/__init__.py +54 -0
  293. runtime/spec/analysis.py +280 -0
  294. runtime/spec/changes.py +179 -0
  295. runtime/spec/engine.py +660 -0
  296. runtime/spec/models.py +201 -0
  297. runtime/spec/review.py +298 -0
  298. runtime/spec/scaffold.py +131 -0
  299. runtime/spec/templates.py +80 -0
  300. runtime/spec_engine.py +61 -0
  301. runtime/stale_api_detector.py +256 -0
  302. runtime/storage_backend.py +561 -0
  303. runtime/supply_chain_guard.py +980 -0
  304. runtime/taint.py +390 -0
  305. runtime/task_contract/__init__.py +55 -0
  306. runtime/task_contract/classifier.py +102 -0
  307. runtime/task_contract/enforce.py +164 -0
  308. runtime/task_contract/engine.py +328 -0
  309. runtime/task_contract/evidence.py +145 -0
  310. runtime/task_contract/models.py +209 -0
  311. runtime/task_contract/validation.py +76 -0
  312. runtime/tech_stack.py +388 -0
  313. runtime/telemetry.py +162 -0
  314. runtime/tool_envelope.py +153 -0
  315. runtime/tool_output_sanitizer.py +171 -0
  316. runtime/tracing.py +212 -0
  317. runtime/tracing_otel.py +120 -0
  318. runtime/ui_a11y_checker.py +288 -0
  319. runtime/uninstaller.py +572 -0
  320. runtime/uninstaller_gui.py +498 -0
  321. runtime/verification.py +121 -0
  322. runtime/workflow.py +228 -0
runtime/_osroot.tar.gz ADDED
Binary file
runtime/abstracts.py ADDED
@@ -0,0 +1,159 @@
1
+ """Tiered context loading (OpenViking adoption).
2
+
3
+ Every context file gets three load levels so an agent checks relevance
4
+ before paying for full content:
5
+
6
+ - **L0 ``.abstract.md``** — generated one-paragraph summary (name +
7
+ description + triggers). ``find``/relevance checks read only this.
8
+ - **L1 overview** — frontmatter + first section, enough for planning.
9
+ - **L2 full** — the original file, read only when actually needed.
10
+
11
+ L0 files are generated artifacts: ``aizee abstract`` regenerates them;
12
+ they carry a ``<!-- generated -->`` marker and are never hand-edited.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import re
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+
21
+ import yaml
22
+
23
+ GENERATED_MARKER = "<!-- generated by aizee abstract — do not edit -->"
24
+ _L1_MAX_LINES = 50
25
+ _TIERED_DIRS = ("skills", "tech-stack", "workflows")
26
+ _ABSTRACT_MAX = 400
27
+ _SKIP_FILES = {"index.json", "README.md"}
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class AbstractResult:
32
+ """Outcome of one abstract generation."""
33
+
34
+ source: str
35
+ abstract_path: str
36
+ written: bool
37
+
38
+
39
+ def _frontmatter(text: str) -> dict[str, object]:
40
+ if not text.startswith("---"):
41
+ return {}
42
+ end = text.find("\n---", 3)
43
+ if end < 0:
44
+ return {}
45
+ data = yaml.safe_load(text[3:end])
46
+ return data if isinstance(data, dict) else {}
47
+
48
+
49
+ def _first_paragraph(body: str) -> str:
50
+ for block in re.split(r"\n\s*\n", body):
51
+ block = block.strip()
52
+ if block and not block.startswith(("#", "---", "<!--")):
53
+ return " ".join(block.split())
54
+ return ""
55
+
56
+
57
+ def generate_abstract(path: Path, text: str) -> str:
58
+ """Build the L0 abstract for one context file."""
59
+ meta = _frontmatter(text)
60
+ name = str(meta.get("name") or path.stem)
61
+ desc = str(meta.get("description") or "").strip()
62
+ triggers = meta.get("triggers")
63
+ if isinstance(triggers, str):
64
+ triggers = [triggers]
65
+ trigger_line = ""
66
+ if isinstance(triggers, list) and triggers:
67
+ shown = ", ".join(str(t) for t in triggers[:8])
68
+ trigger_line = f"\nUse when: {shown}"
69
+ if not desc:
70
+ body = text.split("---", 2)[-1] if text.startswith("---") else text
71
+ desc = _first_paragraph(body)
72
+ abstract = f"{GENERATED_MARKER}\n# {name}\n{desc}{trigger_line}\n"
73
+ if len(abstract) > _ABSTRACT_MAX:
74
+ abstract = abstract[: _ABSTRACT_MAX - 2].rstrip() + "…\n"
75
+ return abstract
76
+
77
+
78
+ def abstract_path_for(source: Path, root: Path) -> Path:
79
+ """Where the L0 file lives: a mirror tree under ``abstracts/``.
80
+
81
+ Sidecars intentionally live OUTSIDE skills/tech-stack/workflows —
82
+ every scanner that globs ``*.md`` there (catalog, ingest, lint) must
83
+ not see generated summaries as broken skills.
84
+ """
85
+ rel = source.relative_to(root)
86
+ return root / "abstracts" / rel
87
+
88
+
89
+ def write_abstract(source: Path, root: Path, force: bool = False) -> AbstractResult:
90
+ rel = str(source.relative_to(root)).replace("\\", "/")
91
+ target = abstract_path_for(source, root)
92
+ if target.exists() and not force:
93
+ return AbstractResult(source=rel, abstract_path=str(target.relative_to(root)), written=False)
94
+ target.parent.mkdir(parents=True, exist_ok=True)
95
+ target.write_text(
96
+ generate_abstract(source, source.read_text(encoding="utf-8")),
97
+ encoding="utf-8",
98
+ )
99
+ return AbstractResult(
100
+ source=rel,
101
+ abstract_path=str(target.relative_to(root)).replace("\\", "/"),
102
+ written=True,
103
+ )
104
+
105
+
106
+ def generate_all(
107
+ root: Path, dirs: tuple[str, ...] = _TIERED_DIRS, force: bool = False
108
+ ) -> dict[str, object]:
109
+ """(Re)generate L0 abstracts across the tiered directories."""
110
+ results: list[AbstractResult] = []
111
+ for dirname in dirs:
112
+ base = root / dirname
113
+ if not base.is_dir():
114
+ continue
115
+ for path in sorted(base.rglob("*.md")):
116
+ if path.name in _SKIP_FILES or "abstracts" in path.parts:
117
+ continue
118
+ results.append(write_abstract(path, root, force=force))
119
+ written = [r for r in results if r.written]
120
+ return {
121
+ "ok": True,
122
+ "scanned": len(results),
123
+ "written": len(written),
124
+ "files": [r.abstract_path for r in written],
125
+ }
126
+
127
+
128
+ def read_context(path: Path, level: str = "l1", root: Path | None = None) -> str:
129
+ """Read a context file at the requested tier.
130
+
131
+ ``l0`` → mirror abstract under ``abstracts/`` (falls back to overview
132
+ when missing); ``l1`` → frontmatter + first section (~50 lines);
133
+ ``l2`` → full text.
134
+ """
135
+ text = path.read_text(encoding="utf-8")
136
+ if level == "l2":
137
+ return text
138
+ if level == "l0":
139
+ base = root or path.parent
140
+ try:
141
+ abstract = abstract_path_for(path, base)
142
+ except ValueError:
143
+ abstract = Path("__nonexistent__")
144
+ if abstract.exists():
145
+ return abstract.read_text(encoding="utf-8")
146
+ return _overview(text, abstract_fallback=True)
147
+ return _overview(text)
148
+
149
+
150
+ def _overview(text: str, abstract_fallback: bool = False) -> str:
151
+ lines = text.splitlines()
152
+ if abstract_fallback:
153
+ return "\n".join(lines[:20])
154
+ # L1: frontmatter + content up to the second `## ` heading, capped.
155
+ cut = len(lines)
156
+ headings = [i for i, line in enumerate(lines) if line.startswith("## ")]
157
+ if len(headings) > 1:
158
+ cut = min(cut, headings[1])
159
+ return "\n".join(lines[: min(cut, _L1_MAX_LINES)])
@@ -0,0 +1,350 @@
1
+ #!/usr/bin/env python3
2
+ """Agent behavioral baseline - runtime detection of anomalous agent actions.
3
+
4
+ Prompt injection itself is invisible (it happens in model context), but
5
+ the **actions** it produces are observable. This module builds a behavioral
6
+ baseline for each agent - what tools it normally calls, what data it
7
+ accesses, what network endpoints it reaches - and flags deviations.
8
+
9
+ This is the "runtime detection" layer from the Sysdig 2026 guide:
10
+ injections produce actions, and actions touch the system.
11
+
12
+ Architecture::
13
+
14
+ agent_action -> AgentBaseline.observe(action)
15
+ -> updates baseline (learning phase)
16
+ OR checks against baseline (detection phase)
17
+ -> if anomalous: AnomalyAlert
18
+
19
+ Usage::
20
+
21
+ from runtime.agent_baseline import AgentBaseline, AnomalyAlert
22
+
23
+ baseline = AgentBaseline(agent_id="research-agent")
24
+
25
+ # Learning phase: observe normal actions
26
+ for action in normal_actions:
27
+ baseline.observe(action)
28
+
29
+ # Detection phase: flag anomalies
30
+ alert = baseline.check(action)
31
+ if alert.is_anomalous:
32
+ logger.warning("Agent anomaly: %s", alert.reason)
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import logging
38
+ from collections import Counter
39
+ from dataclasses import dataclass, field
40
+ from datetime import datetime, timezone
41
+ from enum import Enum
42
+ from typing import ClassVar
43
+
44
+ from runtime.schemas import AizeeError, ErrorSeverity
45
+
46
+ _logger = logging.getLogger(__name__)
47
+
48
+
49
+ class AnomalyType(str, Enum):
50
+ """Type of behavioral anomaly detected."""
51
+
52
+ NEW_TOOL = "new_tool" # agent called a tool it never used before
53
+ NEW_DATA_SOURCE = "new_data_source" # agent accessed a data source it never touched
54
+ NEW_ENDPOINT = "new_endpoint" # agent reached a network endpoint it never contacted
55
+ RARE_ACTION = "rare_action" # action type is very rare for this agent
56
+ VOLUME_SPIKE = "volume_spike" # sudden burst of actions
57
+ OFF_TASK = "off_task" # action doesn't match the agent's normal task patterns
58
+
59
+
60
+ class BaselinePhase(str, Enum):
61
+ """Whether the baseline is still learning or actively detecting."""
62
+
63
+ LEARNING = "learning"
64
+ DETECTING = "detecting"
65
+
66
+
67
+ @dataclass
68
+ class AgentAction:
69
+ """A single observed agent action for baseline tracking.
70
+
71
+ Attributes:
72
+ tool_name: The tool/function called.
73
+ action_type: Category (read, write, exec, network, etc.).
74
+ data_source: File path, DB table, or resource accessed.
75
+ endpoint: Network endpoint (URL/host) if applicable.
76
+ timestamp: When the action occurred.
77
+ task_context: What task the agent was performing.
78
+ """
79
+
80
+ tool_name: str
81
+ action_type: str = "unknown"
82
+ data_source: str | None = None
83
+ endpoint: str | None = None
84
+ timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
85
+ task_context: str | None = None
86
+
87
+
88
+ @dataclass(frozen=True)
89
+ class AnomalyAlert:
90
+ """An alert raised when an agent action deviates from its baseline.
91
+
92
+ Attributes:
93
+ anomaly_type: What kind of anomaly was detected.
94
+ agent_id: Which agent triggered the alert.
95
+ action: The anomalous action.
96
+ reason: Human-readable explanation.
97
+ severity: How serious the deviation is (0.0 to 1.0).
98
+ """
99
+
100
+ anomaly_type: AnomalyType
101
+ agent_id: str
102
+ action: AgentAction
103
+ reason: str
104
+ severity: float
105
+
106
+ @property
107
+ def is_anomalous(self) -> bool:
108
+ """Always True: existence of an alert implies anomaly.
109
+
110
+ Kept as a property (not a stored field) so callers can
111
+ uniformly test ``if alert and alert.is_anomalous`` without
112
+ None-checks; a None return from ``check()`` means "not anomalous".
113
+ """
114
+ return True # AnomalyAlert is always anomalous by definition
115
+
116
+ def to_dict(self) -> dict[str, object]:
117
+ return {
118
+ "anomaly_type": self.anomaly_type.value,
119
+ "agent_id": self.agent_id,
120
+ "reason": self.reason,
121
+ "severity": round(self.severity, 3),
122
+ "action": {
123
+ "tool_name": self.action.tool_name,
124
+ "action_type": self.action.action_type,
125
+ "data_source": self.action.data_source,
126
+ "endpoint": self.action.endpoint,
127
+ "task_context": self.action.task_context,
128
+ },
129
+ }
130
+
131
+
132
+ class AgentBaselineError(AizeeError):
133
+ """Raised when the baseline tracker encounters an error."""
134
+
135
+ def __init__(self, message: str, context: dict[str, object] | None = None) -> None:
136
+ super().__init__("BASELINE_ERROR", message, ErrorSeverity.MEDIUM, context)
137
+
138
+
139
+ # ---------------------------------------------------------------------------
140
+ # Baseline
141
+ # ---------------------------------------------------------------------------
142
+
143
+
144
+ class AgentBaseline:
145
+ """Behavioral baseline for a single agent.
146
+
147
+ Tracks the distribution of tools, data sources, endpoints, and action
148
+ types the agent normally uses. After a learning period, deviations
149
+ from this baseline are flagged as potential injection-induced anomalies.
150
+ """
151
+
152
+ LEARNING_THRESHOLD: ClassVar[int] = 20 # min observations before detecting
153
+ RARE_ACTION_THRESHOLD: ClassVar[float] = 0.05 # <5% frequency = rare
154
+ VOLUME_SPIKE_WINDOW: ClassVar[int] = 10 # actions in this window
155
+ VOLUME_SPIKE_MULTIPLIER: ClassVar[float] = 3.0 # 3x normal rate
156
+
157
+ def __init__(self, agent_id: str) -> None:
158
+ self.agent_id = agent_id
159
+ self._phase: BaselinePhase = BaselinePhase.LEARNING
160
+
161
+ # Frequency counters
162
+ self._tool_counts: Counter[str] = Counter()
163
+ self._action_type_counts: Counter[str] = Counter()
164
+ self._data_source_counts: Counter[str] = Counter()
165
+ self._endpoint_counts: Counter[str] = Counter()
166
+ self._task_context_counts: Counter[str] = Counter()
167
+
168
+ # Total observations
169
+ self._total_observations: int = 0
170
+
171
+ # Rolling window for volume-spike detection
172
+ self._recent_timestamps: list[datetime] = []
173
+
174
+ @property
175
+ def phase(self) -> BaselinePhase:
176
+ return self._phase
177
+
178
+ @property
179
+ def is_learning(self) -> bool:
180
+ return self._phase is BaselinePhase.LEARNING
181
+
182
+ @property
183
+ def total_observations(self) -> int:
184
+ return self._total_observations
185
+
186
+ def observe(self, action: AgentAction) -> None:
187
+ """Record an action in the baseline (learning phase)."""
188
+ self._tool_counts[action.tool_name] += 1
189
+ self._action_type_counts[action.action_type] += 1
190
+ if action.data_source:
191
+ self._data_source_counts[action.data_source] += 1
192
+ if action.endpoint:
193
+ self._endpoint_counts[action.endpoint] += 1
194
+ if action.task_context:
195
+ self._task_context_counts[action.task_context] += 1
196
+
197
+ self._total_observations += 1
198
+ self._recent_timestamps.append(action.timestamp)
199
+ # Keep only recent timestamps for volume calculation
200
+ cutoff_count = self.VOLUME_SPIKE_WINDOW * 3
201
+ if len(self._recent_timestamps) > cutoff_count:
202
+ self._recent_timestamps = self._recent_timestamps[-cutoff_count:]
203
+
204
+ # Transition to detecting phase after enough observations
205
+ if self._phase is BaselinePhase.LEARNING and self._total_observations >= self.LEARNING_THRESHOLD:
206
+ self._phase = BaselinePhase.DETECTING
207
+
208
+ def check(self, action: AgentAction) -> AnomalyAlert | None:
209
+ """Check an action against the baseline (detection phase).
210
+
211
+ Returns an :class:`AnomalyAlert` if the action is anomalous, or
212
+ None if it's within normal behavior. During the learning phase,
213
+ always returns None (still building the baseline).
214
+ """
215
+ if self._phase is BaselinePhase.LEARNING:
216
+ return None
217
+
218
+ # Check: new tool
219
+ if action.tool_name not in self._tool_counts:
220
+ return AnomalyAlert(
221
+ anomaly_type=AnomalyType.NEW_TOOL,
222
+ agent_id=self.agent_id,
223
+ action=action,
224
+ reason=f"tool '{action.tool_name}' never used before by {self.agent_id}",
225
+ severity=0.7,
226
+ )
227
+
228
+ # Check: new data source
229
+ if action.data_source and action.data_source not in self._data_source_counts:
230
+ return AnomalyAlert(
231
+ anomaly_type=AnomalyType.NEW_DATA_SOURCE,
232
+ agent_id=self.agent_id,
233
+ action=action,
234
+ reason=f"data source '{action.data_source}' never accessed before",
235
+ severity=0.6,
236
+ )
237
+
238
+ # Check: new network endpoint
239
+ if action.endpoint and action.endpoint not in self._endpoint_counts:
240
+ return AnomalyAlert(
241
+ anomaly_type=AnomalyType.NEW_ENDPOINT,
242
+ agent_id=self.agent_id,
243
+ action=action,
244
+ reason=f"endpoint '{action.endpoint}' never contacted before",
245
+ severity=0.8,
246
+ )
247
+
248
+ # Check: rare action type
249
+ total = sum(self._action_type_counts.values())
250
+ if total > 0:
251
+ freq = self._action_type_counts.get(action.action_type, 0) / total
252
+ if freq < self.RARE_ACTION_THRESHOLD:
253
+ return AnomalyAlert(
254
+ anomaly_type=AnomalyType.RARE_ACTION,
255
+ agent_id=self.agent_id,
256
+ action=action,
257
+ reason=f"action type '{action.action_type}' is rare ({freq:.1%} of actions)",
258
+ severity=0.5,
259
+ )
260
+
261
+ # Check: volume spike (recent rate vs baseline mean rate)
262
+ spike = self._check_volume_spike(action)
263
+ if spike is not None:
264
+ return spike
265
+
266
+ return None
267
+
268
+ def _check_volume_spike(self, action: AgentAction) -> AnomalyAlert | None:
269
+ """Compare recent action rate vs baseline mean rate.
270
+
271
+ Recent rate = VOLUME_SPIKE_WINDOW actions over their time span;
272
+ baseline mean = all retained observations over their time span.
273
+ Flags VOLUME_SPIKE when recent rate exceeds mean by
274
+ VOLUME_SPIKE_MULTIPLIER. Returns None on insufficient data or
275
+ zero-duration windows (clock granularity).
276
+ """
277
+ window = self.VOLUME_SPIKE_WINDOW
278
+ recent = self._recent_timestamps
279
+ if len(recent) < window:
280
+ return None
281
+ try:
282
+ recent_span = (recent[-1] - recent[-window]).total_seconds()
283
+ total_span = (recent[-1] - recent[0]).total_seconds()
284
+ except (IndexError, TypeError):
285
+ return None
286
+ if recent_span <= 0 or total_span <= 0:
287
+ return None
288
+ recent_rate = window / recent_span
289
+ mean_rate = len(recent) / total_span
290
+ if mean_rate <= 0: # pragma: no cover - total_span > 0 implies mean_rate > 0
291
+ return None
292
+ if recent_rate > mean_rate * self.VOLUME_SPIKE_MULTIPLIER:
293
+ return AnomalyAlert(
294
+ anomaly_type=AnomalyType.VOLUME_SPIKE,
295
+ agent_id=self.agent_id,
296
+ action=action,
297
+ reason=(
298
+ f"volume spike: recent rate {recent_rate:.2f}/s > "
299
+ f"{self.VOLUME_SPIKE_MULTIPLIER}x baseline {mean_rate:.2f}/s"
300
+ ),
301
+ severity=0.6,
302
+ )
303
+ return None
304
+
305
+ def stats(self) -> dict[str, object]:
306
+ """Return baseline statistics for monitoring."""
307
+ return {
308
+ "agent_id": self.agent_id,
309
+ "phase": self._phase.value,
310
+ "total_observations": self._total_observations,
311
+ "unique_tools": len(self._tool_counts),
312
+ "unique_data_sources": len(self._data_source_counts),
313
+ "unique_endpoints": len(self._endpoint_counts),
314
+ "top_tools": self._tool_counts.most_common(5),
315
+ "top_action_types": self._action_type_counts.most_common(5),
316
+ }
317
+
318
+
319
+ # ---------------------------------------------------------------------------
320
+ # Registry (multi-agent)
321
+ # ---------------------------------------------------------------------------
322
+
323
+
324
+ class BaselineRegistry:
325
+ """Manages baselines for multiple agents."""
326
+
327
+ def __init__(self) -> None:
328
+ self._baselines: dict[str, AgentBaseline] = {}
329
+
330
+ def get_or_create(self, agent_id: str) -> AgentBaseline:
331
+ """Get an existing baseline or create a new one."""
332
+ if agent_id not in self._baselines:
333
+ self._baselines[agent_id] = AgentBaseline(agent_id)
334
+ return self._baselines[agent_id]
335
+
336
+ def observe(self, agent_id: str, action: AgentAction) -> None:
337
+ """Record an action for an agent."""
338
+ self.get_or_create(agent_id).observe(action)
339
+
340
+ def check(self, agent_id: str, action: AgentAction) -> AnomalyAlert | None:
341
+ """Check an action against an agent's baseline."""
342
+ if agent_id not in self._baselines:
343
+ _logger.info("unknown agent %s: treating as LEARNING (creating baseline)", agent_id)
344
+ self._baselines[agent_id] = AgentBaseline(agent_id)
345
+ return None
346
+ return self._baselines[agent_id].check(action)
347
+
348
+ def all_stats(self) -> dict[str, dict[str, object]]:
349
+ """Return stats for all tracked agents."""
350
+ return {aid: bl.stats() for aid, bl in self._baselines.items()}