jarviscore-framework 0.3.0__py3-none-any.whl → 0.3.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. examples/cloud_deployment_example.py +3 -3
  2. examples/{listeneragent_cognitive_discovery_example.py → customagent_cognitive_discovery_example.py} +55 -14
  3. examples/customagent_distributed_example.py +140 -1
  4. examples/fastapi_integration_example.py +74 -11
  5. jarviscore/__init__.py +8 -11
  6. jarviscore/cli/smoketest.py +1 -1
  7. jarviscore/core/mesh.py +158 -0
  8. jarviscore/data/examples/cloud_deployment_example.py +3 -3
  9. jarviscore/data/examples/custom_profile_decorator.py +134 -0
  10. jarviscore/data/examples/custom_profile_wrap.py +168 -0
  11. jarviscore/data/examples/{listeneragent_cognitive_discovery_example.py → customagent_cognitive_discovery_example.py} +55 -14
  12. jarviscore/data/examples/customagent_distributed_example.py +140 -1
  13. jarviscore/data/examples/fastapi_integration_example.py +74 -11
  14. jarviscore/docs/API_REFERENCE.md +576 -47
  15. jarviscore/docs/CHANGELOG.md +131 -0
  16. jarviscore/docs/CONFIGURATION.md +1 -1
  17. jarviscore/docs/CUSTOMAGENT_GUIDE.md +591 -153
  18. jarviscore/docs/GETTING_STARTED.md +186 -329
  19. jarviscore/docs/TROUBLESHOOTING.md +1 -1
  20. jarviscore/docs/USER_GUIDE.md +292 -12
  21. jarviscore/integrations/fastapi.py +4 -4
  22. jarviscore/p2p/coordinator.py +36 -7
  23. jarviscore/p2p/messages.py +13 -0
  24. jarviscore/p2p/peer_client.py +380 -21
  25. jarviscore/p2p/peer_tool.py +17 -11
  26. jarviscore/profiles/__init__.py +2 -4
  27. jarviscore/profiles/customagent.py +302 -74
  28. jarviscore/testing/__init__.py +35 -0
  29. jarviscore/testing/mocks.py +578 -0
  30. {jarviscore_framework-0.3.0.dist-info → jarviscore_framework-0.3.2.dist-info}/METADATA +61 -46
  31. {jarviscore_framework-0.3.0.dist-info → jarviscore_framework-0.3.2.dist-info}/RECORD +42 -34
  32. tests/test_13_dx_improvements.py +37 -37
  33. tests/test_15_llm_cognitive_discovery.py +18 -18
  34. tests/test_16_unified_dx_flow.py +3 -3
  35. tests/test_17_session_context.py +489 -0
  36. tests/test_18_mesh_diagnostics.py +465 -0
  37. tests/test_19_async_requests.py +516 -0
  38. tests/test_20_load_balancing.py +546 -0
  39. tests/test_21_mock_testing.py +776 -0
  40. jarviscore/profiles/listeneragent.py +0 -292
  41. {jarviscore_framework-0.3.0.dist-info → jarviscore_framework-0.3.2.dist-info}/WHEEL +0 -0
  42. {jarviscore_framework-0.3.0.dist-info → jarviscore_framework-0.3.2.dist-info}/licenses/LICENSE +0 -0
  43. {jarviscore_framework-0.3.0.dist-info → jarviscore_framework-0.3.2.dist-info}/top_level.txt +0 -0
@@ -1,87 +1,130 @@
1
1
  """
2
- CustomAgent - User-controlled execution profile.
3
-
4
- User provides their own implementation using any framework:
5
- - LangChain
6
- - MCP (Model Context Protocol)
7
- - CrewAI
8
- - Raw Python
9
- - Any other tool/framework
2
+ CustomAgent - User-controlled execution profile with P2P message handling.
3
+
4
+ Unified profile for building agents that:
5
+ - Handle P2P mesh communication (requests, notifications)
6
+ - Execute workflow tasks
7
+ - Integrate with HTTP APIs (FastAPI, Flask, etc.)
8
+
9
+ Example - Basic P2P Agent:
10
+ class AnalystAgent(CustomAgent):
11
+ role = "analyst"
12
+ capabilities = ["analysis"]
13
+
14
+ async def on_peer_request(self, msg):
15
+ result = await self.analyze(msg.data)
16
+ return {"status": "success", "result": result}
17
+
18
+ Example - With FastAPI:
19
+ from fastapi import FastAPI
20
+ from jarviscore.integrations.fastapi import JarvisLifespan
21
+
22
+ class ProcessorAgent(CustomAgent):
23
+ role = "processor"
24
+ capabilities = ["processing"]
25
+
26
+ async def on_peer_request(self, msg):
27
+ return {"result": await self.process(msg.data)}
28
+
29
+ app = FastAPI(lifespan=JarvisLifespan(ProcessorAgent(), mode="p2p"))
10
30
  """
