-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenclaw_memory.py
More file actions
4031 lines (3454 loc) · 141 KB
/
Copy pathopenclaw_memory.py
File metadata and controls
4031 lines (3454 loc) · 141 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
OpenClaw Operational Memory - Neo4j-backed operational memory for the 6-agent system.
This module provides the OperationalMemory class for managing tasks, notifications,
rate limiting, and agent state in a Neo4j graph database.
"""
import logging
import uuid
import time
import functools
from datetime import datetime, timezone
from typing import Dict, List, Optional, Tuple, Any, Callable
from contextlib import contextmanager
from neo4j import GraphDatabase, Driver, Session
from neo4j.exceptions import ServiceUnavailable, Neo4jError, TransientError
# Configure logging
logger = logging.getLogger(__name__)
class RaceConditionError(Exception):
"""Raised when another agent claims a task simultaneously."""
pass
class NoPendingTaskError(Exception):
"""Raised when no pending tasks are available."""
pass
class Neo4jUnavailableError(Exception):
"""Raised when Neo4j is unavailable and fallback mode is disabled."""
pass
def retry_on_race_condition(max_retries: int = 3, base_delay: float = 0.1):
"""
Decorator for automatic retry on race conditions.
Args:
max_retries: Maximum number of retry attempts
base_delay: Base delay between retries (uses exponential backoff)
"""
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
def wrapper(*args, **kwargs):
last_exception = None
for attempt in range(max_retries):
try:
return func(*args, **kwargs)
except RaceConditionError as e:
last_exception = e
if attempt < max_retries - 1:
delay = base_delay * (2 ** attempt)
logger.warning(
f"Race condition in {func.__name__}, "
f"retrying in {delay}s (attempt {attempt + 1}/{max_retries})"
)
time.sleep(delay)
else:
logger.error(
f"Race condition in {func.__name__} persisted after "
f"{max_retries} attempts"
)
raise last_exception
return wrapper
return decorator
class OperationalMemory:
"""
Core operational memory component backed by Neo4j.
Manages:
- Task lifecycle (create, claim, complete)
- Notifications between agents
- Rate limiting
- Agent heartbeat tracking
- Health monitoring
"""
def __init__(
self,
uri: str = "bolt://localhost:7687",
username: str = "neo4j",
password: str | None = None,
database: str = "neo4j",
fallback_mode: bool = True,
max_connection_pool_size: int = 50,
connection_timeout: int = 30,
max_retry_time: int = 30
):
"""
Initialize OperationalMemory with Neo4j connection.
Args:
uri: Neo4j bolt URI
username: Neo4j username
password: Neo4j password (required, must be provided explicitly)
database: Neo4j database name
fallback_mode: If True, return empty results when Neo4j unavailable
max_connection_pool_size: Maximum connections in pool
connection_timeout: Connection timeout in seconds
max_retry_time: Maximum retry time for transient errors
Raises:
ValueError: If password is not provided
"""
if password is None:
raise ValueError("Neo4j password is required. Provide it explicitly or via NEO4J_PASSWORD environment variable.")
self.uri = uri
self.username = username
self.password = password
self.database = database
self.fallback_mode = fallback_mode
self._driver: Optional[Driver] = None
self._pool_config = {
"max_connection_pool_size": max_connection_pool_size,
"connection_timeout": connection_timeout,
"max_transaction_retry_time": max_retry_time
}
self._initialize_driver()
def _initialize_driver(self) -> None:
"""Initialize Neo4j driver with connection pooling."""
try:
self._driver = GraphDatabase.driver(
self.uri,
auth=(self.username, self.password),
**self._pool_config
)
# Verify connectivity
self._driver.verify_connectivity()
logger.info(f"Neo4j driver initialized: {self.uri}")
except ServiceUnavailable as e:
logger.error(f"Failed to connect to Neo4j: {e}")
self._driver = None
if not self.fallback_mode:
raise Neo4jUnavailableError(f"Neo4j unavailable: {e}")
def _ensure_driver(self) -> bool:
"""Ensure driver is available, attempt reconnection if needed."""
if self._driver is None:
self._initialize_driver()
return self._driver is not None
@contextmanager
def _session(self):
"""Context manager for Neo4j sessions."""
if not self._ensure_driver():
if self.fallback_mode:
logger.warning("Neo4j unavailable, operating in fallback mode")
yield None
return
else:
raise Neo4jUnavailableError("Neo4j is not available")
session = None
try:
session = self._driver.session(database=self.database)
yield session
except ServiceUnavailable as e:
logger.error(f"Neo4j service unavailable: {e}")
self._driver = None
if self.fallback_mode:
yield None
else:
raise Neo4jUnavailableError(f"Neo4j service unavailable: {e}")
finally:
if session:
session.close()
def _generate_id(self) -> str:
"""Generate a unique ID."""
return str(uuid.uuid4())
def _now(self) -> datetime:
"""Get current UTC datetime."""
return datetime.now(timezone.utc)
# =======================================================================
# Task Lifecycle
# =======================================================================
def create_task(
self,
task_type: str,
description: str,
delegated_by: str,
assigned_to: str,
priority: str = "normal",
**kwargs
) -> str:
"""
Create a new task node, return task ID.
Args:
task_type: Type of task (e.g., 'code_review', 'deploy')
description: Task description
delegated_by: Agent that delegated the task
assigned_to: Agent assigned to the task (or 'any' for unassigned)
priority: Task priority ('low', 'normal', 'high', 'critical')
**kwargs: Additional task properties
Returns:
Task ID string
"""
task_id = self._generate_id()
created_at = self._now()
# Normalize assigned_to - None or 'any' means unassigned
if assigned_to == 'any':
assigned_to_value = None
else:
assigned_to_value = assigned_to
cypher = """
CREATE (t:Task {
id: $task_id,
type: $task_type,
description: $description,
status: 'pending',
delegated_by: $delegated_by,
assigned_to: $assigned_to,
priority: $priority,
created_at: $created_at,
claimed_at: null,
completed_at: null,
claimed_by: null,
results: null,
error_message: null
})
RETURN t.id as task_id
"""
with self._session() as session:
if session is None:
logger.warning(f"Fallback mode: Task creation simulated for {task_type}")
return task_id
try:
result = session.run(
cypher,
task_id=task_id,
task_type=task_type,
description=description,
delegated_by=delegated_by,
assigned_to=assigned_to_value,
priority=priority,
created_at=created_at
)
record = result.single()
if record:
logger.info(f"Task created: {task_id} (type: {task_type}, assigned_to: {assigned_to})")
return record["task_id"]
else:
raise RuntimeError("Task creation failed: no record returned")
except Neo4jError as e:
logger.error(f"Failed to create task: {e}")
raise
@retry_on_race_condition(max_retries=3, base_delay=0.1)
def claim_task(self, agent: str) -> Optional[Dict]:
"""
Atomically claim a pending task.
Args:
agent: Agent claiming the task
Returns:
Task dict if successful, None if no tasks available
Raises:
RaceConditionError: If another agent claimed the task simultaneously
NoPendingTaskError: If no pending tasks are available
"""
claimed_at = self._now()
# Use explicit locking pattern for atomic claim
cypher = """
MATCH (t:Task {status: 'pending'})
WHERE t.assigned_to = $agent OR t.assigned_to IS NULL
WITH t ORDER BY
CASE t.priority
WHEN 'critical' THEN 4
WHEN 'high' THEN 3
WHEN 'normal' THEN 2
WHEN 'low' THEN 1
ELSE 0
END DESC,
t.created_at ASC
LIMIT 1
SET t.status = 'in_progress',
t.claimed_by = $agent,
t.claimed_at = $claimed_at
RETURN t
"""
with self._session() as session:
if session is None:
logger.warning(f"Fallback mode: Task claim simulated for {agent}")
return None
try:
result = session.run(
cypher,
agent=agent,
claimed_at=claimed_at
)
record = result.single()
if record is None:
raise NoPendingTaskError(f"No pending tasks available for {agent}")
task_node = record["t"]
task_dict = dict(task_node)
logger.info(f"Task claimed: {task_dict['id']} by {agent}")
return task_dict
except (RaceConditionError, NoPendingTaskError):
raise
except Neo4jError as e:
logger.error(f"Failed to claim task: {e}")
raise
def complete_task(
self,
task_id: str,
results: Dict,
notify_delegator: bool = True
) -> bool:
"""
Mark task as complete with results.
Args:
task_id: Task ID to complete
results: Task results dictionary
notify_delegator: Whether to create notification for delegator
Returns:
True if successful
"""
completed_at = self._now()
cypher = """
MATCH (t:Task {id: $task_id})
WHERE t.status = 'in_progress'
SET t.status = 'completed',
t.completed_at = $completed_at,
t.results = $results
RETURN t.delegated_by as delegated_by, t.claimed_by as claimed_by
"""
with self._session() as session:
if session is None:
logger.warning(f"Fallback mode: Task completion simulated for {task_id}")
return True
try:
result = session.run(
cypher,
task_id=task_id,
completed_at=completed_at,
results=str(results) # Neo4j doesn't support nested dicts directly
)
record = result.single()
if record is None:
logger.warning(f"Task not found or not in_progress: {task_id}")
return False
# Create notification for delegator if requested
if notify_delegator and record["delegated_by"]:
self.create_notification(
agent=record["delegated_by"],
type="task_completed",
summary=f"Task {task_id} completed by {record['claimed_by']}",
task_id=task_id
)
logger.info(f"Task completed: {task_id}")
return True
except Neo4jError as e:
logger.error(f"Failed to complete task: {e}")
raise
def fail_task(self, task_id: str, error_message: str) -> bool:
"""
Mark task as failed with error message.
Args:
task_id: Task ID to fail
error_message: Error message describing the failure
Returns:
True if successful
"""
completed_at = self._now()
cypher = """
MATCH (t:Task {id: $task_id})
WHERE t.status = 'in_progress'
SET t.status = 'failed',
t.completed_at = $completed_at,
t.error_message = $error_message
RETURN t.delegated_by as delegated_by, t.claimed_by as claimed_by
"""
with self._session() as session:
if session is None:
logger.warning(f"Fallback mode: Task failure simulated for {task_id}")
return True
try:
result = session.run(
cypher,
task_id=task_id,
completed_at=completed_at,
error_message=error_message
)
record = result.single()
if record is None:
logger.warning(f"Task not found or not in_progress: {task_id}")
return False
# Create notification for delegator
if record["delegated_by"]:
self.create_notification(
agent=record["delegated_by"],
type="task_failed",
summary=f"Task {task_id} failed: {error_message[:100]}",
task_id=task_id
)
logger.info(f"Task failed: {task_id} - {error_message[:100]}")
return True
except Neo4jError as e:
logger.error(f"Failed to mark task as failed: {e}")
raise
def get_task(self, task_id: str) -> Optional[Dict]:
"""
Get task by ID.
Args:
task_id: Task ID to retrieve
Returns:
Task dict if found, None otherwise
"""
cypher = """
MATCH (t:Task {id: $task_id})
RETURN t
"""
with self._session() as session:
if session is None:
return None
try:
result = session.run(cypher, task_id=task_id)
record = result.single()
return dict(record["t"]) if record else None
except Neo4jError as e:
logger.error(f"Failed to get task: {e}")
raise
def list_pending_tasks(self, agent: Optional[str] = None) -> List[Dict]:
"""
List pending tasks, optionally filtered by assigned agent.
Args:
agent: Filter by assigned agent (None for all)
Returns:
List of task dicts
"""
if agent:
cypher = """
MATCH (t:Task {status: 'pending'})
WHERE t.assigned_to = $agent OR t.assigned_to IS NULL
RETURN t
ORDER BY
CASE t.priority
WHEN 'critical' THEN 4
WHEN 'high' THEN 3
WHEN 'normal' THEN 2
WHEN 'low' THEN 1
ELSE 0
END DESC,
t.created_at ASC
"""
params = {"agent": agent}
else:
cypher = """
MATCH (t:Task {status: 'pending'})
RETURN t
ORDER BY
CASE t.priority
WHEN 'critical' THEN 4
WHEN 'high' THEN 3
WHEN 'normal' THEN 2
WHEN 'low' THEN 1
ELSE 0
END DESC,
t.created_at ASC
"""
params = {}
with self._session() as session:
if session is None:
return []
try:
result = session.run(cypher, **params)
return [dict(record["t"]) for record in result]
except Neo4jError as e:
logger.error(f"Failed to list pending tasks: {e}")
raise
def list_tasks_by_status(self, status: str, agent: Optional[str] = None) -> List[Dict]:
"""
List tasks by status.
Args:
status: Task status ('pending', 'in_progress', 'completed', 'failed')
agent: Filter by claimed_by agent (optional)
Returns:
List of task dicts
"""
if agent:
cypher = """
MATCH (t:Task {status: $status, claimed_by: $agent})
RETURN t
ORDER BY t.created_at DESC
"""
params = {"status": status, "agent": agent}
else:
cypher = """
MATCH (t:Task {status: $status})
RETURN t
ORDER BY t.created_at DESC
"""
params = {"status": status}
with self._session() as session:
if session is None:
return []
try:
result = session.run(cypher, **params)
return [dict(record["t"]) for record in result]
except Neo4jError as e:
logger.error(f"Failed to list tasks: {e}")
raise
# =======================================================================
# Notification System
# =======================================================================
def create_notification(
self,
agent: str,
type: str,
summary: str,
task_id: Optional[str] = None
) -> str:
"""
Create notification for an agent.
Args:
agent: Agent to notify
type: Notification type (e.g., 'task_completed', 'task_failed')
summary: Notification summary
task_id: Associated task ID (optional)
Returns:
Notification ID
"""
notification_id = self._generate_id()
created_at = self._now()
cypher = """
CREATE (n:Notification {
id: $notification_id,
agent: $agent,
type: $type,
summary: $summary,
task_id: $task_id,
read: false,
created_at: $created_at
})
RETURN n.id as notification_id
"""
with self._session() as session:
if session is None:
logger.warning(f"Fallback mode: Notification creation simulated for {agent}")
return notification_id
try:
result = session.run(
cypher,
notification_id=notification_id,
agent=agent,
type=type,
summary=summary,
task_id=task_id,
created_at=created_at
)
record = result.single()
if record:
logger.info(f"Notification created: {notification_id} for {agent}")
return record["notification_id"]
else:
raise RuntimeError("Notification creation failed")
except Neo4jError as e:
logger.error(f"Failed to create notification: {e}")
raise
def get_notifications(
self,
agent: str,
unread_only: bool = True
) -> List[Dict]:
"""
Get notifications for an agent.
Args:
agent: Agent to get notifications for
unread_only: If True, only return unread notifications
Returns:
List of notification dicts
"""
if unread_only:
cypher = """
MATCH (n:Notification {agent: $agent, read: false})
RETURN n
ORDER BY n.created_at DESC
"""
else:
cypher = """
MATCH (n:Notification {agent: $agent})
RETURN n
ORDER BY n.created_at DESC
"""
with self._session() as session:
if session is None:
return []
try:
result = session.run(cypher, agent=agent)
return [dict(record["n"]) for record in result]
except Neo4jError as e:
logger.error(f"Failed to get notifications: {e}")
raise
def mark_notification_read(self, notification_id: str) -> bool:
"""
Mark notification as read.
Args:
notification_id: Notification ID to mark as read
Returns:
True if successful
"""
cypher = """
MATCH (n:Notification {id: $notification_id})
SET n.read = true
RETURN n.id as notification_id
"""
with self._session() as session:
if session is None:
return True
try:
result = session.run(cypher, notification_id=notification_id)
record = result.single()
if record:
logger.debug(f"Notification marked read: {notification_id}")
return True
return False
except Neo4jError as e:
logger.error(f"Failed to mark notification as read: {e}")
raise
def mark_all_notifications_read(self, agent: str) -> int:
"""
Mark all notifications as read for an agent.
Args:
agent: Agent to mark notifications for
Returns:
Number of notifications marked as read
"""
cypher = """
MATCH (n:Notification {agent: $agent, read: false})
SET n.read = true
RETURN count(n) as count
"""
with self._session() as session:
if session is None:
return 0
try:
result = session.run(cypher, agent=agent)
record = result.single()
count = record["count"] if record else 0
logger.info(f"Marked {count} notifications as read for {agent}")
return count
except Neo4jError as e:
logger.error(f"Failed to mark notifications as read: {e}")
raise
# =======================================================================
# Rate Limiting
# =======================================================================
def check_rate_limit(
self,
agent: str,
operation: str,
max_requests: int = 1000
) -> Tuple[bool, int, int]:
"""
Check if operation is within rate limit.
Uses hourly buckets for rate limiting.
Args:
agent: Agent making the request
operation: Operation type being rate limited
max_requests: Maximum requests per hour
Returns:
Tuple of (allowed, current_count, reset_time)
- allowed: True if within limit
- current_count: Current request count
- reset_time: Unix timestamp when bucket resets
"""
now = self._now()
current_date = now.date()
current_hour = now.hour
# Calculate reset time (start of next hour)
from datetime import timedelta
if current_hour == 23:
reset_time = int((datetime.combine(current_date + timedelta(days=1), datetime.min.time().replace(hour=0)) - datetime(1970, 1, 1)).total_seconds())
else:
reset_time = int((datetime.combine(current_date, datetime.min.time().replace(hour=current_hour + 1)) - datetime(1970, 1, 1)).total_seconds())
cypher = """
MATCH (r:RateLimit {agent: $agent, operation: $operation, date: $date, hour: $hour})
RETURN r.count as count
"""
with self._session() as session:
if session is None:
# In fallback mode, always allow
return (True, 0, reset_time)
try:
result = session.run(
cypher,
agent=agent,
operation=operation,
date=current_date,
hour=current_hour
)
record = result.single()
if record is None:
# No rate limit record yet, create one
self._create_rate_limit_record(agent, operation, current_date, current_hour)
return (True, 0, reset_time)
count = record["count"]
allowed = count < max_requests
return (allowed, count, reset_time)
except Neo4jError as e:
logger.error(f"Failed to check rate limit: {e}")
# Fail open - allow the request
return (True, 0, reset_time)
def _create_rate_limit_record(
self,
agent: str,
operation: str,
date,
hour: int
) -> None:
"""Create a new rate limit record."""
cypher = """
MERGE (r:RateLimit {agent: $agent, operation: $operation, date: $date, hour: $hour})
ON CREATE SET r.count = 0, r.last_updated = $last_updated
"""
with self._session() as session:
if session is None:
return
try:
session.run(
cypher,
agent=agent,
operation=operation,
date=date,
hour=hour,
last_updated=self._now()
)
except Neo4jError as e:
logger.error(f"Failed to create rate limit record: {e}")
def record_rate_limit_hit(self, agent: str, operation: str) -> bool:
"""
Record a rate limit hit.
Args:
agent: Agent making the request
operation: Operation type
Returns:
True if successful
"""
now = self._now()
current_date = now.date()
current_hour = now.hour
cypher = """
MERGE (r:RateLimit {agent: $agent, operation: $operation, date: $date, hour: $hour})
ON CREATE SET r.count = 1, r.last_updated = $last_updated
ON MATCH SET r.count = r.count + 1, r.last_updated = $last_updated
RETURN r.count as count
"""
with self._session() as session:
if session is None:
return True
try:
result = session.run(
cypher,
agent=agent,
operation=operation,
date=current_date,
hour=current_hour,
last_updated=now
)
record = result.single()
if record:
logger.debug(
f"Rate limit hit recorded: {agent}/{operation} = {record['count']}"
)
return True
return False
except Neo4jError as e:
logger.error(f"Failed to record rate limit hit: {e}")
return False
# =======================================================================
# Agent State Management
# =======================================================================
def update_agent_heartbeat(self, agent: str, status: str = "active") -> bool:
"""
Update agent heartbeat timestamp.
Args:
agent: Agent name
status: Agent status ('active', 'busy', 'idle', 'offline')
Returns:
True if successful
"""
now = self._now()
cypher = """
MERGE (a:Agent {name: $agent})
ON CREATE SET a.created_at = $now
SET a.last_heartbeat = $now,
a.status = $status
RETURN a.name as name
"""
with self._session() as session:
if session is None:
return True
try:
result = session.run(
cypher,
agent=agent,
status=status,
now=now
)
record = result.single()
if record:
logger.debug(f"Agent heartbeat updated: {agent} ({status})")
return True
return False
except Neo4jError as e:
logger.error(f"Failed to update agent heartbeat: {e}")
raise
def get_agent_status(self, agent: str) -> Optional[Dict]:
"""
Get agent status including last heartbeat.
Args:
agent: Agent name
Returns:
Agent status dict if found, None otherwise
"""
cypher = """
MATCH (a:Agent {name: $agent})
RETURN a
"""
with self._session() as session:
if session is None:
return None
try:
result = session.run(cypher, agent=agent)
record = result.single()
return dict(record["a"]) if record else None
except Neo4jError as e:
logger.error(f"Failed to get agent status: {e}")
raise
def list_active_agents(self, inactive_threshold_seconds: int = 300) -> List[Dict]:
"""
List all active agents.
Args:
inactive_threshold_seconds: Consider agent inactive after this many seconds
Returns:
List of agent dicts with activity status
"""
now = self._now()
cypher = """
MATCH (a:Agent)
RETURN a,
CASE
WHEN a.last_heartbeat >= datetime($threshold) THEN true
ELSE false
END as is_active
ORDER BY a.last_heartbeat DESC
"""
threshold = (now.timestamp() - inactive_threshold_seconds) * 1000 # milliseconds
with self._session() as session:
if session is None:
return []
try:
result = session.run(cypher, threshold=threshold)
agents = []
for record in result:
agent_dict = dict(record["a"])
agent_dict["is_active"] = record["is_active"]
agents.append(agent_dict)
return agents
except Neo4jError as e:
logger.error(f"Failed to list active agents: {e}")
raise
def set_agent_busy(self, agent: str, busy: bool = True) -> bool:
"""
Set agent busy status.
Args:
agent: Agent name
busy: True to mark as busy, False for available
Returns:
True if successful
"""
status = "busy" if busy else "active"
return self.update_agent_heartbeat(agent, status)