You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@carbondata.apache.org by ch...@apache.org on 2026/04/21 12:36:05 UTC
(carbondata) branch master updated: refactor Agent_module, fix not working issues
This is an automated email from the ASF dual-hosted git repository.
chenliang613 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/carbondata.git
The following commit(s) were added to refs/heads/master by this push:
new 020445b6e8 refactor Agent_module, fix not working issues
new 2496b87532 Merge branch 'master' of https://github.com/apache/carbondata
020445b6e8 is described below
commit 020445b6e8c22422ecdf64db97f3d8386ccbc2ae
Author: chenliang613 <ch...@apache.org>
AuthorDate: Tue Apr 21 20:34:56 2026 +0800
refactor Agent_module, fix not working issues
---
Agent_module/Agent_Demo.py | 206 ----------
Agent_module/Chat_Agent.py | 97 -----
Agent_module/ContextBridge.py | 152 --------
Agent_module/ContextStore_Demo.py | 274 --------------
Agent_module/Example/02_framework_agents.py | 249 -------------
Agent_module/Example/03_agent_manager.py | 271 --------------
Agent_module/Example/04_context_store.py | 389 -------------------
Agent_module/Example/_loader.py | 49 ---
Agent_module/Example/run_all.py | 52 ---
Agent_module/Framework.py | 78 ----
Agent_module/Implementation.py | 119 ------
Agent_module/Manager.py | 103 -----
Agent_module/QUICKSTART.md | 414 ---------------------
Agent_module/README.md | 328 +++++-----------
Agent_module/SharedContext.py | 216 -----------
Agent_module/SharedContext_Demo.py | 217 -----------
Agent_module/__init__.py | 48 +++
Agent_module/agents.py | 205 ++++++++++
Agent_module/{ContextStore.py => context_store.py} | 270 ++++----------
Agent_module/demos/__init__.py | 0
Agent_module/demos/agent_demo.py | 91 +++++
Agent_module/demos/context_store_demo.py | 184 +++++++++
.../{Example => examples}/01_data_models.py | 0
Agent_module/examples/02_framework_agents.py | 232 ++++++++++++
Agent_module/examples/03_agent_manager.py | 236 ++++++++++++
Agent_module/examples/04_context_store.py | 334 +++++++++++++++++
Agent_module/examples/__init__.py | 0
.../agent_format_example.py} | 0
Agent_module/examples/run_all.py | 64 ++++
Agent_module/framework.py | 90 +++++
Agent_module/manager.py | 114 ++++++
Agent_module/safe_eval.py | 68 ++++
Agent_module/tests/__init__.py | 0
Agent_module/tests/conftest.py | 10 +
Agent_module/tests/test_async_callbacks.py | 86 +++++
Agent_module/tests/test_safe_eval.py | 94 +++++
36 files changed, 2038 insertions(+), 3302 deletions(-)
diff --git a/Agent_module/Agent_Demo.py b/Agent_module/Agent_Demo.py
deleted file mode 100644
index b401860845..0000000000
--- a/Agent_module/Agent_Demo.py
+++ /dev/null
@@ -1,206 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-async def demo_single_agents():
- """Demo individual agents"""
- print("=== Single Agent Demo ===\n")
-
- # Create agents
- echo_agent = EchoAgent()
- calculator_agent = CalculatorAgent()
- weather_agent = WeatherAgent()
- translator_agent = TranslatorAgent()
- chat_agent = ChatAgent()
-
- # Test echo agent
- print("1. Testing Echo Agent:")
- response = await echo_agent.process(AgentMessage(
- content="Hello, world!",
- sender="User",
- timestamp=time.time()
- ))
- print(f"Input: Hello, world!")
- print(f"Output: {response.content}\n")
-
- # Test calculator agent
- print("2. Testing Calculator Agent:")
- response = await calculator_agent.process(AgentMessage(
- content="(15 + 25) * 2",
- sender="User",
- timestamp=time.time()
- ))
- print(f"Input: (15 + 25) * 2")
- print(f"Output: {response.content}\n")
-
- # Test weather agent
- print("3. Testing Weather Agent:")
- response = await weather_agent.process(AgentMessage(
- content="Tokyo",
- sender="User",
- timestamp=time.time()
- ))
- print(f"Input: Tokyo")
- print(f"Output: {response.content}\n")
-
- # Test translator agent
- print("4. Testing Translator Agent:")
- response = await translator_agent.process(AgentMessage(
- content="Hello, how are you?",
- sender="User",
- timestamp=time.time(),
- metadata={"target_language": "french"}
- ))
- print(f"Input: Hello, how are you? (to French)")
- print(f"Output: {response.content}\n")
-
- # Test chat agent
- print("5. Testing Chat Agent:")
- response = await chat_agent.process(AgentMessage(
- content="Hello! What can you do?",
- sender="User",
- timestamp=time.time()
- ))
- print(f"Input: Hello! What can you do?")
- print(f"Output: {response.content}\n")
-
-async def demo_agent_system():
- """Demo the complete agent system"""
- print("\n=== Agent System Demo ===\n")
-
- # Create agent manager and register agents
- manager = AgentManager()
-
- manager.register_agent(EchoAgent())
- manager.register_agent(CalculatorAgent())
- manager.register_agent(WeatherAgent())
- manager.register_agent(TranslatorAgent())
- manager.register_agent(ChatAgent())
-
- print(f"Registered {len(manager.agents)} agents:")
- for agent_name in manager.agents.keys():
- print(f" - {agent_name}")
-
- # Test individual agent communication
- print("\n1. Testing Calculator Agent through Manager:")
- response = await manager.send_message("CalculatorAgent", "45 + 17 * 3")
- print(f"Response: {response.content}")
-
- print("\n2. Testing Weather Agent through Manager:")
- response = await manager.send_message("WeatherAgent", "London")
- print(f"Response: {response.content}")
-
- print("\n3. Testing Broadcast Message:")
- responses = await manager.broadcast_message("Hello everyone!")
- print("Broadcast responses:")
- for agent_name, response in responses.items():
- print(f" {agent_name}: {response.content[:50]}...")
-
- # Demonstrate agent discovery
- print("\n4. Agent Discovery:")
- math_agents = manager.find_agent_by_capability("calculation")
- print(f"Agents for calculations: {math_agents}")
-
- weather_agents = manager.find_agent_by_capability("weather")
- print(f"Agents for weather: {weather_agents}")
-
- # Show system statistics
- print("\n5. System Statistics:")
- stats = manager.get_system_stats()
- for key, value in stats.items():
- print(f" {key}: {value}")
-
-async def interactive_demo():
- """Interactive demo where users can talk to agents"""
- print("\n=== Interactive Demo ===\n")
-
- manager = AgentManager()
- manager.register_agent(ChatAgent())
- manager.register_agent(CalculatorAgent())
- manager.register_agent(WeatherAgent())
- manager.register_agent(TranslatorAgent())
-
- print("Available agents: ChatAgent, CalculatorAgent, WeatherAgent, TranslatorAgent")
- print("Type 'quit' to exit, 'help' for commands, 'agents' to list agents\n")
-
- while True:
- try:
- user_input = input("You: ").strip()
-
- if user_input.lower() in ['quit', 'exit']:
- break
- elif user_input.lower() == 'help':
- print("\nAvailable commands:")
- print(" 'calc [expression]' - Use calculator")
- print(" 'weather [city]' - Get weather")
- print(" 'translate [text] to [language]' - Translate text")
- print(" 'agents' - List all agents")
- print(" 'stats' - Show system statistics")
- print(" 'quit' - Exit\n")
- continue
- elif user_input.lower() == 'agents':
- print("\nRegistered agents:")
- for name, agent in manager.agents.items():
- print(f" {name}: {agent.description}")
- print()
- continue
- elif user_input.lower() == 'stats':
- stats = manager.get_system_stats()
- print("\nSystem Statistics:")
- for key, value in stats.items():
- print(f" {key}: {value}")
- print()
- continue
-
- # Route to appropriate agent based on input
- if user_input.startswith('calc '):
- expression = user_input[5:]
- response = await manager.send_message("CalculatorAgent", expression)
- print(f"Calculator: {response.content}\n")
-
- elif user_input.startswith('weather '):
- city = user_input[8:]
- response = await manager.send_message("WeatherAgent", city)
- print(f"Weather: {response.content}\n")
-
- elif user_input.startswith('translate '):
- # Simple parsing for translation commands
- parts = user_input[10:].split(' to ')
- if len(parts) == 2:
- text, language = parts
- response = await manager.send_message(
- "TranslatorAgent",
- text,
- {"target_language": language.strip()}
- )
- print(f"Translator: {response.content}\n")
- else:
- print("Usage: translate [text] to [language]\n")
-
- else:
- # Default to chat agent
- response = await manager.send_message("ChatAgent", user_input)
- print(f"ChatAgent: {response.content}\n")
-
- except KeyboardInterrupt:
- break
- except Exception as e:
- print(f"Error: {e}\n")
-
-if __name__ == "__main__":
- # Run demos
- asyncio.run(demo_single_agents())
- asyncio.run(demo_agent_system())
diff --git a/Agent_module/Chat_Agent.py b/Agent_module/Chat_Agent.py
deleted file mode 100644
index 2a4a45ccdf..0000000000
--- a/Agent_module/Chat_Agent.py
+++ /dev/null
@@ -1,97 +0,0 @@
-class ChatAgent(BaseAgent):
- """Intelligent chat agent with context awareness"""
-
- def __init__(self, name: str = "ChatAgent"):
- super().__init__(name, "Intelligent conversational agent")
- self.context = {}
- self.personality_traits = [
- "friendly", "helpful", "knowledgeable", "enthusiastic"
- ]
-
- async def _process_impl(self, message: AgentMessage) -> AgentMessage:
- user_input = str(message.content).lower()
- user_id = message.metadata.get("user_id", "unknown")
-
- # Update context
- if user_id not in self.context:
- self.context[user_id] = {
- "conversation_count": 0,
- "last_interaction": time.time(),
- "topics": set()
- }
-
- self.context[user_id]["conversation_count"] += 1
- self.context[user_id]["last_interaction"] = time.time()
-
- # Simple intent recognition
- response = await self._generate_response(user_input, user_id)
-
- return AgentMessage(
- content=response,
- sender=self.name,
- timestamp=time.time(),
- message_type="chat_response",
- metadata={"user_context": self.context[user_id]}
- )
-
- async def _generate_response(self, user_input: str, user_id: str) -> str:
- """Generate context-aware responses"""
-
- # Greeting detection
- if any(word in user_input for word in ["hello", "hi", "hey", "greetings"]):
- return random.choice([
- "Hello! How can I assist you today?",
- "Hi there! What can I help you with?",
- "Greetings! I'm here to help.",
- "Hello! Nice to meet you."
- ])
-
- # Question detection
- elif "?" in user_input or any(word in user_input for word in ["what", "how", "when", "where", "why"]):
- return await self._answer_question(user_input)
-
- # Weather inquiry
- elif "weather" in user_input:
- return "I can help with weather information! Please use the WeatherAgent for accurate weather data."
-
- # Calculation request
- elif any(word in user_input for word in ["calculate", "math", "equation"]):
- return "I can help with calculations! Try using the CalculatorAgent for mathematical operations."
-
- # Translation request
- elif any(word in user_input for word in ["translate", "translation"]):
- return "I can assist with translations! The TranslatorAgent specializes in language translation."
-
- # Default response
- else:
- return random.choice([
- "That's interesting! Can you tell me more?",
- "I understand. How can I help you with that?",
- "Thanks for sharing! Is there anything specific you'd like to know?",
- "I see. What would you like to do next?"
- ])
-
- async def _answer_question(self, question: str) -> str:
- """Answer general knowledge questions"""
- question_lower = question.lower()
-
- if "time" in question_lower:
- return f"The current time is {time.strftime('%H:%M:%S')}"
-
- elif "date" in question_lower:
- return f"Today's date is {time.strftime('%Y-%m-%d')}"
-
- elif "name" in question_lower:
- return "I'm ChatAgent, your friendly AI assistant!"
-
- elif "purpose" in question_lower or "what can you do" in question_lower:
- return "I can chat with you, answer questions, and coordinate with other specialized agents for weather, calculations, translations, and more!"
-
- else:
- responses = [
- "That's a good question! Let me think about it...",
- "I'm not entirely sure about that, but I'd be happy to help you find out!",
- "Interesting question! Here's what I know about that topic...",
- "I understand your curiosity about that subject."
- ]
- return random.choice(responses)
\ No newline at end of file
diff --git a/Agent_module/ContextBridge.py b/Agent_module/ContextBridge.py
deleted file mode 100644
index 9cb595a427..0000000000
--- a/Agent_module/ContextBridge.py
+++ /dev/null
@@ -1,152 +0,0 @@
-from dataclasses import dataclass, field
-from typing import Any, Callable, Dict, List, Optional
-from datetime import datetime
-
-# Load SharedContext from the same directory.
-# .python extension requires importlib to load by file path.
-import sys, os, importlib.util as _ilu
-
-def _load(name: str):
- from importlib.machinery import SourceFileLoader
- here = os.path.dirname(os.path.abspath(__file__))
- path = os.path.join(here, f"{name}.python")
- loader = SourceFileLoader(name, path)
- spec = _ilu.spec_from_loader(name, loader)
- mod = _ilu.module_from_spec(spec)
- sys.modules[name] = mod
- loader.exec_module(mod)
- return mod
-
-_sc = _load("SharedContext")
-SharedContext = _sc.SharedContext
-ContextEntry = _sc.ContextEntry
-
-# ============================================================================
-# Pub/Sub Bridge
-# ============================================================================
-
-@dataclass
-class ContextSubscription:
- """Subscription record: which agent watches which keys."""
- agent_id: str
- keys: List[str] # empty list = subscribe to ALL keys
- callback: Callable # called as callback(key, entry) on change
-
-
-class ContextBridge:
- """
- Connects agents to a SharedContext and fires callbacks on writes.
-
- Usage pattern:
- bridge = ContextBridge(context)
- bridge.register_agent("monitor", on_change) # subscribe to all
- bridge.write("coordinator", "task", {"id": 1})
- """
-
- def __init__(self, context: SharedContext):
- self._context = context
- self._subscriptions: Dict[str, ContextSubscription] = {}
- self._access_log: List[Dict[str, Any]] = []
-
- # ------------------------------------------------------------------
- # Agent registration
- # ------------------------------------------------------------------
-
- def register_agent(
- self,
- agent_id: str,
- callback: Callable,
- keys: Optional[List[str]] = None,
- ) -> None:
- """Subscribe *agent_id* to context changes on *keys* (all if empty)."""
- self._subscriptions[agent_id] = ContextSubscription(
- agent_id=agent_id,
- keys=keys or [],
- callback=callback,
- )
-
- def unregister_agent(self, agent_id: str) -> None:
- """Remove the subscription for *agent_id*."""
- self._subscriptions.pop(agent_id, None)
-
- # ------------------------------------------------------------------
- # Writes
- # ------------------------------------------------------------------
-
- def write(
- self,
- agent_id: str,
- key: str,
- value: Any,
- ttl: Optional[int] = None,
- tags: Optional[List[str]] = None,
- ) -> ContextEntry:
- """Write *key* → *value* on behalf of *agent_id*, then notify."""
- entry = self._context.set(key, value, agent_id, ttl=ttl, tags=tags)
- self._notify(key, entry)
- return entry
-
- def broadcast(
- self,
- agent_id: str,
- data: Dict[str, Any],
- ttl: Optional[int] = None,
- tags: Optional[List[str]] = None,
- ) -> List[ContextEntry]:
- """Write multiple keys atomically (no interleaved notifications)."""
- written: List[ContextEntry] = []
- for key, value in data.items():
- entry = self._context.set(key, value, agent_id, ttl=ttl, tags=tags)
- written.append(entry)
- # Notify after all entries are committed
- for entry in written:
- self._notify(entry.key, entry)
- return written
-
- # ------------------------------------------------------------------
- # Reads
- # ------------------------------------------------------------------
-
- def read(self, agent_id: str, key: str) -> Optional[Any]:
- """Read *key* on behalf of *agent_id*; access is logged."""
- value = self._context.get(key)
- self._log_access(agent_id, "read", key)
- return value
-
- def read_all(self, agent_id: str) -> Dict[str, Any]:
- """Return a snapshot of all non-expired entries visible to *agent_id*."""
- self._log_access(agent_id, "read_all", "*")
- return self._context.snapshot()
-
- # ------------------------------------------------------------------
- # Internal helpers
- # ------------------------------------------------------------------
-
- def _notify(self, changed_key: str, entry: ContextEntry) -> None:
- """Fire callbacks for every subscriber that watches *changed_key*."""
- for sub in self._subscriptions.values():
- # Skip the writer itself (no self-notification)
- if sub.agent_id == entry.agent_id:
- continue
- if sub.keys and changed_key not in sub.keys:
- continue
- try:
- sub.callback(changed_key, entry)
- except Exception:
- pass # Don't let a bad callback break the bridge
-
- def _log_access(self, agent_id: str, operation: str, key: str) -> None:
- self._access_log.append({
- "agent_id": agent_id,
- "operation": operation,
- "key": key,
- "timestamp": datetime.now().isoformat(),
- })
-
- # ------------------------------------------------------------------
- # Diagnostics
- # ------------------------------------------------------------------
-
- def access_log(self) -> List[Dict[str, Any]]:
- """Return a copy of the access log."""
- return list(self._access_log)
diff --git a/Agent_module/ContextStore_Demo.py b/Agent_module/ContextStore_Demo.py
deleted file mode 100644
index 5552f839da..0000000000
--- a/Agent_module/ContextStore_Demo.py
+++ /dev/null
@@ -1,274 +0,0 @@
-"""
-ContextStore_Demo.py
-====================
-End-to-end demonstration of the ContextStore multi-agent data exchange system.
-
-Scenarios covered
------------------
- 1. coordinator writes task → worker reads and processes → monitor observes
- changes via pub/sub async callback
- 2. history() returns all write versions (newest-first)
- 3. Directed channel: coordinator → worker messages; inbox() aggregates all
- 4. TTL entry written, expires after 3 seconds, get() returns None
- 5. query(writer="worker") returns only entries written by worker
- 6. merge() correctly resolves version conflicts (higher version wins)
- 7. to_json() fully serialises the entire store
-
-Run:
- python3 Agent_module/ContextStore_Demo.py
-"""
-
-import asyncio
-import json
-import sys
-import os
-
-# ---------------------------------------------------------------------------
-# Load ContextStore from the same directory (supports .py extension)
-# ---------------------------------------------------------------------------
-sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
-from ContextStore import (
- ContextStore,
- ContextNamespace,
- ContextRecord,
-)
-
-
-# ============================================================================
-# Helpers
-# ============================================================================
-
-
-def section(title: str) -> None:
- print("\n" + "=" * 70)
- print(f" {title}")
- print("=" * 70)
-
-
-# ============================================================================
-# Shared observation log for the async monitor callback
-# ============================================================================
-
-_change_log: list = []
-
-
-async def monitor_callback(key: str, record: ContextRecord) -> None:
- """Async pub/sub callback — called after every put() that monitor watches."""
- msg = (
- f" [MONITOR] key={key!r:20s} "
- f"writer={record.writer:15s} "
- f"v{record.version} "
- f"value={str(record.value)!r:.55s}"
- )
- print(msg)
- _change_log.append(
- {"key": key, "writer": record.writer, "value": record.value}
- )
-
-
-# ============================================================================
-# Main demo
-# ============================================================================
-
-
-async def main() -> None:
-
- store = ContextStore()
- ns = ContextNamespace(store, "data_pipeline_v1")
-
- # -----------------------------------------------------------------------
- # 1. Setup — Subscribe monitor, then coordinator assigns task
- # -----------------------------------------------------------------------
- section("1. Setup + coordinator assigns task [pub/sub demo]")
-
- # Monitor subscribes to ALL keys in the namespace (async callback)
- ns.subscribe("monitor", monitor_callback)
-
- # Coordinator writes task and initial status
- await ns.put("task", {"id": "task_001", "description": "Analyse Q1 sales", "priority": "high"}, writer="coordinator")
- await ns.put("status", "pending", writer="coordinator")
- await ns.put("deadline", "2026-02-18T18:00:00", writer="coordinator", tags=["meta"])
-
- # Worker reads task, updates status, writes result
- task = await ns.get("task")
- print(f"\n Worker received task: {task}")
-
- await ns.put("status", "in_progress", writer="worker")
- print(" Worker processing …")
- await asyncio.sleep(0.05)
-
- await ns.put(
- "result",
- {"task_id": task["id"], "summary": "Q1 revenue +12% YoY; top SKU: widget-X", "rows_processed": 14_320},
- writer="worker",
- tags=["output"],
- )
- await ns.put("status", "completed", writer="worker")
-
- print(f"\n Final status: {await ns.get('status')!r}")
- print(f" Result: {await ns.get('result')}")
-
- # -----------------------------------------------------------------------
- # 2. history() — newest-first
- # -----------------------------------------------------------------------
- section("2. history('status') — all write versions, newest-first")
-
- records = await ns.history("status")
- for r in records:
- print(f" v{r.version} writer={r.writer:15s} value={r.value!r} ts={r.timestamp}")
-
- assert records[0].value == "completed", "Newest record should be 'completed'"
- assert records[-1].value == "pending", "Oldest record should be 'pending'"
- print(f"\n Total writes to 'status': {len(records)} ✓")
-
- # -----------------------------------------------------------------------
- # 3. Directed channels + inbox()
- # -----------------------------------------------------------------------
- section("3. Directed channels: coordinator → worker, inbox() aggregation")
-
- await store.send("coordinator", "worker", {"cmd": "run_report", "format": "pdf"}, tags=["cmd"])
- await store.send("coordinator", "worker", {"cmd": "upload_results", "dest": "s3://bucket/q1"}, tags=["cmd"])
- await store.send("monitor", "worker", {"cmd": "health_check"}, tags=["admin"])
-
- ch_len = len(store.channel("coordinator", "worker"))
- print(f" coordinator→worker queue depth: {ch_len}")
-
- # peek without consuming
- peeked = await store.channel("coordinator", "worker").peek()
- print(f" Peeked first message: {peeked.payload}")
-
- # inbox() collects from ALL senders and sorts by time
- inbox_msgs = await store.inbox("worker")
- print(f"\n inbox('worker') received {len(inbox_msgs)} message(s):")
- for m in inbox_msgs:
- print(f" from={m.sender:15s} payload={m.payload}")
-
- assert len(inbox_msgs) == 3, "Worker should have 3 messages in inbox"
- print(" inbox() aggregation ✓")
-
- # -----------------------------------------------------------------------
- # 4. TTL — entry expires after 3 seconds
- # -----------------------------------------------------------------------
- section("4. TTL — heartbeat entry expires after 3 seconds")
-
- await ns.put(
- "heartbeat",
- {"alive": True, "load": 0.42},
- writer="worker",
- ttl=3,
- tags=["health"],
- )
- immediate = await ns.get("heartbeat")
- print(f" Immediate read → {immediate}")
- assert immediate is not None, "Heartbeat should be readable immediately"
-
- print(" Sleeping 3.5 s for TTL expiry …")
- await asyncio.sleep(3.5)
-
- expired_val = await ns.get("heartbeat")
- print(f" After 3.5 s read → {expired_val} (None = expired correctly)")
- assert expired_val is None, "Heartbeat should have expired"
-
- removed = await ns.cleanup_expired()
- print(f" cleanup_expired() removed {removed} additional stale key(s) ✓")
-
- # -----------------------------------------------------------------------
- # 5. query(writer="worker") — filter by writer
- # -----------------------------------------------------------------------
- section("5. query(writer='worker') — only worker-written entries")
-
- worker_entries = await ns.query(writer="worker")
- print(f" Entries written by worker ({len(worker_entries)}):")
- for e in worker_entries:
- print(f" key={e.current.key!r:15s} v{e.current.version} tags={list(e.current.tags)}")
-
- for e in worker_entries:
- assert e.current.writer == "worker", f"Expected writer='worker', got {e.current.writer!r}"
- print(" All returned entries are from worker ✓")
-
- # Also verify coordinator entries are NOT in the result
- coordinator_entries = await ns.query(writer="coordinator")
- print(f"\n Entries written by coordinator ({len(coordinator_entries)}):")
- for e in coordinator_entries:
- print(f" key={e.current.key!r:15s} v{e.current.version}")
-
- # -----------------------------------------------------------------------
- # 6. merge() — version conflict resolution
- # -----------------------------------------------------------------------
- section("6. merge() — last-write-wins by version number")
-
- remote_store = ContextStore()
-
- # Remote has a HIGHER version of "status" → should win
- # We manually set version by writing multiple times
- await remote_store.put("status", "archived", writer="archiver", namespace="data_pipeline_v1")
- await remote_store.put("status", "archived_v2", writer="archiver", namespace="data_pipeline_v1")
- await remote_store.put("archived_at", "2026-02-18T19:00:00", writer="archiver", namespace="data_pipeline_v1")
-
- remote_status_v = (await remote_store.get_entry("status", "data_pipeline_v1")).current.version
- local_status_v = (await store.get_entry("status", "data_pipeline_v1")).current.version
- print(f" Before merge: local status v{local_status_v}, remote status v{remote_status_v}")
-
- merged_count = await store.merge(remote_store, "data_pipeline_v1")
- print(f" merge() accepted {merged_count} entry/entries from remote")
-
- merged_status = await store.get("status", "data_pipeline_v1")
- print(f" status after merge → {merged_status!r}")
-
- if remote_status_v > local_status_v:
- assert merged_status == "archived_v2", "Higher-version remote value should have won"
- print(" Higher remote version won ✓")
- else:
- print(" Local version was already higher; remote was ignored ✓")
-
- # -----------------------------------------------------------------------
- # 7. to_json() — full serialisation
- # -----------------------------------------------------------------------
- section("7. to_json() — full store serialisation")
-
- json_str = await store.to_json()
- parsed = json.loads(json_str)
-
- print(f" Serialised namespaces: {list(parsed['entries'].keys())}")
- print(f" Channels captured: {list(parsed['channels'].keys())}")
- print(f" Subscriptions: {list(parsed['subscriptions'].keys())}")
-
- # Verify roundtrip: all namespace keys appear in JSON
- local_keys = set(await ns.keys())
- json_keys = set(parsed["entries"].get("data_pipeline_v1", {}).keys())
- assert local_keys == json_keys, f"JSON keys mismatch: {local_keys} vs {json_keys}"
- print(" Key set roundtrip matches ✓")
-
- # Print a condensed preview
- condensed = {
- "entries_count": {
- ns_name: len(keys)
- for ns_name, keys in parsed["entries"].items()
- },
- "channels": parsed["channels"],
- }
- print("\n Condensed summary:")
- print(json.dumps(condensed, indent=4, ensure_ascii=False))
-
- # -----------------------------------------------------------------------
- # 8. Final stats
- # -----------------------------------------------------------------------
- section("8. Store stats")
-
- stats = await store.stats()
- print(json.dumps(stats, indent=2, ensure_ascii=False))
-
- # -----------------------------------------------------------------------
- # 9. Monitor change log summary
- # -----------------------------------------------------------------------
- section("9. Monitor pub/sub change log summary")
-
- print(f" Total changes observed by monitor: {len(_change_log)}")
- for i, entry in enumerate(_change_log, 1):
- print(f" {i:2d}. [{entry['writer']:15s}] {entry['key']!r}")
-
- section("Demo complete — all scenarios passed ✓")
-
-
-if __name__ == "__main__":
- asyncio.run(main())
diff --git a/Agent_module/Example/02_framework_agents.py b/Agent_module/Example/02_framework_agents.py
deleted file mode 100644
index a2deb930b4..0000000000
--- a/Agent_module/Example/02_framework_agents.py
+++ /dev/null
@@ -1,249 +0,0 @@
-"""
-02_framework_agents.py
-======================
-Tests BaseAgent subclassing, AgentStatus lifecycle, message history,
-callbacks, and error handling from Framework.py and Implementation.py.
-
-Run:
- python3 Agent_module/Example/02_framework_agents.py
-"""
-
-import asyncio
-import sys
-import os
-import time
-
-sys.path.insert(0, os.path.dirname(__file__))
-
-from _loader import load
-
-_m = load("Framework", "Implementation")
-BaseAgent = _m.BaseAgent
-AgentMessage = _m.AgentMessage
-AgentStatus = _m.AgentStatus
-EchoAgent = _m.EchoAgent
-CalculatorAgent = _m.CalculatorAgent
-WeatherAgent = _m.WeatherAgent
-TranslatorAgent = _m.TranslatorAgent
-
-# ============================================================================
-# Test helpers
-# ============================================================================
-
-_passed = 0
-_failed = 0
-
-
-def check(label: str, condition: bool) -> None:
- global _passed, _failed
- if condition:
- _passed += 1
- print(f" PASS {label}")
- else:
- _failed += 1
- print(f" FAIL {label}")
-
-
-def section(title: str) -> None:
- print(f"\n{'=' * 60}")
- print(f" {title}")
- print(f"{'=' * 60}")
-
-
-def msg(content: str, **meta) -> AgentMessage:
- return AgentMessage(content=content, sender="tester", timestamp=time.time(), metadata=meta)
-
-
-# ============================================================================
-# Custom agent used in tests
-# ============================================================================
-
-class UpperCaseAgent(BaseAgent):
- """Returns the message content uppercased."""
-
- def __init__(self):
- super().__init__(name="UpperCaseAgent", description="Converts text to uppercase")
-
- async def _process_impl(self, message: AgentMessage) -> AgentMessage:
- return AgentMessage(
- content=str(message.content).upper(),
- sender=self.name,
- timestamp=time.time(),
- message_type="uppercase_response",
- )
-
-
-class BrokenAgent(BaseAgent):
- """Always raises an exception — tests error handling."""
-
- def __init__(self):
- super().__init__(name="BrokenAgent", description="Always fails")
-
- async def _process_impl(self, message: AgentMessage) -> AgentMessage:
- raise RuntimeError("intentional failure")
-
-
-# ============================================================================
-# Tests
-# ============================================================================
-
-async def test_custom_agent() -> None:
- section("Custom agent — UpperCaseAgent")
-
- agent = UpperCaseAgent()
- check("initial status is IDLE", agent.status == AgentStatus.IDLE)
- check("name set correctly", agent.name == "UpperCaseAgent")
- check("history starts empty", len(agent.message_history) == 0)
-
- response = await agent.process(msg("hello world"))
- check("response content uppercased", response.content == "HELLO WORLD")
- check("response sender is agent name", response.sender == "UpperCaseAgent")
- check("message_type preserved", response.message_type == "uppercase_response")
- check("status returns to IDLE", agent.status == AgentStatus.IDLE)
- check("input added to history", len(agent.message_history) == 1)
-
- # Send a second message
- await agent.process(msg("second message"))
- check("history grows with each message", len(agent.message_history) == 2)
- check("get_recent_messages(1) returns 1", len(agent.get_recent_messages(1)) == 1)
- check("get_recent_messages(5) returns 2", len(agent.get_recent_messages(5)) == 2)
-
-
-async def test_error_handling() -> None:
- section("Error handling — BrokenAgent")
-
- agent = BrokenAgent()
- response = await agent.process(msg("trigger error"))
-
- check("response message_type is error", response.message_type == "error")
- check("response content contains 'Error'", "Error" in response.content)
- check("status set to ERROR", agent.status == AgentStatus.ERROR)
-
-
-async def test_callbacks() -> None:
- section("Callbacks")
-
- agent = UpperCaseAgent()
- log: list = []
-
- def record(input_msg: AgentMessage, output_msg: AgentMessage) -> None:
- log.append((input_msg.content, output_msg.content))
-
- agent.add_callback(record)
- await agent.process(msg("ping"))
- await agent.process(msg("pong"))
-
- check("callback fired for each message", len(log) == 2)
- check("callback received correct input", log[0][0] == "ping")
- check("callback received correct output", log[0][1] == "PING")
- check("second callback entry correct", log[1] == ("pong", "PONG"))
-
- # A crashing callback must not break the agent
- def bad_callback(i, o):
- raise ValueError("bad callback")
-
- agent.add_callback(bad_callback)
- response = await agent.process(msg("still works"))
- check("agent survives a crashing callback", response.content == "STILL WORKS")
-
-
-async def test_echo_agent() -> None:
- section("EchoAgent")
-
- agent = EchoAgent()
- response = await agent.process(msg("hello"))
- check("response starts with 'Echo:'", response.content.startswith("Echo:"))
- check("original content echoed", "hello" in response.content)
- check("message_type is echo_response", response.message_type == "echo_response")
-
-
-async def test_calculator_agent() -> None:
- section("CalculatorAgent")
-
- agent = CalculatorAgent()
-
- cases = [
- ("2 + 2", "4"),
- ("10 * 5", "50"),
- ("100 / 4", "25.0"),
- ("(3 + 7) * 2", "20"),
- ]
- for expr, expected in cases:
- r = await agent.process(msg(expr))
- check(f" {expr} = {expected}", expected in r.content)
-
- # Invalid input should return an error message, not crash
- r = await agent.process(msg("__import__('os')"))
- check("invalid chars -> error message", "error" in r.content.lower() or "Error" in r.content)
-
- r = await agent.process(msg("1 / 0"))
- check("division by zero -> error message", "error" in r.content.lower() or "Error" in r.content)
-
-
-async def test_weather_agent() -> None:
- section("WeatherAgent")
-
- agent = WeatherAgent()
-
- known_cities = ["New York", "London", "Tokyo", "Sydney"]
- for city in known_cities:
- r = await agent.process(msg(city))
- check(f" {city}: contains city name", city in r.content)
- check(f" {city}: contains Temperature", "Temperature" in r.content)
- check(f" {city}: message_type correct", r.message_type == "weather_report")
-
- # Unknown city should still return a response (simulated)
- r = await agent.process(msg("Atlantis"))
- check("unknown city returns simulated data", "Atlantis" in r.content)
- check("simulated data has Temperature field", "Temperature" in r.content)
-
-
-async def test_translator_agent() -> None:
- section("TranslatorAgent")
-
- agent = TranslatorAgent()
-
- supported = ["spanish", "french", "german", "italian"]
- for lang in supported:
- r = await agent.process(msg("Hello", target_language=lang))
- check(f" {lang}: lang name in response", lang.upper() in r.content)
- check(f" {lang}: message_type correct", r.message_type == "translation")
-
- # Unsupported language
- r = await agent.process(msg("Hello", target_language="klingon"))
- check("unsupported language returns error text", "don't support" in r.content or "klingon" in r.content.lower())
-
-
-# ============================================================================
-# Entry point
-# ============================================================================
-
-async def _run_all() -> bool:
- global _passed, _failed
- _passed = _failed = 0
-
- await test_custom_agent()
- await test_error_handling()
- await test_callbacks()
- await test_echo_agent()
- await test_calculator_agent()
- await test_weather_agent()
- await test_translator_agent()
-
- total = _passed + _failed
- print(f"\n{'=' * 60}")
- print(f" Result: {_passed}/{total} passed", "✓" if _failed == 0 else "✗")
- print(f"{'=' * 60}")
- return _failed == 0
-
-
-def run() -> bool:
- print("\n" + "=" * 60)
- print(" 02 — Framework Agents")
- print("=" * 60)
- return asyncio.run(_run_all())
-
-
-if __name__ == "__main__":
- ok = run()
- sys.exit(0 if ok else 1)
diff --git a/Agent_module/Example/03_agent_manager.py b/Agent_module/Example/03_agent_manager.py
deleted file mode 100644
index 92ea5a636a..0000000000
--- a/Agent_module/Example/03_agent_manager.py
+++ /dev/null
@@ -1,271 +0,0 @@
-"""
-03_agent_manager.py
-===================
-Tests AgentManager: registration, unicast, broadcast, capability
-discovery, system statistics, and concurrent execution.
-
-Run:
- python3 Agent_module/Example/03_agent_manager.py
-"""
-
-import asyncio
-import sys
-import os
-import time
-
-sys.path.insert(0, os.path.dirname(__file__))
-
-from _loader import load
-
-_m = load("Framework", "Implementation", "Manager", "Chat_Agent")
-BaseAgent = _m.BaseAgent
-AgentMessage = _m.AgentMessage
-AgentStatus = _m.AgentStatus
-AgentManager = _m.AgentManager
-EchoAgent = _m.EchoAgent
-CalculatorAgent = _m.CalculatorAgent
-WeatherAgent = _m.WeatherAgent
-TranslatorAgent = _m.TranslatorAgent
-ChatAgent = _m.ChatAgent
-
-# ============================================================================
-# Test helpers
-# ============================================================================
-
-_passed = 0
-_failed = 0
-
-
-def check(label: str, condition: bool) -> None:
- global _passed, _failed
- if condition:
- _passed += 1
- print(f" PASS {label}")
- else:
- _failed += 1
- print(f" FAIL {label}")
-
-
-def section(title: str) -> None:
- print(f"\n{'=' * 60}")
- print(f" {title}")
- print(f"{'=' * 60}")
-
-
-# ============================================================================
-# Helper agent
-# ============================================================================
-
-class TagAgent(BaseAgent):
- """Returns a fixed tag — useful for verifying broadcast routing."""
-
- def __init__(self, name: str, tag: str):
- super().__init__(name=name, description=f"Returns tag: {tag}")
- self.tag = tag
-
- async def _process_impl(self, message: AgentMessage) -> AgentMessage:
- return AgentMessage(
- content=self.tag,
- sender=self.name,
- timestamp=time.time(),
- )
-
-
-# ============================================================================
-# Tests
-# ============================================================================
-
-async def test_registration() -> None:
- section("Agent registration")
-
- manager = AgentManager()
- a1 = EchoAgent()
- a2 = CalculatorAgent()
-
- manager.register_agent(a1)
- manager.register_agent(a2)
-
- check("two agents registered", len(manager.agents) == 2)
- check("EchoAgent found by name", "EchoAgent" in manager.agents)
- check("CalculatorAgent found by name", "CalculatorAgent" in manager.agents)
-
- # Re-registering with the same name replaces the entry
- a3 = EchoAgent()
- manager.register_agent(a3)
- check("re-register keeps count at 2", len(manager.agents) == 2)
- check("replaced agent is the new one", manager.agents["EchoAgent"] is a3)
-
-
-async def test_send_message() -> None:
- section("Unicast — send_message")
-
- manager = AgentManager()
- manager.register_agent(CalculatorAgent())
- manager.register_agent(WeatherAgent())
-
- r = await manager.send_message("CalculatorAgent", "6 * 7")
- check("calculator returns correct result", "42" in r.content)
- check("sender is CalculatorAgent", r.sender == "CalculatorAgent")
-
- r = await manager.send_message("WeatherAgent", "Tokyo")
- check("weather response contains Tokyo", "Tokyo" in r.content)
-
- # Unknown agent should raise ValueError
- try:
- await manager.send_message("NonExistentAgent", "hello")
- check("ValueError raised for unknown agent", False)
- except ValueError:
- check("ValueError raised for unknown agent", True)
-
-
-async def test_broadcast() -> None:
- section("Broadcast — broadcast_message")
-
- manager = AgentManager()
- manager.register_agent(TagAgent("Alpha", "alpha-reply"))
- manager.register_agent(TagAgent("Beta", "beta-reply"))
- manager.register_agent(TagAgent("Gamma", "gamma-reply"))
-
- responses = await manager.broadcast_message("ping")
-
- check("all three agents responded", len(responses) == 3)
- check("Alpha response correct", responses["Alpha"].content == "alpha-reply")
- check("Beta response correct", responses["Beta"].content == "beta-reply")
- check("Gamma response correct", responses["Gamma"].content == "gamma-reply")
-
-
-async def test_broadcast_with_failure() -> None:
- section("Broadcast — partial failure handled gracefully")
-
- class FailingAgent(BaseAgent):
- def __init__(self):
- super().__init__(name="FailingAgent", description="always fails")
-
- async def _process_impl(self, m: AgentMessage) -> AgentMessage:
- raise RuntimeError("boom")
-
- manager = AgentManager()
- manager.register_agent(TagAgent("Good", "ok"))
- manager.register_agent(FailingAgent())
-
- responses = await manager.broadcast_message("test")
-
- check("both agents have a response entry", len(responses) == 2)
- check("Good agent responded normally", responses["Good"].content == "ok")
- # FailingAgent's error is caught inside BaseAgent.process(), not in broadcast
- check("FailingAgent returned an error message", responses["FailingAgent"].message_type == "error")
-
-
-async def test_capability_discovery() -> None:
- section("Capability discovery — find_agent_by_capability")
-
- manager = AgentManager()
- manager.register_agent(CalculatorAgent()) # description: "Performs mathematical calculations"
- manager.register_agent(WeatherAgent()) # description: "Provides weather information"
- manager.register_agent(TranslatorAgent()) # description: "Translates text between languages"
-
- calc_agents = manager.find_agent_by_capability("calculation")
- weather_agents = manager.find_agent_by_capability("weather")
- trans_agents = manager.find_agent_by_capability("translat")
- none_agents = manager.find_agent_by_capability("nonexistent_xyz")
-
- check("calculator found by 'calculation'", "CalculatorAgent" in calc_agents)
- check("weather found by 'weather'", "WeatherAgent" in weather_agents)
- check("translator found by 'translat'", "TranslatorAgent" in trans_agents)
- check("empty list for no match", none_agents == [])
-
-
-async def test_system_stats() -> None:
- section("System statistics")
-
- manager = AgentManager()
- manager.register_agent(EchoAgent())
- manager.register_agent(CalculatorAgent())
-
- await manager.send_message("EchoAgent", "msg 1")
- await manager.send_message("EchoAgent", "msg 2")
- await manager.send_message("CalculatorAgent", "1 + 1")
-
- stats = manager.get_system_stats()
-
- check("total_agents is 2", stats["total_agents"] == 2)
- check("total_messages_processed is 3", stats["total_messages_processed"] == 3)
- check("conversation_log_entries is 3", stats["conversation_log_entries"] == 3)
- check("agent_statuses dict present", "agent_statuses" in stats)
- check("EchoAgent status is idle", stats["agent_statuses"]["EchoAgent"] == "idle")
-
-
-async def test_metadata_routing() -> None:
- section("Metadata routing — TranslatorAgent target_language")
-
- manager = AgentManager()
- manager.register_agent(TranslatorAgent())
-
- r = await manager.send_message(
- "TranslatorAgent",
- "Good morning",
- metadata={"target_language": "german"}
- )
- check("german translation triggered", "GERMAN" in r.content)
- check("original text present", "Good morning" in r.content)
-
-
-async def test_chat_agent() -> None:
- section("ChatAgent — basic intent detection")
-
- manager = AgentManager()
- manager.register_agent(ChatAgent())
-
- greetings = ["hello", "hi there", "hey", "greetings"]
- for g in greetings:
- r = await manager.send_message("ChatAgent", g, metadata={"user_id": "u1"})
- check(f" greeting '{g}' gets a reply", len(r.content) > 0)
- check(f" message_type is chat_response", r.message_type == "chat_response")
-
- r = await manager.send_message("ChatAgent", "what is your name?", metadata={"user_id": "u1"})
- check("question gets an answer", len(r.content) > 0)
-
- # Conversation count should increment in context
- r1 = await manager.send_message("ChatAgent", "hello", metadata={"user_id": "ctx_user"})
- # Read count1 immediately — the metadata dict is a live reference that will
- # be mutated by subsequent messages for the same user_id.
- count1 = r1.metadata.get("user_context", {}).get("conversation_count", 0)
- r2 = await manager.send_message("ChatAgent", "hello", metadata={"user_id": "ctx_user"})
- count2 = r2.metadata.get("user_context", {}).get("conversation_count", 0)
- check("conversation_count increments per user", count2 == count1 + 1)
-
-
-# ============================================================================
-# Entry point
-# ============================================================================
-
-async def _run_all() -> bool:
- global _passed, _failed
- _passed = _failed = 0
-
- await test_registration()
- await test_send_message()
- await test_broadcast()
- await test_broadcast_with_failure()
- await test_capability_discovery()
- await test_system_stats()
- await test_metadata_routing()
- await test_chat_agent()
-
- total = _passed + _failed
- print(f"\n{'=' * 60}")
- print(f" Result: {_passed}/{total} passed", "✓" if _failed == 0 else "✗")
- print(f"{'=' * 60}")
- return _failed == 0
-
-
-def run() -> bool:
- print("\n" + "=" * 60)
- print(" 03 — AgentManager")
- print("=" * 60)
- return asyncio.run(_run_all())
-
-
-if __name__ == "__main__":
- ok = run()
- sys.exit(0 if ok else 1)
diff --git a/Agent_module/Example/04_context_store.py b/Agent_module/Example/04_context_store.py
deleted file mode 100644
index 6f5f4650bd..0000000000
--- a/Agent_module/Example/04_context_store.py
+++ /dev/null
@@ -1,389 +0,0 @@
-"""
-04_context_store.py
-===================
-Tests every major feature of ContextStore and ContextNamespace:
- put / get / delete / history / keys / query
- P2P channels (send / receive / inbox / peek)
- Pub/Sub (subscribe / unsubscribe / callback ordering)
- TTL expiry (lazy + batch cleanup)
- Namespace isolation
- Merge (last-write-wins by version)
- Snapshot and to_json serialisation
- Stats
-
-Run:
- python3 Agent_module/Example/04_context_store.py
-"""
-
-import asyncio
-import sys
-import os
-
-sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
-
-from ContextStore import ContextStore, ContextNamespace, ContextRecord
-
-# ============================================================================
-# Test helpers
-# ============================================================================
-
-_passed = 0
-_failed = 0
-
-
-def check(label: str, condition: bool) -> None:
- global _passed, _failed
- if condition:
- _passed += 1
- print(f" PASS {label}")
- else:
- _failed += 1
- print(f" FAIL {label}")
-
-
-def section(title: str) -> None:
- print(f"\n{'=' * 60}")
- print(f" {title}")
- print(f"{'=' * 60}")
-
-
-# ============================================================================
-# Tests
-# ============================================================================
-
-async def test_basic_put_get() -> None:
- section("Basic put / get / delete")
-
- store = ContextStore()
-
- rec = await store.put("color", "red", writer="alice")
- check("put returns a ContextRecord", isinstance(rec, ContextRecord))
- check("record key is correct", rec.key == "color")
- check("record value is correct", rec.value == "red")
- check("record writer is correct", rec.writer == "alice")
- check("first write gets version 1", rec.version == 1)
- check("record_id is a non-empty string", len(rec.record_id) > 0)
-
- val = await store.get("color")
- check("get returns current value", val == "red")
-
- # Overwrite
- rec2 = await store.put("color", "blue", writer="bob")
- check("second write gets version 2", rec2.version == 2)
- check("get returns updated value", await store.get("color") == "blue")
-
- # Missing key
- check("get missing key returns None", await store.get("__missing__") is None)
-
- # Delete
- deleted = await store.delete("color", writer="alice")
- check("delete returns True for existing key", deleted)
- check("get after delete returns None", await store.get("color") is None)
-
- not_deleted = await store.delete("__missing__", writer="alice")
- check("delete returns False for missing key", not not_deleted)
-
-
-async def test_history() -> None:
- section("History")
-
- store = ContextStore()
-
- await store.put("status", "pending", writer="coordinator")
- await store.put("status", "in_progress", writer="worker")
- await store.put("status", "completed", writer="worker")
-
- history = await store.history("status")
- check("history returns 3 records", len(history) == 3)
- check("history is newest-first", history[0].value == "completed")
- check("oldest record is pending", history[-1].value == "pending")
-
- limited = await store.history("status", limit=2)
- check("limit=2 returns 2 records", len(limited) == 2)
- check("limit respects newest-first order", limited[0].value == "completed")
-
- empty = await store.history("__missing__")
- check("history for missing key is []", empty == [])
-
-
-async def test_keys_and_query() -> None:
- section("keys() and query()")
-
- store = ContextStore()
- ns = "test_ns"
-
- await store.put("a", 1, writer="alice", namespace=ns, tags=["x"])
- await store.put("b", 2, writer="bob", namespace=ns, tags=["x", "y"])
- await store.put("c", 3, writer="alice", namespace=ns, tags=["y"])
-
- all_keys = await store.keys(namespace=ns)
- check("keys() returns all 3 keys", set(all_keys) == {"a", "b", "c"})
-
- alice_entries = await store.query(namespace=ns, writer="alice")
- check("query(writer='alice') returns 2 entries", len(alice_entries) == 2)
- check("all alice entries have writer='alice'",
- all(e.current.writer == "alice" for e in alice_entries))
-
- tag_x = await store.query(namespace=ns, tags=["x"])
- check("query(tags=['x']) returns 2 entries", len(tag_x) == 2)
-
- tag_xy = await store.query(namespace=ns, tags=["x", "y"])
- check("query(tags=['x','y']) returns 1 entry", len(tag_xy) == 1)
- check("that entry is 'b'", tag_xy[0].current.key == "b")
-
- no_match = await store.query(namespace=ns, writer="nobody")
- check("query with no match returns []", no_match == [])
-
-
-async def test_namespace_isolation() -> None:
- section("Namespace isolation")
-
- store = ContextStore()
-
- await store.put("key", "ns1-value", writer="agent", namespace="ns1")
- await store.put("key", "ns2-value", writer="agent", namespace="ns2")
-
- check("ns1 reads its own value", await store.get("key", namespace="ns1") == "ns1-value")
- check("ns2 reads its own value", await store.get("key", namespace="ns2") == "ns2-value")
- check("default ns is empty", await store.get("key") is None)
-
- ns1_keys = await store.keys(namespace="ns1")
- ns2_keys = await store.keys(namespace="ns2")
- check("ns1 has exactly 1 key", ns1_keys == ["key"])
- check("ns2 has exactly 1 key", ns2_keys == ["key"])
-
-
-async def test_context_namespace_proxy() -> None:
- section("ContextNamespace proxy")
-
- store = ContextStore()
- ns = ContextNamespace(store, "proxy_ns")
-
- check("namespace property correct", ns.namespace == "proxy_ns")
-
- await ns.put("x", 42, writer="agent")
- check("ns.put writes to correct namespace", await ns.get("x") == 42)
- check("direct store read matches", await store.get("x", "proxy_ns") == 42)
-
- await ns.delete("x", writer="agent")
- check("ns.delete removes the key", await ns.get("x") is None)
-
- await ns.put("h", "v1", writer="a")
- await ns.put("h", "v2", writer="b")
- hist = await ns.history("h")
- check("ns.history returns 2 records", len(hist) == 2)
-
- keys = await ns.keys()
- check("ns.keys() returns ['h']", keys == ["h"])
-
-
-async def test_channels() -> None:
- section("P2P Channels — send / receive / peek / inbox")
-
- store = ContextStore()
-
- # Send two messages from coordinator to worker
- m1 = await store.send("coordinator", "worker", {"cmd": "run"})
- m2 = await store.send("coordinator", "worker", {"cmd": "stop"})
- check("send returns a ContextMessage", m1.sender == "coordinator")
- check("message_id is unique", m1.message_id != m2.message_id)
-
- ch = store.channel("coordinator", "worker")
- check("channel depth is 2", len(ch) == 2)
-
- # Peek does not consume
- peeked = await ch.peek()
- check("peek returns first message", peeked.payload == {"cmd": "run"})
- check("peek does not consume (depth still 2)", len(ch) == 2)
-
- # Receive consumes one
- r = await store.receive("coordinator", "worker")
- check("receive returns oldest message (FIFO)", r.payload == {"cmd": "run"})
- check("channel depth is now 1", len(ch) == 1)
-
- # Drain with inbox across multiple senders
- await store.send("auditor", "worker", {"cmd": "check"})
- inbox = await store.inbox("worker")
- check("inbox collects from all senders", len(inbox) == 2)
- check("inbox sorted oldest-first by timestamp", inbox[0].payload == {"cmd": "stop"})
- check("inbox is destructive (channel empty)", len(store.channel("coordinator", "worker")) == 0)
-
- # Empty channel
- empty = await store.receive("coordinator", "worker")
- check("receive on empty channel returns None", empty is None)
-
- # Tags on messages
- tagged = await store.send("a", "b", "payload", tags=["urgent"])
- check("message tags preserved", "urgent" in tagged.tags)
-
-
-async def test_pubsub() -> None:
- section("Pub/Sub")
-
- store = ContextStore()
- ns = ContextNamespace(store, "pubsub_ns")
- log: list = []
-
- async def async_cb(key: str, record: ContextRecord) -> None:
- log.append(("async", key, record.value, record.writer))
-
- def sync_cb(key: str, record: ContextRecord) -> None:
- log.append(("sync", key, record.value, record.writer))
-
- # Subscribe monitor (async) and logger (sync) to all keys
- ns.subscribe("monitor", async_cb)
- ns.subscribe("logger", sync_cb)
-
- await ns.put("status", "started", writer="coordinator")
- check("async callback fired", any(e[0] == "async" for e in log))
- check("sync callback fired", any(e[0] == "sync" for e in log))
- check("both callbacks fired (2 entries)", len(log) == 2)
- check("correct key delivered", all(e[1] == "status" for e in log))
- check("correct value delivered", all(e[2] == "started" for e in log))
-
- # Writer does NOT receive their own notification
- log.clear()
- ns.subscribe("coordinator", lambda k, r: log.append("self-notified"))
- await ns.put("status", "done", writer="coordinator")
- check("writer not notified of own write", "self-notified" not in log)
- check("other subscribers still notified", len(log) == 2)
-
- # Key-filtered subscription
- log.clear()
- ns.unsubscribe("monitor")
- ns.unsubscribe("logger")
- ns.unsubscribe("coordinator")
-
- ns.subscribe("watcher", lambda k, r: log.append(k), keys=["important"])
- await ns.put("important", "yes", writer="a")
- await ns.put("unimportant", "skip", writer="a")
- check("key filter: watched key triggers callback", "important" in log)
- check("key filter: unwatched key does not trigger", "unimportant" not in log)
-
- # Unsubscribe
- log.clear()
- ns.unsubscribe("watcher")
- await ns.put("important", "again", writer="a")
- check("after unsubscribe, no callback fires", log == [])
-
-
-async def test_ttl() -> None:
- section("TTL expiry")
-
- store = ContextStore()
- ns = ContextNamespace(store, "ttl_ns")
-
- await ns.put("short", "alive", writer="agent", ttl=1)
- check("immediate read returns value", await ns.get("short") == "alive")
-
- await asyncio.sleep(1.2)
- check("read after TTL returns None", await ns.get("short") is None)
-
- # Batch cleanup
- await ns.put("a", 1, writer="x", ttl=1)
- await ns.put("b", 2, writer="x", ttl=1)
- await ns.put("c", 3, writer="x") # no TTL — should survive
-
- await asyncio.sleep(1.2)
- removed = await ns.cleanup_expired()
- check("cleanup_expired removed 2 keys", removed == 2)
- check("non-expiring key 'c' still readable", await ns.get("c") == 3)
-
-
-async def test_merge() -> None:
- section("Merge — last-write-wins by version")
-
- store_a = ContextStore()
- store_b = ContextStore()
- ns = "merge_ns"
-
- # store_a writes status twice (version 2)
- await store_a.put("status", "v1", writer="a", namespace=ns)
- await store_a.put("status", "v2", writer="a", namespace=ns)
-
- # store_b writes status once (version 1) — lower version
- await store_b.put("status", "b-v1", writer="b", namespace=ns)
- await store_b.put("extra", "only-in-b", writer="b", namespace=ns)
-
- # Merge b into a — b's status (v1) should NOT overwrite a's status (v2)
- merged = await store_a.merge(store_b, namespace=ns)
- check("merge returns count of accepted entries", merged >= 1)
- check("higher-version local value retained", await store_a.get("status", ns) == "v2")
- check("new key from b accepted", await store_a.get("extra", ns) == "only-in-b")
-
- # Merge a into b — a's status (v2) should overwrite b's status (v1)
- await store_b.merge(store_a, namespace=ns)
- check("higher-version remote value wins on merge", await store_b.get("status", ns) == "v2")
-
-
-async def test_snapshot_and_serialisation() -> None:
- section("Snapshot and serialisation")
-
- import json
-
- store = ContextStore()
- ns = ContextNamespace(store, "serial_ns")
-
- await ns.put("k1", "v1", writer="a", tags=["t1"])
- await ns.put("k2", {"nested": True}, writer="b")
- await store.send("a", "b", {"cmd": "go"})
-
- # Snapshot
- snap = await ns.snapshot()
- check("snapshot has k1 and k2", set(snap.keys()) == {"k1", "k2"})
- check("snapshot is a deep copy", snap["k1"]["current"]["value"] == "v1")
-
- # to_json
- json_str = await store.to_json()
- parsed = json.loads(json_str)
-
- check("to_json produces valid JSON",
- "entries" in parsed and "channels" in parsed and "subscriptions" in parsed)
- check("namespace present in JSON", "serial_ns" in parsed["entries"])
- check("k1 present in JSON entries", "k1" in parsed["entries"]["serial_ns"])
- check("channel captured in JSON", "a->b" in parsed["channels"])
-
- # Stats
- stats = await store.stats()
- check("stats has namespaces key", "namespaces" in stats)
- check("stats has total_channels key", "total_channels" in stats)
- check("serial_ns appears in stats", "serial_ns" in stats["namespaces"])
- check("total_channels >= 1", stats["total_channels"] >= 1)
-
-
-# ============================================================================
-# Entry point
-# ============================================================================
-
-async def _run_all() -> bool:
- global _passed, _failed
- _passed = _failed = 0
-
- await test_basic_put_get()
- await test_history()
- await test_keys_and_query()
- await test_namespace_isolation()
- await test_context_namespace_proxy()
- await test_channels()
- await test_pubsub()
- await test_ttl()
- await test_merge()
- await test_snapshot_and_serialisation()
-
- total = _passed + _failed
- print(f"\n{'=' * 60}")
- print(f" Result: {_passed}/{total} passed", "✓" if _failed == 0 else "✗")
- print(f"{'=' * 60}")
- return _failed == 0
-
-
-def run() -> bool:
- print("\n" + "=" * 60)
- print(" 04 — ContextStore")
- print("=" * 60)
- return asyncio.run(_run_all())
-
-
-if __name__ == "__main__":
- ok = run()
- sys.exit(0 if ok else 1)
diff --git a/Agent_module/Example/_loader.py b/Agent_module/Example/_loader.py
deleted file mode 100644
index 2e307b4bf4..0000000000
--- a/Agent_module/Example/_loader.py
+++ /dev/null
@@ -1,49 +0,0 @@
-"""
-_loader.py
-==========
-Utility for loading Agent_module source files that share a namespace.
-
-Framework.py, Implementation.py, Manager.py, and Chat_Agent.py were written
-as a single-namespace codebase (no per-file imports). This loader execs them
-together into one shared dict so the cross-file dependencies resolve correctly.
-
-Usage:
- from _loader import load
- m = load("Framework", "Implementation", "Manager", "Chat_Agent")
- BaseAgent = m.BaseAgent
- EchoAgent = m.EchoAgent
- AgentManager = m.AgentManager
-"""
-
-import os
-import types
-import asyncio
-import time
-import random
-import json
-
-_MODULE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
-
-
-def load(*names: str) -> types.SimpleNamespace:
- """
- Execute each named .py file in _MODULE_DIR into a shared namespace
- and return a SimpleNamespace with all defined names as attributes.
-
- Example:
- m = load("Framework", "Implementation")
- agent = m.EchoAgent()
- """
- ns: dict = {
- "__builtins__": __builtins__,
- "asyncio": asyncio,
- "time": time,
- "random": random,
- "json": json,
- }
- for name in names:
- path = os.path.join(_MODULE_DIR, f"{name}.py")
- with open(path) as fh:
- exec(compile(fh.read(), path, "exec"), ns)
-
- return types.SimpleNamespace(**{k: v for k, v in ns.items() if not k.startswith("_")})
diff --git a/Agent_module/Example/run_all.py b/Agent_module/Example/run_all.py
deleted file mode 100644
index 4dcb120810..0000000000
--- a/Agent_module/Example/run_all.py
+++ /dev/null
@@ -1,52 +0,0 @@
-"""
-run_all.py
-==========
-Runs all example test files and prints a summary.
-
-Run:
- python3 Agent_module/Example/run_all.py
-"""
-
-import sys
-import os
-import importlib
-
-sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
-sys.path.insert(0, os.path.dirname(__file__))
-
-EXAMPLES = [
- ("01_data_models", "Agent Data Models"),
- ("02_framework_agents", "Framework Agents"),
- ("03_agent_manager", "AgentManager"),
- ("04_context_store", "ContextStore"),
-]
-
-
-def main() -> None:
- results: list = []
-
- for module_name, label in EXAMPLES:
- mod = importlib.import_module(module_name)
- ok = mod.run()
- results.append((label, ok))
-
- # Summary
- print("\n" + "=" * 60)
- print(" SUMMARY")
- print("=" * 60)
- all_passed = True
- for label, ok in results:
- status = "PASS" if ok else "FAIL"
- print(f" {status} {label}")
- if not ok:
- all_passed = False
-
- print("=" * 60)
- print(f" {'All examples passed ✓' if all_passed else 'Some examples FAILED ✗'}")
- print("=" * 60)
-
- sys.exit(0 if all_passed else 1)
-
-
-if __name__ == "__main__":
- main()
diff --git a/Agent_module/Framework.py b/Agent_module/Framework.py
deleted file mode 100644
index d7c5e6b902..0000000000
--- a/Agent_module/Framework.py
+++ /dev/null
@@ -1,78 +0,0 @@
-import asyncio
-import time
-from abc import ABC, abstractmethod
-from typing import Any, Dict, List, Optional, Callable
-from dataclasses import dataclass
-from enum import Enum
-import random
-import json
-
-class AgentStatus(Enum):
- IDLE = "idle"
- PROCESSING = "processing"
- ERROR = "error"
- STOPPED = "stopped"
-
-@dataclass
-class AgentMessage:
- content: Any
- sender: str
- timestamp: float
- message_type: str = "text"
- metadata: Dict[str, Any] = None
-
- def __post_init__(self):
- if self.metadata is None:
- self.metadata = {}
- self.timestamp = self.timestamp or time.time()
-
-class BaseAgent(ABC):
- """Base class for all agents"""
-
- def __init__(self, name: str, description: str = ""):
- self.name = name
- self.description = description
- self.status = AgentStatus.IDLE
- self.message_history: List[AgentMessage] = []
- self._callbacks: List[Callable] = []
-
- async def process(self, message: AgentMessage) -> AgentMessage:
- """Process a message and return response"""
- self.status = AgentStatus.PROCESSING
- self.message_history.append(message)
-
- try:
- result = await self._process_impl(message)
- self.status = AgentStatus.IDLE
- self._notify_callbacks(message, result)
- return result
- except Exception as e:
- self.status = AgentStatus.ERROR
- error_msg = AgentMessage(
- content=f"Error: {str(e)}",
- sender=self.name,
- timestamp=time.time(),
- message_type="error"
- )
- return error_msg
-
- @abstractmethod
- async def _process_impl(self, message: AgentMessage) -> AgentMessage:
- """Agent-specific processing logic"""
- pass
-
- def add_callback(self, callback: Callable):
- """Add callback for message processing events"""
- self._callbacks.append(callback)
-
- def _notify_callbacks(self, input_msg: AgentMessage, output_msg: AgentMessage):
- """Notify all callbacks"""
- for callback in self._callbacks:
- try:
- callback(input_msg, output_msg)
- except Exception:
- pass # Don't break agent if callback fails
-
- def get_recent_messages(self, count: int = 10) -> List[AgentMessage]:
- """Get recent message history"""
- return self.message_history[-count:]
\ No newline at end of file
diff --git a/Agent_module/Implementation.py b/Agent_module/Implementation.py
deleted file mode 100644
index 59a806ce50..0000000000
--- a/Agent_module/Implementation.py
+++ /dev/null
@@ -1,119 +0,0 @@
-class EchoAgent(BaseAgent):
- """Simple echo agent that repeats messages"""
-
- def __init__(self, name: str = "EchoAgent"):
- super().__init__(name, "Echoes back received messages")
-
- async def _process_impl(self, message: AgentMessage) -> AgentMessage:
- await asyncio.sleep(0.1) # Simulate processing time
-
- response_content = f"Echo: {message.content}"
-
- return AgentMessage(
- content=response_content,
- sender=self.name,
- timestamp=time.time(),
- message_type="echo_response"
- )
-
-class CalculatorAgent(BaseAgent):
- """Agent that performs mathematical calculations"""
-
- def __init__(self, name: str = "CalculatorAgent"):
- super().__init__(name, "Performs mathematical calculations")
-
- async def _process_impl(self, message: AgentMessage) -> AgentMessage:
- try:
- expression = str(message.content).strip()
- # Security: Only allow basic math operations
- allowed_chars = set('0123456789+-*/.() ')
- if not all(c in allowed_chars for c in expression):
- raise ValueError("Invalid characters in expression")
-
- result = eval(expression) # In real code, use a safe eval or parser
-
- return AgentMessage(
- content=f"{expression} = {result}",
- sender=self.name,
- timestamp=time.time(),
- message_type="calculation_result"
- )
- except Exception as e:
- return AgentMessage(
- content=f"Calculation error: {str(e)}",
- sender=self.name,
- timestamp=time.time(),
- message_type="error"
- )
-
-class WeatherAgent(BaseAgent):
- """Simulated weather information agent"""
-
- def __init__(self, name: str = "WeatherAgent"):
- super().__init__(name, "Provides weather information")
- self.weather_data = {
- "New York": {"temp": 22, "condition": "Sunny", "humidity": 65},
- "London": {"temp": 15, "condition": "Cloudy", "humidity": 80},
- "Tokyo": {"temp": 18, "condition": "Rainy", "humidity": 75},
- "Sydney": {"temp": 25, "condition": "Clear", "humidity": 60}
- }
-
- async def _process_impl(self, message: AgentMessage) -> AgentMessage:
- location = str(message.content).strip().title()
-
- await asyncio.sleep(0.2) # Simulate API call
-
- if location in self.weather_data:
- weather = self.weather_data[location]
- response = (
- f"Weather in {location}:\n"
- f"Temperature: {weather['temp']}°C\n"
- f"Condition: {weather['condition']}\n"
- f"Humidity: {weather['humidity']}%"
- )
- else:
- # Generate random weather for unknown locations
- temp = random.randint(-10, 35)
- conditions = ["Sunny", "Cloudy", "Rainy", "Snowy"]
- condition = random.choice(conditions)
- humidity = random.randint(30, 95)
-
- response = (
- f"Weather in {location} (simulated):\n"
- f"Temperature: {temp}°C\n"
- f"Condition: {condition}\n"
- f"Humidity: {humidity}%"
- )
-
- return AgentMessage(
- content=response,
- sender=self.name,
- timestamp=time.time(),
- message_type="weather_report"
- )
-
-class TranslatorAgent(BaseAgent):
- """Simple translation agent (simulated)"""
-
- def __init__(self, name: str = "TranslatorAgent"):
- super().__init__(name, "Translates text between languages")
- self.supported_languages = ["english", "spanish", "french", "german", "italian"]
-
- async def _process_impl(self, message: AgentMessage) -> AgentMessage:
- text = str(message.content)
- target_language = message.metadata.get("target_language", "spanish").lower()
-
- await asyncio.sleep(0.3) # Simulate translation processing
-
- if target_language not in self.supported_languages:
- response = f"Sorry, I don't support {target_language}. Supported languages: {', '.join(self.supported_languages)}"
- else:
- # Simulated translation - in real world, this would call a translation API
- response = f"[{target_language.upper()} TRANSLATION] {text} -> Translated text in {target_language}"
-
- return AgentMessage(
- content=response,
- sender=self.name,
- timestamp=time.time(),
- message_type="translation"
- )
\ No newline at end of file
diff --git a/Agent_module/Manager.py b/Agent_module/Manager.py
deleted file mode 100644
index ff51910795..0000000000
--- a/Agent_module/Manager.py
+++ /dev/null
@@ -1,103 +0,0 @@
-class AgentManager:
- """Manages multiple agents and coordinates between them"""
-
- def __init__(self):
- self.agents: Dict[str, BaseAgent] = {}
- self.conversation_log: List[Dict] = []
-
- def register_agent(self, agent: BaseAgent):
- """Register a new agent"""
- self.agents[agent.name] = agent
-
- # Add logging callback to all agents
- agent.add_callback(self._log_interaction)
-
- async def send_message(self, agent_name: str, content: Any,
- metadata: Dict[str, Any] = None) -> AgentMessage:
- """Send message to specific agent"""
- if agent_name not in self.agents:
- raise ValueError(f"Agent '{agent_name}' not found")
-
- message = AgentMessage(
- content=content,
- sender="User",
- timestamp=time.time(),
- metadata=metadata or {}
- )
-
- agent = self.agents[agent_name]
- response = await agent.process(message)
-
- return response
-
- async def broadcast_message(self, content: Any,
- metadata: Dict[str, Any] = None) -> Dict[str, AgentMessage]:
- """Send message to all agents and collect responses"""
- message = AgentMessage(
- content=content,
- sender="Broadcast",
- timestamp=time.time(),
- metadata=metadata or {}
- )
-
- tasks = []
- for agent_name, agent in self.agents.items():
- tasks.append(agent.process(message))
-
- responses = await asyncio.gather(*tasks, return_exceptions=True)
-
- results = {}
- for agent_name, response in zip(self.agents.keys(), responses):
- if isinstance(response, Exception):
- results[agent_name] = AgentMessage(
- content=f"Error: {str(response)}",
- sender=agent_name,
- timestamp=time.time(),
- message_type="error"
- )
- else:
- results[agent_name] = response
-
- return results
-
- def find_agent_by_capability(self, keyword: str) -> List[str]:
- """Find agents that might handle a specific capability"""
- matching_agents = []
- for agent_name, agent in self.agents.items():
- if (keyword.lower() in agent.name.lower() or
- keyword.lower() in agent.description.lower()):
- matching_agents.append(agent_name)
- return matching_agents
-
- def _log_interaction(self, input_msg: AgentMessage, output_msg: AgentMessage):
- """Log agent interactions"""
- log_entry = {
- "timestamp": time.time(),
- "input": {
- "content": input_msg.content,
- "sender": input_msg.sender,
- "type": input_msg.message_type
- },
- "output": {
- "content": output_msg.content,
- "sender": output_msg.sender,
- "type": output_msg.message_type
- },
- "processing_time": output_msg.timestamp - input_msg.timestamp
- }
- self.conversation_log.append(log_entry)
-
- def get_agent_statuses(self) -> Dict[str, str]:
- """Get status of all agents"""
- return {name: agent.status.value for name, agent in self.agents.items()}
-
- def get_system_stats(self) -> Dict[str, Any]:
- """Get system statistics"""
- total_messages = sum(len(agent.message_history) for agent in self.agents.values())
-
- return {
- "total_agents": len(self.agents),
- "total_messages_processed": total_messages,
- "conversation_log_entries": len(self.conversation_log),
- "agent_statuses": self.get_agent_statuses()
- }
\ No newline at end of file
diff --git a/Agent_module/QUICKSTART.md b/Agent_module/QUICKSTART.md
deleted file mode 100644
index 7ecb01c9d2..0000000000
--- a/Agent_module/QUICKSTART.md
+++ /dev/null
@@ -1,414 +0,0 @@
-# Quick Start for CarbonData's Agent
-
-CarbonData as Agent metadata storage , how to support Multi Agents work together.
-
-**Requirements**: Python 3.10+ — no third-party packages needed, stdlib only.
-
----
-
-## Step 1 — Run a Built-in Agent
-
-The simplest starting point: instantiate one of the built-in agents and send it a message.
-
-```python
-# step1_single_agent.py
-import asyncio
-import time
-import sys, os
-sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
-
-from Framework import AgentMessage
-from Implementation import CalculatorAgent, WeatherAgent, TranslatorAgent
-
-async def main():
- # --- Calculator ---
- calc = CalculatorAgent()
- response = await calc.process(AgentMessage(
- content="(10 + 5) * 4",
- sender="User",
- timestamp=time.time()
- ))
- print(response.content) # (10 + 5) * 4 = 60
-
- # --- Weather ---
- weather = WeatherAgent()
- response = await weather.process(AgentMessage(
- content="Tokyo",
- sender="User",
- timestamp=time.time()
- ))
- print(response.content)
-
- # --- Translator (target language via metadata) ---
- translator = TranslatorAgent()
- response = await translator.process(AgentMessage(
- content="Good morning",
- sender="User",
- timestamp=time.time(),
- metadata={"target_language": "french"}
- ))
- print(response.content)
-
-asyncio.run(main())
-```
-
----
-
-## Step 2 — Write Your Own Agent
-
-Subclass `BaseAgent` and implement `_process_impl`. That is the only requirement.
-
-```python
-# step2_custom_agent.py
-import asyncio
-import time
-import sys, os
-sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
-
-from Framework import BaseAgent, AgentMessage
-
-class GreetingAgent(BaseAgent):
- def __init__(self):
- super().__init__(
- name="GreetingAgent",
- description="Returns a personalised greeting"
- )
-
- async def _process_impl(self, message: AgentMessage) -> AgentMessage:
- name = message.metadata.get("user_name", "stranger")
- return AgentMessage(
- content=f"Hello, {name}! You said: '{message.content}'",
- sender=self.name,
- timestamp=time.time(),
- message_type="greeting"
- )
-
-async def main():
- agent = GreetingAgent()
- response = await agent.process(AgentMessage(
- content="Nice to meet you",
- sender="User",
- timestamp=time.time(),
- metadata={"user_name": "Alice"}
- ))
- print(response.content)
- # Hello, Alice! You said: 'Nice to meet you'
-
- print("Agent status:", agent.status.value) # idle
- print("Messages processed:", len(agent.message_history)) # 1
-
-asyncio.run(main())
-```
-
----
-
-## Step 3 — Manage Multiple Agents
-
-`AgentManager` handles registration, routing, and broadcast. Use it when you have more than one agent.
-
-```python
-# step3_manager.py
-import asyncio
-import sys, os
-sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
-
-from Manager import AgentManager
-from Implementation import CalculatorAgent, WeatherAgent, TranslatorAgent
-from Chat_Agent import ChatAgent
-
-async def main():
- manager = AgentManager()
- manager.register_agent(CalculatorAgent())
- manager.register_agent(WeatherAgent())
- manager.register_agent(TranslatorAgent())
- manager.register_agent(ChatAgent())
-
- # --- Unicast: send to one agent by name ---
- response = await manager.send_message("CalculatorAgent", "99 / 3")
- print(response.content) # 99 / 3 = 33.0
-
- response = await manager.send_message("WeatherAgent", "London")
- print(response.content)
-
- # --- Broadcast: send to every agent concurrently ---
- print("\n--- Broadcast ---")
- responses = await manager.broadcast_message("Hello!")
- for agent_name, resp in responses.items():
- print(f" {agent_name}: {resp.content[:60]}")
-
- # --- Capability discovery: find agents by keyword ---
- print("\n--- Discovery ---")
- print(manager.find_agent_by_capability("weather"))
- print(manager.find_agent_by_capability("calculation"))
-
- # --- System statistics ---
- print("\n--- Stats ---")
- stats = manager.get_system_stats()
- for k, v in stats.items():
- print(f" {k}: {v}")
-
-asyncio.run(main())
-```
-
----
-
-## Step 4 — Share State Between Agents with ContextStore
-
-`ContextStore` is the recommended way for agents to exchange data. It is async, namespace-isolated, and keeps a full write history per key.
-
-```python
-# step4_context_store.py
-import asyncio
-import sys, os
-sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
-
-from ContextStore import ContextStore, ContextNamespace
-
-async def main():
- store = ContextStore()
- ns = ContextNamespace(store, "pipeline_v1")
-
- # --- coordinator writes a task ---
- await ns.put("task", {"id": "t1", "desc": "process sales data"}, writer="coordinator")
- await ns.put("status", "pending", writer="coordinator")
-
- # --- worker reads the task and updates state ---
- task = await ns.get("task")
- print("Task received:", task)
-
- await ns.put("status", "in_progress", writer="worker")
- await ns.put("result", {"rows": 5000, "errors": 0}, writer="worker", tags=["output"])
- await ns.put("status", "completed", writer="worker")
-
- # --- read the final status ---
- print("Final status:", await ns.get("status"))
-
- # --- inspect the full write history for "status" (newest first) ---
- print("\nStatus history:")
- for record in await ns.history("status"):
- print(f" v{record.version} [{record.writer}] -> {record.value!r}")
-
- # --- query all entries written by "worker" ---
- print("\nWorker entries:")
- for entry in await ns.query(writer="worker"):
- print(f" {entry.current.key}: {entry.current.value}")
-
-asyncio.run(main())
-```
-
----
-
-## Step 5 — React to Changes with Pub/Sub
-
-Subscribe a callback to be notified whenever a key is written.
-
-```python
-# step5_pubsub.py
-import asyncio
-import sys, os
-sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
-
-from ContextStore import ContextStore, ContextNamespace, ContextRecord
-
-store = ContextStore()
-ns = ContextNamespace(store, "pipeline_v1")
-
-# Callback can be sync or async
-async def on_status_change(key: str, record: ContextRecord) -> None:
- print(f" [monitor] {key} -> {record.value!r} (writer: {record.writer})")
-
-async def main():
- # Subscribe to specific keys
- ns.subscribe("monitor", on_status_change, keys=["status"])
-
- print("Writing status updates...")
- await ns.put("status", "pending", writer="coordinator")
- await ns.put("status", "in_progress", writer="worker")
- await ns.put("status", "completed", writer="worker")
-
- # The writer does not receive its own notifications.
- # Subscribing with no keys list watches the entire namespace.
- ns.subscribe("logger", lambda k, r: print(f" [logger] {k}={r.value}"))
- await ns.put("result", {"score": 0.98}, writer="worker")
-
-asyncio.run(main())
-```
-
-Expected output:
-```
-Writing status updates...
- [monitor] status -> 'pending' (writer: coordinator)
- [monitor] status -> 'in_progress' (writer: worker)
- [monitor] status -> 'completed' (writer: worker)
- [logger] result={'score': 0.98}
-```
-
----
-
-## Step 6 — Send Direct Messages Between Agents
-
-Use channels for point-to-point communication that does not go through the shared state.
-
-```python
-# step6_channels.py
-import asyncio
-import sys, os
-sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
-
-from ContextStore import ContextStore
-
-async def main():
- store = ContextStore()
-
- # coordinator sends two commands to worker
- await store.send("coordinator", "worker", {"cmd": "run_report", "format": "pdf"})
- await store.send("coordinator", "worker", {"cmd": "upload", "dest": "s3://bucket"})
-
- # auditor sends a health check to worker
- await store.send("auditor", "worker", {"cmd": "health_check"})
-
- # worker drains its entire inbox (all senders, sorted by time)
- inbox = await store.inbox("worker")
- print(f"Worker has {len(inbox)} message(s):")
- for msg in inbox:
- print(f" from={msg.sender:<15} payload={msg.payload}")
-
- # inbox is now empty
- print("Inbox after drain:", await store.inbox("worker"))
-
-asyncio.run(main())
-```
-
----
-
-## Step 7 — Write Time-Limited Data with TTL
-
-Entries with a TTL are automatically evicted after the specified number of seconds.
-
-```python
-# step7_ttl.py
-import asyncio
-import sys, os
-sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
-
-from ContextStore import ContextStore, ContextNamespace
-
-async def main():
- store = ContextStore()
- ns = ContextNamespace(store, "pipeline_v1")
-
- # Write a heartbeat that expires in 3 seconds
- await ns.put("heartbeat", {"alive": True, "load": 0.42}, writer="worker", ttl=3)
-
- print("Immediate read:", await ns.get("heartbeat")) # {'alive': True, 'load': 0.42}
-
- await asyncio.sleep(3.5)
-
- print("After 3.5 s: ", await ns.get("heartbeat")) # None (expired)
-
- # Optional: batch-remove any remaining stale entries
- removed = await ns.cleanup_expired()
- print(f"Cleaned up {removed} expired key(s)")
-
-asyncio.run(main())
-```
-
----
-
-## Step 8 — Connect Agents to ContextStore
-
-Combine the agent framework with `ContextStore` to build a full pipeline.
-
-```python
-# step8_pipeline.py
-import asyncio
-import time
-import sys, os
-sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
-
-from Framework import BaseAgent, AgentMessage
-from ContextStore import ContextStore, ContextNamespace, ContextRecord
-
-store = ContextStore()
-ns = ContextNamespace(store, "pipeline")
-
-
-class CoordinatorAgent(BaseAgent):
- async def _process_impl(self, message: AgentMessage) -> AgentMessage:
- task = {"id": "t1", "desc": message.content}
- await ns.put("task", task, writer=self.name)
- await ns.put("status", "pending", writer=self.name)
- return AgentMessage(content=f"Task assigned: {task['id']}",
- sender=self.name, timestamp=time.time())
-
-
-class WorkerAgent(BaseAgent):
- async def _process_impl(self, message: AgentMessage) -> AgentMessage:
- task = await ns.get("task")
- if task is None:
- return AgentMessage(content="No task found",
- sender=self.name, timestamp=time.time())
-
- await ns.put("status", "in_progress", writer=self.name)
- # Simulate work
- await asyncio.sleep(0.1)
- await ns.put("result", {"task_id": task["id"], "output": "done"},
- writer=self.name, tags=["output"])
- await ns.put("status", "completed", writer=self.name)
- return AgentMessage(content="Work completed", sender=self.name, timestamp=time.time())
-
-
-async def main():
- coordinator = CoordinatorAgent(name="coordinator")
- worker = WorkerAgent(name="worker")
-
- # Monitor all context changes
- def log(key: str, record: ContextRecord) -> None:
- print(f" [monitor] {key} = {record.value!r}")
- ns.subscribe("monitor", log)
-
- print("=== Coordinator assigns task ===")
- r = await coordinator.process(AgentMessage(
- content="Analyse Q1 sales", sender="orchestrator", timestamp=time.time()
- ))
- print(r.content)
-
- print("\n=== Worker processes task ===")
- r = await worker.process(AgentMessage(
- content="start", sender="orchestrator", timestamp=time.time()
- ))
- print(r.content)
-
- print("\n=== Final state ===")
- print("status:", await ns.get("status"))
- print("result:", await ns.get("result"))
-
- print("\n=== Status history ===")
- for rec in await ns.history("status"):
- print(f" v{rec.version} [{rec.writer}] -> {rec.value!r}")
-
-asyncio.run(main())
-```
-
----
-
-## Patterns at a Glance
-
-| Goal | What to use |
-|---|---|
-| Build a new agent | Subclass `BaseAgent`, implement `_process_impl` |
-| Run multiple agents | `AgentManager.register_agent()` + `send_message()` |
-| Share data between agents | `ContextStore` / `ContextNamespace` — `put()` / `get()` |
-| React to data changes | `ns.subscribe(agent_id, callback)` |
-| Send agent-to-agent commands | `store.send()` / `store.inbox()` |
-| Expire data automatically | `ns.put(..., ttl=<seconds>)` |
-| Audit what was written | `ns.history(key)` |
-| Filter entries by author/tag | `ns.query(writer=..., tags=[...])` |
-
----
-
-## Legacy API (SharedContext)
-
-If you need the older synchronous API, use `SharedContext` + `ContextBridge` directly. The `SharedContext_Demo.py` file shows the full pattern. Note that `ContextBridge` loads its dependency using a custom `importlib` loader — refer to the demo's `_load()` helper for the correct usage.
-
-For all new development, use `ContextStore`.
diff --git a/Agent_module/README.md b/Agent_module/README.md
index b05aa6d82a..f62a9f6009 100644
--- a/Agent_module/README.md
+++ b/Agent_module/README.md
@@ -1,230 +1,62 @@
# Agent Module
-A Python multi-agent framework providing an abstract agent base class, an orchestration manager, and a thread-safe async context sharing system.
+A small multi-agent framework with a thread-safe async context store.
----
-
-## Directory Structure
-
-```
-Agent_module/
-├── Framework.py # Core abstractions: BaseAgent, AgentMessage, AgentStatus
-├── Manager.py # Multi-agent orchestration and routing
-├── Implementation.py # Built-in agents: Echo / Calculator / Weather / Translator
-├── Chat_Agent.py # Rule-based conversational agent
-├── ContextStore.py # Unified async context store (recommended)
-├── SharedContext.py # Synchronous shared memory (legacy)
-├── ContextBridge.py # Pub/sub bridge for SharedContext (legacy)
-├── Agent_Demo.py # Full agent system demo
-├── ContextStore_Demo.py # ContextStore feature demo
-├── SharedContext_Demo.py # SharedContext feature demo
-└── Example/
- └── Agent_format_example.py # Complete LLM-oriented agent data structure example
-```
-
----
-
-## Core Modules
-
-### Framework.py — Base Abstraction
-
-Shared base class and data models for all agents.
-
-```python
-from Framework import BaseAgent, AgentMessage, AgentStatus
-import time
-
-class MyAgent(BaseAgent):
- def __init__(self):
- super().__init__(name="MyAgent", description="An example agent")
-
- async def _process_impl(self, message: AgentMessage) -> AgentMessage:
- return AgentMessage(
- content=f"Processed: {message.content}",
- sender=self.name,
- timestamp=time.time()
- )
-```
-
-**`AgentMessage` fields**
-
-| Field | Type | Description |
-|---|---|---|
-| `content` | `Any` | Message payload |
-| `sender` | `str` | Sender identifier |
-| `timestamp` | `float` | Unix timestamp |
-| `message_type` | `str` | Type label (default: `"text"`) |
-| `metadata` | `dict` | Arbitrary additional data |
-
-**`AgentStatus` enum**: `IDLE` / `PROCESSING` / `ERROR` / `STOPPED`
-
----
-
-### Manager.py — Orchestration Layer
-
-Register multiple agents with support for unicast, broadcast, and capability discovery.
-
-```python
-from Manager import AgentManager
-
-manager = AgentManager()
-manager.register_agent(MyAgent())
-
-# Unicast to a specific agent
-response = await manager.send_message("MyAgent", "hello")
-
-# Broadcast to all agents concurrently (asyncio.gather)
-responses = await manager.broadcast_message("ping")
-
-# Discover agents by capability keyword
-agents = manager.find_agent_by_capability("calculation")
-
-# System statistics
-stats = manager.get_system_stats()
-```
+**Requirements:** Python 3.10+. No third-party packages required (pytest only for the test suite).
---
-### ContextStore.py — Async Context Store (Recommended)
-
-The unified data exchange layer for multi-agent systems. Replaces the legacy `SharedContext` + `ContextBridge` pair.
-
-#### Features
-
-| Feature | Description |
-|---|---|
-| Async-first | All read/write operations are `async`, protected by `asyncio.Lock` |
-| Write history | Each key retains the last 50 write records |
-| P2P channels | `send` / `receive` / `inbox` FIFO queues between agents |
-| Pub/sub | Subscribers are notified after every `put()`; supports sync and async callbacks |
-| TTL eviction | Lazy expiry on reads; batch eviction via `cleanup_expired()` |
-| Namespace isolation | Multi-tenancy support; `ContextNamespace` provides a scoped proxy view |
-| Merge strategy | Last-write-wins by version number; supports cross-store merging |
-| Serialization | Full snapshot and restore via `to_dict()` / `to_json()` |
-
-#### State Read / Write
-
-```python
-from ContextStore import ContextStore, ContextNamespace
-
-store = ContextStore()
-ns = ContextNamespace(store, "pipeline_v1")
-
-# Write a value
-record = await ns.put("status", "running", writer="coordinator")
-
-# Read the current value
-value = await ns.get("status")
-
-# Read the full entry (current record + history)
-entry = await ns.get_entry("status")
+## Layout
-# Write history, newest-first
-history = await ns.history("status")
-
-# Write with TTL (seconds)
-await ns.put("heartbeat", {"alive": True}, writer="worker", ttl=30)
-
-# Write with tags
-await ns.put("result", data, writer="worker", tags=["output"])
-
-# Query by writer and/or tags
-entries = await ns.query(writer="worker", tags=["output"])
```
-
-#### P2P Message Channels
-
-```python
-# Send a message from coordinator to worker
-await store.send("coordinator", "worker", {"cmd": "run"})
-
-# Receive the next message from a specific channel
-msg = await store.receive("coordinator", "worker")
-
-# Collect all pending messages for worker (across all senders, sorted by time)
-inbox = await store.inbox("worker")
-```
-
-#### Pub/Sub
-
-```python
-async def on_change(key: str, record) -> None:
- print(f"Changed: {key} = {record.value}")
-
-# Subscribe to all keys in the namespace
-ns.subscribe("monitor", on_change)
-
-# Subscribe to specific keys only
-ns.subscribe("monitor", on_change, keys=["status", "result"])
-
-# Unsubscribe
-ns.unsubscribe("monitor")
-```
-
-> Writers do not receive their own notifications. Callbacks fire after the lock is released to prevent re-entrant deadlocks.
-
-#### Maintenance and Serialization
-
-```python
-# Remove all expired entries
-removed = await ns.cleanup_expired()
-
-# Deep-copy snapshot of current state
-snapshot = await ns.snapshot()
-
-# Merge another ContextStore (last-write-wins by version)
-merged = await store.merge(other_store, namespace="pipeline_v1")
-
-# Store statistics
-stats = await store.stats()
-
-# Full JSON serialization
-json_str = await store.to_json()
+Agent_module/
+├── __init__.py # Re-exports the public API
+├── framework.py # BaseAgent, AgentMessage, AgentStatus
+├── manager.py # AgentManager — registry + routing
+├── agents.py # Built-in agents (Echo/Calculator/Weather/Translator/Chat)
+├── safe_eval.py # AST-based arithmetic evaluator (no eval())
+├── context_store.py # Async context store + P2P channels + pub/sub
+├── demos/
+│ ├── agent_demo.py # Agent system walkthrough
+│ └── context_store_demo.py # ContextStore walkthrough
+├── examples/
+│ ├── 01_data_models.py # LLM-oriented agent data format
+│ ├── agent_format_example.py # Same, with a worked example
+│ ├── 02_framework_agents.py # Integration tests for agents
+│ ├── 03_agent_manager.py # Integration tests for the manager
+│ ├── 04_context_store.py # Integration tests for ContextStore
+│ └── run_all.py # Runs every example and prints a summary
+└── tests/
+ ├── test_safe_eval.py # pytest: safe_eval arithmetic + rejections
+ └── test_async_callbacks.py # pytest: sync/async callback dispatch
```
---
-### Built-in Agents
-
-| Agent | Description |
-|---|---|
-| `EchoAgent` | Echoes back every received message |
-| `CalculatorAgent` | Evaluates math expressions (character whitelist filter) |
-| `WeatherAgent` | Simulated weather lookup (4 preset cities; random data for others) |
-| `TranslatorAgent` | Simulated translation; target language set via `metadata.target_language` |
-| `ChatAgent` | Rule-based conversational agent with greeting / Q&A / routing intent detection |
-
----
-
## Quick Start
-### Single Agent
+### Single agent
```python
import asyncio
-import time
-from Framework import AgentMessage
-from Implementation import CalculatorAgent
+from Agent_module import AgentMessage, CalculatorAgent
async def main():
agent = CalculatorAgent()
response = await agent.process(AgentMessage(
content="(15 + 25) * 2",
sender="User",
- timestamp=time.time()
))
- print(response.content) # (15 + 25) * 2 = 80
+ print(response.content) # (15 + 25) * 2 = 80
asyncio.run(main())
```
-### Multi-Agent Orchestration
+### Multiple agents via `AgentManager`
```python
import asyncio
-from Manager import AgentManager
-from Implementation import CalculatorAgent, WeatherAgent
-from Chat_Agent import ChatAgent
+from Agent_module import AgentManager, CalculatorAgent, WeatherAgent, ChatAgent
async def main():
manager = AgentManager()
@@ -232,36 +64,50 @@ async def main():
manager.register_agent(WeatherAgent())
manager.register_agent(ChatAgent())
- result = await manager.send_message("CalculatorAgent", "3.14 * 2")
- print(result.content)
+ print((await manager.send_message("CalculatorAgent", "3.14 * 2")).content)
+ print((await manager.send_message("WeatherAgent", "Tokyo")).content)
- weather = await manager.send_message("WeatherAgent", "Tokyo")
- print(weather.content)
+ responses = await manager.broadcast_message("Hello!")
+ for name, r in responses.items():
+ print(f"{name}: {r.content[:60]}")
asyncio.run(main())
```
-### Shared Context Between Agents
+### Writing your own agent
+
+Subclass `BaseAgent` and implement `_process_impl`:
+
+```python
+from Agent_module import AgentMessage, BaseAgent
+
+class GreetingAgent(BaseAgent):
+ def __init__(self):
+ super().__init__(name="GreetingAgent", description="Says hi")
+
+ async def _process_impl(self, message: AgentMessage) -> AgentMessage:
+ name = message.metadata.get("user_name", "stranger")
+ return AgentMessage(content=f"Hello, {name}!", sender=self.name)
+```
+
+### Shared context across agents
```python
import asyncio
-from ContextStore import ContextStore, ContextNamespace
+from Agent_module import ContextStore, ContextNamespace
async def main():
store = ContextStore()
ns = ContextNamespace(store, "my_pipeline")
- # Coordinator assigns a task
await ns.put("task", {"id": "001", "desc": "Process data"}, writer="coordinator")
await ns.put("status", "pending", writer="coordinator")
- # Worker processes the task
task = await ns.get("task")
await ns.put("status", "in_progress", writer="worker")
await ns.put("result", {"processed": 1000}, writer="worker")
await ns.put("status", "completed", writer="worker")
- # Inspect write history
for r in await ns.history("status"):
print(f"v{r.version} [{r.writer}] -> {r.value}")
@@ -270,39 +116,65 @@ asyncio.run(main())
---
-## Running the Demos
+## Public API
-```bash
-# Agent system demo (single agent + multi-agent broadcast)
-python3 Agent_Demo.py
+### `framework.py`
-# ContextStore feature demo (pub/sub, channels, TTL, merge, serialization)
-python3 ContextStore_Demo.py
+| Symbol | Notes |
+|---|---|
+| `AgentStatus` | Enum: `IDLE`, `PROCESSING`, `ERROR`, `STOPPED` |
+| `AgentMessage` | Dataclass — `content`, `sender`, `timestamp` (default=now), `message_type`, `metadata` |
+| `BaseAgent` | Abstract base. Subclasses implement `async _process_impl`. `add_callback()` accepts **sync or async** callables. |
-# SharedContext feature demo (legacy synchronous API)
-python3 SharedContext_Demo.py
+### `manager.py`
-# Agent data structure format demo (LLM-oriented)
-python3 Example/Agent_format_example.py
-```
+`AgentManager` — `register_agent`, `send_message`, `broadcast_message` (concurrent via `asyncio.gather`), `find_agent_by_capability`, `get_system_stats`.
+
+### `agents.py`
+
+| Agent | Summary |
+|---|---|
+| `EchoAgent` | Echoes every input |
+| `CalculatorAgent` | Arithmetic via `safe_eval` — only `+ - * / // % **` and numeric literals |
+| `WeatherAgent` | Simulated: four preset cities, random data for others |
+| `TranslatorAgent` | Simulated; target language from `metadata.target_language` |
+| `ChatAgent` | Rule-based, keeps per-user context |
+
+### `context_store.py`
+
+| Feature | Description |
+|---|---|
+| Async-first | Every read/write is `async`, protected by `asyncio.Lock` |
+| Write history | Up to 50 records per key |
+| P2P channels | `send` / `receive` / `inbox` FIFO queues between agents |
+| Pub/sub | Subscribers notified after `put()`; sync + async callbacks |
+| TTL | Lazy eviction on reads; batch via `cleanup_expired()` |
+| Namespaces | Multi-tenant isolation; `ContextNamespace` is a scoped proxy |
+| Merge | Last-write-wins by version number |
+| Serialisation | `snapshot()`, `to_dict()`, `to_json()` |
+
+Writers do not receive their own notifications. Callbacks fire **after** the store lock is released — safe from re-entrant deadlocks.
---
-## Module Evolution
+## Running
-```
-SharedContext.py + ContextBridge.py <- Legacy (synchronous, not thread-safe)
- |
- v refactored
- ContextStore.py <- Current recommendation (async, thread-safe)
-```
+Run as a package (from the repo root):
+
+```bash
+# Demos
+python3 -m Agent_module.demos.agent_demo
+python3 -m Agent_module.demos.context_store_demo
+
+# Integration tests
+python3 Agent_module/examples/run_all.py
-`SharedContext` and `ContextBridge` are retained for reference. New development should use `ContextStore` directly.
+# Unit tests
+pytest Agent_module/tests/ -v
+```
---
-## Notes
+## Notes on security
-- **`ContextBridge.py`**: Loads its dependency via `importlib` using a `.python` file extension, which does not match the current `.py` extension. Direct import will fail. Refer to `SharedContext_Demo.py` for the correct loading pattern if you need the legacy API.
-- **`CalculatorAgent`**: Uses a character whitelist before calling `eval()`. Suitable only for trusted input. Replace with a dedicated math parser library for production use.
-- **`SharedContext`** is not thread-safe. Use `ContextStore` for any concurrent workload.
+`CalculatorAgent` uses `safe_eval.py`, which parses the input with `ast.parse` and only accepts arithmetic nodes — attribute access, function calls, names, comprehensions, and comparisons are rejected *before* any code runs. It is safe to feed untrusted input.
diff --git a/Agent_module/SharedContext.py b/Agent_module/SharedContext.py
deleted file mode 100644
index e7eb96291f..0000000000
--- a/Agent_module/SharedContext.py
+++ /dev/null
@@ -1,216 +0,0 @@
-from dataclasses import dataclass, field
-from typing import Any, Dict, List, Optional
-from datetime import datetime
-import copy
-import json
-
-# ============================================================================
-# Core Data Models — Shared Context
-# NOTE: SharedContext is NOT thread-safe by default. For concurrent access,
-# callers must provide external locking (e.g., threading.Lock).
-# ============================================================================
-
-@dataclass
-class ContextEntry:
- """A single key/value entry written by an agent into the shared context."""
- key: str
- value: Any
- agent_id: str
- timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
- version: int = 1
- ttl: Optional[int] = None # seconds until expiry; None = forever
- tags: List[str] = field(default_factory=list)
-
- def is_expired(self) -> bool:
- """Return True if this entry has passed its TTL."""
- if self.ttl is None:
- return False
- written_at = datetime.fromisoformat(self.timestamp)
- elapsed = (datetime.now() - written_at).total_seconds()
- return elapsed > self.ttl
-
- def to_dict(self) -> Dict[str, Any]:
- return {
- "key": self.key,
- "value": self.value,
- "agent_id": self.agent_id,
- "timestamp": self.timestamp,
- "version": self.version,
- "ttl": self.ttl,
- "tags": self.tags,
- }
-
- @classmethod
- def from_dict(cls, data: Dict[str, Any]) -> "ContextEntry":
- return cls(
- key=data["key"],
- value=data["value"],
- agent_id=data["agent_id"],
- timestamp=data.get("timestamp", datetime.now().isoformat()),
- version=data.get("version", 1),
- ttl=data.get("ttl"),
- tags=data.get("tags", []),
- )
-
-
-@dataclass
-class SharedContext:
- """
- A namespace-scoped shared memory store for multiple agents.
-
- Agents read and write ContextEntry objects keyed by string.
- Version numbers enable last-write-wins conflict resolution during merge.
-
- NOTE: Not thread-safe. Use external locking for concurrent access.
- """
- namespace: str
- entries: Dict[str, ContextEntry] = field(default_factory=dict)
- version: int = 0
- created_at: str = field(default_factory=lambda: datetime.now().isoformat())
- updated_at: str = field(default_factory=lambda: datetime.now().isoformat())
-
- # ------------------------------------------------------------------
- # Write
- # ------------------------------------------------------------------
-
- def set(
- self,
- key: str,
- value: Any,
- agent_id: str,
- ttl: Optional[int] = None,
- tags: Optional[List[str]] = None,
- ) -> ContextEntry:
- """Write a value. Bumps the store-level version counter."""
- existing = self.entries.get(key)
- entry_version = (existing.version + 1) if existing else 1
-
- entry = ContextEntry(
- key=key,
- value=value,
- agent_id=agent_id,
- version=entry_version,
- ttl=ttl,
- tags=tags or [],
- )
- self.entries[key] = entry
- self.version += 1
- self.updated_at = datetime.now().isoformat()
- return entry
-
- # ------------------------------------------------------------------
- # Read
- # ------------------------------------------------------------------
-
- def get(self, key: str) -> Optional[Any]:
- """Return the value for *key*, or None if missing or TTL-expired."""
- entry = self.entries.get(key)
- if entry is None:
- return None
- if entry.is_expired():
- del self.entries[key]
- return None
- return entry.value
-
- def get_entry(self, key: str) -> Optional[ContextEntry]:
- """Return the full ContextEntry for *key*, or None if missing/expired."""
- entry = self.entries.get(key)
- if entry is None:
- return None
- if entry.is_expired():
- del self.entries[key]
- return None
- return entry
-
- # ------------------------------------------------------------------
- # Delete
- # ------------------------------------------------------------------
-
- def delete(self, key: str, agent_id: str) -> bool:
- """Remove *key* from the store. Returns True if it existed."""
- if key in self.entries:
- del self.entries[key]
- self.version += 1
- self.updated_at = datetime.now().isoformat()
- return True
- return False
-
- # ------------------------------------------------------------------
- # Iteration helpers
- # ------------------------------------------------------------------
-
- def keys(self) -> List[str]:
- """Return all non-expired keys."""
- self.cleanup_expired()
- return list(self.entries.keys())
-
- def items(self) -> List[tuple]:
- """Return all non-expired (key, value) pairs."""
- self.cleanup_expired()
- return [(k, e.value) for k, e in self.entries.items()]
-
- # ------------------------------------------------------------------
- # Snapshot / merge
- # ------------------------------------------------------------------
-
- def snapshot(self) -> Dict[str, Any]:
- """Return a deep copy of the current (non-expired) entries as a dict."""
- self.cleanup_expired()
- return copy.deepcopy({k: e.to_dict() for k, e in self.entries.items()})
-
- def merge(self, other: "SharedContext") -> None:
- """
- Merge *other* into this context using last-write-wins by entry version.
- Only entries with a higher version number replace existing ones.
- """
- for key, other_entry in other.entries.items():
- existing = self.entries.get(key)
- if existing is None or other_entry.version > existing.version:
- self.entries[key] = copy.deepcopy(other_entry)
- self.version = max(self.version, other.version)
- self.updated_at = datetime.now().isoformat()
-
- # ------------------------------------------------------------------
- # Maintenance
- # ------------------------------------------------------------------
-
- def cleanup_expired(self) -> List[str]:
- """Remove all TTL-expired entries. Returns the list of removed keys."""
- expired = [k for k, e in self.entries.items() if e.is_expired()]
- for k in expired:
- del self.entries[k]
- if expired:
- self.updated_at = datetime.now().isoformat()
- return expired
-
- # ------------------------------------------------------------------
- # Serialisation
- # ------------------------------------------------------------------
-
- def to_dict(self) -> Dict[str, Any]:
- return {
- "namespace": self.namespace,
- "entries": {k: e.to_dict() for k, e in self.entries.items()},
- "version": self.version,
- "created_at": self.created_at,
- "updated_at": self.updated_at,
- }
-
- def to_json(self, indent: int = 2) -> str:
- return json.dumps(self.to_dict(), indent=indent, ensure_ascii=False)
-
- @classmethod
- def from_dict(cls, data: Dict[str, Any]) -> "SharedContext":
- ctx = cls(
- namespace=data["namespace"],
- version=data.get("version", 0),
- created_at=data.get("created_at", datetime.now().isoformat()),
- updated_at=data.get("updated_at", datetime.now().isoformat()),
- )
- for key, entry_data in data.get("entries", {}).items():
- ctx.entries[key] = ContextEntry.from_dict(entry_data)
- return ctx
-
- @classmethod
- def from_json(cls, json_str: str) -> "SharedContext":
- return cls.from_dict(json.loads(json_str))
diff --git a/Agent_module/SharedContext_Demo.py b/Agent_module/SharedContext_Demo.py
deleted file mode 100644
index 484edc1ea3..0000000000
--- a/Agent_module/SharedContext_Demo.py
+++ /dev/null
@@ -1,217 +0,0 @@
-"""
-SharedContext_Demo.python
-=========================
-End-to-end demonstration of multi-agent shared memory.
-
-Scenario
---------
- coordinator — assigns a task, sets status to "pending"
- worker — picks up the task, processes it, writes result back
- monitor — passive observer; callback fires on every change
-
-Run:
- python3 Agent_module/SharedContext_Demo.python
-"""
-
-import sys, os, json, time, importlib.util as _ilu
-
-def _load(name: str):
- from importlib.machinery import SourceFileLoader
- here = os.path.dirname(os.path.abspath(__file__))
- path = os.path.join(here, f"{name}.python")
- loader = SourceFileLoader(name, path)
- spec = _ilu.spec_from_loader(name, loader)
- mod = _ilu.module_from_spec(spec)
- sys.modules[name] = mod
- loader.exec_module(mod)
- return mod
-
-_sc = _load("SharedContext")
-_cb = _load("ContextBridge")
-
-SharedContext = _sc.SharedContext
-ContextEntry = _sc.ContextEntry
-ContextBridge = _cb.ContextBridge
-
-# ============================================================================
-# Helper: pretty section headers
-# ============================================================================
-
-def section(title: str) -> None:
- print("\n" + "=" * 70)
- print(f" {title}")
- print("=" * 70)
-
-
-# ============================================================================
-# Monitor callback — fires whenever a subscribed key changes
-# ============================================================================
-
-_change_log: list = [] # record all changes for summary at the end
-
-def monitor_callback(key: str, entry: ContextEntry) -> None:
- msg = (
- f"[MONITOR] key={key!r:20s} "
- f"agent={entry.agent_id:15s} "
- f"value={str(entry.value)!r:.60s}"
- )
- print(msg)
- _change_log.append({"key": key, "agent_id": entry.agent_id, "value": entry.value})
-
-
-# ============================================================================
-# Main demo
-# ============================================================================
-
-def main() -> None:
-
- # ------------------------------------------------------------------
- # 1. Create SharedContext and wrap in ContextBridge
- # ------------------------------------------------------------------
- section("1. Setup — SharedContext + ContextBridge")
-
- ctx = SharedContext(namespace="data_pipeline_v1")
- bridge = ContextBridge(ctx)
-
- # ------------------------------------------------------------------
- # 2. Register agents
- # ------------------------------------------------------------------
- section("2. Agent registration")
-
- # Monitor subscribes to ALL keys (empty keys list)
- bridge.register_agent("monitor", monitor_callback, keys=[])
-
- # Coordinator and worker subscribe to keys they care about,
- # but we skip giving them callbacks in this demo (they act, not react).
- bridge.register_agent("coordinator", lambda k, e: None, keys=["result"])
- bridge.register_agent("worker", lambda k, e: None, keys=["task", "status"])
-
- print(" Registered: coordinator, worker, monitor")
-
- # ------------------------------------------------------------------
- # 3. Coordinator writes task + initial status
- # ------------------------------------------------------------------
- section("3. Coordinator assigns task")
-
- bridge.write(
- agent_id="coordinator",
- key="task",
- value={
- "id": "task_001",
- "description": "Analyse sales data for Q1",
- "priority": "high",
- },
- )
- bridge.write(agent_id="coordinator", key="status", value="pending")
- bridge.write(
- agent_id="coordinator",
- key="deadline",
- value="2026-02-18T18:00:00",
- tags=["meta"],
- )
-
- # ------------------------------------------------------------------
- # 4. Worker reads task, updates status, writes result
- # ------------------------------------------------------------------
- section("4. Worker processes task")
-
- task = bridge.read("worker", "task")
- print(f" Worker received task: {task}")
-
- bridge.write(agent_id="worker", key="status", value="in_progress")
-
- # Simulate processing
- print(" Worker processing …")
- time.sleep(0.05)
-
- bridge.write(
- agent_id="worker",
- key="result",
- value={
- "task_id": task["id"],
- "summary": "Q1 revenue up 12 % YoY; top SKU: widget-X",
- "rows_processed": 14_320,
- },
- )
- bridge.write(agent_id="worker", key="status", value="completed")
-
- # ------------------------------------------------------------------
- # 5. Short-lived TTL entry (expires in 2 seconds)
- # ------------------------------------------------------------------
- section("5. TTL demo — heartbeat entry (TTL = 2 s)")
-
- bridge.write(
- agent_id="worker",
- key="heartbeat",
- value={"alive": True, "load": 0.42},
- ttl=2,
- tags=["health"],
- )
- print(" heartbeat written (TTL=2s)")
- print(f" Immediate read → {bridge.read('coordinator', 'heartbeat')}")
-
- print(" Sleeping 3 s …")
- time.sleep(3)
-
- expired_val = bridge.read("coordinator", "heartbeat")
- print(f" After 3 s read → {expired_val} (None = expired correctly)")
-
- removed = ctx.cleanup_expired()
- print(f" cleanup_expired() removed: {removed}")
-
- # ------------------------------------------------------------------
- # 6. Atomic broadcast
- # ------------------------------------------------------------------
- section("6. Atomic broadcast by coordinator")
-
- bridge.broadcast(
- agent_id="coordinator",
- data={
- "audit_approved": True,
- "reviewer": "agent_audit_bot",
- },
- tags=["audit"],
- )
-
- # ------------------------------------------------------------------
- # 7. Full context snapshot
- # ------------------------------------------------------------------
- section("7. Full context snapshot (read_all)")
-
- snapshot = bridge.read_all("monitor")
- print(json.dumps(snapshot, indent=2, ensure_ascii=False))
-
- # ------------------------------------------------------------------
- # 8. Merge demo
- # ------------------------------------------------------------------
- section("8. Merge — remote snapshot into local context")
-
- remote_ctx = SharedContext(namespace="data_pipeline_v1")
- remote_ctx.set("status", "archived", "archiver")
- remote_ctx.set("archived_at", "2026-02-18T19:00:00", "archiver")
-
- ctx.merge(remote_ctx)
- print(" Merged remote context (status overridden by higher version).")
- print(f" status after merge → {ctx.get('status')!r}")
-
- # ------------------------------------------------------------------
- # 9. Export final context to JSON
- # ------------------------------------------------------------------
- section("9. Final context — to_json() export")
-
- print(ctx.to_json())
-
- # ------------------------------------------------------------------
- # 10. Monitor change summary
- # ------------------------------------------------------------------
- section("10. Monitor change log summary")
-
- print(f" Total changes observed by monitor: {len(_change_log)}")
- for i, entry in enumerate(_change_log, 1):
- print(f" {i:2d}. [{entry['agent_id']:15s}] {entry['key']}")
-
- section("Demo complete")
-
-
-if __name__ == "__main__":
- main()
diff --git a/Agent_module/__init__.py b/Agent_module/__init__.py
new file mode 100644
index 0000000000..24bd81c104
--- /dev/null
+++ b/Agent_module/__init__.py
@@ -0,0 +1,48 @@
+"""
+Agent_module
+============
+Multi-agent framework with an async context store.
+
+Public API:
+
+ from Agent_module import (
+ AgentMessage, AgentStatus, BaseAgent,
+ AgentManager,
+ EchoAgent, CalculatorAgent, WeatherAgent, TranslatorAgent, ChatAgent,
+ ContextStore, ContextNamespace, ContextRecord, ContextEntry, ContextMessage,
+ )
+"""
+
+from .framework import AgentMessage, AgentStatus, BaseAgent
+from .manager import AgentManager
+from .agents import (
+ EchoAgent,
+ CalculatorAgent,
+ WeatherAgent,
+ TranslatorAgent,
+ ChatAgent,
+)
+from .context_store import (
+ ContextStore,
+ ContextNamespace,
+ ContextRecord,
+ ContextEntry,
+ ContextMessage,
+)
+
+__all__ = [
+ "AgentMessage",
+ "AgentStatus",
+ "BaseAgent",
+ "AgentManager",
+ "EchoAgent",
+ "CalculatorAgent",
+ "WeatherAgent",
+ "TranslatorAgent",
+ "ChatAgent",
+ "ContextStore",
+ "ContextNamespace",
+ "ContextRecord",
+ "ContextEntry",
+ "ContextMessage",
+]
diff --git a/Agent_module/agents.py b/Agent_module/agents.py
new file mode 100644
index 0000000000..8ecad89387
--- /dev/null
+++ b/Agent_module/agents.py
@@ -0,0 +1,205 @@
+"""
+agents.py
+=========
+Built-in agent implementations.
+
+ EchoAgent — echoes every input
+ CalculatorAgent — arithmetic via safe_eval (no eval/import access)
+ WeatherAgent — simulated weather lookup
+ TranslatorAgent — simulated translation
+ ChatAgent — rule-based conversational agent with per-user context
+"""
+
+from __future__ import annotations
+
+import asyncio
+import random
+import time
+from typing import Any
+
+from .framework import AgentMessage, BaseAgent
+from .safe_eval import safe_eval
+
+
+class EchoAgent(BaseAgent):
+ """Repeats every received message."""
+
+ def __init__(self, name: str = "EchoAgent") -> None:
+ super().__init__(name, "Echoes back received messages")
+
+ async def _process_impl(self, message: AgentMessage) -> AgentMessage:
+ await asyncio.sleep(0.1)
+ return AgentMessage(
+ content=f"Echo: {message.content}",
+ sender=self.name,
+ message_type="echo_response",
+ )
+
+
+class CalculatorAgent(BaseAgent):
+ """Evaluates arithmetic expressions using an AST allowlist."""
+
+ def __init__(self, name: str = "CalculatorAgent") -> None:
+ super().__init__(name, "Performs mathematical calculations")
+
+ async def _process_impl(self, message: AgentMessage) -> AgentMessage:
+ expression = str(message.content).strip()
+ try:
+ result = safe_eval(expression)
+ return AgentMessage(
+ content=f"{expression} = {result}",
+ sender=self.name,
+ message_type="calculation_result",
+ )
+ except (ValueError, ZeroDivisionError, OverflowError) as exc:
+ return AgentMessage(
+ content=f"Calculation error: {exc}",
+ sender=self.name,
+ message_type="error",
+ )
+
+
+class WeatherAgent(BaseAgent):
+ """Simulated weather lookup: four preset cities, random data for others."""
+
+ _PRESETS: dict[str, dict[str, Any]] = {
+ "New York": {"temp": 22, "condition": "Sunny", "humidity": 65},
+ "London": {"temp": 15, "condition": "Cloudy", "humidity": 80},
+ "Tokyo": {"temp": 18, "condition": "Rainy", "humidity": 75},
+ "Sydney": {"temp": 25, "condition": "Clear", "humidity": 60},
+ }
+
+ def __init__(self, name: str = "WeatherAgent") -> None:
+ super().__init__(name, "Provides weather information")
+
+ async def _process_impl(self, message: AgentMessage) -> AgentMessage:
+ location = str(message.content).strip().title()
+ await asyncio.sleep(0.2)
+
+ if location in self._PRESETS:
+ w = self._PRESETS[location]
+ body = (
+ f"Weather in {location}:\n"
+ f"Temperature: {w['temp']}°C\n"
+ f"Condition: {w['condition']}\n"
+ f"Humidity: {w['humidity']}%"
+ )
+ else:
+ body = (
+ f"Weather in {location} (simulated):\n"
+ f"Temperature: {random.randint(-10, 35)}°C\n"
+ f"Condition: {random.choice(['Sunny', 'Cloudy', 'Rainy', 'Snowy'])}\n"
+ f"Humidity: {random.randint(30, 95)}%"
+ )
+
+ return AgentMessage(
+ content=body,
+ sender=self.name,
+ message_type="weather_report",
+ )
+
+
+class TranslatorAgent(BaseAgent):
+ """Simulated translator. Target language set via metadata.target_language."""
+
+ _SUPPORTED = ["english", "spanish", "french", "german", "italian"]
+
+ def __init__(self, name: str = "TranslatorAgent") -> None:
+ super().__init__(name, "Translates text between languages")
+
+ async def _process_impl(self, message: AgentMessage) -> AgentMessage:
+ text = str(message.content)
+ target = str(message.metadata.get("target_language", "spanish")).lower()
+ await asyncio.sleep(0.3)
+
+ if target not in self._SUPPORTED:
+ body = (
+ f"Sorry, I don't support {target}. "
+ f"Supported languages: {', '.join(self._SUPPORTED)}"
+ )
+ else:
+ body = f"[{target.upper()} TRANSLATION] {text} -> Translated text in {target}"
+
+ return AgentMessage(
+ content=body,
+ sender=self.name,
+ message_type="translation",
+ )
+
+
+class ChatAgent(BaseAgent):
+ """Rule-based conversational agent with per-user context."""
+
+ _GREETINGS = ("hello", "hi", "hey", "greetings")
+ _QUESTION_WORDS = ("what", "how", "when", "where", "why")
+
+ _GREETING_REPLIES = (
+ "Hello! How can I assist you today?",
+ "Hi there! What can I help you with?",
+ "Greetings! I'm here to help.",
+ "Hello! Nice to meet you.",
+ )
+ _DEFAULT_REPLIES = (
+ "That's interesting! Can you tell me more?",
+ "I understand. How can I help you with that?",
+ "Thanks for sharing! Is there anything specific you'd like to know?",
+ "I see. What would you like to do next?",
+ )
+ _FALLBACK_QA = (
+ "That's a good question! Let me think about it...",
+ "I'm not entirely sure about that, but I'd be happy to help you find out!",
+ "Interesting question! Here's what I know about that topic...",
+ "I understand your curiosity about that subject.",
+ )
+
+ def __init__(self, name: str = "ChatAgent") -> None:
+ super().__init__(name, "Intelligent conversational agent")
+ self._context: dict[str, dict[str, Any]] = {}
+
+ async def _process_impl(self, message: AgentMessage) -> AgentMessage:
+ user_input = str(message.content).lower()
+ user_id = message.metadata.get("user_id", "unknown")
+
+ ctx = self._context.setdefault(
+ user_id,
+ {"conversation_count": 0, "last_interaction": time.time(), "topics": set()},
+ )
+ ctx["conversation_count"] += 1
+ ctx["last_interaction"] = time.time()
+
+ reply = self._generate_response(user_input)
+
+ return AgentMessage(
+ content=reply,
+ sender=self.name,
+ message_type="chat_response",
+ metadata={"user_context": ctx},
+ )
+
+ def _generate_response(self, user_input: str) -> str:
+ if any(w in user_input for w in self._GREETINGS):
+ return random.choice(self._GREETING_REPLIES)
+ if "?" in user_input or any(w in user_input for w in self._QUESTION_WORDS):
+ return self._answer_question(user_input)
+ if "weather" in user_input:
+ return "I can help with weather information! Please use the WeatherAgent for accurate weather data."
+ if any(w in user_input for w in ("calculate", "math", "equation")):
+ return "I can help with calculations! Try using the CalculatorAgent for mathematical operations."
+ if any(w in user_input for w in ("translate", "translation")):
+ return "I can assist with translations! The TranslatorAgent specializes in language translation."
+ return random.choice(self._DEFAULT_REPLIES)
+
+ def _answer_question(self, question: str) -> str:
+ q = question.lower()
+ if "time" in q:
+ return f"The current time is {time.strftime('%H:%M:%S')}"
+ if "date" in q:
+ return f"Today's date is {time.strftime('%Y-%m-%d')}"
+ if "name" in q:
+ return "I'm ChatAgent, your friendly AI assistant!"
+ if "purpose" in q or "what can you do" in q:
+ return (
+ "I can chat with you, answer questions, and coordinate with other "
+ "specialized agents for weather, calculations, translations, and more!"
+ )
+ return random.choice(self._FALLBACK_QA)
diff --git a/Agent_module/ContextStore.py b/Agent_module/context_store.py
similarity index 66%
rename from Agent_module/ContextStore.py
rename to Agent_module/context_store.py
index 34e5d56442..2d62024d6d 100644
--- a/Agent_module/ContextStore.py
+++ b/Agent_module/context_store.py
@@ -1,43 +1,26 @@
"""
-ContextStore.py
-===============
+context_store.py
+================
Unified, thread-safe, async-first context exchange for multi-agent systems.
-Replaces SharedContext + ContextBridge with a single module that provides:
+Provides:
- Keyed state store with full write history (last 50 writes per key)
- Point-to-point FIFO message channels between agents
- Pub/sub notifications supporting both sync and async callbacks
- TTL, tagging, querying, merge, snapshot, and serialisation
-
-Usage:
- store = ContextStore()
-
- # State store
- rec = await store.put("task", {"id": 1}, writer="coordinator")
- val = await store.get("task")
-
- # Channels
- await store.send("coordinator", "worker", {"cmd": "run"})
- msg = await store.receive("coordinator", "worker")
-
- # Pub/sub
- store.subscribe("monitor", my_callback)
-
- # Namespace-scoped view
- ns = ContextNamespace(store, "pipeline_v1")
- await ns.put("status", "running", writer="coordinator")
"""
from __future__ import annotations
import asyncio
import copy
+import inspect
import json
import uuid
from collections import deque
from dataclasses import dataclass, field
from datetime import datetime
-from typing import Any, Callable, Dict, List, Optional, Set, Tuple
+from typing import Any, Callable
# ============================================================================
@@ -47,12 +30,7 @@ from typing import Any, Callable, Dict, List, Optional, Set, Tuple
@dataclass(frozen=True)
class ContextRecord:
- """
- Immutable record of a single write.
-
- Every put() call appends a new ContextRecord to the key's history.
- Frozen so the record is safe to share across tasks without copying.
- """
+ """Immutable record of a single write."""
key: str
value: Any
@@ -60,17 +38,16 @@ class ContextRecord:
version: int
timestamp: str
record_id: str
- ttl: Optional[int] # seconds until expiry; None = never expires
- tags: Tuple[str, ...]
+ ttl: int | None # seconds until expiry; None = never expires
+ tags: tuple[str, ...]
def is_expired(self) -> bool:
- """Return True if this record has passed its TTL."""
if self.ttl is None:
return False
written_at = datetime.fromisoformat(self.timestamp)
return (datetime.now() - written_at).total_seconds() > self.ttl
- def to_dict(self) -> Dict[str, Any]:
+ def to_dict(self) -> dict[str, Any]:
return {
"key": self.key,
"value": self.value,
@@ -83,7 +60,7 @@ class ContextRecord:
}
@classmethod
- def from_dict(cls, data: Dict[str, Any]) -> "ContextRecord":
+ def from_dict(cls, data: dict[str, Any]) -> ContextRecord:
return cls(
key=data["key"],
value=data["value"],
@@ -98,12 +75,7 @@ class ContextRecord:
@dataclass
class ContextEntry:
- """
- Active state for one key: current record + full write history.
-
- history is a deque with maxlen=50; oldest records are dropped
- automatically when the limit is reached.
- """
+ """Active state for one key: current record plus bounded write history."""
current: ContextRecord
history: deque = field(default_factory=lambda: deque(maxlen=50))
@@ -111,14 +83,14 @@ class ContextEntry:
def is_expired(self) -> bool:
return self.current.is_expired()
- def to_dict(self) -> Dict[str, Any]:
+ def to_dict(self) -> dict[str, Any]:
return {
"current": self.current.to_dict(),
"history": [r.to_dict() for r in self.history],
}
@classmethod
- def from_dict(cls, data: Dict[str, Any]) -> "ContextEntry":
+ def from_dict(cls, data: dict[str, Any]) -> ContextEntry:
current = ContextRecord.from_dict(data["current"])
history: deque = deque(
[ContextRecord.from_dict(r) for r in data.get("history", [])],
@@ -136,9 +108,9 @@ class ContextMessage:
payload: Any
timestamp: str
message_id: str
- tags: Tuple[str, ...]
+ tags: tuple[str, ...]
- def to_dict(self) -> Dict[str, Any]:
+ def to_dict(self) -> dict[str, Any]:
return {
"sender": self.sender,
"receiver": self.receiver,
@@ -149,7 +121,7 @@ class ContextMessage:
}
@classmethod
- def from_dict(cls, data: Dict[str, Any]) -> "ContextMessage":
+ def from_dict(cls, data: dict[str, Any]) -> ContextMessage:
return cls(
sender=data["sender"],
receiver=data["receiver"],
@@ -176,20 +148,17 @@ class ContextChannel:
async with self._lock:
self._queue.append(message)
- async def receive(self) -> Optional[ContextMessage]:
- """Pop and return the oldest message, or None if empty."""
+ async def receive(self) -> ContextMessage | None:
async with self._lock:
return self._queue.popleft() if self._queue else None
- async def receive_all(self) -> List[ContextMessage]:
- """Pop and return all pending messages in FIFO order."""
+ async def receive_all(self) -> list[ContextMessage]:
async with self._lock:
msgs = list(self._queue)
self._queue.clear()
return msgs
- async def peek(self) -> Optional[ContextMessage]:
- """Return the oldest message without removing it."""
+ async def peek(self) -> ContextMessage | None:
async with self._lock:
return self._queue[0] if self._queue else None
@@ -208,8 +177,8 @@ class Subscription:
agent_id: str
namespace: str
- keys: Set[str] # empty set = subscribe to ALL keys in namespace
- callback: Callable # sync or async; called as callback(key, record)
+ keys: set[str] # empty set = subscribe to ALL keys in namespace
+ callback: Callable
# ============================================================================
@@ -223,10 +192,10 @@ class ContextStore:
Internal layout
---------------
- _entries: Dict[namespace, Dict[key, ContextEntry]] — asyncio.Lock protected
- _channels: Dict[(sender, receiver), ContextChannel] — each has its own lock
- _subs: Dict[namespace, Dict[agent_id, Subscription]]
- _lock: asyncio.Lock (single global lock protecting _entries)
+ _entries: dict[namespace, dict[key, ContextEntry]] — asyncio.Lock protected
+ _channels: dict[(sender, receiver), ContextChannel] — each has its own lock
+ _subs: dict[namespace, dict[agent_id, Subscription]]
+ _lock: asyncio.Lock (single global lock protecting _entries)
Notification contract
---------------------
@@ -241,22 +210,21 @@ class ContextStore:
"""
def __init__(self) -> None:
- self._entries: Dict[str, Dict[str, ContextEntry]] = {}
- self._channels: Dict[Tuple[str, str], ContextChannel] = {}
- self._subs: Dict[str, Dict[str, Subscription]] = {}
+ self._entries: dict[str, dict[str, ContextEntry]] = {}
+ self._channels: dict[tuple[str, str], ContextChannel] = {}
+ self._subs: dict[str, dict[str, Subscription]] = {}
self._lock = asyncio.Lock()
# -----------------------------------------------------------------------
# Internal helpers
# -----------------------------------------------------------------------
- def _ns_entries(self, namespace: str) -> Dict[str, ContextEntry]:
- """Return (creating if needed) the entries dict for *namespace*."""
+ def _ns_entries(self, namespace: str) -> dict[str, ContextEntry]:
if namespace not in self._entries:
self._entries[namespace] = {}
return self._entries[namespace]
- def _ns_subs(self, namespace: str) -> Dict[str, Subscription]:
+ def _ns_subs(self, namespace: str) -> dict[str, Subscription]:
if namespace not in self._subs:
self._subs[namespace] = {}
return self._subs[namespace]
@@ -271,18 +239,11 @@ class ContextStore:
value: Any,
writer: str,
namespace: str = "default",
- ttl: Optional[int] = None,
- tags: Optional[List[str]] = None,
+ ttl: int | None = None,
+ tags: list[str] | None = None,
) -> ContextRecord:
- """
- Write *key* → *value* on behalf of *writer*.
-
- Creates a new ContextRecord and appends it to the key's history.
- Notifies subscribers after the lock is released.
- Returns the new ContextRecord.
- """
- to_notify: List[Subscription] = []
- record: ContextRecord
+ """Write *key* → *value* on behalf of *writer*."""
+ to_notify: list[Subscription] = []
async with self._lock:
entries = self._ns_entries(namespace)
@@ -308,22 +269,20 @@ class ContextStore:
existing.history.append(record)
existing.current = record
- # Collect subscribers before releasing the lock
for sub in self._ns_subs(namespace).values():
if sub.agent_id == writer:
- continue # no self-notification
+ continue
if sub.keys and key not in sub.keys:
continue
to_notify.append(sub)
- # Fire callbacks AFTER the lock is released
for sub in to_notify:
try:
result = sub.callback(key, record)
- if asyncio.iscoroutine(result):
+ if inspect.isawaitable(result):
await result
except Exception:
- pass # bad callbacks must not crash the store
+ pass
return record
@@ -331,20 +290,13 @@ class ContextStore:
# State API — reads
# -----------------------------------------------------------------------
- async def get(self, key: str, namespace: str = "default") -> Optional[Any]:
- """Return current value for *key*, or None if missing or TTL-expired."""
+ async def get(self, key: str, namespace: str = "default") -> Any | None:
entry = await self.get_entry(key, namespace)
return entry.current.value if entry else None
async def get_entry(
self, key: str, namespace: str = "default"
- ) -> Optional[ContextEntry]:
- """
- Return the full ContextEntry (current + history) for *key*.
-
- Lazily evicts the entry if its TTL has expired.
- Returns None if missing or expired.
- """
+ ) -> ContextEntry | None:
async with self._lock:
entries = self._ns_entries(namespace)
entry = entries.get(key)
@@ -358,7 +310,6 @@ class ContextStore:
async def delete(
self, key: str, writer: str, namespace: str = "default"
) -> bool:
- """Remove *key* from the store. Returns True if it existed."""
async with self._lock:
entries = self._ns_entries(namespace)
if key in entries:
@@ -370,22 +321,15 @@ class ContextStore:
self,
key: str,
namespace: str = "default",
- limit: Optional[int] = None,
- ) -> List[ContextRecord]:
- """
- Return write history for *key*, newest-first.
-
- Returns at most *limit* records if specified.
- Returns [] if the key does not exist or is expired.
- """
+ limit: int | None = None,
+ ) -> list[ContextRecord]:
entry = await self.get_entry(key, namespace)
if entry is None:
return []
records = list(reversed(entry.history))
return records[:limit] if limit is not None else records
- async def keys(self, namespace: str = "default") -> List[str]:
- """Return all non-expired keys in *namespace*."""
+ async def keys(self, namespace: str = "default") -> list[str]:
await self.cleanup_expired(namespace)
async with self._lock:
return list(self._ns_entries(namespace).keys())
@@ -394,25 +338,18 @@ class ContextStore:
self,
namespace: str = "default",
*,
- writer: Optional[str] = None,
- tags: Optional[List[str]] = None,
- since: Optional[str] = None, # ISO-8601 datetime string (inclusive)
- until: Optional[str] = None, # ISO-8601 datetime string (inclusive)
- ) -> List[ContextEntry]:
- """
- Return ContextEntry objects whose current record matches all filters.
-
- writer — only entries last written by this agent
- tags — entry must have ALL of these tags
- since — entry timestamp >= since
- until — entry timestamp <= until
- """
+ writer: str | None = None,
+ tags: list[str] | None = None,
+ since: str | None = None,
+ until: str | None = None,
+ ) -> list[ContextEntry]:
+ """Filter entries by writer / tags / since / until."""
await self.cleanup_expired(namespace)
tag_set = set(tags) if tags else None
async with self._lock:
entries = self._ns_entries(namespace)
- results: List[ContextEntry] = []
+ results: list[ContextEntry] = []
for entry in entries.values():
rec = entry.current
if writer and rec.writer != writer:
@@ -431,7 +368,6 @@ class ContextStore:
# -----------------------------------------------------------------------
def channel(self, sender: str, receiver: str) -> ContextChannel:
- """Return (creating if needed) the channel from *sender* to *receiver*."""
key = (sender, receiver)
if key not in self._channels:
self._channels[key] = ContextChannel()
@@ -442,9 +378,8 @@ class ContextStore:
sender: str,
receiver: str,
payload: Any,
- tags: Optional[List[str]] = None,
+ tags: list[str] | None = None,
) -> ContextMessage:
- """Send a directed message from *sender* to *receiver*."""
msg = ContextMessage(
sender=sender,
receiver=receiver,
@@ -458,19 +393,13 @@ class ContextStore:
async def receive(
self, sender: str, receiver: str
- ) -> Optional[ContextMessage]:
- """Pop the next message from the *sender* → *receiver* channel."""
+ ) -> ContextMessage | None:
return await self.channel(sender, receiver).receive()
- async def inbox(self, receiver: str) -> List[ContextMessage]:
- """
- Collect and return all pending messages for *receiver* across every
- sender channel, sorted by timestamp (oldest first).
-
- This is a destructive read — messages are removed from the channel.
- """
- msgs: List[ContextMessage] = []
- for (s, r), ch in self._channels.items():
+ async def inbox(self, receiver: str) -> list[ContextMessage]:
+ """Destructively collect every pending message addressed to *receiver*."""
+ msgs: list[ContextMessage] = []
+ for (_, r), ch in self._channels.items():
if r == receiver:
msgs.extend(await ch.receive_all())
msgs.sort(key=lambda m: m.timestamp)
@@ -485,14 +414,11 @@ class ContextStore:
agent_id: str,
callback: Callable,
namespace: str = "default",
- keys: Optional[List[str]] = None,
+ keys: list[str] | None = None,
) -> None:
"""
- Register *agent_id* to be notified on writes to *keys*.
-
- keys=None (or []) means subscribe to ALL keys in the namespace.
- callback(key, record) is called after each put(); both sync and
- async callbacks are supported.
+ Register *agent_id* to be notified on writes. keys=None subscribes
+ to every key in *namespace*.
"""
subs = self._ns_subs(namespace)
subs[agent_id] = Subscription(
@@ -503,7 +429,6 @@ class ContextStore:
)
def unsubscribe(self, agent_id: str, namespace: str = "default") -> None:
- """Remove *agent_id*'s subscription in *namespace*."""
self._ns_subs(namespace).pop(agent_id, None)
# -----------------------------------------------------------------------
@@ -511,10 +436,6 @@ class ContextStore:
# -----------------------------------------------------------------------
async def cleanup_expired(self, namespace: str = "default") -> int:
- """
- Remove all TTL-expired entries from *namespace*.
- Returns the number of keys removed.
- """
async with self._lock:
entries = self._ns_entries(namespace)
expired = [k for k, e in entries.items() if e.is_expired()]
@@ -522,27 +443,16 @@ class ContextStore:
del entries[k]
return len(expired)
- async def snapshot(self, namespace: str = "default") -> Dict[str, Any]:
- """
- Return a deep copy of current non-expired entries in *namespace*
- as a plain dictionary (key → entry dict).
- """
+ async def snapshot(self, namespace: str = "default") -> dict[str, Any]:
await self.cleanup_expired(namespace)
async with self._lock:
entries = self._ns_entries(namespace)
return copy.deepcopy({k: e.to_dict() for k, e in entries.items()})
async def merge(
- self, other: "ContextStore", namespace: str = "default"
+ self, other: ContextStore, namespace: str = "default"
) -> int:
- """
- Merge entries from *other* into this store for *namespace*.
-
- Uses last-write-wins by version number: an entry from *other* is
- accepted only if its current version is higher than the local one.
- Returns the number of entries merged (updated or inserted).
- """
- # Copy other's entries while holding *its* lock (avoids concurrent mutation)
+ """Merge *other*'s entries into this store (last-write-wins by version)."""
async with other._lock:
other_snapshot = copy.deepcopy(
dict(other._entries.get(namespace, {}))
@@ -561,10 +471,9 @@ class ContextStore:
merged += 1
return merged
- async def stats(self) -> Dict[str, Any]:
- """Return high-level statistics about the store."""
+ async def stats(self) -> dict[str, Any]:
async with self._lock:
- ns_stats = {}
+ ns_stats: dict[str, Any] = {}
for ns, entries in self._entries.items():
subs = self._subs.get(ns, {})
ns_stats[ns] = {
@@ -586,11 +495,9 @@ class ContextStore:
"total_channels": len(self._channels),
}
- async def to_dict(self) -> Dict[str, Any]:
- """Full serialisation of the store to a plain Python dict."""
- # Snapshot all namespaces, filtering out expired entries in one lock pass
+ async def to_dict(self) -> dict[str, Any]:
async with self._lock:
- entries_dict: Dict[str, Any] = {}
+ entries_dict: dict[str, Any] = {}
for ns, entries in self._entries.items():
entries_dict[ns] = {
k: e.to_dict()
@@ -598,13 +505,12 @@ class ContextStore:
if not e.is_expired()
}
- # Snapshot channels (each under its own lock)
- channels_dict: Dict[str, Any] = {}
+ channels_dict: dict[str, Any] = {}
for (s, r), ch in self._channels.items():
async with ch._lock:
channels_dict[f"{s}->{r}"] = [m.to_dict() for m in ch._queue]
- subs_dict: Dict[str, Any] = {
+ subs_dict: dict[str, Any] = {
ns: {
aid: {
"agent_id": sub.agent_id,
@@ -623,7 +529,6 @@ class ContextStore:
}
async def to_json(self, indent: int = 2) -> str:
- """Return a JSON string of the full store."""
return json.dumps(await self.to_dict(), indent=indent, ensure_ascii=False)
@@ -633,18 +538,7 @@ class ContextStore:
class ContextNamespace:
- """
- A proxy view of ContextStore that fixes the *namespace* parameter.
-
- All methods have the same signatures as ContextStore but without needing
- to specify *namespace* on every call.
-
- Example:
- store = ContextStore()
- ns = ContextNamespace(store, "pipeline_v1")
- await ns.put("status", "running", writer="coordinator")
- val = await ns.get("status")
- """
+ """Proxy view of ContextStore that fixes the *namespace* parameter."""
def __init__(self, store: ContextStore, namespace: str) -> None:
self._store = store
@@ -661,38 +555,38 @@ class ContextNamespace:
key: str,
value: Any,
writer: str,
- ttl: Optional[int] = None,
- tags: Optional[List[str]] = None,
+ ttl: int | None = None,
+ tags: list[str] | None = None,
) -> ContextRecord:
return await self._store.put(
key, value, writer, self._namespace, ttl, tags
)
- async def get(self, key: str) -> Optional[Any]:
+ async def get(self, key: str) -> Any | None:
return await self._store.get(key, self._namespace)
- async def get_entry(self, key: str) -> Optional[ContextEntry]:
+ async def get_entry(self, key: str) -> ContextEntry | None:
return await self._store.get_entry(key, self._namespace)
async def delete(self, key: str, writer: str) -> bool:
return await self._store.delete(key, writer, self._namespace)
async def history(
- self, key: str, limit: Optional[int] = None
- ) -> List[ContextRecord]:
+ self, key: str, limit: int | None = None
+ ) -> list[ContextRecord]:
return await self._store.history(key, self._namespace, limit)
- async def keys(self) -> List[str]:
+ async def keys(self) -> list[str]:
return await self._store.keys(self._namespace)
async def query(
self,
*,
- writer: Optional[str] = None,
- tags: Optional[List[str]] = None,
- since: Optional[str] = None,
- until: Optional[str] = None,
- ) -> List[ContextEntry]:
+ writer: str | None = None,
+ tags: list[str] | None = None,
+ since: str | None = None,
+ until: str | None = None,
+ ) -> list[ContextEntry]:
return await self._store.query(
self._namespace, writer=writer, tags=tags, since=since, until=until
)
@@ -703,7 +597,7 @@ class ContextNamespace:
self,
agent_id: str,
callback: Callable,
- keys: Optional[List[str]] = None,
+ keys: list[str] | None = None,
) -> None:
self._store.subscribe(agent_id, callback, self._namespace, keys)
@@ -715,7 +609,7 @@ class ContextNamespace:
async def cleanup_expired(self) -> int:
return await self._store.cleanup_expired(self._namespace)
- async def snapshot(self) -> Dict[str, Any]:
+ async def snapshot(self) -> dict[str, Any]:
return await self._store.snapshot(self._namespace)
async def merge(self, other: ContextStore) -> int:
diff --git a/Agent_module/demos/__init__.py b/Agent_module/demos/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/Agent_module/demos/agent_demo.py b/Agent_module/demos/agent_demo.py
new file mode 100644
index 0000000000..8ebd638877
--- /dev/null
+++ b/Agent_module/demos/agent_demo.py
@@ -0,0 +1,91 @@
+"""
+agent_demo.py
+=============
+End-to-end demo of the agent system: single-agent usage, manager routing,
+broadcast, capability discovery, and system stats.
+
+Run:
+ python3 -m Agent_module.demos.agent_demo
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+from Agent_module import (
+ AgentManager,
+ AgentMessage,
+ CalculatorAgent,
+ ChatAgent,
+ EchoAgent,
+ TranslatorAgent,
+ WeatherAgent,
+)
+
+
+async def demo_single_agents() -> None:
+ print("=== Single Agent Demo ===\n")
+
+ print("1. EchoAgent:")
+ r = await EchoAgent().process(AgentMessage(content="Hello, world!", sender="User"))
+ print(f" {r.content}\n")
+
+ print("2. CalculatorAgent:")
+ r = await CalculatorAgent().process(AgentMessage(content="(15 + 25) * 2", sender="User"))
+ print(f" {r.content}\n")
+
+ print("3. WeatherAgent:")
+ r = await WeatherAgent().process(AgentMessage(content="Tokyo", sender="User"))
+ print(f" {r.content}\n")
+
+ print("4. TranslatorAgent:")
+ r = await TranslatorAgent().process(AgentMessage(
+ content="Hello, how are you?",
+ sender="User",
+ metadata={"target_language": "french"},
+ ))
+ print(f" {r.content}\n")
+
+ print("5. ChatAgent:")
+ r = await ChatAgent().process(AgentMessage(content="Hello! What can you do?", sender="User"))
+ print(f" {r.content}\n")
+
+
+async def demo_agent_system() -> None:
+ print("\n=== Agent System Demo ===\n")
+
+ manager = AgentManager()
+ for agent in (EchoAgent(), CalculatorAgent(), WeatherAgent(), TranslatorAgent(), ChatAgent()):
+ manager.register_agent(agent)
+
+ print(f"Registered {len(manager.agents)} agents: {', '.join(manager.agents)}")
+
+ print("\n1. CalculatorAgent via Manager:")
+ r = await manager.send_message("CalculatorAgent", "45 + 17 * 3")
+ print(f" {r.content}")
+
+ print("\n2. WeatherAgent via Manager:")
+ r = await manager.send_message("WeatherAgent", "London")
+ print(f" {r.content}")
+
+ print("\n3. Broadcast:")
+ responses = await manager.broadcast_message("Hello everyone!")
+ for name, resp in responses.items():
+ print(f" {name}: {str(resp.content)[:60]}...")
+
+ print("\n4. Capability discovery:")
+ print(f" calculation -> {manager.find_agent_by_capability('calculation')}")
+ print(f" weather -> {manager.find_agent_by_capability('weather')}")
+
+ print("\n5. System stats:")
+ for k, v in manager.get_system_stats().items():
+ print(f" {k}: {v}")
+
+
+async def main() -> None:
+ await demo_single_agents()
+ await demo_agent_system()
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/Agent_module/demos/context_store_demo.py b/Agent_module/demos/context_store_demo.py
new file mode 100644
index 0000000000..bce2965091
--- /dev/null
+++ b/Agent_module/demos/context_store_demo.py
@@ -0,0 +1,184 @@
+"""
+context_store_demo.py
+=====================
+End-to-end demonstration of the ContextStore multi-agent data exchange.
+
+Scenarios covered
+-----------------
+ 1. coordinator writes task → worker reads and processes → monitor observes
+ changes via pub/sub async callback
+ 2. history() returns all write versions (newest-first)
+ 3. Directed channel: coordinator → worker messages; inbox() aggregates all
+ 4. TTL entry written, expires after 3 seconds, get() returns None
+ 5. query(writer="worker") returns only entries written by worker
+ 6. merge() correctly resolves version conflicts (higher version wins)
+ 7. to_json() fully serialises the entire store
+
+Run:
+ python3 -m Agent_module.demos.context_store_demo
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+
+from Agent_module import ContextNamespace, ContextRecord, ContextStore
+
+
+def section(title: str) -> None:
+ print("\n" + "=" * 70)
+ print(f" {title}")
+ print("=" * 70)
+
+
+_change_log: list[dict] = []
+
+
+async def monitor_callback(key: str, record: ContextRecord) -> None:
+ """Async pub/sub callback — called after every put() that monitor watches."""
+ msg = (
+ f" [MONITOR] key={key!r:20s} "
+ f"writer={record.writer:15s} "
+ f"v{record.version} "
+ f"value={str(record.value)!r:.55s}"
+ )
+ print(msg)
+ _change_log.append({"key": key, "writer": record.writer, "value": record.value})
+
+
+async def main() -> None:
+ store = ContextStore()
+ ns = ContextNamespace(store, "data_pipeline_v1")
+
+ # 1. Setup + coordinator assigns task
+ section("1. Setup + coordinator assigns task [pub/sub demo]")
+ ns.subscribe("monitor", monitor_callback)
+
+ await ns.put(
+ "task",
+ {"id": "task_001", "description": "Analyse Q1 sales", "priority": "high"},
+ writer="coordinator",
+ )
+ await ns.put("status", "pending", writer="coordinator")
+ await ns.put("deadline", "2026-02-18T18:00:00", writer="coordinator", tags=["meta"])
+
+ task = await ns.get("task")
+ print(f"\n Worker received task: {task}")
+
+ await ns.put("status", "in_progress", writer="worker")
+ print(" Worker processing …")
+ await asyncio.sleep(0.05)
+
+ await ns.put(
+ "result",
+ {"task_id": task["id"], "summary": "Q1 revenue +12% YoY", "rows_processed": 14_320},
+ writer="worker",
+ tags=["output"],
+ )
+ await ns.put("status", "completed", writer="worker")
+
+ print(f"\n Final status: {await ns.get('status')!r}")
+ print(f" Result: {await ns.get('result')}")
+
+ # 2. history — newest-first
+ section("2. history('status') — all write versions, newest-first")
+ records = await ns.history("status")
+ for r in records:
+ print(f" v{r.version} writer={r.writer:15s} value={r.value!r} ts={r.timestamp}")
+ assert records[0].value == "completed"
+ assert records[-1].value == "pending"
+ print(f"\n Total writes to 'status': {len(records)} ✓")
+
+ # 3. channels + inbox
+ section("3. Directed channels: coordinator → worker, inbox() aggregation")
+ await store.send("coordinator", "worker", {"cmd": "run_report", "format": "pdf"}, tags=["cmd"])
+ await store.send("coordinator", "worker", {"cmd": "upload_results", "dest": "s3://bucket/q1"}, tags=["cmd"])
+ await store.send("monitor", "worker", {"cmd": "health_check"}, tags=["admin"])
+
+ print(f" coordinator→worker queue depth: {len(store.channel('coordinator', 'worker'))}")
+ peeked = await store.channel("coordinator", "worker").peek()
+ print(f" Peeked first message: {peeked.payload}")
+
+ inbox_msgs = await store.inbox("worker")
+ print(f"\n inbox('worker') received {len(inbox_msgs)} message(s):")
+ for m in inbox_msgs:
+ print(f" from={m.sender:15s} payload={m.payload}")
+ assert len(inbox_msgs) == 3
+ print(" inbox() aggregation ✓")
+
+ # 4. TTL
+ section("4. TTL — heartbeat entry expires after 3 seconds")
+ await ns.put("heartbeat", {"alive": True, "load": 0.42}, writer="worker", ttl=3, tags=["health"])
+ immediate = await ns.get("heartbeat")
+ print(f" Immediate read → {immediate}")
+ assert immediate is not None
+
+ print(" Sleeping 3.5 s for TTL expiry …")
+ await asyncio.sleep(3.5)
+ expired_val = await ns.get("heartbeat")
+ print(f" After 3.5 s read → {expired_val} (None = expired correctly)")
+ assert expired_val is None
+
+ removed = await ns.cleanup_expired()
+ print(f" cleanup_expired() removed {removed} additional stale key(s) ✓")
+
+ # 5. query
+ section("5. query(writer='worker') — only worker-written entries")
+ worker_entries = await ns.query(writer="worker")
+ print(f" Entries written by worker ({len(worker_entries)}):")
+ for e in worker_entries:
+ print(f" key={e.current.key!r:15s} v{e.current.version} tags={list(e.current.tags)}")
+ for e in worker_entries:
+ assert e.current.writer == "worker"
+ print(" All returned entries are from worker ✓")
+
+ # 6. merge
+ section("6. merge() — last-write-wins by version number")
+ remote_store = ContextStore()
+ await remote_store.put("status", "archived", writer="archiver", namespace="data_pipeline_v1")
+ await remote_store.put("status", "archived_v2", writer="archiver", namespace="data_pipeline_v1")
+ await remote_store.put("archived_at", "2026-02-18T19:00:00", writer="archiver", namespace="data_pipeline_v1")
+
+ remote_v = (await remote_store.get_entry("status", "data_pipeline_v1")).current.version
+ local_v = (await store.get_entry("status", "data_pipeline_v1")).current.version
+ print(f" Before merge: local status v{local_v}, remote status v{remote_v}")
+
+ merged_count = await store.merge(remote_store, "data_pipeline_v1")
+ print(f" merge() accepted {merged_count} entry/entries from remote")
+ merged_status = await store.get("status", "data_pipeline_v1")
+ print(f" status after merge → {merged_status!r}")
+ if remote_v > local_v:
+ assert merged_status == "archived_v2"
+ print(" Higher remote version won ✓")
+ else:
+ print(" Local version was already higher; remote was ignored ✓")
+
+ # 7. to_json
+ section("7. to_json() — full store serialisation")
+ json_str = await store.to_json()
+ parsed = json.loads(json_str)
+ print(f" Serialised namespaces: {list(parsed['entries'].keys())}")
+ print(f" Channels captured: {list(parsed['channels'].keys())}")
+ print(f" Subscriptions: {list(parsed['subscriptions'].keys())}")
+
+ local_keys = set(await ns.keys())
+ json_keys = set(parsed["entries"].get("data_pipeline_v1", {}).keys())
+ assert local_keys == json_keys
+ print(" Key set roundtrip matches ✓")
+
+ # 8. stats
+ section("8. Store stats")
+ print(json.dumps(await store.stats(), indent=2, ensure_ascii=False))
+
+ # 9. monitor summary
+ section("9. Monitor pub/sub change log summary")
+ print(f" Total changes observed by monitor: {len(_change_log)}")
+ for i, entry in enumerate(_change_log, 1):
+ print(f" {i:2d}. [{entry['writer']:15s}] {entry['key']!r}")
+
+ section("Demo complete — all scenarios passed ✓")
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/Agent_module/Example/01_data_models.py b/Agent_module/examples/01_data_models.py
similarity index 100%
rename from Agent_module/Example/01_data_models.py
rename to Agent_module/examples/01_data_models.py
diff --git a/Agent_module/examples/02_framework_agents.py b/Agent_module/examples/02_framework_agents.py
new file mode 100644
index 0000000000..54a0fe53be
--- /dev/null
+++ b/Agent_module/examples/02_framework_agents.py
@@ -0,0 +1,232 @@
+"""
+02_framework_agents.py
+======================
+Tests BaseAgent subclassing, AgentStatus lifecycle, message history,
+callbacks, and error handling; also exercises the built-in agents.
+
+Run:
+ python3 Agent_module/examples/02_framework_agents.py
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import sys
+import time
+
+# Make the parent package importable when run as a script.
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from Agent_module import (
+ AgentMessage,
+ AgentStatus,
+ BaseAgent,
+ CalculatorAgent,
+ EchoAgent,
+ TranslatorAgent,
+ WeatherAgent,
+)
+
+
+_passed = 0
+_failed = 0
+
+
+def check(label: str, condition: bool) -> None:
+ global _passed, _failed
+ if condition:
+ _passed += 1
+ print(f" PASS {label}")
+ else:
+ _failed += 1
+ print(f" FAIL {label}")
+
+
+def section(title: str) -> None:
+ print(f"\n{'=' * 60}")
+ print(f" {title}")
+ print(f"{'=' * 60}")
+
+
+def msg(content: str, **meta) -> AgentMessage:
+ return AgentMessage(content=content, sender="tester", timestamp=time.time(), metadata=meta)
+
+
+class UpperCaseAgent(BaseAgent):
+ def __init__(self):
+ super().__init__(name="UpperCaseAgent", description="Converts text to uppercase")
+
+ async def _process_impl(self, message: AgentMessage) -> AgentMessage:
+ return AgentMessage(
+ content=str(message.content).upper(),
+ sender=self.name,
+ message_type="uppercase_response",
+ )
+
+
+class BrokenAgent(BaseAgent):
+ def __init__(self):
+ super().__init__(name="BrokenAgent", description="Always fails")
+
+ async def _process_impl(self, message: AgentMessage) -> AgentMessage:
+ raise RuntimeError("intentional failure")
+
+
+async def test_custom_agent() -> None:
+ section("Custom agent — UpperCaseAgent")
+
+ agent = UpperCaseAgent()
+ check("initial status is IDLE", agent.status == AgentStatus.IDLE)
+ check("name set correctly", agent.name == "UpperCaseAgent")
+ check("history starts empty", len(agent.message_history) == 0)
+
+ response = await agent.process(msg("hello world"))
+ check("response content uppercased", response.content == "HELLO WORLD")
+ check("response sender is agent name", response.sender == "UpperCaseAgent")
+ check("message_type preserved", response.message_type == "uppercase_response")
+ check("status returns to IDLE", agent.status == AgentStatus.IDLE)
+ check("input added to history", len(agent.message_history) == 1)
+
+ await agent.process(msg("second message"))
+ check("history grows with each message", len(agent.message_history) == 2)
+ check("get_recent_messages(1) returns 1", len(agent.get_recent_messages(1)) == 1)
+ check("get_recent_messages(5) returns 2", len(agent.get_recent_messages(5)) == 2)
+
+
+async def test_error_handling() -> None:
+ section("Error handling — BrokenAgent")
+
+ agent = BrokenAgent()
+ response = await agent.process(msg("trigger error"))
+
+ check("response message_type is error", response.message_type == "error")
+ check("response content contains 'Error'", "Error" in response.content)
+ check("status set to ERROR", agent.status == AgentStatus.ERROR)
+
+
+async def test_callbacks() -> None:
+ section("Callbacks — sync + async")
+
+ agent = UpperCaseAgent()
+ log: list = []
+
+ def sync_cb(input_msg: AgentMessage, output_msg: AgentMessage) -> None:
+ log.append(("sync", input_msg.content, output_msg.content))
+
+ async def async_cb(input_msg: AgentMessage, output_msg: AgentMessage) -> None:
+ log.append(("async", input_msg.content, output_msg.content))
+
+ agent.add_callback(sync_cb)
+ agent.add_callback(async_cb)
+ await agent.process(msg("ping"))
+
+ check("both callbacks fired", len(log) == 2)
+ check("sync callback received correct input", log[0][1] == "ping" and log[0][2] == "PING")
+ check("async callback received correct input", log[1][0] == "async" and log[1][2] == "PING")
+
+ # A crashing callback must not break the agent
+ def bad_callback(i, o):
+ raise ValueError("bad callback")
+
+ agent.add_callback(bad_callback)
+ response = await agent.process(msg("still works"))
+ check("agent survives a crashing callback", response.content == "STILL WORKS")
+
+
+async def test_echo_agent() -> None:
+ section("EchoAgent")
+
+ agent = EchoAgent()
+ response = await agent.process(msg("hello"))
+ check("response starts with 'Echo:'", response.content.startswith("Echo:"))
+ check("original content echoed", "hello" in response.content)
+ check("message_type is echo_response", response.message_type == "echo_response")
+
+
+async def test_calculator_agent() -> None:
+ section("CalculatorAgent — safe AST evaluator")
+
+ agent = CalculatorAgent()
+
+ cases = [
+ ("2 + 2", "4"),
+ ("10 * 5", "50"),
+ ("100 / 4", "25.0"),
+ ("(3 + 7) * 2", "20"),
+ ("2 ** 8", "256"),
+ ]
+ for expr, expected in cases:
+ r = await agent.process(msg(expr))
+ check(f" {expr} = {expected}", expected in r.content)
+
+ # Malicious input must be rejected
+ for bad in ("__import__('os')", "open('/etc/passwd')", "a + b"):
+ r = await agent.process(msg(bad))
+ check(f"rejected: {bad}", r.message_type == "error" or "error" in r.content.lower())
+
+ r = await agent.process(msg("1 / 0"))
+ check("division by zero -> error message", r.message_type == "error")
+
+
+async def test_weather_agent() -> None:
+ section("WeatherAgent")
+
+ agent = WeatherAgent()
+
+ known_cities = ["New York", "London", "Tokyo", "Sydney"]
+ for city in known_cities:
+ r = await agent.process(msg(city))
+ check(f" {city}: contains city name", city in r.content)
+ check(f" {city}: contains Temperature", "Temperature" in r.content)
+ check(f" {city}: message_type correct", r.message_type == "weather_report")
+
+ r = await agent.process(msg("Atlantis"))
+ check("unknown city returns simulated data", "Atlantis" in r.content)
+ check("simulated data has Temperature field", "Temperature" in r.content)
+
+
+async def test_translator_agent() -> None:
+ section("TranslatorAgent")
+
+ agent = TranslatorAgent()
+
+ supported = ["spanish", "french", "german", "italian"]
+ for lang in supported:
+ r = await agent.process(msg("Hello", target_language=lang))
+ check(f" {lang}: lang name in response", lang.upper() in r.content)
+ check(f" {lang}: message_type correct", r.message_type == "translation")
+
+ r = await agent.process(msg("Hello", target_language="klingon"))
+ check("unsupported language returns error text", "don't support" in r.content or "klingon" in r.content.lower())
+
+
+async def _run_all() -> bool:
+ global _passed, _failed
+ _passed = _failed = 0
+
+ await test_custom_agent()
+ await test_error_handling()
+ await test_callbacks()
+ await test_echo_agent()
+ await test_calculator_agent()
+ await test_weather_agent()
+ await test_translator_agent()
+
+ total = _passed + _failed
+ print(f"\n{'=' * 60}")
+ print(f" Result: {_passed}/{total} passed", "✓" if _failed == 0 else "✗")
+ print(f"{'=' * 60}")
+ return _failed == 0
+
+
+def run() -> bool:
+ print("\n" + "=" * 60)
+ print(" 02 — Framework Agents")
+ print("=" * 60)
+ return asyncio.run(_run_all())
+
+
+if __name__ == "__main__":
+ ok = run()
+ sys.exit(0 if ok else 1)
diff --git a/Agent_module/examples/03_agent_manager.py b/Agent_module/examples/03_agent_manager.py
new file mode 100644
index 0000000000..53a94a7967
--- /dev/null
+++ b/Agent_module/examples/03_agent_manager.py
@@ -0,0 +1,236 @@
+"""
+03_agent_manager.py
+===================
+Tests AgentManager: registration, unicast, broadcast, capability
+discovery, system statistics, and concurrent execution.
+
+Run:
+ python3 Agent_module/examples/03_agent_manager.py
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from Agent_module import (
+ AgentManager,
+ AgentMessage,
+ BaseAgent,
+ CalculatorAgent,
+ ChatAgent,
+ EchoAgent,
+ TranslatorAgent,
+ WeatherAgent,
+)
+
+
+_passed = 0
+_failed = 0
+
+
+def check(label: str, condition: bool) -> None:
+ global _passed, _failed
+ if condition:
+ _passed += 1
+ print(f" PASS {label}")
+ else:
+ _failed += 1
+ print(f" FAIL {label}")
+
+
+def section(title: str) -> None:
+ print(f"\n{'=' * 60}")
+ print(f" {title}")
+ print(f"{'=' * 60}")
+
+
+class TagAgent(BaseAgent):
+ """Returns a fixed tag — useful for verifying broadcast routing."""
+
+ def __init__(self, name: str, tag: str):
+ super().__init__(name=name, description=f"Returns tag: {tag}")
+ self.tag = tag
+
+ async def _process_impl(self, message: AgentMessage) -> AgentMessage:
+ return AgentMessage(content=self.tag, sender=self.name)
+
+
+async def test_registration() -> None:
+ section("Agent registration")
+
+ manager = AgentManager()
+ manager.register_agent(EchoAgent())
+ manager.register_agent(CalculatorAgent())
+
+ check("two agents registered", len(manager.agents) == 2)
+ check("EchoAgent found by name", "EchoAgent" in manager.agents)
+ check("CalculatorAgent found by name", "CalculatorAgent" in manager.agents)
+
+ a3 = EchoAgent()
+ manager.register_agent(a3)
+ check("re-register keeps count at 2", len(manager.agents) == 2)
+ check("replaced agent is the new one", manager.agents["EchoAgent"] is a3)
+
+
+async def test_send_message() -> None:
+ section("Unicast — send_message")
+
+ manager = AgentManager()
+ manager.register_agent(CalculatorAgent())
+ manager.register_agent(WeatherAgent())
+
+ r = await manager.send_message("CalculatorAgent", "6 * 7")
+ check("calculator returns correct result", "42" in r.content)
+ check("sender is CalculatorAgent", r.sender == "CalculatorAgent")
+
+ r = await manager.send_message("WeatherAgent", "Tokyo")
+ check("weather response contains Tokyo", "Tokyo" in r.content)
+
+ try:
+ await manager.send_message("NonExistentAgent", "hello")
+ check("ValueError raised for unknown agent", False)
+ except ValueError:
+ check("ValueError raised for unknown agent", True)
+
+
+async def test_broadcast() -> None:
+ section("Broadcast — broadcast_message")
+
+ manager = AgentManager()
+ manager.register_agent(TagAgent("Alpha", "alpha-reply"))
+ manager.register_agent(TagAgent("Beta", "beta-reply"))
+ manager.register_agent(TagAgent("Gamma", "gamma-reply"))
+
+ responses = await manager.broadcast_message("ping")
+
+ check("all three agents responded", len(responses) == 3)
+ check("Alpha response correct", responses["Alpha"].content == "alpha-reply")
+ check("Beta response correct", responses["Beta"].content == "beta-reply")
+ check("Gamma response correct", responses["Gamma"].content == "gamma-reply")
+
+
+async def test_broadcast_with_failure() -> None:
+ section("Broadcast — partial failure handled gracefully")
+
+ class FailingAgent(BaseAgent):
+ def __init__(self):
+ super().__init__(name="FailingAgent", description="always fails")
+
+ async def _process_impl(self, m: AgentMessage) -> AgentMessage:
+ raise RuntimeError("boom")
+
+ manager = AgentManager()
+ manager.register_agent(TagAgent("Good", "ok"))
+ manager.register_agent(FailingAgent())
+
+ responses = await manager.broadcast_message("test")
+
+ check("both agents have a response entry", len(responses) == 2)
+ check("Good agent responded normally", responses["Good"].content == "ok")
+ check("FailingAgent returned an error message", responses["FailingAgent"].message_type == "error")
+
+
+async def test_capability_discovery() -> None:
+ section("Capability discovery — find_agent_by_capability")
+
+ manager = AgentManager()
+ manager.register_agent(CalculatorAgent())
+ manager.register_agent(WeatherAgent())
+ manager.register_agent(TranslatorAgent())
+
+ check("calculator found by 'calculation'", "CalculatorAgent" in manager.find_agent_by_capability("calculation"))
+ check("weather found by 'weather'", "WeatherAgent" in manager.find_agent_by_capability("weather"))
+ check("translator found by 'translat'", "TranslatorAgent" in manager.find_agent_by_capability("translat"))
+ check("empty list for no match", manager.find_agent_by_capability("nonexistent_xyz") == [])
+
+
+async def test_system_stats() -> None:
+ section("System statistics")
+
+ manager = AgentManager()
+ manager.register_agent(EchoAgent())
+ manager.register_agent(CalculatorAgent())
+
+ await manager.send_message("EchoAgent", "msg 1")
+ await manager.send_message("EchoAgent", "msg 2")
+ await manager.send_message("CalculatorAgent", "1 + 1")
+
+ stats = manager.get_system_stats()
+
+ check("total_agents is 2", stats["total_agents"] == 2)
+ check("total_messages_processed is 3", stats["total_messages_processed"] == 3)
+ check("conversation_log_entries is 3", stats["conversation_log_entries"] == 3)
+ check("agent_statuses dict present", "agent_statuses" in stats)
+ check("EchoAgent status is idle", stats["agent_statuses"]["EchoAgent"] == "idle")
+
+
+async def test_metadata_routing() -> None:
+ section("Metadata routing — TranslatorAgent target_language")
+
+ manager = AgentManager()
+ manager.register_agent(TranslatorAgent())
+
+ r = await manager.send_message(
+ "TranslatorAgent",
+ "Good morning",
+ metadata={"target_language": "german"},
+ )
+ check("german translation triggered", "GERMAN" in r.content)
+ check("original text present", "Good morning" in r.content)
+
+
+async def test_chat_agent() -> None:
+ section("ChatAgent — basic intent detection")
+
+ manager = AgentManager()
+ manager.register_agent(ChatAgent())
+
+ for g in ["hello", "hi there", "hey", "greetings"]:
+ r = await manager.send_message("ChatAgent", g, metadata={"user_id": "u1"})
+ check(f" greeting '{g}' gets a reply", len(r.content) > 0)
+ check(f" message_type is chat_response", r.message_type == "chat_response")
+
+ r = await manager.send_message("ChatAgent", "what is your name?", metadata={"user_id": "u1"})
+ check("question gets an answer", len(r.content) > 0)
+
+ r1 = await manager.send_message("ChatAgent", "hello", metadata={"user_id": "ctx_user"})
+ count1 = r1.metadata.get("user_context", {}).get("conversation_count", 0)
+ r2 = await manager.send_message("ChatAgent", "hello", metadata={"user_id": "ctx_user"})
+ count2 = r2.metadata.get("user_context", {}).get("conversation_count", 0)
+ check("conversation_count increments per user", count2 == count1 + 1)
+
+
+async def _run_all() -> bool:
+ global _passed, _failed
+ _passed = _failed = 0
+
+ await test_registration()
+ await test_send_message()
+ await test_broadcast()
+ await test_broadcast_with_failure()
+ await test_capability_discovery()
+ await test_system_stats()
+ await test_metadata_routing()
+ await test_chat_agent()
+
+ total = _passed + _failed
+ print(f"\n{'=' * 60}")
+ print(f" Result: {_passed}/{total} passed", "✓" if _failed == 0 else "✗")
+ print(f"{'=' * 60}")
+ return _failed == 0
+
+
+def run() -> bool:
+ print("\n" + "=" * 60)
+ print(" 03 — AgentManager")
+ print("=" * 60)
+ return asyncio.run(_run_all())
+
+
+if __name__ == "__main__":
+ ok = run()
+ sys.exit(0 if ok else 1)
diff --git a/Agent_module/examples/04_context_store.py b/Agent_module/examples/04_context_store.py
new file mode 100644
index 0000000000..ac3a6aac55
--- /dev/null
+++ b/Agent_module/examples/04_context_store.py
@@ -0,0 +1,334 @@
+"""
+04_context_store.py
+===================
+Tests every major feature of ContextStore and ContextNamespace.
+
+Run:
+ python3 Agent_module/examples/04_context_store.py
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from Agent_module import ContextNamespace, ContextRecord, ContextStore
+
+
+_passed = 0
+_failed = 0
+
+
+def check(label: str, condition: bool) -> None:
+ global _passed, _failed
+ if condition:
+ _passed += 1
+ print(f" PASS {label}")
+ else:
+ _failed += 1
+ print(f" FAIL {label}")
+
+
+def section(title: str) -> None:
+ print(f"\n{'=' * 60}")
+ print(f" {title}")
+ print(f"{'=' * 60}")
+
+
+async def test_basic_put_get() -> None:
+ section("Basic put / get / delete")
+
+ store = ContextStore()
+
+ rec = await store.put("color", "red", writer="alice")
+ check("put returns a ContextRecord", isinstance(rec, ContextRecord))
+ check("record key is correct", rec.key == "color")
+ check("record value is correct", rec.value == "red")
+ check("record writer is correct", rec.writer == "alice")
+ check("first write gets version 1", rec.version == 1)
+ check("record_id is a non-empty string", len(rec.record_id) > 0)
+
+ check("get returns current value", await store.get("color") == "red")
+
+ rec2 = await store.put("color", "blue", writer="bob")
+ check("second write gets version 2", rec2.version == 2)
+ check("get returns updated value", await store.get("color") == "blue")
+
+ check("get missing key returns None", await store.get("__missing__") is None)
+
+ deleted = await store.delete("color", writer="alice")
+ check("delete returns True for existing key", deleted)
+ check("get after delete returns None", await store.get("color") is None)
+ check("delete returns False for missing key", not await store.delete("__missing__", writer="alice"))
+
+
+async def test_history() -> None:
+ section("History")
+
+ store = ContextStore()
+ await store.put("status", "pending", writer="coordinator")
+ await store.put("status", "in_progress", writer="worker")
+ await store.put("status", "completed", writer="worker")
+
+ history = await store.history("status")
+ check("history returns 3 records", len(history) == 3)
+ check("history is newest-first", history[0].value == "completed")
+ check("oldest record is pending", history[-1].value == "pending")
+
+ limited = await store.history("status", limit=2)
+ check("limit=2 returns 2 records", len(limited) == 2)
+ check("limit respects newest-first order", limited[0].value == "completed")
+
+ check("history for missing key is []", await store.history("__missing__") == [])
+
+
+async def test_keys_and_query() -> None:
+ section("keys() and query()")
+
+ store = ContextStore()
+ ns = "test_ns"
+
+ await store.put("a", 1, writer="alice", namespace=ns, tags=["x"])
+ await store.put("b", 2, writer="bob", namespace=ns, tags=["x", "y"])
+ await store.put("c", 3, writer="alice", namespace=ns, tags=["y"])
+
+ check("keys() returns all 3 keys", set(await store.keys(namespace=ns)) == {"a", "b", "c"})
+
+ alice_entries = await store.query(namespace=ns, writer="alice")
+ check("query(writer='alice') returns 2 entries", len(alice_entries) == 2)
+ check("all alice entries have writer='alice'",
+ all(e.current.writer == "alice" for e in alice_entries))
+
+ tag_x = await store.query(namespace=ns, tags=["x"])
+ check("query(tags=['x']) returns 2 entries", len(tag_x) == 2)
+
+ tag_xy = await store.query(namespace=ns, tags=["x", "y"])
+ check("query(tags=['x','y']) returns 1 entry", len(tag_xy) == 1)
+ check("that entry is 'b'", tag_xy[0].current.key == "b")
+
+ check("query with no match returns []", await store.query(namespace=ns, writer="nobody") == [])
+
+
+async def test_namespace_isolation() -> None:
+ section("Namespace isolation")
+
+ store = ContextStore()
+ await store.put("key", "ns1-value", writer="agent", namespace="ns1")
+ await store.put("key", "ns2-value", writer="agent", namespace="ns2")
+
+ check("ns1 reads its own value", await store.get("key", namespace="ns1") == "ns1-value")
+ check("ns2 reads its own value", await store.get("key", namespace="ns2") == "ns2-value")
+ check("default ns is empty", await store.get("key") is None)
+ check("ns1 has exactly 1 key", await store.keys(namespace="ns1") == ["key"])
+ check("ns2 has exactly 1 key", await store.keys(namespace="ns2") == ["key"])
+
+
+async def test_context_namespace_proxy() -> None:
+ section("ContextNamespace proxy")
+
+ store = ContextStore()
+ ns = ContextNamespace(store, "proxy_ns")
+
+ check("namespace property correct", ns.namespace == "proxy_ns")
+
+ await ns.put("x", 42, writer="agent")
+ check("ns.put writes to correct namespace", await ns.get("x") == 42)
+ check("direct store read matches", await store.get("x", "proxy_ns") == 42)
+
+ await ns.delete("x", writer="agent")
+ check("ns.delete removes the key", await ns.get("x") is None)
+
+ await ns.put("h", "v1", writer="a")
+ await ns.put("h", "v2", writer="b")
+ check("ns.history returns 2 records", len(await ns.history("h")) == 2)
+ check("ns.keys() returns ['h']", await ns.keys() == ["h"])
+
+
+async def test_channels() -> None:
+ section("P2P Channels — send / receive / peek / inbox")
+
+ store = ContextStore()
+ m1 = await store.send("coordinator", "worker", {"cmd": "run"})
+ m2 = await store.send("coordinator", "worker", {"cmd": "stop"})
+ check("send returns a ContextMessage", m1.sender == "coordinator")
+ check("message_id is unique", m1.message_id != m2.message_id)
+
+ ch = store.channel("coordinator", "worker")
+ check("channel depth is 2", len(ch) == 2)
+
+ peeked = await ch.peek()
+ check("peek returns first message", peeked.payload == {"cmd": "run"})
+ check("peek does not consume (depth still 2)", len(ch) == 2)
+
+ r = await store.receive("coordinator", "worker")
+ check("receive returns oldest message (FIFO)", r.payload == {"cmd": "run"})
+ check("channel depth is now 1", len(ch) == 1)
+
+ await store.send("auditor", "worker", {"cmd": "check"})
+ inbox = await store.inbox("worker")
+ check("inbox collects from all senders", len(inbox) == 2)
+ check("inbox sorted oldest-first by timestamp", inbox[0].payload == {"cmd": "stop"})
+ check("inbox is destructive (channel empty)", len(store.channel("coordinator", "worker")) == 0)
+
+ check("receive on empty channel returns None", await store.receive("coordinator", "worker") is None)
+
+ tagged = await store.send("a", "b", "payload", tags=["urgent"])
+ check("message tags preserved", "urgent" in tagged.tags)
+
+
+async def test_pubsub() -> None:
+ section("Pub/Sub")
+
+ store = ContextStore()
+ ns = ContextNamespace(store, "pubsub_ns")
+ log: list = []
+
+ async def async_cb(key: str, record: ContextRecord) -> None:
+ log.append(("async", key, record.value, record.writer))
+
+ def sync_cb(key: str, record: ContextRecord) -> None:
+ log.append(("sync", key, record.value, record.writer))
+
+ ns.subscribe("monitor", async_cb)
+ ns.subscribe("logger", sync_cb)
+
+ await ns.put("status", "started", writer="coordinator")
+ check("async callback fired", any(e[0] == "async" for e in log))
+ check("sync callback fired", any(e[0] == "sync" for e in log))
+ check("both callbacks fired (2 entries)", len(log) == 2)
+ check("correct key delivered", all(e[1] == "status" for e in log))
+ check("correct value delivered", all(e[2] == "started" for e in log))
+
+ log.clear()
+ ns.subscribe("coordinator", lambda k, r: log.append("self-notified"))
+ await ns.put("status", "done", writer="coordinator")
+ check("writer not notified of own write", "self-notified" not in log)
+ check("other subscribers still notified", len(log) == 2)
+
+ log.clear()
+ ns.unsubscribe("monitor")
+ ns.unsubscribe("logger")
+ ns.unsubscribe("coordinator")
+
+ ns.subscribe("watcher", lambda k, r: log.append(k), keys=["important"])
+ await ns.put("important", "yes", writer="a")
+ await ns.put("unimportant", "skip", writer="a")
+ check("key filter: watched key triggers callback", "important" in log)
+ check("key filter: unwatched key does not trigger", "unimportant" not in log)
+
+ log.clear()
+ ns.unsubscribe("watcher")
+ await ns.put("important", "again", writer="a")
+ check("after unsubscribe, no callback fires", log == [])
+
+
+async def test_ttl() -> None:
+ section("TTL expiry")
+
+ store = ContextStore()
+ ns = ContextNamespace(store, "ttl_ns")
+
+ await ns.put("short", "alive", writer="agent", ttl=1)
+ check("immediate read returns value", await ns.get("short") == "alive")
+
+ await asyncio.sleep(1.2)
+ check("read after TTL returns None", await ns.get("short") is None)
+
+ await ns.put("a", 1, writer="x", ttl=1)
+ await ns.put("b", 2, writer="x", ttl=1)
+ await ns.put("c", 3, writer="x")
+
+ await asyncio.sleep(1.2)
+ removed = await ns.cleanup_expired()
+ check("cleanup_expired removed 2 keys", removed == 2)
+ check("non-expiring key 'c' still readable", await ns.get("c") == 3)
+
+
+async def test_merge() -> None:
+ section("Merge — last-write-wins by version")
+
+ store_a = ContextStore()
+ store_b = ContextStore()
+ ns = "merge_ns"
+
+ await store_a.put("status", "v1", writer="a", namespace=ns)
+ await store_a.put("status", "v2", writer="a", namespace=ns)
+
+ await store_b.put("status", "b-v1", writer="b", namespace=ns)
+ await store_b.put("extra", "only-in-b", writer="b", namespace=ns)
+
+ merged = await store_a.merge(store_b, namespace=ns)
+ check("merge returns count of accepted entries", merged >= 1)
+ check("higher-version local value retained", await store_a.get("status", ns) == "v2")
+ check("new key from b accepted", await store_a.get("extra", ns) == "only-in-b")
+
+ await store_b.merge(store_a, namespace=ns)
+ check("higher-version remote value wins on merge", await store_b.get("status", ns) == "v2")
+
+
+async def test_snapshot_and_serialisation() -> None:
+ section("Snapshot and serialisation")
+
+ store = ContextStore()
+ ns = ContextNamespace(store, "serial_ns")
+
+ await ns.put("k1", "v1", writer="a", tags=["t1"])
+ await ns.put("k2", {"nested": True}, writer="b")
+ await store.send("a", "b", {"cmd": "go"})
+
+ snap = await ns.snapshot()
+ check("snapshot has k1 and k2", set(snap.keys()) == {"k1", "k2"})
+ check("snapshot is a deep copy", snap["k1"]["current"]["value"] == "v1")
+
+ json_str = await store.to_json()
+ parsed = json.loads(json_str)
+
+ check("to_json produces valid JSON",
+ "entries" in parsed and "channels" in parsed and "subscriptions" in parsed)
+ check("namespace present in JSON", "serial_ns" in parsed["entries"])
+ check("k1 present in JSON entries", "k1" in parsed["entries"]["serial_ns"])
+ check("channel captured in JSON", "a->b" in parsed["channels"])
+
+ stats = await store.stats()
+ check("stats has namespaces key", "namespaces" in stats)
+ check("stats has total_channels key", "total_channels" in stats)
+ check("serial_ns appears in stats", "serial_ns" in stats["namespaces"])
+ check("total_channels >= 1", stats["total_channels"] >= 1)
+
+
+async def _run_all() -> bool:
+ global _passed, _failed
+ _passed = _failed = 0
+
+ await test_basic_put_get()
+ await test_history()
+ await test_keys_and_query()
+ await test_namespace_isolation()
+ await test_context_namespace_proxy()
+ await test_channels()
+ await test_pubsub()
+ await test_ttl()
+ await test_merge()
+ await test_snapshot_and_serialisation()
+
+ total = _passed + _failed
+ print(f"\n{'=' * 60}")
+ print(f" Result: {_passed}/{total} passed", "✓" if _failed == 0 else "✗")
+ print(f"{'=' * 60}")
+ return _failed == 0
+
+
+def run() -> bool:
+ print("\n" + "=" * 60)
+ print(" 04 — ContextStore")
+ print("=" * 60)
+ return asyncio.run(_run_all())
+
+
+if __name__ == "__main__":
+ ok = run()
+ sys.exit(0 if ok else 1)
diff --git a/Agent_module/examples/__init__.py b/Agent_module/examples/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/Agent_module/Example/Agent_format_example.py b/Agent_module/examples/agent_format_example.py
similarity index 100%
rename from Agent_module/Example/Agent_format_example.py
rename to Agent_module/examples/agent_format_example.py
diff --git a/Agent_module/examples/run_all.py b/Agent_module/examples/run_all.py
new file mode 100644
index 0000000000..5be85b057b
--- /dev/null
+++ b/Agent_module/examples/run_all.py
@@ -0,0 +1,64 @@
+"""
+run_all.py
+==========
+Runs every example file in order and prints a summary.
+
+Run:
+ python3 Agent_module/examples/run_all.py
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import os
+import sys
+from types import ModuleType
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+ROOT = os.path.dirname(os.path.dirname(HERE))
+sys.path.insert(0, ROOT)
+
+EXAMPLES = [
+ ("01_data_models.py", "Agent Data Models"),
+ ("02_framework_agents.py", "Framework Agents"),
+ ("03_agent_manager.py", "AgentManager"),
+ ("04_context_store.py", "ContextStore"),
+]
+
+
+def _load_module(path: str) -> ModuleType:
+ """Load a source file as a module, regardless of its filename."""
+ name = os.path.splitext(os.path.basename(path))[0]
+ spec = importlib.util.spec_from_file_location(f"example_{name}", path)
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def main() -> None:
+ results: list[tuple[str, bool]] = []
+
+ for filename, label in EXAMPLES:
+ module = _load_module(os.path.join(HERE, filename))
+ results.append((label, module.run()))
+
+ print("\n" + "=" * 60)
+ print(" SUMMARY")
+ print("=" * 60)
+ all_passed = True
+ for label, ok in results:
+ status = "PASS" if ok else "FAIL"
+ print(f" {status} {label}")
+ if not ok:
+ all_passed = False
+
+ print("=" * 60)
+ print(f" {'All examples passed ✓' if all_passed else 'Some examples FAILED ✗'}")
+ print("=" * 60)
+
+ sys.exit(0 if all_passed else 1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/Agent_module/framework.py b/Agent_module/framework.py
new file mode 100644
index 0000000000..f5fddd3363
--- /dev/null
+++ b/Agent_module/framework.py
@@ -0,0 +1,90 @@
+"""
+framework.py
+============
+Core abstractions: AgentStatus, AgentMessage, BaseAgent.
+
+BaseAgent subclasses implement `_process_impl` and inherit a lifecycle
+wrapper (`process`) that updates status, records history, and dispatches
+callbacks. Callbacks may be sync or async.
+"""
+
+from __future__ import annotations
+
+import inspect
+import time
+from abc import ABC, abstractmethod
+from dataclasses import dataclass, field
+from enum import Enum
+from typing import Any, Awaitable, Callable, Union
+
+
+class AgentStatus(Enum):
+ IDLE = "idle"
+ PROCESSING = "processing"
+ ERROR = "error"
+ STOPPED = "stopped"
+
+
+@dataclass
+class AgentMessage:
+ content: Any
+ sender: str
+ timestamp: float = field(default_factory=time.time)
+ message_type: str = "text"
+ metadata: dict[str, Any] = field(default_factory=dict)
+
+
+CallbackResult = Union[None, Awaitable[None]]
+AgentCallback = Callable[[AgentMessage, AgentMessage], CallbackResult]
+
+
+class BaseAgent(ABC):
+ """Base class for all agents."""
+
+ def __init__(self, name: str, description: str = "") -> None:
+ self.name = name
+ self.description = description
+ self.status = AgentStatus.IDLE
+ self.message_history: list[AgentMessage] = []
+ self._callbacks: list[AgentCallback] = []
+
+ async def process(self, message: AgentMessage) -> AgentMessage:
+ """Dispatch *message* to `_process_impl` with lifecycle bookkeeping."""
+ self.status = AgentStatus.PROCESSING
+ self.message_history.append(message)
+
+ try:
+ result = await self._process_impl(message)
+ except Exception as exc:
+ self.status = AgentStatus.ERROR
+ return AgentMessage(
+ content=f"Error: {exc}",
+ sender=self.name,
+ message_type="error",
+ )
+
+ self.status = AgentStatus.IDLE
+ await self._notify_callbacks(message, result)
+ return result
+
+ @abstractmethod
+ async def _process_impl(self, message: AgentMessage) -> AgentMessage:
+ """Agent-specific processing logic."""
+
+ def add_callback(self, callback: AgentCallback) -> None:
+ self._callbacks.append(callback)
+
+ async def _notify_callbacks(
+ self, input_msg: AgentMessage, output_msg: AgentMessage
+ ) -> None:
+ """Fire every registered callback. Callbacks may be sync or async."""
+ for cb in self._callbacks:
+ try:
+ result = cb(input_msg, output_msg)
+ if inspect.isawaitable(result):
+ await result
+ except Exception:
+ pass
+
+ def get_recent_messages(self, count: int = 10) -> list[AgentMessage]:
+ return self.message_history[-count:]
diff --git a/Agent_module/manager.py b/Agent_module/manager.py
new file mode 100644
index 0000000000..91c97c9461
--- /dev/null
+++ b/Agent_module/manager.py
@@ -0,0 +1,114 @@
+"""
+manager.py
+==========
+AgentManager — registers agents, routes messages, and collects statistics.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import time
+from typing import Any
+
+from .framework import AgentMessage, BaseAgent
+
+
+class AgentManager:
+ """Registry and dispatcher for a set of BaseAgent instances."""
+
+ def __init__(self) -> None:
+ self.agents: dict[str, BaseAgent] = {}
+ self.conversation_log: list[dict[str, Any]] = []
+
+ def register_agent(self, agent: BaseAgent) -> None:
+ """Register *agent*. Re-registering by the same name replaces the entry."""
+ self.agents[agent.name] = agent
+ agent.add_callback(self._log_interaction)
+
+ async def send_message(
+ self,
+ agent_name: str,
+ content: Any,
+ metadata: dict[str, Any] | None = None,
+ ) -> AgentMessage:
+ """Send *content* to a specific agent and return its response."""
+ if agent_name not in self.agents:
+ raise ValueError(f"Agent '{agent_name}' not found")
+
+ message = AgentMessage(
+ content=content,
+ sender="User",
+ metadata=metadata or {},
+ )
+ return await self.agents[agent_name].process(message)
+
+ async def broadcast_message(
+ self,
+ content: Any,
+ metadata: dict[str, Any] | None = None,
+ ) -> dict[str, AgentMessage]:
+ """Send *content* to every registered agent concurrently."""
+ message = AgentMessage(
+ content=content,
+ sender="Broadcast",
+ metadata=metadata or {},
+ )
+
+ names = list(self.agents.keys())
+ responses = await asyncio.gather(
+ *(self.agents[n].process(message) for n in names),
+ return_exceptions=True,
+ )
+
+ results: dict[str, AgentMessage] = {}
+ for name, response in zip(names, responses):
+ if isinstance(response, Exception):
+ results[name] = AgentMessage(
+ content=f"Error: {response}",
+ sender=name,
+ message_type="error",
+ )
+ else:
+ results[name] = response
+ return results
+
+ def find_agent_by_capability(self, keyword: str) -> list[str]:
+ """Return names of agents whose name or description contains *keyword*."""
+ needle = keyword.lower()
+ return [
+ name
+ for name, agent in self.agents.items()
+ if needle in agent.name.lower() or needle in agent.description.lower()
+ ]
+
+ def _log_interaction(
+ self, input_msg: AgentMessage, output_msg: AgentMessage
+ ) -> None:
+ self.conversation_log.append({
+ "timestamp": time.time(),
+ "input": {
+ "content": input_msg.content,
+ "sender": input_msg.sender,
+ "type": input_msg.message_type,
+ },
+ "output": {
+ "content": output_msg.content,
+ "sender": output_msg.sender,
+ "type": output_msg.message_type,
+ },
+ "processing_time": output_msg.timestamp - input_msg.timestamp,
+ })
+
+ def get_agent_statuses(self) -> dict[str, str]:
+ return {name: agent.status.value for name, agent in self.agents.items()}
+
+ def get_system_stats(self) -> dict[str, Any]:
+ total_messages = sum(
+ len(agent.message_history) for agent in self.agents.values()
+ )
+ return {
+ "total_agents": len(self.agents),
+ "total_messages_processed": total_messages,
+ "conversation_log_entries": len(self.conversation_log),
+ "agent_statuses": self.get_agent_statuses(),
+ }
diff --git a/Agent_module/safe_eval.py b/Agent_module/safe_eval.py
new file mode 100644
index 0000000000..eb13c7d8a0
--- /dev/null
+++ b/Agent_module/safe_eval.py
@@ -0,0 +1,68 @@
+"""
+safe_eval.py
+============
+Restricted arithmetic evaluator. Parses a string into Python's AST and
+walks it with an allowlist of node types — so `__import__('os')`, attribute
+access, function calls, and names are all rejected before any code runs.
+
+Supports: + - * / // % **, unary +/-, parenthesised grouping, int and float
+literals. Nothing else.
+
+Raises ValueError for anything outside the allowlist.
+"""
+
+from __future__ import annotations
+
+import ast
+import operator
+from typing import Union
+
+Number = Union[int, float]
+
+
+_BIN_OPS = {
+ ast.Add: operator.add,
+ ast.Sub: operator.sub,
+ ast.Mult: operator.mul,
+ ast.Div: operator.truediv,
+ ast.FloorDiv: operator.floordiv,
+ ast.Mod: operator.mod,
+ ast.Pow: operator.pow,
+}
+
+_UNARY_OPS = {
+ ast.UAdd: operator.pos,
+ ast.USub: operator.neg,
+}
+
+
+def safe_eval(expression: str) -> Number:
+ """Evaluate *expression* as arithmetic. Raises ValueError on anything else."""
+ try:
+ tree = ast.parse(expression, mode="eval")
+ except SyntaxError as exc:
+ raise ValueError(f"invalid expression: {exc.msg}") from None
+ return _eval_node(tree.body)
+
+
+def _eval_node(node: ast.AST) -> Number:
+ if isinstance(node, ast.Constant):
+ if isinstance(node.value, bool) or not isinstance(node.value, (int, float)):
+ raise ValueError(f"unsupported literal: {node.value!r}")
+ return node.value
+
+ if isinstance(node, ast.BinOp):
+ op_type = type(node.op)
+ if op_type not in _BIN_OPS:
+ raise ValueError(f"operator not allowed: {op_type.__name__}")
+ left = _eval_node(node.left)
+ right = _eval_node(node.right)
+ return _BIN_OPS[op_type](left, right)
+
+ if isinstance(node, ast.UnaryOp):
+ op_type = type(node.op)
+ if op_type not in _UNARY_OPS:
+ raise ValueError(f"unary operator not allowed: {op_type.__name__}")
+ return _UNARY_OPS[op_type](_eval_node(node.operand))
+
+ raise ValueError(f"node type not allowed: {type(node).__name__}")
diff --git a/Agent_module/tests/__init__.py b/Agent_module/tests/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/Agent_module/tests/conftest.py b/Agent_module/tests/conftest.py
new file mode 100644
index 0000000000..a97804a619
--- /dev/null
+++ b/Agent_module/tests/conftest.py
@@ -0,0 +1,10 @@
+"""Make the Agent_module package importable when running pytest from the repo root."""
+
+import os
+import sys
+
+# Add the repo root (parent of Agent_module/) to sys.path so `import Agent_module` works
+# regardless of where pytest is invoked from.
+_REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+if _REPO_ROOT not in sys.path:
+ sys.path.insert(0, _REPO_ROOT)
diff --git a/Agent_module/tests/test_async_callbacks.py b/Agent_module/tests/test_async_callbacks.py
new file mode 100644
index 0000000000..5f4c5d236e
--- /dev/null
+++ b/Agent_module/tests/test_async_callbacks.py
@@ -0,0 +1,86 @@
+"""Verify that BaseAgent dispatches both sync and async callbacks."""
+
+from __future__ import annotations
+
+import pytest
+
+from Agent_module import AgentMessage, BaseAgent
+
+
+class _UpperAgent(BaseAgent):
+ def __init__(self):
+ super().__init__(name="UpperAgent", description="uppercases")
+
+ async def _process_impl(self, message: AgentMessage) -> AgentMessage:
+ return AgentMessage(content=str(message.content).upper(), sender=self.name)
+
+
+@pytest.mark.asyncio
+async def test_sync_callback_fires():
+ agent = _UpperAgent()
+ log: list = []
+
+ def cb(input_msg: AgentMessage, output_msg: AgentMessage) -> None:
+ log.append((input_msg.content, output_msg.content))
+
+ agent.add_callback(cb)
+ await agent.process(AgentMessage(content="hi", sender="test"))
+
+ assert log == [("hi", "HI")]
+
+
+@pytest.mark.asyncio
+async def test_async_callback_is_awaited():
+ agent = _UpperAgent()
+ log: list = []
+
+ async def async_cb(input_msg: AgentMessage, output_msg: AgentMessage) -> None:
+ log.append(output_msg.content)
+
+ agent.add_callback(async_cb)
+ await agent.process(AgentMessage(content="hi", sender="test"))
+
+ # If the coroutine wasn't awaited, log would still be empty.
+ assert log == ["HI"]
+
+
+@pytest.mark.asyncio
+async def test_sync_and_async_callbacks_both_fire():
+ agent = _UpperAgent()
+ log: list = []
+
+ def sync_cb(i: AgentMessage, o: AgentMessage) -> None:
+ log.append(("sync", o.content))
+
+ async def async_cb(i: AgentMessage, o: AgentMessage) -> None:
+ log.append(("async", o.content))
+
+ agent.add_callback(sync_cb)
+ agent.add_callback(async_cb)
+ await agent.process(AgentMessage(content="x", sender="test"))
+
+ assert ("sync", "X") in log
+ assert ("async", "X") in log
+
+
+@pytest.mark.asyncio
+async def test_crashing_callback_does_not_break_agent():
+ agent = _UpperAgent()
+ survived = []
+
+ def bad_sync(i, o):
+ raise RuntimeError("sync boom")
+
+ async def bad_async(i, o):
+ raise RuntimeError("async boom")
+
+ def good(i, o):
+ survived.append(o.content)
+
+ agent.add_callback(bad_sync)
+ agent.add_callback(bad_async)
+ agent.add_callback(good)
+
+ response = await agent.process(AgentMessage(content="ok", sender="test"))
+ assert response.content == "OK"
+ assert survived == ["OK"]
diff --git a/Agent_module/tests/test_safe_eval.py b/Agent_module/tests/test_safe_eval.py
new file mode 100644
index 0000000000..c6c60aef2f
--- /dev/null
+++ b/Agent_module/tests/test_safe_eval.py
@@ -0,0 +1,94 @@
+"""Unit tests for safe_eval — the AST-based replacement for eval()."""
+
+from __future__ import annotations
+
+import pytest
+
+from Agent_module.safe_eval import safe_eval
+
+
+class TestArithmetic:
+ def test_addition(self):
+ assert safe_eval("2 + 3") == 5
+
+ def test_subtraction(self):
+ assert safe_eval("10 - 7") == 3
+
+ def test_multiplication(self):
+ assert safe_eval("4 * 5") == 20
+
+ def test_true_division(self):
+ assert safe_eval("10 / 4") == 2.5
+
+ def test_floor_division(self):
+ assert safe_eval("10 // 3") == 3
+
+ def test_modulo(self):
+ assert safe_eval("10 % 3") == 1
+
+ def test_power(self):
+ assert safe_eval("2 ** 10") == 1024
+
+ def test_parentheses(self):
+ assert safe_eval("(2 + 3) * 4") == 20
+
+ def test_unary_minus(self):
+ assert safe_eval("-5 + 3") == -2
+
+ def test_unary_plus(self):
+ assert safe_eval("+5") == 5
+
+ def test_float_literal(self):
+ assert safe_eval("1.5 * 2") == 3.0
+
+ def test_nested(self):
+ assert safe_eval("((1 + 2) * 3 - 4) ** 2") == 25
+
+
+class TestSecurityRejections:
+ """Anything outside the arithmetic allowlist must raise ValueError."""
+
+ @pytest.mark.parametrize("expr", [
+ "__import__('os')",
+ "open('/etc/passwd')",
+ "print(1)",
+ "a + 1",
+ "os.system('ls')",
+ "[1, 2, 3]",
+ "{1: 2}",
+ "lambda: 1",
+ "1 if True else 2",
+ "True and False",
+ "1 == 1",
+ "x := 1",
+ ])
+ def test_rejects_non_arithmetic(self, expr):
+ with pytest.raises(ValueError):
+ safe_eval(expr)
+
+ def test_rejects_boolean_literal(self):
+ # bool is a subclass of int — we must still reject it explicitly.
+ with pytest.raises(ValueError):
+ safe_eval("True")
+
+ def test_rejects_string_literal(self):
+ with pytest.raises(ValueError):
+ safe_eval("'hello'")
+
+ def test_syntax_error_becomes_value_error(self):
+ with pytest.raises(ValueError):
+ safe_eval("1 +")
+
+ def test_empty_string_raises(self):
+ with pytest.raises(ValueError):
+ safe_eval("")
+
+
+class TestArithmeticErrors:
+ def test_divide_by_zero_raises(self):
+ with pytest.raises(ZeroDivisionError):
+ safe_eval("1 / 0")
+
+ def test_floor_divide_by_zero_raises(self):
+ with pytest.raises(ZeroDivisionError):
+ safe_eval("1 // 0")