11
- from typing import Dict, Any
31
+ from typing import Dict, Any, Optional
32
+ import asyncio
33
+ import logging
34
+
12
35
  from jarviscore.core.profile import Profile
13
36
 
37
+ logger = logging.getLogger(__name__)
38
+
14
39
 
15
40
  class CustomAgent(Profile):
16
41
  """
17
- Custom execution profile with full user control.
42
+ User-controlled agent profile with P2P message handling.
43
+
44
+ For P2P messaging, implement these handlers:
45
+ on_peer_request(msg) - Handle requests, return response
46
+ on_peer_notify(msg) - Handle notifications (fire-and-forget)
47
+ on_error(error, msg) - Handle errors
18
48
 
19
- User defines:
20
- - role: str
21
- - capabilities: List[str]
22
- - setup(): Initialize custom framework/tools
23
- - execute_task(): Custom execution logic
49
+ For workflow execution:
50
+ execute_task(task) - Handle workflow tasks directly
51
+ (defaults to delegating to on_peer_request)
24
52
 
25
- Framework provides:
26
- - Orchestration (task claiming, dependencies, nudging)
27
- - P2P coordination (agent discovery, task routing)
28
- - State management (crash recovery, HITL)
29
- - Cost tracking (if user provides token counts)
53
+ Configuration:
54
+ listen_timeout: Seconds to wait for messages (default: 1.0)
55
+ auto_respond: Auto-send on_peer_request return value (default: True)
30
56
 
31
- Example with LangChain:
32
- class APIAgent(CustomAgent):
33
- role = "api_client"
34
- capabilities = ["api_calls"]
57
+ Example - P2P Agent:
58
+ class AnalystAgent(CustomAgent):
59
+ role = "analyst"
60
+ capabilities = ["analysis"]
61
+
62
+ async def on_peer_request(self, msg):
63
+ result = await self.analyze(msg.data)
64
+ return {"status": "success", "result": result}
65
+
66
+ Example - With LangChain:
67
+ class LangChainAgent(CustomAgent):
68
+ role = "assistant"
69
+ capabilities = ["chat"]
35
70
 
36
71
  async def setup(self):
37
72
  await super().setup()
38
73
  from langchain.agents import Agent
39
74
  self.lc_agent = Agent(...)
40
75
 
41
- async def execute_task(self, task):
42
- result = await self.lc_agent.run(task["task"])
76
+ async def on_peer_request(self, msg):
77
+ result = await self.lc_agent.run(msg.data["query"])
43
78
  return {"status": "success", "output": result}
44
79
 
45
- Example with MCP:
80
+ Example - With MCP:
46
81
  class MCPAgent(CustomAgent):
47
82
  role = "tool_user"
48
83
  capabilities = ["mcp_tools"]
49
- mcp_server_url = "stdio://./server.py"
50
84
 
51
85
  async def setup(self):
52
86
  await super().setup()
53
87
  from mcp import Client
54
- self.mcp = Client(self.mcp_server_url)
88
+ self.mcp = Client("stdio://./server.py")
55
89
  await self.mcp.connect()
56
90
 
57
- async def execute_task(self, task):
58
- result = await self.mcp.call_tool("my_tool", task["params"])
91
+ async def on_peer_request(self, msg):
92
+ result = await self.mcp.call_tool("my_tool", msg.data)
59
93
  return {"status": "success", "data": result}
60
94
 
61
- Example with Raw Python:
62
- class DataProcessor(CustomAgent):
95
+ Example - With FastAPI:
96
+ from fastapi import FastAPI
97
+ from jarviscore.integrations.fastapi import JarvisLifespan
98
+
99
+ class ProcessorAgent(CustomAgent):
63
100
  role = "processor"
64
101
  capabilities = ["data_processing"]
65
102
 
66
- async def execute_task(self, task):
67
- # Pure Python logic
68
- data = task["params"]["data"]
69
- processed = [x * 2 for x in data]
70
- return {"status": "success", "output": processed}
103
+ async def on_peer_request(self, msg):
104
+ if msg.data.get("action") == "process":
105
+ return {"result": await self.process(msg.data["payload"])}
106
+ return {"error": "unknown action"}
107
+
108
+ agent = ProcessorAgent()
109
+ app = FastAPI(lifespan=JarvisLifespan(agent, mode="p2p"))
110
+
111
+ @app.post("/process")
112
+ async def process_endpoint(data: dict, request: Request):
113
+ # HTTP endpoint - primary interface
114
+ agent = request.app.state.jarvis_agents["processor"]
115
+ return await agent.process(data)
71
116
  """
