nodus-session 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,33 @@
1
+ """nodus-session — full session lifecycle for multi-channel AI systems.
2
+
3
+ Builds on nodus-state's SessionKey and adds: entry lifecycle, transcript
4
+ management, pruning policies, and compaction triggers.
5
+
6
+ Entry:
7
+ SessionEntry — transcript, metadata, provenance, timestamps
8
+ SessionKey — re-exported from nodus-state (identifier only)
9
+
10
+ Store:
11
+ SessionStore — protocol for persistence backends
12
+ InMemorySessionStore — thread-safe dict-backed store
13
+
14
+ Policy:
15
+ SessionPruningPolicy — age/inactivity/message-count/per-agent rules
16
+ should_delete() / should_compact()
17
+
18
+ Manager:
19
+ SessionManager — get_or_create, append_message, prune, compact
20
+ """
21
+ from .entry import SessionEntry, SessionKey
22
+ from .manager import SessionManager
23
+ from .policy import SessionPruningPolicy
24
+ from .store import InMemorySessionStore, SessionStore
25
+
26
+ __all__ = [
27
+ "SessionEntry",
28
+ "SessionKey",
29
+ "SessionStore",
30
+ "InMemorySessionStore",
31
+ "SessionPruningPolicy",
32
+ "SessionManager",
33
+ ]
nodus_session/entry.py ADDED
@@ -0,0 +1,71 @@
1
+ """SessionEntry — the full state of one conversation session."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass, field
5
+ from datetime import datetime, timezone
6
+ from typing import Any
7
+
8
+ try:
9
+ from nodus_state import SessionKey
10
+ except ImportError:
11
+ # Fallback when nodus-state isn't installed (for minimal test environments)
12
+ from dataclasses import dataclass as _dc
13
+ @_dc
14
+ class SessionKey: # type: ignore[no-redef]
15
+ agent_id: str
16
+ channel: str | None = None
17
+ peer: str | None = None
18
+ thread: str | None = None
19
+ def to_string(self): return self.agent_id
20
+ @classmethod
21
+ def from_string(cls, raw): return cls(agent_id=raw)
22
+
23
+
24
+ @dataclass
25
+ class SessionEntry:
26
+ """Full state of one conversation session.
27
+
28
+ Attributes
29
+ ----------
30
+ key: Structured session identity (from nodus-state).
31
+ created_at: UTC timestamp when the session was first created.
32
+ last_active_at: UTC timestamp of the last message or activity.
33
+ messages: Ordered transcript: ``[{role, content, timestamp, ...}]``.
34
+ metadata: Arbitrary session metadata dict.
35
+ provenance: How the session was created: ``{channel_id, peer_id, agent_id}``.
36
+ compaction_count: Number of times the transcript has been compacted.
37
+ """
38
+
39
+ key: "SessionKey"
40
+ created_at: datetime
41
+ last_active_at: datetime
42
+ messages: list[dict[str, Any]] = field(default_factory=list)
43
+ metadata: dict[str, Any] = field(default_factory=dict)
44
+ provenance: dict[str, Any] = field(default_factory=dict)
45
+ compaction_count: int = 0
46
+
47
+ @classmethod
48
+ def create(
49
+ cls,
50
+ key: "SessionKey",
51
+ *,
52
+ provenance: dict[str, Any] | None = None,
53
+ ) -> "SessionEntry":
54
+ now = datetime.now(timezone.utc)
55
+ return cls(
56
+ key=key,
57
+ created_at=now,
58
+ last_active_at=now,
59
+ provenance=dict(provenance or {}),
60
+ )
61
+
62
+ def touch(self) -> None:
63
+ """Update last_active_at to now."""
64
+ self.last_active_at = datetime.now(timezone.utc)
65
+
66
+ def append_message(self, message: dict[str, Any]) -> None:
67
+ """Append *message* to the transcript and touch the session."""
68
+ if "timestamp" not in message:
69
+ message = dict(message, timestamp=datetime.now(timezone.utc).isoformat())
70
+ self.messages.append(message)
71
+ self.touch()
@@ -0,0 +1,120 @@
1
+ """SessionManager — full session lifecycle: create, append, prune, compact."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any, Optional
5
+
6
+ from .entry import SessionEntry, SessionKey
7
+ from .policy import SessionPruningPolicy
8
+ from .store import SessionStore
9
+
10
+
11
+ class SessionManager:
12
+ """Manage session lifecycle.
13
+
14
+ Args:
15
+ store: Backend persistence for session entries.
16
+ policy: Optional pruning/compaction policy applied on ``prune()``.
17
+ """
18
+
19
+ def __init__(
20
+ self,
21
+ store: SessionStore,
22
+ policy: Optional[SessionPruningPolicy] = None,
23
+ ) -> None:
24
+ self._store = store
25
+ self._policy = policy
26
+
27
+ def get_or_create(
28
+ self,
29
+ key: SessionKey,
30
+ provenance: dict[str, Any] | None = None,
31
+ ) -> SessionEntry:
32
+ """Load an existing session or create a new one.
33
+
34
+ Args:
35
+ key: Session identity.
36
+ provenance: Metadata about how the session was created
37
+ (``{channel_id, peer_id, agent_id}``).
38
+ """
39
+ entry = self._store.load(key)
40
+ if entry is None:
41
+ entry = SessionEntry.create(key, provenance=provenance)
42
+ self._store.save(entry)
43
+ return entry
44
+
45
+ def append_message(self, key: SessionKey, message: dict[str, Any]) -> None:
46
+ """Append *message* to the session transcript.
47
+
48
+ Creates the session if it does not exist.
49
+ """
50
+ entry = self.get_or_create(key)
51
+ entry.append_message(message)
52
+ self._store.save(entry)
53
+
54
+ def prune(self, agent_id: str | None = None) -> int:
55
+ """Delete sessions that violate the policy.
56
+
57
+ Args:
58
+ agent_id: Limit pruning to sessions for this agent.
59
+
60
+ Returns:
61
+ Number of sessions deleted.
62
+ """
63
+ if self._policy is None:
64
+ return 0
65
+
66
+ sessions = (
67
+ self._store.list_by_agent(agent_id)
68
+ if agent_id is not None
69
+ else self._store.list_by_agent("") # all
70
+ )
71
+ # If no agent_id filter, get everything by listing all known sessions
72
+ if agent_id is None:
73
+ # Gather all agents from known sessions and list each
74
+ # (InMemorySessionStore doesn't have a list_all method — iterate via known entries)
75
+ all_sessions = []
76
+ if hasattr(self._store, "_sessions"):
77
+ all_sessions = list(getattr(self._store, "_sessions").values())
78
+ else:
79
+ all_sessions = sessions
80
+ sessions = all_sessions
81
+
82
+ deleted = 0
83
+ for entry in sessions:
84
+ if self._policy.should_delete(entry):
85
+ self._store.delete(entry.key)
86
+ deleted += 1
87
+
88
+ # max_sessions_per_agent
89
+ if self._policy.max_sessions_per_agent is not None and agent_id is not None:
90
+ remaining = self._store.list_by_agent(agent_id)
91
+ remaining.sort(key=lambda e: e.last_active_at, reverse=True)
92
+ for old in remaining[self._policy.max_sessions_per_agent:]:
93
+ self._store.delete(old.key)
94
+ deleted += 1
95
+
96
+ return deleted
97
+
98
+ def compact(self, key: SessionKey, strategy: Any) -> int:
99
+ """Run a compaction strategy on *key*'s transcript.
100
+
101
+ Args:
102
+ key: Session to compact.
103
+ strategy: A ``CompactionStrategy`` (from nodus-context) or any
104
+ callable ``(messages) → messages``.
105
+
106
+ Returns:
107
+ Number of messages removed.
108
+ """
109
+ entry = self._store.load(key)
110
+ if entry is None:
111
+ return 0
112
+ before = len(entry.messages)
113
+ # Strategy accepts list[dict] (session messages, not ContextMessages)
114
+ if callable(strategy):
115
+ entry.messages = list(strategy(entry.messages))
116
+ else:
117
+ entry.messages = list(strategy.compact(entry.messages))
118
+ entry.compaction_count += 1
119
+ self._store.save(entry)
120
+ return before - len(entry.messages)
@@ -0,0 +1,54 @@
1
+ """SessionPruningPolicy — rules for evicting old or inactive sessions."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+ from datetime import datetime, timezone, timedelta
6
+ from typing import Optional
7
+
8
+ from .entry import SessionEntry
9
+
10
+
11
+ @dataclass
12
+ class SessionPruningPolicy:
13
+ """Rules for evicting sessions that exceed configured thresholds.
14
+
15
+ All constraints are optional; None = no limit on that dimension.
16
+
17
+ Attributes
18
+ ----------
19
+ max_age_days: Delete sessions older than this many days.
20
+ max_inactivity_days: Delete sessions inactive for this many days.
21
+ max_messages: Compact sessions with more messages than this.
22
+ max_sessions_per_agent: Keep only the N most-recently-active sessions per agent.
23
+ """
24
+
25
+ max_age_days: Optional[int] = None
26
+ max_inactivity_days: Optional[int] = None
27
+ max_messages: Optional[int] = None
28
+ max_sessions_per_agent: Optional[int] = None
29
+
30
+ def should_delete(self, entry: SessionEntry) -> bool:
31
+ """Return True if *entry* should be deleted by this policy."""
32
+ now = datetime.now(timezone.utc)
33
+
34
+ if self.max_age_days is not None:
35
+ age = now - entry.created_at.replace(tzinfo=timezone.utc) if entry.created_at.tzinfo is None \
36
+ else now - entry.created_at
37
+ if age > timedelta(days=self.max_age_days):
38
+ return True
39
+
40
+ if self.max_inactivity_days is not None:
41
+ last = entry.last_active_at
42
+ if last.tzinfo is None:
43
+ last = last.replace(tzinfo=timezone.utc)
44
+ inactivity = now - last
45
+ if inactivity > timedelta(days=self.max_inactivity_days):
46
+ return True
47
+
48
+ return False
49
+
50
+ def should_compact(self, entry: SessionEntry) -> bool:
51
+ """Return True if *entry*'s transcript should be compacted."""
52
+ if self.max_messages is not None:
53
+ return len(entry.messages) > self.max_messages
54
+ return False
nodus_session/store.py ADDED
@@ -0,0 +1,64 @@
1
+ """SessionStore protocol and InMemorySessionStore."""
2
+ from __future__ import annotations
3
+
4
+ import threading
5
+ from typing import Optional
6
+
7
+ try:
8
+ from typing import Protocol, runtime_checkable
9
+ except ImportError:
10
+ from typing_extensions import Protocol, runtime_checkable # type: ignore[assignment]
11
+
12
+ from .entry import SessionEntry, SessionKey
13
+
14
+
15
+ @runtime_checkable
16
+ class SessionStore(Protocol):
17
+ """Persistence layer for session entries."""
18
+
19
+ def load(self, key: SessionKey) -> Optional[SessionEntry]: ...
20
+ def save(self, entry: SessionEntry) -> None: ...
21
+ def delete(self, key: SessionKey) -> bool: ...
22
+ def list_by_agent(self, agent_id: str) -> list[SessionEntry]: ...
23
+
24
+
25
+ class InMemorySessionStore:
26
+ """Thread-safe in-process session store for tests and single-process apps."""
27
+
28
+ def __init__(self) -> None:
29
+ self._sessions: dict[str, SessionEntry] = {}
30
+ self._lock = threading.Lock()
31
+
32
+ def _key_str(self, key: SessionKey) -> str:
33
+ return key.to_string() if hasattr(key, "to_string") else str(key)
34
+
35
+ def load(self, key: SessionKey) -> Optional[SessionEntry]:
36
+ with self._lock:
37
+ return self._sessions.get(self._key_str(key))
38
+
39
+ def save(self, entry: SessionEntry) -> None:
40
+ with self._lock:
41
+ self._sessions[self._key_str(entry.key)] = entry
42
+
43
+ def delete(self, key: SessionKey) -> bool:
44
+ with self._lock:
45
+ return self._sessions.pop(self._key_str(key), None) is not None
46
+
47
+ def list_by_agent(self, agent_id: str) -> list[SessionEntry]:
48
+ with self._lock:
49
+ return [
50
+ e for e in self._sessions.values()
51
+ if _agent_id_of(e) == agent_id
52
+ ]
53
+
54
+ def __len__(self) -> int:
55
+ with self._lock:
56
+ return len(self._sessions)
57
+
58
+
59
+ def _agent_id_of(entry: SessionEntry) -> str:
60
+ key = entry.key
61
+ if hasattr(key, "agent_id"):
62
+ return key.agent_id
63
+ # Fallback: try provenance
64
+ return entry.provenance.get("agent_id", "")
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.4
2
+ Name: nodus-session
3
+ Version: 0.1.0
4
+ Summary: Full session lifecycle: entry, transcript, pruning, and compaction for multi-channel AI systems
5
+ Author: Shawn Knight
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/Masterplanner25/nodus-session
8
+ Project-URL: Repository, https://github.com/Masterplanner25/nodus-session
9
+ Keywords: session,transcript,lifecycle,ai,nodus
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Topic :: Software Development :: Libraries
16
+ Requires-Python: >=3.11
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Provides-Extra: nodus-state
20
+ Requires-Dist: nodus-state>=0.1.0; extra == "nodus-state"
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest>=8.0; extra == "dev"
23
+ Dynamic: license-file
24
+
25
+ # nodus-session
26
+
27
+ Full session lifecycle for multi-channel AI systems. Manages conversation
28
+ entries, transcripts, pruning, and compaction. Zero required dependencies —
29
+ pure Python stdlib. Optionally integrates with `nodus-state` for typed
30
+ session keys.
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ pip install nodus-session
36
+
37
+ # With nodus-state integration (typed SessionKey)
38
+ pip install "nodus-session[nodus-state]"
39
+ ```
40
+
41
+ ## Usage
42
+
43
+ ### Session entries
44
+
45
+ ```python
46
+ from nodus_session import SessionEntry, SessionKey, InMemorySessionStore
47
+
48
+ store = InMemorySessionStore()
49
+
50
+ key = SessionKey(agent_id="assistant", channel="web", peer="user-1")
51
+ entry = SessionEntry.create(key, provenance={"channel_id": "web"})
52
+ entry.append_message({"role": "user", "content": "Hello"})
53
+ entry.append_message({"role": "assistant", "content": "Hi there!"})
54
+ store.save(entry)
55
+ ```
56
+
57
+ ### Session manager
58
+
59
+ ```python
60
+ from nodus_session import SessionManager, InMemorySessionStore, SessionKey
61
+
62
+ store = InMemorySessionStore()
63
+ manager = SessionManager(store)
64
+
65
+ key = SessionKey(agent_id="assistant", channel="api", peer="user-42")
66
+ manager.append_message(key, {"role": "user", "content": "What time is it?"})
67
+
68
+ entry = manager.get_or_create(key)
69
+ print(len(entry.messages)) # 1
70
+ ```
71
+
72
+ ### Pruning policy
73
+
74
+ ```python
75
+ from nodus_session import SessionManager, SessionPruningPolicy, InMemorySessionStore
76
+
77
+ policy = SessionPruningPolicy(
78
+ max_age_days=30,
79
+ max_inactivity_days=7,
80
+ max_messages=200,
81
+ max_sessions_per_agent=10,
82
+ )
83
+ manager = SessionManager(InMemorySessionStore(), policy=policy)
84
+
85
+ # Delete sessions that violate the policy
86
+ deleted = manager.prune(agent_id="assistant")
87
+ ```
88
+
89
+ ### Compaction
90
+
91
+ ```python
92
+ # Pass any callable (messages: list[dict]) -> list[dict]
93
+ def keep_last_50(messages):
94
+ return messages[-50:]
95
+
96
+ removed = manager.compact(key, strategy=keep_last_50)
97
+ print(f"Compacted {removed} messages")
98
+ ```
@@ -0,0 +1,10 @@
1
+ nodus_session/__init__.py,sha256=iw9unStOVbYYUim6JEuiZpymK6e9jq7uHGxqhXC4Pm0,1051
2
+ nodus_session/entry.py,sha256=kEytskQMoTRk4aOSCgu_2g3bzLBHDu1SuDc-JzGpHN8,2437
3
+ nodus_session/manager.py,sha256=3X1IkLlQSacnQKMFAUtwIN2Ba05BFqsTCSXB1qZf-SM,4032
4
+ nodus_session/policy.py,sha256=ZWXp2oo_DIJ7u3gp9vx0pWfGAOCPVx8U7c6ZT9yETJM,1997
5
+ nodus_session/store.py,sha256=hNmXHzfTn8VhH7M-emEyJlLxbrt-3ypZimCpjjDj0X8,2008
6
+ nodus_session-0.1.0.dist-info/licenses/LICENSE,sha256=fPXtVFKk3GVjyErjlaH2F56cuzEfzln8OP_ElB7cXTI,1069
7
+ nodus_session-0.1.0.dist-info/METADATA,sha256=BoIJ05sx2YTTdLtAd_qSTgGwM83z_IeRFDlq2SLA5uA,2904
8
+ nodus_session-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
9
+ nodus_session-0.1.0.dist-info/top_level.txt,sha256=dunEAGqAtsO0NOu3hRwHmhE6YDyD7wRoH-7J0EwjHvA,14
10
+ nodus_session-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Shawn Knight
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ nodus_session