l9-graphite-memory 2.3.1__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.
- l9_graphite_memory/__init__.py +37 -0
- l9_graphite_memory/__main__.py +15 -0
- l9_graphite_memory/active/__init__.py +98 -0
- l9_graphite_memory/active/client.py +448 -0
- l9_graphite_memory/active/credentials.py +253 -0
- l9_graphite_memory/active/deployment.py +163 -0
- l9_graphite_memory/active/errors.py +81 -0
- l9_graphite_memory/active/inmemory.py +406 -0
- l9_graphite_memory/active/lifecycle.py +120 -0
- l9_graphite_memory/active/models.py +408 -0
- l9_graphite_memory/active/null_adapters.py +118 -0
- l9_graphite_memory/active/ports.py +170 -0
- l9_graphite_memory/active/redis_adapters.py +510 -0
- l9_graphite_memory/adapters/__init__.py +42 -0
- l9_graphite_memory/adapters/factory.py +81 -0
- l9_graphite_memory/adapters/graphiti_projection.py +267 -0
- l9_graphite_memory/adapters/in_memory_store.py +548 -0
- l9_graphite_memory/adapters/null_projection.py +82 -0
- l9_graphite_memory/adapters/postgres_store.py +1359 -0
- l9_graphite_memory/adapters/sqlite_store.py +1278 -0
- l9_graphite_memory/admission/__init__.py +22 -0
- l9_graphite_memory/admission/engine.py +126 -0
- l9_graphite_memory/admission/normalization.py +110 -0
- l9_graphite_memory/admission/policy.py +32 -0
- l9_graphite_memory/authz/__init__.py +16 -0
- l9_graphite_memory/authz/authenticator.py +84 -0
- l9_graphite_memory/authz/policy.py +87 -0
- l9_graphite_memory/circuit_breaker.py +92 -0
- l9_graphite_memory/cli.py +1283 -0
- l9_graphite_memory/client_config/__init__.py +55 -0
- l9_graphite_memory/client_config/contracts.py +141 -0
- l9_graphite_memory/client_config/cursor.py +422 -0
- l9_graphite_memory/client_config/mcp_probe.py +358 -0
- l9_graphite_memory/config/__init__.py +16 -0
- l9_graphite_memory/config/loader.py +183 -0
- l9_graphite_memory/config/models.py +139 -0
- l9_graphite_memory/contracts/__init__.py +204 -0
- l9_graphite_memory/contracts/capabilities.py +179 -0
- l9_graphite_memory/contracts/enums.py +139 -0
- l9_graphite_memory/contracts/evidence.py +258 -0
- l9_graphite_memory/contracts/generated_data.py +269 -0
- l9_graphite_memory/contracts/identity.py +55 -0
- l9_graphite_memory/contracts/maintenance.py +118 -0
- l9_graphite_memory/contracts/memory.py +104 -0
- l9_graphite_memory/contracts/privacy.py +64 -0
- l9_graphite_memory/contracts/profiles.py +96 -0
- l9_graphite_memory/contracts/projection.py +122 -0
- l9_graphite_memory/contracts/receipts.py +383 -0
- l9_graphite_memory/contracts/requests.py +184 -0
- l9_graphite_memory/contracts/review.py +101 -0
- l9_graphite_memory/contracts/temporal.py +91 -0
- l9_graphite_memory/curation/__init__.py +35 -0
- l9_graphite_memory/curation/procedural.py +173 -0
- l9_graphite_memory/curation/promotion.py +59 -0
- l9_graphite_memory/curation/quarantine.py +265 -0
- l9_graphite_memory/curation/retention.py +109 -0
- l9_graphite_memory/episode_contract.py +68 -0
- l9_graphite_memory/errors.py +102 -0
- l9_graphite_memory/extraction/__init__.py +30 -0
- l9_graphite_memory/extraction/atomic.py +218 -0
- l9_graphite_memory/extraction/distiller.py +141 -0
- l9_graphite_memory/graphiti_gate_lib.py +67 -0
- l9_graphite_memory/graphiti_memory_client.py +21 -0
- l9_graphite_memory/group_resolver.py +155 -0
- l9_graphite_memory/ingestion/__init__.py +50 -0
- l9_graphite_memory/ingestion/document.py +140 -0
- l9_graphite_memory/ingestion/profiles.py +187 -0
- l9_graphite_memory/ingestion/publication_identity.py +460 -0
- l9_graphite_memory/ingestion/repository.py +85 -0
- l9_graphite_memory/ingestion/topology_publication.py +623 -0
- l9_graphite_memory/integrations/__init__.py +47 -0
- l9_graphite_memory/integrations/constellation.py +134 -0
- l9_graphite_memory/integrations/gate_client.py +251 -0
- l9_graphite_memory/integrations/session.py +126 -0
- l9_graphite_memory/integrations/transport_packet.py +201 -0
- l9_graphite_memory/integrity/__init__.py +15 -0
- l9_graphite_memory/integrity/checkpoint.py +98 -0
- l9_graphite_memory/lineage/__init__.py +15 -0
- l9_graphite_memory/lineage/replay.py +123 -0
- l9_graphite_memory/maintenance/__init__.py +21 -0
- l9_graphite_memory/maintenance/planner.py +562 -0
- l9_graphite_memory/maintenance/service.py +542 -0
- l9_graphite_memory/mcp_tools.py +760 -0
- l9_graphite_memory/memory_guard.py +248 -0
- l9_graphite_memory/migration/__init__.py +35 -0
- l9_graphite_memory/migration/backend_transition.py +173 -0
- l9_graphite_memory/migration/legacy_write_queue.py +209 -0
- l9_graphite_memory/observability/__init__.py +15 -0
- l9_graphite_memory/observability/logging.py +81 -0
- l9_graphite_memory/ports/__init__.py +49 -0
- l9_graphite_memory/ports/clock.py +25 -0
- l9_graphite_memory/ports/constellation.py +66 -0
- l9_graphite_memory/ports/phase_lock.py +73 -0
- l9_graphite_memory/ports/projection.py +92 -0
- l9_graphite_memory/ports/record_store.py +285 -0
- l9_graphite_memory/ports/review.py +34 -0
- l9_graphite_memory/ports/service_capability.py +74 -0
- l9_graphite_memory/ports/synthesis.py +34 -0
- l9_graphite_memory/projections/__init__.py +43 -0
- l9_graphite_memory/projections/compiler.py +117 -0
- l9_graphite_memory/projections/contracts.py +292 -0
- l9_graphite_memory/projections/manifest.py +55 -0
- l9_graphite_memory/projections/render.py +110 -0
- l9_graphite_memory/prune.py +42 -0
- l9_graphite_memory/rate_limiter.py +79 -0
- l9_graphite_memory/resources/active_memory_redis_capabilities.yaml +34 -0
- l9_graphite_memory/resources/defaults.yaml +24 -0
- l9_graphite_memory/resources/group_registry.yaml +37 -0
- l9_graphite_memory/resources/memory_contract.yaml +48 -0
- l9_graphite_memory/resources/projections/schema.json +408 -0
- l9_graphite_memory/retrieval/__init__.py +24 -0
- l9_graphite_memory/retrieval/budget.py +100 -0
- l9_graphite_memory/retrieval/planner.py +265 -0
- l9_graphite_memory/retrieval/query_classifier.py +89 -0
- l9_graphite_memory/retrieval/ranking.py +161 -0
- l9_graphite_memory/runtime.py +116 -0
- l9_graphite_memory/schema/__init__.py +17 -0
- l9_graphite_memory/schema/registry.py +88 -0
- l9_graphite_memory/schema/upcasters.py +184 -0
- l9_graphite_memory/sdk.py +88 -0
- l9_graphite_memory/secrets.py +189 -0
- l9_graphite_memory/server.py +285 -0
- l9_graphite_memory/services/__init__.py +17 -0
- l9_graphite_memory/services/generated_data.py +350 -0
- l9_graphite_memory/services/memory_service.py +1346 -0
- l9_graphite_memory/services/outbox_worker.py +356 -0
- l9_graphite_memory/transport.py +343 -0
- l9_graphite_memory/trust_boundary.py +78 -0
- l9_graphite_memory/version.py +32 -0
- l9_graphite_memory/zep_transport.py +225 -0
- l9_graphite_memory-2.3.1.dist-info/METADATA +213 -0
- l9_graphite_memory-2.3.1.dist-info/RECORD +136 -0
- l9_graphite_memory-2.3.1.dist-info/WHEEL +5 -0
- l9_graphite_memory-2.3.1.dist-info/entry_points.txt +4 -0
- l9_graphite_memory-2.3.1.dist-info/licenses/LICENSE +104 -0
- l9_graphite_memory-2.3.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# L9_META
|
|
2
|
+
# l9_schema: 1
|
|
3
|
+
# repo: Quantum-L9/l9-graphiti-memory
|
|
4
|
+
# path: src/l9_graphite_memory/__init__.py
|
|
5
|
+
# layer: package
|
|
6
|
+
# owner: memory-control-plane
|
|
7
|
+
# status: active
|
|
8
|
+
# version: 2.2.0
|
|
9
|
+
# updated: 2026-07-22
|
|
10
|
+
|
|
11
|
+
"""L9 Graphite Memory public API."""
|
|
12
|
+
|
|
13
|
+
from . import contracts
|
|
14
|
+
from .integrations import ContextRestorer, SessionEvent, SessionIngestor
|
|
15
|
+
from .integrity import CheckpointEnvelope, CheckpointIntegrity
|
|
16
|
+
from .migration import LegacyDrainReport, LegacyWriteQueueDrain
|
|
17
|
+
from .sdk import MemorySDK
|
|
18
|
+
from .services.memory_service import MemoryService
|
|
19
|
+
from .version import MEMORY_SCHEMA_VERSION, PACKAGE_VERSION
|
|
20
|
+
|
|
21
|
+
__version__ = PACKAGE_VERSION
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"MEMORY_SCHEMA_VERSION",
|
|
25
|
+
"PACKAGE_VERSION",
|
|
26
|
+
"CheckpointEnvelope",
|
|
27
|
+
"CheckpointIntegrity",
|
|
28
|
+
"ContextRestorer",
|
|
29
|
+
"LegacyDrainReport",
|
|
30
|
+
"LegacyWriteQueueDrain",
|
|
31
|
+
"MemorySDK",
|
|
32
|
+
"MemoryService",
|
|
33
|
+
"SessionEvent",
|
|
34
|
+
"SessionIngestor",
|
|
35
|
+
"__version__",
|
|
36
|
+
"contracts",
|
|
37
|
+
]
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# L9_META
|
|
2
|
+
# l9_schema: 1
|
|
3
|
+
# repo: Quantum-L9/l9-graphiti-memory
|
|
4
|
+
# path: src/l9_graphite_memory/__main__.py
|
|
5
|
+
# layer: package
|
|
6
|
+
# owner: memory-control-plane
|
|
7
|
+
# status: active
|
|
8
|
+
# version: 2.2.0
|
|
9
|
+
# updated: 2026-07-22
|
|
10
|
+
|
|
11
|
+
"""Run the package CLI with ``python -m l9_graphite_memory``."""
|
|
12
|
+
|
|
13
|
+
from .cli import main
|
|
14
|
+
|
|
15
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# L9_META
|
|
2
|
+
# l9_schema: 1
|
|
3
|
+
# repo: Quantum-L9/l9-graphiti-memory
|
|
4
|
+
# path: src/l9_graphite_memory/active/__init__.py
|
|
5
|
+
# layer: package
|
|
6
|
+
# owner: memory-control-plane
|
|
7
|
+
# status: active
|
|
8
|
+
# version: 2.2.0
|
|
9
|
+
# updated: 2026-07-22
|
|
10
|
+
|
|
11
|
+
"""Active multi-agent memory subsystem (deployment-neutral).
|
|
12
|
+
|
|
13
|
+
This package provides the deployment-identity, secret-file credential
|
|
14
|
+
resolution, and stable external SDK contracts for the Redis-backed
|
|
15
|
+
active-memory layer described in ADR-065 through ADR-068.
|
|
16
|
+
|
|
17
|
+
This package intentionally contains no consumer-specific (e.g. Igorbot,
|
|
18
|
+
OpenClaw, Hetzner) identifiers, configuration, or deployment logic. All
|
|
19
|
+
contents here are domain-neutral and reusable by any external runtime.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from l9_graphite_memory.active.client import (
|
|
23
|
+
ActiveAgentClient,
|
|
24
|
+
ActiveAgentSession,
|
|
25
|
+
)
|
|
26
|
+
from l9_graphite_memory.active.credentials import (
|
|
27
|
+
AmbiguousCredentialSourceError,
|
|
28
|
+
CredentialResolutionError,
|
|
29
|
+
RedisCredentialSettings,
|
|
30
|
+
ResolvedRedisCredential,
|
|
31
|
+
resolve_redis_credential,
|
|
32
|
+
)
|
|
33
|
+
from l9_graphite_memory.active.deployment import (
|
|
34
|
+
ActiveDeployment,
|
|
35
|
+
DeploymentEnvironment,
|
|
36
|
+
DeploymentIdentityError,
|
|
37
|
+
derive_deployment_hash,
|
|
38
|
+
validate_identifier,
|
|
39
|
+
)
|
|
40
|
+
from l9_graphite_memory.active.errors import (
|
|
41
|
+
ActiveMemoryError,
|
|
42
|
+
ActiveMemoryUnavailableError,
|
|
43
|
+
ContextVersionConflictError,
|
|
44
|
+
LeaseExpiredError,
|
|
45
|
+
SchemaCompatibilityError,
|
|
46
|
+
)
|
|
47
|
+
from l9_graphite_memory.active.lifecycle import (
|
|
48
|
+
ActiveAgentSessionState,
|
|
49
|
+
LifecycleTransitionError,
|
|
50
|
+
SessionLifecycle,
|
|
51
|
+
)
|
|
52
|
+
from l9_graphite_memory.active.models import (
|
|
53
|
+
ActiveContext,
|
|
54
|
+
ActiveContextDraft,
|
|
55
|
+
ActiveObservation,
|
|
56
|
+
AgentEvent,
|
|
57
|
+
AgentEventType,
|
|
58
|
+
AgentIdentity,
|
|
59
|
+
AgentLease,
|
|
60
|
+
AgentPresence,
|
|
61
|
+
AgentScope,
|
|
62
|
+
AgentStatus,
|
|
63
|
+
AgentSubscription,
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
__all__ = [
|
|
67
|
+
"ActiveAgentClient",
|
|
68
|
+
"ActiveAgentSession",
|
|
69
|
+
"ActiveAgentSessionState",
|
|
70
|
+
"ActiveContext",
|
|
71
|
+
"ActiveContextDraft",
|
|
72
|
+
"ActiveDeployment",
|
|
73
|
+
"ActiveMemoryError",
|
|
74
|
+
"ActiveMemoryUnavailableError",
|
|
75
|
+
"ActiveObservation",
|
|
76
|
+
"AgentEvent",
|
|
77
|
+
"AgentEventType",
|
|
78
|
+
"AgentIdentity",
|
|
79
|
+
"AgentLease",
|
|
80
|
+
"AgentPresence",
|
|
81
|
+
"AgentScope",
|
|
82
|
+
"AgentStatus",
|
|
83
|
+
"AgentSubscription",
|
|
84
|
+
"AmbiguousCredentialSourceError",
|
|
85
|
+
"ContextVersionConflictError",
|
|
86
|
+
"CredentialResolutionError",
|
|
87
|
+
"DeploymentEnvironment",
|
|
88
|
+
"DeploymentIdentityError",
|
|
89
|
+
"LeaseExpiredError",
|
|
90
|
+
"LifecycleTransitionError",
|
|
91
|
+
"RedisCredentialSettings",
|
|
92
|
+
"ResolvedRedisCredential",
|
|
93
|
+
"SchemaCompatibilityError",
|
|
94
|
+
"SessionLifecycle",
|
|
95
|
+
"derive_deployment_hash",
|
|
96
|
+
"resolve_redis_credential",
|
|
97
|
+
"validate_identifier",
|
|
98
|
+
]
|
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
# L9_META
|
|
2
|
+
# l9_schema: 1
|
|
3
|
+
# repo: Quantum-L9/l9-graphiti-memory
|
|
4
|
+
# path: src/l9_graphite_memory/active/client.py
|
|
5
|
+
# layer: package
|
|
6
|
+
# owner: memory-control-plane
|
|
7
|
+
# status: active
|
|
8
|
+
# version: 2.2.0
|
|
9
|
+
# updated: 2026-07-22
|
|
10
|
+
|
|
11
|
+
"""Stable external SDK surface for the active-memory subsystem.
|
|
12
|
+
|
|
13
|
+
`ActiveAgentClient` and `ActiveAgentSession` are the ONLY supported
|
|
14
|
+
integration points for external consumer applications (per ADR-067).
|
|
15
|
+
Consumers MUST NOT import `l9_graphite_memory.active.inmemory` or any
|
|
16
|
+
future Redis adapter module directly; those are internal implementation
|
|
17
|
+
details subject to change without a major version bump.
|
|
18
|
+
|
|
19
|
+
This module depends only on the ports defined in
|
|
20
|
+
`l9_graphite_memory.active.ports`, so it works identically against the
|
|
21
|
+
in-memory reference adapter, the null adapter, or a Redis adapter,
|
|
22
|
+
without any consumer-specific branching.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import asyncio
|
|
28
|
+
import logging
|
|
29
|
+
import uuid
|
|
30
|
+
from collections.abc import AsyncIterator, Callable
|
|
31
|
+
from contextlib import asynccontextmanager
|
|
32
|
+
from dataclasses import dataclass
|
|
33
|
+
from datetime import datetime, timedelta, timezone
|
|
34
|
+
|
|
35
|
+
from l9_graphite_memory.active.errors import (
|
|
36
|
+
ActiveMemoryUnavailableError,
|
|
37
|
+
LeaseExpiredError,
|
|
38
|
+
)
|
|
39
|
+
from l9_graphite_memory.active.lifecycle import (
|
|
40
|
+
ActiveAgentSessionState,
|
|
41
|
+
LifecycleTransitionError,
|
|
42
|
+
SessionLifecycle,
|
|
43
|
+
)
|
|
44
|
+
from l9_graphite_memory.active.models import (
|
|
45
|
+
ActiveContext,
|
|
46
|
+
ActiveContextDraft,
|
|
47
|
+
AgentEvent,
|
|
48
|
+
AgentIdentity,
|
|
49
|
+
AgentLease,
|
|
50
|
+
AgentPresence,
|
|
51
|
+
AgentScope,
|
|
52
|
+
AgentStatus,
|
|
53
|
+
AgentSubscription,
|
|
54
|
+
)
|
|
55
|
+
from l9_graphite_memory.active.ports import ActiveStore, AwarenessBus
|
|
56
|
+
|
|
57
|
+
logger = logging.getLogger("l9_graphite_memory.active.client")
|
|
58
|
+
|
|
59
|
+
Clock = Callable[[], datetime]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _default_clock() -> datetime:
|
|
63
|
+
return datetime.now(timezone.utc)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(slots=True)
|
|
67
|
+
class _SessionRuntimeConfig:
|
|
68
|
+
heartbeat_interval_seconds: int
|
|
69
|
+
lease_ttl_seconds: int
|
|
70
|
+
heartbeat_failure_threshold: int
|
|
71
|
+
resync_backoff_seconds: float
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class ActiveAgentClient:
|
|
75
|
+
"""Entry point for constructing external-runtime active-memory sessions.
|
|
76
|
+
|
|
77
|
+
Instances are constructed by the runtime factory
|
|
78
|
+
(`l9_graphite_memory.adapters.factory.ActiveMemoryFactory`) and bound
|
|
79
|
+
to exactly one `ActiveStore`/`AwarenessBus` pair for one deployment.
|
|
80
|
+
External consumer code receives an already-constructed
|
|
81
|
+
`ActiveAgentClient` and never instantiates adapters itself.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
def __init__(
|
|
85
|
+
self,
|
|
86
|
+
*,
|
|
87
|
+
store: ActiveStore,
|
|
88
|
+
bus: AwarenessBus,
|
|
89
|
+
deployment_id: str,
|
|
90
|
+
clock: Clock = _default_clock,
|
|
91
|
+
heartbeat_interval_seconds: int = 10,
|
|
92
|
+
lease_ttl_seconds: int = 30,
|
|
93
|
+
heartbeat_failure_threshold: int = 3,
|
|
94
|
+
resync_backoff_seconds: float = 1.0,
|
|
95
|
+
) -> None:
|
|
96
|
+
self._store = store
|
|
97
|
+
self._bus = bus
|
|
98
|
+
self._deployment_id = deployment_id
|
|
99
|
+
self._clock = clock
|
|
100
|
+
self._runtime_config = _SessionRuntimeConfig(
|
|
101
|
+
heartbeat_interval_seconds=heartbeat_interval_seconds,
|
|
102
|
+
lease_ttl_seconds=lease_ttl_seconds,
|
|
103
|
+
heartbeat_failure_threshold=heartbeat_failure_threshold,
|
|
104
|
+
resync_backoff_seconds=resync_backoff_seconds,
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
@asynccontextmanager
|
|
108
|
+
async def open_session(
|
|
109
|
+
self,
|
|
110
|
+
*,
|
|
111
|
+
agent_id: str,
|
|
112
|
+
role: str,
|
|
113
|
+
principal_id: str,
|
|
114
|
+
group_ids: tuple[str, ...] = (),
|
|
115
|
+
session_id: str | None = None,
|
|
116
|
+
capabilities: frozenset[str] = frozenset(),
|
|
117
|
+
) -> AsyncIterator[ActiveAgentSession]:
|
|
118
|
+
"""Open a supervised active-agent session as an async context manager.
|
|
119
|
+
|
|
120
|
+
On exit (including exception), the session transitions through
|
|
121
|
+
DRAINING to CLOSED, unregistering its lease and stopping all
|
|
122
|
+
background tasks. This is the only supported way to obtain an
|
|
123
|
+
`ActiveAgentSession`.
|
|
124
|
+
"""
|
|
125
|
+
session = ActiveAgentSession(
|
|
126
|
+
store=self._store,
|
|
127
|
+
bus=self._bus,
|
|
128
|
+
deployment_id=self._deployment_id,
|
|
129
|
+
agent_id=agent_id,
|
|
130
|
+
role=role,
|
|
131
|
+
principal_id=principal_id,
|
|
132
|
+
group_ids=group_ids,
|
|
133
|
+
session_id=session_id,
|
|
134
|
+
capabilities=capabilities,
|
|
135
|
+
clock=self._clock,
|
|
136
|
+
runtime_config=self._runtime_config,
|
|
137
|
+
)
|
|
138
|
+
try:
|
|
139
|
+
await session.start()
|
|
140
|
+
yield session
|
|
141
|
+
finally:
|
|
142
|
+
await session.close()
|
|
143
|
+
|
|
144
|
+
async def close(self) -> None:
|
|
145
|
+
"""Release the underlying store and bus resources.
|
|
146
|
+
|
|
147
|
+
Must be called once during application shutdown after all
|
|
148
|
+
sessions have been closed.
|
|
149
|
+
"""
|
|
150
|
+
await self._store.close()
|
|
151
|
+
await self._bus.close()
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class ActiveAgentSession:
|
|
155
|
+
"""One external agent's supervised active-memory session.
|
|
156
|
+
|
|
157
|
+
Manages: registration, heartbeat renewal, context writes, peer
|
|
158
|
+
discovery, event subscription, degradation detection, reconnect and
|
|
159
|
+
resynchronization, and graceful shutdown. See ADR-067 for the full
|
|
160
|
+
state machine and background-task supervision requirements.
|
|
161
|
+
"""
|
|
162
|
+
|
|
163
|
+
def __init__(
|
|
164
|
+
self,
|
|
165
|
+
*,
|
|
166
|
+
store: ActiveStore,
|
|
167
|
+
bus: AwarenessBus,
|
|
168
|
+
deployment_id: str,
|
|
169
|
+
agent_id: str,
|
|
170
|
+
role: str,
|
|
171
|
+
principal_id: str,
|
|
172
|
+
group_ids: tuple[str, ...],
|
|
173
|
+
session_id: str | None,
|
|
174
|
+
capabilities: frozenset[str],
|
|
175
|
+
clock: Clock,
|
|
176
|
+
runtime_config: _SessionRuntimeConfig,
|
|
177
|
+
) -> None:
|
|
178
|
+
self._store = store
|
|
179
|
+
self._bus = bus
|
|
180
|
+
self._deployment_id = deployment_id
|
|
181
|
+
self._agent_id = agent_id
|
|
182
|
+
self._role = role
|
|
183
|
+
self._principal_id = principal_id
|
|
184
|
+
self._group_ids = group_ids
|
|
185
|
+
self._session_id = session_id
|
|
186
|
+
self._capabilities = capabilities
|
|
187
|
+
self._clock = clock
|
|
188
|
+
self._runtime_config = runtime_config
|
|
189
|
+
|
|
190
|
+
self._lifecycle = SessionLifecycle()
|
|
191
|
+
self._instance_id = self._generate_instance_id()
|
|
192
|
+
self._lease: AgentLease | None = None
|
|
193
|
+
self._heartbeat_task: asyncio.Task[None] | None = None
|
|
194
|
+
self._heartbeat_failures = 0
|
|
195
|
+
self._background_exception: BaseException | None = None
|
|
196
|
+
self._closed = asyncio.Event()
|
|
197
|
+
|
|
198
|
+
@staticmethod
|
|
199
|
+
def _generate_instance_id() -> str:
|
|
200
|
+
return uuid.uuid4().hex
|
|
201
|
+
|
|
202
|
+
@property
|
|
203
|
+
def state(self) -> ActiveAgentSessionState:
|
|
204
|
+
"""Current lifecycle state of this session."""
|
|
205
|
+
return self._lifecycle.state
|
|
206
|
+
|
|
207
|
+
@property
|
|
208
|
+
def instance_id(self) -> str:
|
|
209
|
+
"""This session's current process-incarnation identifier.
|
|
210
|
+
|
|
211
|
+
Changes on every re-registration; the `agent_id` remains stable.
|
|
212
|
+
"""
|
|
213
|
+
return self._instance_id
|
|
214
|
+
|
|
215
|
+
def background_exception(self) -> BaseException | None:
|
|
216
|
+
"""Return any exception raised by a supervised background task.
|
|
217
|
+
|
|
218
|
+
External runtimes MUST poll this (or check it after `close()`)
|
|
219
|
+
to avoid silently losing heartbeat/subscription failures.
|
|
220
|
+
"""
|
|
221
|
+
return self._background_exception
|
|
222
|
+
|
|
223
|
+
async def start(self) -> None:
|
|
224
|
+
"""Register this agent instance and start heartbeat supervision.
|
|
225
|
+
|
|
226
|
+
Raises:
|
|
227
|
+
ActiveMemoryUnavailableError: if registration fails because
|
|
228
|
+
the backend cannot be reached.
|
|
229
|
+
"""
|
|
230
|
+
self._lifecycle.transition_to(ActiveAgentSessionState.REGISTERING)
|
|
231
|
+
try:
|
|
232
|
+
await self._register()
|
|
233
|
+
except ActiveMemoryUnavailableError:
|
|
234
|
+
self._lifecycle.transition_to(ActiveAgentSessionState.FAILED)
|
|
235
|
+
raise
|
|
236
|
+
self._lifecycle.transition_to(ActiveAgentSessionState.ACTIVE)
|
|
237
|
+
self._heartbeat_task = asyncio.ensure_future(self._heartbeat_loop())
|
|
238
|
+
|
|
239
|
+
async def _register(self) -> None:
|
|
240
|
+
now = self._clock()
|
|
241
|
+
identity = AgentIdentity(
|
|
242
|
+
agent_id=self._agent_id,
|
|
243
|
+
instance_id=self._instance_id,
|
|
244
|
+
role=self._role,
|
|
245
|
+
principal_id=self._principal_id,
|
|
246
|
+
capabilities=self._capabilities,
|
|
247
|
+
session_id=self._session_id,
|
|
248
|
+
memory_group_ids=self._group_ids,
|
|
249
|
+
)
|
|
250
|
+
lease = AgentLease(
|
|
251
|
+
lease_id=uuid.uuid4().hex,
|
|
252
|
+
agent_id=self._agent_id,
|
|
253
|
+
instance_id=self._instance_id,
|
|
254
|
+
issued_at=now,
|
|
255
|
+
expires_at=now + timedelta(seconds=self._runtime_config.lease_ttl_seconds),
|
|
256
|
+
heartbeat_interval_seconds=self._runtime_config.heartbeat_interval_seconds,
|
|
257
|
+
)
|
|
258
|
+
await self._store.register(identity, lease)
|
|
259
|
+
self._lease = lease
|
|
260
|
+
self._heartbeat_failures = 0
|
|
261
|
+
|
|
262
|
+
async def _heartbeat_loop(self) -> None:
|
|
263
|
+
interval = self._runtime_config.heartbeat_interval_seconds
|
|
264
|
+
try:
|
|
265
|
+
while not self._closed.is_set():
|
|
266
|
+
await asyncio.sleep(interval)
|
|
267
|
+
if self._closed.is_set():
|
|
268
|
+
return
|
|
269
|
+
await self._heartbeat_once()
|
|
270
|
+
except asyncio.CancelledError:
|
|
271
|
+
raise
|
|
272
|
+
except BaseException as exc: # noqa: BLE001 must observe all failures # NOSONAR(S5754)
|
|
273
|
+
self._background_exception = exc
|
|
274
|
+
logger.warning(
|
|
275
|
+
"active-memory heartbeat loop failed for agent_id=%s instance_id=%s: %s",
|
|
276
|
+
self._agent_id,
|
|
277
|
+
self._instance_id,
|
|
278
|
+
exc,
|
|
279
|
+
)
|
|
280
|
+
if self._lifecycle.state is ActiveAgentSessionState.ACTIVE:
|
|
281
|
+
self._lifecycle.transition_to(ActiveAgentSessionState.DEGRADED)
|
|
282
|
+
|
|
283
|
+
async def _heartbeat_once(self) -> None:
|
|
284
|
+
assert self._lease is not None
|
|
285
|
+
try:
|
|
286
|
+
await self._store.renew(self._lease)
|
|
287
|
+
self._heartbeat_failures = 0
|
|
288
|
+
if self._lifecycle.state is ActiveAgentSessionState.DEGRADED:
|
|
289
|
+
await self._resynchronize()
|
|
290
|
+
except LeaseExpiredError:
|
|
291
|
+
await self._reregister()
|
|
292
|
+
except ActiveMemoryUnavailableError:
|
|
293
|
+
self._heartbeat_failures += 1
|
|
294
|
+
if (
|
|
295
|
+
self._heartbeat_failures >= self._runtime_config.heartbeat_failure_threshold
|
|
296
|
+
and self._lifecycle.state is ActiveAgentSessionState.ACTIVE
|
|
297
|
+
):
|
|
298
|
+
self._lifecycle.transition_to(ActiveAgentSessionState.DEGRADED)
|
|
299
|
+
|
|
300
|
+
async def _resynchronize(self) -> None:
|
|
301
|
+
self._lifecycle.transition_to(ActiveAgentSessionState.RESYNCHRONIZING)
|
|
302
|
+
try:
|
|
303
|
+
presence = await self._store.get_presence(self._agent_id, self._instance_id)
|
|
304
|
+
if presence is None:
|
|
305
|
+
await self._reregister()
|
|
306
|
+
return
|
|
307
|
+
self._lifecycle.transition_to(ActiveAgentSessionState.ACTIVE)
|
|
308
|
+
except ActiveMemoryUnavailableError:
|
|
309
|
+
self._lifecycle.transition_to(ActiveAgentSessionState.DEGRADED)
|
|
310
|
+
|
|
311
|
+
async def _reregister(self) -> None:
|
|
312
|
+
self._lifecycle.transition_to(ActiveAgentSessionState.RE_REGISTERING)
|
|
313
|
+
self._instance_id = self._generate_instance_id()
|
|
314
|
+
try:
|
|
315
|
+
await self._register()
|
|
316
|
+
except ActiveMemoryUnavailableError:
|
|
317
|
+
self._lifecycle.transition_to(ActiveAgentSessionState.DEGRADED)
|
|
318
|
+
return
|
|
319
|
+
self._lifecycle.transition_to(ActiveAgentSessionState.RESYNCHRONIZING)
|
|
320
|
+
self._lifecycle.transition_to(ActiveAgentSessionState.ACTIVE)
|
|
321
|
+
|
|
322
|
+
async def replace_context(
|
|
323
|
+
self,
|
|
324
|
+
*,
|
|
325
|
+
objective: str | None,
|
|
326
|
+
status: AgentStatus,
|
|
327
|
+
working_on: tuple[str, ...] = (),
|
|
328
|
+
blockers: tuple[str, ...] = (),
|
|
329
|
+
expected_version: int | None = None,
|
|
330
|
+
) -> ActiveContext:
|
|
331
|
+
"""Atomically replace this session's active context.
|
|
332
|
+
|
|
333
|
+
Raises:
|
|
334
|
+
ActiveMemoryUnavailableError: if the session is not in the
|
|
335
|
+
ACTIVE state, or if the backend cannot be reached.
|
|
336
|
+
ContextVersionConflictError: if `expected_version` does not
|
|
337
|
+
match the currently stored version.
|
|
338
|
+
LeaseExpiredError: if the lease has expired; caller should
|
|
339
|
+
allow the session to re-register before retrying.
|
|
340
|
+
"""
|
|
341
|
+
if not self._lifecycle.can_write():
|
|
342
|
+
raise ActiveMemoryUnavailableError(
|
|
343
|
+
f"cannot write context while session is in state {self._lifecycle.state.value!r}"
|
|
344
|
+
)
|
|
345
|
+
assert self._lease is not None
|
|
346
|
+
draft = ActiveContextDraft(
|
|
347
|
+
objective=objective,
|
|
348
|
+
status=status,
|
|
349
|
+
working_on=working_on,
|
|
350
|
+
blockers=blockers,
|
|
351
|
+
)
|
|
352
|
+
return await self._store.put_context(self._lease, expected_version, draft)
|
|
353
|
+
|
|
354
|
+
async def list_active(
|
|
355
|
+
self, *, group_id: str | None = None, roles: frozenset[str] | None = None
|
|
356
|
+
) -> tuple[AgentPresence, ...]:
|
|
357
|
+
"""Return currently active peers matching the given filters.
|
|
358
|
+
|
|
359
|
+
Note: `roles` filtering beyond a single role is applied
|
|
360
|
+
client-side over one or more scoped calls; the underlying port
|
|
361
|
+
supports a single role filter per call.
|
|
362
|
+
"""
|
|
363
|
+
scope = AgentScope(
|
|
364
|
+
deployment_id=self._deployment_id,
|
|
365
|
+
group_id=group_id,
|
|
366
|
+
role=next(iter(roles)) if roles and len(roles) == 1 else None,
|
|
367
|
+
)
|
|
368
|
+
page = await self._store.list_active(scope, cursor=None, limit=100)
|
|
369
|
+
items = page.items
|
|
370
|
+
if roles and len(roles) != 1:
|
|
371
|
+
items = tuple(p for p in items if p.identity.role in roles)
|
|
372
|
+
return items
|
|
373
|
+
|
|
374
|
+
async def subscribe(self, *, group_id: str | None = None) -> AsyncIterator[AgentEvent]:
|
|
375
|
+
"""Subscribe to awareness events scoped to this deployment.
|
|
376
|
+
|
|
377
|
+
This is a best-effort, at-most-once stream (see `AwarenessBus`).
|
|
378
|
+
Consumers MUST treat gaps as expected and re-read current state
|
|
379
|
+
via `list_active()` / context reads rather than assuming
|
|
380
|
+
delivery completeness.
|
|
381
|
+
"""
|
|
382
|
+
scope = AgentScope(deployment_id=self._deployment_id, group_id=group_id)
|
|
383
|
+
subscription = AgentSubscription(scope=scope)
|
|
384
|
+
async for event in self._bus.subscribe(subscription):
|
|
385
|
+
yield event
|
|
386
|
+
|
|
387
|
+
async def drain(self) -> None: # NOSONAR(S7503) - kept async for SDK-wide calling consistency
|
|
388
|
+
"""Begin graceful shutdown: stop writes, keep lease until close()."""
|
|
389
|
+
if self._lifecycle.state in (
|
|
390
|
+
ActiveAgentSessionState.ACTIVE,
|
|
391
|
+
ActiveAgentSessionState.DEGRADED,
|
|
392
|
+
):
|
|
393
|
+
self._lifecycle.transition_to(ActiveAgentSessionState.DRAINING)
|
|
394
|
+
|
|
395
|
+
async def _cancel_heartbeat_task(self) -> None:
|
|
396
|
+
if self._heartbeat_task is None:
|
|
397
|
+
return
|
|
398
|
+
self._heartbeat_task.cancel()
|
|
399
|
+
try:
|
|
400
|
+
await self._heartbeat_task
|
|
401
|
+
except asyncio.CancelledError: # NOSONAR(S7497)
|
|
402
|
+
# Expected: we just cancelled this task ourselves above, and this
|
|
403
|
+
# `close()` coroutine is not itself being cancelled, so the
|
|
404
|
+
# cancellation does not need to propagate further.
|
|
405
|
+
pass
|
|
406
|
+
|
|
407
|
+
async def _unregister_lease(self) -> None:
|
|
408
|
+
if self._lifecycle.state != ActiveAgentSessionState.DRAINING:
|
|
409
|
+
try:
|
|
410
|
+
self._lifecycle.transition_to(ActiveAgentSessionState.DRAINING)
|
|
411
|
+
except LifecycleTransitionError:
|
|
412
|
+
pass
|
|
413
|
+
if self._lease is None:
|
|
414
|
+
return
|
|
415
|
+
try:
|
|
416
|
+
await self._store.unregister(self._lease)
|
|
417
|
+
except ActiveMemoryUnavailableError:
|
|
418
|
+
logger.warning(
|
|
419
|
+
"failed to unregister lease during close for "
|
|
420
|
+
"agent_id=%s instance_id=%s; lease will expire naturally",
|
|
421
|
+
self._agent_id,
|
|
422
|
+
self._instance_id,
|
|
423
|
+
)
|
|
424
|
+
|
|
425
|
+
def _finalize_closed_state(self) -> None:
|
|
426
|
+
if self._lifecycle.state == ActiveAgentSessionState.CLOSED:
|
|
427
|
+
return
|
|
428
|
+
try:
|
|
429
|
+
self._lifecycle.transition_to(ActiveAgentSessionState.CLOSED)
|
|
430
|
+
except LifecycleTransitionError:
|
|
431
|
+
if self._lifecycle.state == ActiveAgentSessionState.NEW:
|
|
432
|
+
self._lifecycle._state = ActiveAgentSessionState.CLOSED
|
|
433
|
+
|
|
434
|
+
async def close(self) -> None:
|
|
435
|
+
"""Idempotently stop background tasks and unregister the lease."""
|
|
436
|
+
if self._closed.is_set():
|
|
437
|
+
return
|
|
438
|
+
self._closed.set()
|
|
439
|
+
|
|
440
|
+
await self._cancel_heartbeat_task()
|
|
441
|
+
try:
|
|
442
|
+
if self._lifecycle.state not in (
|
|
443
|
+
ActiveAgentSessionState.CLOSED,
|
|
444
|
+
ActiveAgentSessionState.NEW,
|
|
445
|
+
):
|
|
446
|
+
await self._unregister_lease()
|
|
447
|
+
finally:
|
|
448
|
+
self._finalize_closed_state()
|