72
117
 
73
- def __init__(self, agent_id=None):
74
- super().__init__(agent_id)
118
+ # Configuration - can be overridden in subclasses
119
+ listen_timeout: float = 1.0 # Seconds to wait for messages
120
+ auto_respond: bool = True # Automatically send response for requests
75
121
 
76
- # User can add any custom attributes
77
- # e.g., mcp_server_url, langchain_config, etc.
122
+ def __init__(self, agent_id: Optional[str] = None):
123
+ super().__init__(agent_id)
78
124
 
79
125
  async def setup(self):
80
126
  """
81
- User implements this to initialize custom framework/tools.
82
-
83
- DAY 1: Base implementation (user overrides)
84
- DAY 5+: Full examples with LangChain, MCP, etc.
127
+ Initialize agent resources. Override to add custom setup.
85
128
 
86
129
  Example:
87
130
  async def setup(self):
@@ -91,47 +134,232 @@ class CustomAgent(Profile):
91
134
  self.agent = Agent(...)
92
135
  """
93
136
  await super().setup()
94
-
95
137
  self._logger.info(f"CustomAgent setup: {self.agent_id}")
96
- self._logger.info(
97
- f" Note: Override setup() to initialize your custom framework"
138
+
139
+ # ─────────────────────────────────────────────────────────────────
140
+ # P2P Message Handling
141
+ # ─────────────────────────────────────────────────────────────────
142
+
143
+ async def run(self):
144
+ """
145
+ Listener loop - receives and dispatches P2P messages.
146
+
147
+ Runs automatically in P2P mode. Dispatches messages to:
148
+ - on_peer_request() for request-response messages
149
+ - on_peer_notify() for fire-and-forget notifications
150
+
151
+ You typically don't need to override this. Just implement the handlers.
152
+ """
153
+ self._logger.info(f"[{self.role}] Listener loop started")
154
+
155
+ while not self.shutdown_requested:
156
+ try:
157
+ # Wait for incoming message with timeout
158
+ # Timeout allows periodic shutdown_requested checks
159
+ msg = await self.peers.receive(timeout=self.listen_timeout)
160
+
161
+ if msg is None:
162
+ # Timeout - no message, continue loop to check shutdown
163
+ continue
164
+
165
+ # Dispatch to appropriate handler
166
+ await self._dispatch_message(msg)
167
+
168
+ except asyncio.CancelledError:
169
+ self._logger.debug(f"[{self.role}] Listener loop cancelled")
170
+ raise
171
+ except Exception as e:
172
+ self._logger.error(f"[{self.role}] Listener loop error: {e}")
173
+ await self.on_error(e, None)
174
+
175
+ self._logger.info(f"[{self.role}] Listener loop stopped")
176
+
177
+ async def _dispatch_message(self, msg):
178
+ """
179
+ Dispatch message to appropriate handler based on message type.
180
+
181
+ Handles:
182
+ - REQUEST messages: calls on_peer_request, sends response if auto_respond=True
183
+ - NOTIFY messages: calls on_peer_notify
184
+ - RESPONSE messages: ignored (handled by _deliver_message resolving futures)
185
+ """
186
+ from jarviscore.p2p.messages import MessageType
187
+
188
+ try:
189
+ # Skip RESPONSE messages - they should be handled by pending request futures
190
+ if msg.type == MessageType.RESPONSE:
191
+ self._logger.debug(
192
+ f"[{self.role}] Ignoring orphaned RESPONSE from {msg.sender} (no pending request)"
193
+ )
194
+ return
195
+
196
+ # Check if this is a request (expects response)
197
+ is_request = (
198
+ msg.type == MessageType.REQUEST or
199
+ getattr(msg, 'is_request', False)
200
+ )
201
+
202
+ if is_request:
203
+ # Request-response: call handler, optionally send response
204
+ response = await self.on_peer_request(msg)
205
+
206
+ if self.auto_respond and response is not None:
207
+ await self.peers.respond(msg, response)
208
+ self._logger.debug(
209
+ f"[{self.role}] Sent response to {msg.sender}"
210
+ )
211
+ else:
212
+ # Notification: fire-and-forget
213
+ await self.on_peer_notify(msg)
214
+
215
+ except Exception as e:
216
+ self._logger.error(
217
+ f"[{self.role}] Error handling message from {msg.sender}: {e}"
218
+ )
219
+ await self.on_error(e, msg)
220
+
221
+ # ─────────────────────────────────────────────────────────────────
222
+ # Message Handlers - Override in your agent
223
+ # ─────────────────────────────────────────────────────────────────
224
+
225
+ async def on_peer_request(self, msg) -> Any:
226
+ """
227
+ Handle incoming peer request.
228
+
229
+ Override to process request-response messages from other agents.
230
+ The return value is automatically sent as response (if auto_respond=True).
231
+
232
+ Args:
233
+ msg: IncomingMessage with:
234
+ - msg.sender: Sender agent ID or role
235
+ - msg.data: Request payload (dict)
236
+ - msg.correlation_id: For response matching (handled automatically)
237
+
238
+ Returns:
239
+ Response data (dict) to send back to the requester.
240
+ Return None to skip sending a response.
241
+
242
+ Example:
243
+ async def on_peer_request(self, msg):
244
+ action = msg.data.get("action")
245
+
246
+ if action == "analyze":
247
+ result = await self.analyze(msg.data["payload"])
248
+ return {"status": "success", "result": result}
249
+
250
+ elif action == "status":
251
+ return {"status": "ok", "queue_size": self.queue_size}
252
+
253
+ return {"status": "error", "message": f"Unknown action: {action}"}
254
+ """
255
+ return None
256
+
257
+ async def on_peer_notify(self, msg) -> None:
258
+ """
259
+ Handle incoming peer notification.
260
+
261
+ Override to process fire-and-forget messages from other agents.
262
+ No response is expected or sent.
263
+
264
+ Args:
265
+ msg: IncomingMessage with:
266
+ - msg.sender: Sender agent ID or role
267
+ - msg.data: Notification payload (dict)
268
+
269
+ Example:
270
+ async def on_peer_notify(self, msg):
271
+ event = msg.data.get("event")
272
+
273
+ if event == "task_complete":
274
+ await self.update_dashboard(msg.data)
275
+ self._logger.info(f"Task completed by {msg.sender}")
276
+
277
+ elif event == "peer_joined":
278
+ self._logger.info(f"New peer in mesh: {msg.data.get('role')}")
279
+ """
280
+ self._logger.debug(
281
+ f"[{self.role}] Received notify from {msg.sender}: "
282
+ f"{list(msg.data.keys()) if isinstance(msg.data, dict) else 'data'}"
98
283
  )
99
284
 
285
+ async def on_error(self, error: Exception, msg=None) -> None:
286
+ """
287
+ Handle errors during message processing.
288
+
289
+ Override to customize error handling (logging, alerting, metrics, etc.)
290
+ Default implementation logs the error and continues processing.
291
+
292
+ Args:
293
+ error: The exception that occurred
294
+ msg: The message being processed when error occurred (may be None)
295
+
296
+ Example:
297
+ async def on_error(self, error, msg):
298
+ # Log with context
299
+ self._logger.error(
300
+ f"Error processing message: {error}",
301
+ extra={"sender": msg.sender if msg else None}
302
+ )
303
+
304
+ # Send to error tracking service
305
+ await self.error_tracker.capture(error, context={"msg": msg})
306
+
307
+ # Optionally notify the sender of failure
308
+ if msg and msg.correlation_id:
309
+ await self.peers.respond(msg, {
310
+ "status": "error",
311
+ "error": str(error)
312
+ })
313
+ """
314
+ if msg:
315
+ self._logger.error(
316
+ f"[{self.role}] Error processing message from {msg.sender}: {error}"
317
+ )
318
+ else:
319
+ self._logger.error(f"[{self.role}] Error in listener loop: {error}")
320
+
321
+ # ─────────────────────────────────────────────────────────────────
322
+ # Workflow Compatibility
323
+ # ─────────────────────────────────────────────────────────────────
324
+
100
325
  async def execute_task(self, task: Dict[str, Any]) -> Dict[str, Any]:
101
326
  """
102
- User implements this with custom execution logic.
327
+ Execute a task (for workflow/distributed modes).
103
328
 
104
- DAY 1: Raises NotImplementedError (user must override)
105
- DAY 5+: Full examples provided
329
+ Default: Delegates to on_peer_request via synthetic message.
330
+ Override for custom workflow logic.
106
331
 
107
332
  Args:
108
- task: Task specification
333
+ task: Task specification dict
109
334
 
110
335
  Returns:
111
- Result dictionary with at least:
112
- - status: "success" or "failure"
113
- - output: Task result
114
- - error (optional): Error message if failed
115
- - tokens_used (optional): For cost tracking
116
- - cost_usd (optional): For cost tracking
336
+ Result dict with status and output
117
337
 
118
338
  Raises:
119
- NotImplementedError: User must override this method
120
-
121
- Example:
122
- async def execute_task(self, task):
123
- result = await self.my_framework.run(task)
124
- return {
125
- "status": "success",
126
- "output": result,
127
- "tokens_used": 1000, # Optional
128
- "cost_usd": 0.002 # Optional
129
- }
339
+ NotImplementedError: If on_peer_request returns None and
340
+ execute_task is not overridden
130
341
  """
342
+ from jarviscore.p2p.messages import IncomingMessage, MessageType
343
+
344
+ # Create a synthetic message to pass to the handler
345
+ synthetic_msg = IncomingMessage(
346
+ sender="workflow",
347
+ sender_node="local",
348
+ type=MessageType.REQUEST,
349
+ data=task,
350
+ correlation_id=None,
351
+ timestamp=0
352
+ )
353
+
354
+ result = await self.on_peer_request(synthetic_msg)
355
+
356
+ if result is not None:
357
+ return {"status": "success", "output": result}
358
+
131
359
  raise NotImplementedError(
132
- f"{self.__class__.__name__} must implement execute_task()\n\n"
360
+ f"{self.__class__.__name__} must implement on_peer_request() or execute_task()\n\n"
133
361
  f"Example:\n"
134
- f" async def execute_task(self, task):\n"
135
- f" result = await self.my_framework.run(task['task'])\n"
136
- f" return {{'status': 'success', 'output': result}}\n"
362
+ f" async def on_peer_request(self, msg):\n"
363
+ f" result = await self.process(msg.data)\n"
364
+ f" return {{'status': 'success', 'result': result}}\n"
137
365
  )
@@ -0,0 +1,35 @@
1
+ """
2
+ Testing utilities for JarvisCore.
3
+
4
+ Provides mock implementations for unit testing agents without
5
+ requiring real P2P infrastructure or network connections.
6
+
7
+ Example:
8
+ from jarviscore.testing import MockMesh, MockPeerClient
9
+
10
+ # Using MockMesh for full integration testing
11
+ mesh = MockMesh()
12
+ mesh.add(MyAgent)
13
+ await mesh.start()
14
+
15
+ agent = mesh.get_agent("my_role")
16
+ agent.peers.set_mock_response("analyst", {"result": "test"})
17
+
18
+ # Test and verify
19
+ await agent.process_request(...)
20
+ agent.peers.assert_requested("analyst")
21
+
22
+ # Using MockPeerClient for unit testing
23
+ agent = MyAgent()
24
+ agent.peers = MockPeerClient(mock_peers=[
25
+ {"role": "analyst", "capabilities": ["analysis"]}
26
+ ])
27
+ """
28
+
29
+ from .mocks import MockMesh, MockPeerClient, MockPeerInfo
30
+
31
+ __all__ = [
32
+ 'MockMesh',
33
+ 'MockPeerClient',
34
+ 'MockPeerInfo',
35
+ ]