nodus-session 0.1.0__tar.gz

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,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,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,74 @@
1
+ # nodus-session
2
+
3
+ Full session lifecycle for multi-channel AI systems. Manages conversation
4
+ entries, transcripts, pruning, and compaction. Zero required dependencies —
5
+ pure Python stdlib. Optionally integrates with `nodus-state` for typed
6
+ session keys.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ pip install nodus-session
12
+
13
+ # With nodus-state integration (typed SessionKey)
14
+ pip install "nodus-session[nodus-state]"
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ ### Session entries
20
+
21
+ ```python
22
+ from nodus_session import SessionEntry, SessionKey, InMemorySessionStore
23
+
24
+ store = InMemorySessionStore()
25
+
26
+ key = SessionKey(agent_id="assistant", channel="web", peer="user-1")
27
+ entry = SessionEntry.create(key, provenance={"channel_id": "web"})
28
+ entry.append_message({"role": "user", "content": "Hello"})
29
+ entry.append_message({"role": "assistant", "content": "Hi there!"})
30
+ store.save(entry)
31
+ ```
32
+
33
+ ### Session manager
34
+
35
+ ```python
36
+ from nodus_session import SessionManager, InMemorySessionStore, SessionKey
37
+
38
+ store = InMemorySessionStore()
39
+ manager = SessionManager(store)
40
+
41
+ key = SessionKey(agent_id="assistant", channel="api", peer="user-42")
42
+ manager.append_message(key, {"role": "user", "content": "What time is it?"})
43
+
44
+ entry = manager.get_or_create(key)
45
+ print(len(entry.messages)) # 1
46
+ ```
47
+
48
+ ### Pruning policy
49
+
50
+ ```python
51
+ from nodus_session import SessionManager, SessionPruningPolicy, InMemorySessionStore
52
+
53
+ policy = SessionPruningPolicy(
54
+ max_age_days=30,
55
+ max_inactivity_days=7,
56
+ max_messages=200,
57
+ max_sessions_per_agent=10,
58
+ )
59
+ manager = SessionManager(InMemorySessionStore(), policy=policy)
60
+
61
+ # Delete sessions that violate the policy
62
+ deleted = manager.prune(agent_id="assistant")
63
+ ```
64
+
65
+ ### Compaction
66
+
67
+ ```python
68
+ # Pass any callable (messages: list[dict]) -> list[dict]
69
+ def keep_last_50(messages):
70
+ return messages[-50:]
71
+
72
+ removed = manager.compact(key, strategy=keep_last_50)
73
+ print(f"Compacted {removed} messages")
74
+ ```
@@ -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
+ ]
@@ -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
@@ -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,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ nodus_session/__init__.py
5
+ nodus_session/entry.py
6
+ nodus_session/manager.py
7
+ nodus_session/policy.py
8
+ nodus_session/store.py
9
+ nodus_session.egg-info/PKG-INFO
10
+ nodus_session.egg-info/SOURCES.txt
11
+ nodus_session.egg-info/dependency_links.txt
12
+ nodus_session.egg-info/requires.txt
13
+ nodus_session.egg-info/top_level.txt
14
+ tests/test_session.py
@@ -0,0 +1,6 @@
1
+
2
+ [dev]
3
+ pytest>=8.0
4
+
5
+ [nodus-state]
6
+ nodus-state>=0.1.0
@@ -0,0 +1 @@
1
+ nodus_session
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["setuptools>=80", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "nodus-session"
7
+ version = "0.1.0"
8
+ description = "Full session lifecycle: entry, transcript, pruning, and compaction for multi-channel AI systems"
9
+ authors = [{ name = "Shawn Knight" }]
10
+ license = { text = "MIT" }
11
+ readme = "README.md"
12
+ requires-python = ">=3.11"
13
+ keywords = ["session", "transcript", "lifecycle", "ai", "nodus"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Topic :: Software Development :: Libraries",
21
+ ]
22
+ dependencies = []
23
+
24
+ [project.optional-dependencies]
25
+ nodus-state = ["nodus-state>=0.1.0"]
26
+ dev = ["pytest>=8.0"]
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/Masterplanner25/nodus-session"
30
+ Repository = "https://github.com/Masterplanner25/nodus-session"
31
+
32
+ [tool.setuptools.packages.find]
33
+ where = ["."]
34
+ include = ["nodus_session*"]
35
+
36
+ [tool.pytest.ini_options]
37
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,147 @@
1
+ from __future__ import annotations
2
+ from datetime import datetime, timezone, timedelta
3
+ from nodus_session import (
4
+ InMemorySessionStore, SessionEntry, SessionKey,
5
+ SessionManager, SessionPruningPolicy,
6
+ )
7
+
8
+
9
+ def _key(agent="main", channel="slack", peer="U1"):
10
+ return SessionKey(agent_id=agent, channel=channel, peer=peer)
11
+
12
+
13
+ # ── SessionEntry ──────────────────────────────────────────────────────────────
14
+
15
+ def test_create_entry():
16
+ k = _key()
17
+ e = SessionEntry.create(k, provenance={"channel_id": "slack"})
18
+ assert e.key is k
19
+ assert len(e.messages) == 0
20
+ assert e.compaction_count == 0
21
+ assert e.provenance["channel_id"] == "slack"
22
+
23
+
24
+ def test_append_message_adds_timestamp():
25
+ e = SessionEntry.create(_key())
26
+ e.append_message({"role": "user", "content": "hi"})
27
+ assert len(e.messages) == 1
28
+ assert "timestamp" in e.messages[0]
29
+
30
+
31
+ def test_touch_updates_last_active():
32
+ e = SessionEntry.create(_key())
33
+ before = e.last_active_at
34
+ import time; time.sleep(0.01)
35
+ e.touch()
36
+ assert e.last_active_at > before
37
+
38
+
39
+ # ── InMemorySessionStore ──────────────────────────────────────────────────────
40
+
41
+ def test_store_save_and_load():
42
+ store = InMemorySessionStore()
43
+ k = _key()
44
+ e = SessionEntry.create(k)
45
+ store.save(e)
46
+ loaded = store.load(k)
47
+ assert loaded is e
48
+
49
+
50
+ def test_store_load_unknown_returns_none():
51
+ assert InMemorySessionStore().load(_key()) is None
52
+
53
+
54
+ def test_store_delete():
55
+ store = InMemorySessionStore()
56
+ k = _key()
57
+ store.save(SessionEntry.create(k))
58
+ assert store.delete(k) is True
59
+ assert store.load(k) is None
60
+
61
+
62
+ def test_store_list_by_agent():
63
+ store = InMemorySessionStore()
64
+ k1 = SessionKey(agent_id="main", channel="slack", peer="U1")
65
+ k2 = SessionKey(agent_id="main", channel="discord", peer="D2")
66
+ k3 = SessionKey(agent_id="research", channel="slack", peer="U3")
67
+ for k in (k1, k2, k3):
68
+ store.save(SessionEntry.create(k, provenance={"agent_id": k.agent_id}))
69
+ main_sessions = store.list_by_agent("main")
70
+ assert len(main_sessions) == 2
71
+
72
+
73
+ # ── SessionPruningPolicy ──────────────────────────────────────────────────────
74
+
75
+ def test_policy_should_delete_old():
76
+ policy = SessionPruningPolicy(max_age_days=1)
77
+ old_time = datetime.now(timezone.utc) - timedelta(days=2)
78
+ e = SessionEntry.create(_key())
79
+ e.created_at = old_time
80
+ assert policy.should_delete(e) is True
81
+
82
+
83
+ def test_policy_should_not_delete_recent():
84
+ policy = SessionPruningPolicy(max_age_days=30)
85
+ e = SessionEntry.create(_key())
86
+ assert policy.should_delete(e) is False
87
+
88
+
89
+ def test_policy_should_compact_over_limit():
90
+ policy = SessionPruningPolicy(max_messages=3)
91
+ e = SessionEntry.create(_key())
92
+ for i in range(4):
93
+ e.append_message({"role": "user", "content": str(i)})
94
+ assert policy.should_compact(e) is True
95
+
96
+
97
+ def test_policy_no_compact_under_limit():
98
+ policy = SessionPruningPolicy(max_messages=10)
99
+ e = SessionEntry.create(_key())
100
+ e.append_message({"role": "user", "content": "hi"})
101
+ assert policy.should_compact(e) is False
102
+
103
+
104
+ # ── SessionManager ────────────────────────────────────────────────────────────
105
+
106
+ def test_manager_get_or_create():
107
+ mgr = SessionManager(InMemorySessionStore())
108
+ k = _key()
109
+ e1 = mgr.get_or_create(k)
110
+ e2 = mgr.get_or_create(k)
111
+ assert e1 is e2 # same instance returned
112
+
113
+
114
+ def test_manager_append_message():
115
+ mgr = SessionManager(InMemorySessionStore())
116
+ k = _key()
117
+ mgr.append_message(k, {"role": "user", "content": "hello"})
118
+ e = mgr.get_or_create(k)
119
+ assert len(e.messages) == 1
120
+ assert e.messages[0]["content"] == "hello"
121
+
122
+
123
+ def test_manager_prune_old():
124
+ store = InMemorySessionStore()
125
+ policy = SessionPruningPolicy(max_inactivity_days=0)
126
+ mgr = SessionManager(store, policy=policy)
127
+ k = _key()
128
+ e = mgr.get_or_create(k, provenance={"agent_id": "main"})
129
+ # Force last_active to be in the past
130
+ e.last_active_at = datetime.now(timezone.utc) - timedelta(seconds=1)
131
+ store.save(e)
132
+ deleted = mgr.prune(agent_id="main")
133
+ assert deleted >= 1
134
+ assert store.load(k) is None
135
+
136
+
137
+ def test_manager_compact():
138
+ mgr = SessionManager(InMemorySessionStore())
139
+ k = _key()
140
+ for i in range(5):
141
+ mgr.append_message(k, {"role": "user", "content": str(i)})
142
+ # Strategy that keeps only last 2 messages
143
+ removed = mgr.compact(k, strategy=lambda msgs: msgs[-2:])
144
+ assert removed == 3
145
+ e = mgr.get_or_create(k)
146
+ assert len(e.messages) == 2
147
+ assert e.compaction_count == 1