refactor: simplify cross-session messaging

This commit is contained in:
chengyongru authored and chengyongru committed 2026-08-19 01:15:56 +08:00
1 parent 0e184965e8
commit 251a1ccd40
78 files changed
+1578 -7569

No files matched your search

+70 -94
View File
@@ -14,7 +14,6 @@ from copy import deepcopy
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from threading import RLock
from typing import Any, Callable, Collection, Generator, Protocol, TypedDict, cast
from weakref import WeakValueDictionary
@@ -180,7 +179,6 @@ class Session:
last_consolidated: int = 0 # Number of messages already consolidated to files
provider_state: ProviderConversationState | None = field(default=None, repr=False)
policy: SessionPolicy = field(default_factory=SessionPolicy, repr=False, compare=False)
discarded: bool = field(default=False, init=False, repr=False, compare=False)
def __post_init__(self) -> None:
if not isinstance(cast(object, self.metadata), dict):
@@ -1522,7 +1520,6 @@ class SessionManager:
self.sessions_dir = self._jsonl_store.sessions_dir
self.legacy_sessions_dir = self._jsonl_store.legacy_sessions_dir
self._cache: OrderedDict[str, Session] = OrderedDict()
self._state_lock = RLock()
# Preserve identity for sessions held by active callers without retaining idle ones.
self._overflow_cache: WeakValueDictionary[str, Session] = WeakValueDictionary()
self._max_cached_sessions = SESSION_CACHE_MAX_SIZE
@@ -1531,26 +1528,24 @@ class SessionManager:
def _remember(self, session: Session) -> None:
"""Keep recent sessions strongly cached without duplicating live objects."""
with self._state_lock:
self._overflow_cache.pop(session.key, None)
self._cache[session.key] = session
self._cache.move_to_end(session.key)
while len(self._cache) > self._max_cached_sessions:
key, evicted = self._cache.popitem(last=False)
self._overflow_cache[key] = evicted
self._overflow_cache.pop(session.key, None)
self._cache[session.key] = session
self._cache.move_to_end(session.key)
while len(self._cache) > self._max_cached_sessions:
key, evicted = self._cache.popitem(last=False)
self._overflow_cache[key] = evicted
def _cached(self, key: str) -> Session | None:
with self._state_lock:
session = self._cache.get(key)
if session is not None:
self._cache.move_to_end(key)
return session
session = self._overflow_cache.get(key)
if session is not None:
self._remember(session)
session = self._cache.get(key)
if session is not None:
self._cache.move_to_end(key)
return session
session = self._overflow_cache.get(key)
if session is not None:
self._remember(session)
return session
def get_cached(self, key: str) -> Session | None:
"""Return a cached session without creating or loading one from disk."""
return self._cached(key)
@@ -1616,28 +1611,16 @@ class SessionManager:
Returns:
The session.
"""
with self._state_lock:
session = self._cached(key)
if session is not None:
return session
session = self._load(key)
if session is None:
session = Session(key=key)
self._remember(session)
session = self._cached(key)
if session is not None:
return session
def get_existing(self, key: str) -> Session | None:
"""Return an existing cached or persisted session without creating one."""
with self._state_lock:
session = self._cached(key)
if session is not None:
return session
session = self._load(key)
if session is not None:
self._remember(session)
return session
session = self._load(key)
if session is None:
session = Session(key=key)
self._remember(session)
return session
def get_or_create_transient(
self,
@@ -1666,62 +1649,61 @@ class SessionManager:
def save(self, session: Session, *, fsync: bool = False) -> None:
"""Persist a session and retain it in the cache."""
with self._state_lock:
if not session.policy.persist or session.discarded:
return
if not session.policy.persist:
return
archiver = self._file_cap_archiver
if archiver is not None:
session.enforce_file_cap(
on_archive=lambda messages: archiver(
messages,
session_key=session.key,
)
archiver = self._file_cap_archiver
if archiver is not None:
session.enforce_file_cap(
on_archive=lambda messages: archiver(
messages,
session_key=session.key,
)
)
self._store.save(session, fsync=fsync)
self._remember(session)
self._store.save(session, fsync=fsync)
self._remember(session)
def rename_model_preset(self, old_name: str, new_name: str) -> int:
"""Rename a session-scoped model preset across durable and live sessions."""
if old_name == new_name:
return 0
with self._state_lock:
cached = dict(self._overflow_cache.items())
cached.update(self._cache)
keys = set(cached)
keys.update(item["key"] for item in self._store.list_sessions())
changed: list[Session] = []
try:
for key in sorted(keys):
session = cached.get(key) or self._load(key)
if (
session is None
or session.metadata.get(SESSION_MODEL_PRESET_METADATA_KEY) != old_name
):
continue
session.metadata[SESSION_MODEL_PRESET_METADATA_KEY] = new_name
changed.append(session)
cached = dict(self._overflow_cache.items())
cached.update(self._cache)
keys = set(cached)
keys.update(item["key"] for item in self._store.list_sessions())
changed: list[Session] = []
try:
for key in sorted(keys):
session = cached.get(key) or self._load(key)
if (
session is None
or session.metadata.get(SESSION_MODEL_PRESET_METADATA_KEY) != old_name
):
continue
session.metadata[SESSION_MODEL_PRESET_METADATA_KEY] = new_name
changed.append(session)
if session.policy.persist:
self.save(session, fsync=True)
else:
self._remember(session)
except BaseException:
for session in reversed(changed):
session.metadata[SESSION_MODEL_PRESET_METADATA_KEY] = old_name
try:
if session.policy.persist:
self.save(session, fsync=True)
else:
self._remember(session)
except BaseException:
for session in reversed(changed):
session.metadata[SESSION_MODEL_PRESET_METADATA_KEY] = old_name
try:
if session.policy.persist:
self.save(session, fsync=True)
else:
self._remember(session)
except Exception:
logger.exception(
"Failed to roll back model preset rename for session {}",
session.key,
)
raise
return len(changed)
except Exception:
logger.exception(
"Failed to roll back model preset rename for session {}",
session.key,
)
raise
return len(changed)
def flush_all(self) -> int:
"""Re-save every cached session with fsync for durable shutdown.
@@ -1743,21 +1725,15 @@ class SessionManager:
def invalidate(self, key: str) -> None:
"""Remove a session from the in-memory cache."""
with self._state_lock:
self._cache.pop(key, None)
self._overflow_cache.pop(key, None)
self._cache.pop(key, None)
self._overflow_cache.pop(key, None)
def delete_session(self, key: str) -> bool:
"""Delete a persisted session and invalidate its cache entry."""
with self._state_lock:
session = self._cached(key)
if session is not None:
session.discarded = True
self.invalidate(key)
deleted = self._store.delete(key)
observer = self._delete_observer
if observer is not None:
observer(key)
self.invalidate(key)
deleted = self._store.delete(key)
if self._delete_observer is not None:
self._delete_observer(key)
return deleted
def restore_sessions_to_workspace(self) -> SessionRestoreResult:
+50 -461
View File
@@ -1,506 +1,95 @@
"""Persistent, globally unique handles for sessions.
The directory is the trusted seam between public ``@name`` handles and private
session keys. Titles and transcript text never participate in handle allocation.
"""
"""Stable public handles derived from persisted session keys."""
from __future__ import annotations
import errno
import hashlib
import json
import os
import re
import threading
import unicodedata
import uuid
from collections.abc import Iterable
from contextlib import suppress
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Protocol, TypedDict, cast, runtime_checkable
from typing import Any, TypedDict
from filelock import FileLock
from nanobot.security.workspace_access import WORKSPACE_SCOPE_METADATA_KEY
from nanobot.session.manager import SessionManager
SESSION_HANDLE_DIRECTORY_VERSION = 1
SESSION_HANDLE_COLOR_SLOTS = 8
_STORE_FILENAME = ".session-handles.json"
_LOCK_FILENAME = ".session-handles.lock"
_MAX_STORE_BYTES = 512 * 1024
_MAX_HANDLES = 2_000
_MAX_SESSION_KEY_CHARS = 512
_MAX_NAME_CHARS = 24
_HANDLE_ID_RE = re.compile(r"^handle_[0-9a-f]{32}$")
_HANDLE_RE = re.compile(r"^[a-z]{2,16}(?:-(?:[2-9]|[1-9][0-9]+))?$")
_HANDLE_RE = re.compile(r"^[a-z]{2,16}-[0-9a-f]{10}$")
# Short, pronounceable names are easier to remember and type than conversation
# title slugs. The UUID-backed starting offset keeps allocation varied while the
# circular scan and file lock make it deterministic and collision-free.
_HANDLE_NAMES = tuple(
"""
ada abby abel adan adil aiko alba alex alia alma amir amos anil anja ari arlo
asha ava bea ben blair bo bruno cal cam cara carl cato celia chen chloe clara
cleo cora dahlia daisy dana dante dara dario dev dina drew eden eira eli elio
ella elsa emil emma enzo eric esme eva farah felix finn flora freya gabe gia
gwen hana harper hazel heidi hugo ida ila iman ines iris ivan ivo jade jamie
joel jona jude jules juno kai ken kira lana lara leif lena leo lia liam lila
lina liv lois lola luca lucy mabel mae malik mara marco maya mila mina mira
nadia nate neve nico nina noah nora omar oren orla otto owen pablo piper priya
quinn rafi remy ren rhea rio robin rosa ruby sage sami sara sena shay silas
sofia sol sora tariq tavi tess theo timo uma val vera vida wes will wren xena
yara yasmin yuki zara zeno zoe
ada abel adil aiko alba alex alia alma amir amos anil anja arlo asha ava bea
ben blair bruno cara carl cato celia chen chloe clara cleo cora dahlia daisy
dana dante dara dario dev dina drew eden eira eli elio ella elsa emil emma
enzo eric esme eva farah felix finn flora freya gabe gia gwen hana harper
hazel heidi hugo ida ila iman ines iris ivan jade jamie joel jona jude jules
juno kai ken kira lana lara leif lena leo lia liam lila lina liv lois lola
luca lucy mabel mae malik mara marco maya mila mina mira nadia nate neve nico
nina noah nora omar oren orla otto owen pablo piper priya quinn rafi remy ren
rhea rio robin rosa ruby sage sami sara sena shay silas sofia sol sora tariq
tavi tess theo timo uma val vera vida wes will wren xena yara yasmin yuki zara
zeno zoe
""".split()
)
class SessionHandleDirectoryError(RuntimeError):
"""The persisted session-handle directory could not be used safely."""
class SessionHandlePayload(TypedDict):
"""Public handle fields safe to return to a client or model boundary."""
id: str
name: str
color_slot: int
@dataclass(frozen=True, slots=True)
class SessionHandle:
"""Trusted handle for one persisted session.
``session_key`` and ``workspace`` remain backend-only routing fields.
"""
"""Public identity plus the private key used for internal routing."""
id: str
name: str
color_slot: int
session_key: str
workspace: Path
def public_payload(self) -> SessionHandlePayload:
return {
"id": self.id,
"name": self.name,
"color_slot": self.color_slot,
}
@dataclass(frozen=True, slots=True)
class SessionHandleSnapshot:
"""Trusted session fields used to provision handles in one batch."""
session_key: str
workspace: Path
@runtime_checkable
class SessionHandleDirectoryProtocol(Protocol):
"""Narrow directory contract consumed by session-message delivery."""
def handle_for_session(self, key: str) -> SessionHandle | None: ...
def resolve(self, name: str) -> SessionHandle | None: ...
@dataclass(frozen=True, slots=True)
class _StoredHandle:
id: str
session_key: str
workspace: str
name: str
@dataclass(frozen=True, slots=True)
class _SessionDescriptor:
workspace: Path
class SessionHandleDirectory:
"""Atomically persist globally unique ``@name`` handles for sessions."""
def __init__(self, sessions: SessionManager) -> None:
self._sessions = sessions
self.store_path = sessions.sessions_dir / _STORE_FILENAME
self.store_path.parent.mkdir(parents=True, exist_ok=True)
self._thread_lock = threading.RLock()
self._file_lock = FileLock(str(sessions.sessions_dir / _LOCK_FILENAME))
def ensure_many(self, session_keys: list[str]) -> dict[str, SessionHandle]:
"""Provision persisted sessions with at most one atomic store write."""
keys = list(dict.fromkeys(_clean_session_key(key) for key in session_keys))
descriptors = {
key: descriptor
for key in keys
if (descriptor := self._session_descriptor(key)) is not None
}
return self._ensure_descriptors(keys, descriptors)
def ensure_snapshot_many(
self,
snapshots: list[SessionHandleSnapshot],
) -> dict[str, SessionHandle]:
"""Provision trusted index snapshots without rereading session files."""
keys: list[str] = []
descriptors: dict[str, _SessionDescriptor] = {}
for snapshot in snapshots:
key = _clean_session_key(snapshot.session_key)
if key in descriptors:
continue
keys.append(key)
descriptors[key] = _SessionDescriptor(
workspace=_canonical_workspace(snapshot.workspace),
)
return self._ensure_descriptors(keys, descriptors)
def _ensure_descriptors(
self,
keys: list[str],
descriptors: dict[str, _SessionDescriptor],
) -> dict[str, SessionHandle]:
with self._thread_lock, self._file_lock:
records = self._load_unlocked()
by_key = {item.session_key: item for item in records}
changed = False
handles: dict[str, SessionHandle] = {}
for key in keys:
descriptor = descriptors.get(key)
if descriptor is None:
continue
existing = by_key.get(key)
workspace = str(descriptor.workspace)
if existing is not None and _same_workspace(existing.workspace, workspace):
handles[key] = _handle(existing, descriptor)
continue
if existing is not None:
records.remove(existing)
handle_id = existing.id if existing is not None else f"handle_{uuid.uuid4().hex}"
record = _StoredHandle(
id=handle_id,
session_key=key,
workspace=workspace,
name=_allocate_name(
handle_id,
records,
preferred=existing.name if existing is not None else None,
),
)
records.append(record)
by_key[key] = record
handles[key] = _handle(record, descriptor)
changed = True
if changed:
self._save_unlocked(records)
return handles
def handle_for_session(self, key: str) -> SessionHandle | None:
"""Return (and lazily provision) the trusted handle for *key*."""
clean_key = _clean_session_key(key)
handle = self.ensure_many([clean_key]).get(clean_key)
if handle is None:
self.remove_many([clean_key])
return handle
def resolve(self, name: str) -> SessionHandle | None:
"""Resolve a globally unique bare or ``@``-prefixed handle."""
try:
clean_name = normalize_session_handle(name)
except ValueError:
return None
with self._thread_lock, self._file_lock:
candidate = next(
(
item
for item in self._load_unlocked()
if item.name == clean_name
),
None,
)
if candidate is None:
return None
current = self.handle_for_session(candidate.session_key)
if current is None or current.name != clean_name:
return None
return current
def list_all(self) -> list[SessionHandle]:
"""List all live handles, ordered by handle."""
with self._thread_lock, self._file_lock:
keys = [item.session_key for item in self._load_unlocked()]
handles = [self.handle_for_session(key) for key in keys]
return sorted(
(handle for handle in handles if handle is not None),
key=lambda handle: handle.name,
)
def remove_many(self, session_keys: Iterable[str]) -> int:
"""Atomically remove handles bound to *session_keys*."""
keys = {_clean_session_key(key) for key in session_keys}
if not keys:
return 0
with self._thread_lock, self._file_lock:
records = self._load_unlocked()
remaining = [item for item in records if item.session_key not in keys]
removed = len(records) - len(remaining)
if removed == 0:
return 0
self._save_unlocked(remaining)
return removed
def _session_descriptor(self, session_key: str) -> _SessionDescriptor | None:
payload = self._sessions.read_session_metadata(session_key)
if payload is None:
return None
raw_metadata = cast(object, payload.get("metadata"))
metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {}
return _SessionDescriptor(
workspace=_workspace_from_metadata(metadata, default=self._sessions.workspace),
)
def _load_unlocked(self) -> list[_StoredHandle]:
if not self.store_path.is_file():
return []
try:
if self.store_path.stat().st_size > _MAX_STORE_BYTES:
raise SessionHandleDirectoryError("session handle store is too large")
raw: object = json.loads(self.store_path.read_text(encoding="utf-8"))
except SessionHandleDirectoryError:
raise
except (OSError, json.JSONDecodeError) as exc:
raise SessionHandleDirectoryError(
f"session handle store could not be read: {self.store_path}"
) from exc
if not isinstance(raw, dict):
raise SessionHandleDirectoryError("session handle store must be a JSON object")
data = cast(dict[str, Any], raw)
version = data.get("version")
raw_records = data.get("handles")
if version != SESSION_HANDLE_DIRECTORY_VERSION or not isinstance(raw_records, list):
raise SessionHandleDirectoryError("unsupported session handle store format")
record_values = cast(list[object], raw_records)
if len(record_values) > _MAX_HANDLES:
raise SessionHandleDirectoryError("session handle store has too many records")
records = [_parse_record(raw_record) for raw_record in record_values]
_validate_unique_records(records, globally_unique_names=False)
records, repaired = _repair_globally_duplicate_names(records)
_validate_unique_records(records)
if repaired:
self._save_unlocked(records)
return records
def _save_unlocked(self, records: list[_StoredHandle]) -> None:
if len(records) > _MAX_HANDLES:
raise SessionHandleDirectoryError("session handle store has too many records")
_validate_unique_records(records)
payload = {
"version": SESSION_HANDLE_DIRECTORY_VERSION,
"handles": [
{
"id": item.id,
"session_key": item.session_key,
"workspace": item.workspace,
"name": item.name,
}
for item in sorted(records, key=lambda item: item.session_key)
],
}
encoded = (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
if len(encoded) > _MAX_STORE_BYTES:
raise SessionHandleDirectoryError("session handle store is too large")
_atomic_write(self.store_path, encoded)
return {"id": self.id, "name": self.name}
def normalize_session_handle(value: str) -> str:
"""Return the canonical bare session handle accepted by the directory."""
name = unicodedata.normalize("NFKC", value.strip())
if name.startswith("@"):
name = name[1:]
name = name.casefold()
if not name or len(name) > _MAX_NAME_CHARS or _HANDLE_RE.fullmatch(name) is None:
raise ValueError("session handle must be a short ASCII name, optionally with a number")
"""Return the canonical bare handle accepted at model and UI boundaries."""
name = value.strip().removeprefix("@").casefold()
if _HANDLE_RE.fullmatch(name) is None:
raise ValueError("session handle is invalid")
return name
def _parse_record(raw: object) -> _StoredHandle:
if not isinstance(raw, dict):
raise SessionHandleDirectoryError("session handle records must be JSON objects")
data = cast(dict[str, Any], raw)
handle_id = data.get("id")
session_key = data.get("session_key")
raw_workspace = data.get("workspace")
raw_name = data.get("name")
if (
not isinstance(handle_id, str)
or _HANDLE_ID_RE.fullmatch(handle_id) is None
or not isinstance(session_key, str)
or not isinstance(raw_workspace, str)
or not isinstance(raw_name, str)
):
raise SessionHandleDirectoryError("invalid session handle record")
try:
clean_key = _clean_session_key(session_key)
workspace = _canonical_workspace(Path(raw_workspace))
name = normalize_session_handle(raw_name)
except ValueError as exc:
raise SessionHandleDirectoryError("invalid session handle record") from exc
if clean_key != session_key or str(workspace) != raw_workspace or name != raw_name:
raise SessionHandleDirectoryError("session handle record is not canonical")
return _StoredHandle(
id=handle_id,
session_key=clean_key,
workspace=str(workspace),
name=name,
)
def _validate_unique_records(
records: list[_StoredHandle],
*,
globally_unique_names: bool = True,
) -> None:
ids: set[str] = set()
session_keys: set[str] = set()
scoped_names: set[tuple[str, str]] = set()
for item in records:
name_scope = "" if globally_unique_names else _workspace_key(item.workspace)
scoped_name = (name_scope, item.name.casefold())
if item.id in ids or item.session_key in session_keys or scoped_name in scoped_names:
raise SessionHandleDirectoryError("session handle store contains duplicate records")
ids.add(item.id)
session_keys.add(item.session_key)
scoped_names.add(scoped_name)
def _repair_globally_duplicate_names(
records: list[_StoredHandle],
) -> tuple[list[_StoredHandle], bool]:
repaired = list(records)
seen: set[str] = set()
changed = False
for index, item in enumerate(repaired):
folded = item.name.casefold()
if folded not in seen:
seen.add(folded)
continue
replacement = _StoredHandle(
id=item.id,
session_key=item.session_key,
workspace=item.workspace,
name=_allocate_name(item.id, repaired[:index] + repaired[index + 1 :]),
)
repaired[index] = replacement
seen.add(replacement.name.casefold())
changed = True
return repaired, changed
def _workspace_from_metadata(metadata: dict[str, Any], *, default: Path) -> Path:
raw_scope = metadata.get(WORKSPACE_SCOPE_METADATA_KEY)
if not isinstance(raw_scope, dict):
return default.expanduser().resolve(strict=False)
raw_path = cast(dict[str, Any], raw_scope).get("project_path")
if raw_path is None:
return default.expanduser().resolve(strict=False)
if not isinstance(raw_path, str) or not raw_path.strip():
raise SessionHandleDirectoryError("session workspace scope has an invalid project path")
try:
return _canonical_workspace(Path(raw_path))
except ValueError as exc:
raise SessionHandleDirectoryError("session workspace scope has an invalid project path") from exc
def _canonical_workspace(path: Path) -> Path:
expanded = path.expanduser()
if not expanded.is_absolute():
raise ValueError("workspace path must be absolute")
return expanded.resolve(strict=False)
def _clean_session_key(value: str) -> str:
key = value.strip()
def session_handle_for_key(session_key: str) -> SessionHandle:
"""Derive a stable handle without creating a second persistence lifecycle."""
key = session_key.strip()
if not key or len(key) > _MAX_SESSION_KEY_CHARS:
raise ValueError("session key is invalid")
return key
def _allocate_name(
handle_id: str,
records: list[_StoredHandle],
*,
preferred: str | None = None,
) -> str:
used = {item.name.casefold() for item in records}
if preferred is not None and preferred.casefold() not in used:
return normalize_session_handle(preferred)
offset = int.from_bytes(
hashlib.sha256(handle_id.encode("ascii")).digest()[:4],
"big",
) % len(_HANDLE_NAMES)
ordered = _HANDLE_NAMES[offset:] + _HANDLE_NAMES[:offset]
for name in ordered:
if name not in used:
return name
suffix = 2
while suffix <= _MAX_HANDLES + 1:
for base in ordered:
candidate = f"{base}-{suffix}"
if candidate not in used:
return candidate
suffix += 1
raise SessionHandleDirectoryError("could not allocate a unique session handle")
def _handle(record: _StoredHandle, descriptor: _SessionDescriptor) -> SessionHandle:
color_slot = int.from_bytes(
hashlib.sha256(record.id.encode("ascii")).digest()[:2],
"big",
) % SESSION_HANDLE_COLOR_SLOTS
digest = hashlib.sha256(key.encode("utf-8")).hexdigest()
word = _HANDLE_NAMES[int(digest[:8], 16) % len(_HANDLE_NAMES)]
return SessionHandle(
id=record.id,
name=record.name,
color_slot=color_slot,
session_key=record.session_key,
workspace=descriptor.workspace,
id=f"handle_{digest[:32]}",
name=f"{word}-{digest[32:42]}",
session_key=key,
)
def _workspace_key(path: str) -> str:
return os.path.normcase(os.path.normpath(path))
class SessionHandleResolver:
"""Resolve derived handles against the current persisted-session list."""
def __init__(self, sessions: SessionManager) -> None:
self._sessions = sessions
def _same_workspace(left: str, right: str) -> bool:
return _workspace_key(left) == _workspace_key(right)
def _atomic_write(path: Path, content: bytes) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp_path = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
try:
with open(tmp_path, "wb") as file:
file.write(content)
file.flush()
os.fsync(file.fileno())
os.replace(tmp_path, path)
with suppress(PermissionError):
directory_fd = os.open(str(path.parent), os.O_RDONLY)
def list_all(self) -> list[SessionHandle]:
handles: list[SessionHandle] = []
for row in self._sessions.list_sessions():
raw_key: Any = row.get("key")
if not isinstance(raw_key, str):
continue
try:
try:
os.fsync(directory_fd)
except OSError as exc:
if exc.errno != errno.EINVAL:
raise
finally:
os.close(directory_fd)
except BaseException:
tmp_path.unlink(missing_ok=True)
raise
handles.append(session_handle_for_key(raw_key))
except ValueError:
continue
return sorted(handles, key=lambda handle: handle.name)
def resolve(self, name: str) -> SessionHandle | None:
try:
normalized = normalize_session_handle(name)
except ValueError:
return None
matches = [handle for handle in self.list_all() if handle.name == normalized]
return matches[0] if len(matches) == 1 else None
+18 -216
View File
@@ -1,4 +1,4 @@
"""Bounded delivery of messages between persisted sessions."""
"""Metadata carried by user input sent between persisted sessions."""
from __future__ import annotations
@@ -6,257 +6,59 @@ import re
from collections.abc import Mapping
from typing import Any, TypedDict, cast
from nanobot.bus.events import InboundMessage
from nanobot.session.session_handles import (
normalize_session_handle as normalize_stored_session_handle,
)
SESSION_MESSAGE_METADATA_KEY = "_session_message"
SESSION_REPLY_TIMEOUT_METADATA_KEY = "_session_reply_timeout"
SESSION_MESSAGE_SENDER_ID = "session"
SESSION_REPLY_TIMEOUT_SENDER_ID = "session_timeout"
MIN_REPLY_TIMEOUT_SECONDS = 5
MAX_REPLY_TIMEOUT_SECONDS = 60
_MAX_SESSION_KEY_CHARS = 512
_MESSAGE_ID_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
class SessionMessageEndpoint(TypedDict):
"""One endpoint stored in an internal session-message envelope."""
name: str
session_key: str
class SessionMessageSourceEndpoint(SessionMessageEndpoint):
"""Source fields used for WebUI provenance."""
handle_id: str
color_slot: int
class SessionMessageEnvelope(TypedDict):
"""Metadata persisted with session-authored user input."""
message_id: str
created_at_ms: int
expect_reply: bool
source: SessionMessageSourceEndpoint
target: SessionMessageEndpoint
class SessionReplyTimeoutEnvelope(SessionMessageEnvelope):
"""Trusted metadata for resuming a session after a session reply deadline."""
timeout_seconds: int
class SessionMessageError(ValueError):
"""A session message was rejected before reaching the inbound bus."""
def __init__(self, code: str, message: str) -> None:
super().__init__(message)
self.code = code
def normalize_session_handle(value: str) -> str:
"""Return the canonical bare session handle accepted by the directory."""
try:
return normalize_stored_session_handle(value)
except ValueError as exc:
raise SessionMessageError("invalid_name", str(exc)) from exc
source_session_key: str
target_session_key: str
def session_message_envelope(
metadata: Mapping[str, Any] | None,
) -> SessionMessageEnvelope | None:
"""Validate and normalize a session envelope from an inbound metadata boundary."""
"""Read a validated envelope from request or persisted-message metadata."""
if not isinstance(metadata, Mapping):
return None
raw = metadata.get(SESSION_MESSAGE_METADATA_KEY)
if not isinstance(raw, Mapping):
return None
data = cast(Mapping[str, object], raw)
message_id = _bounded_id(data.get("message_id"))
message_id = data.get("message_id")
created_at_ms = data.get("created_at_ms")
expect_reply = data.get("expect_reply")
source = _session_source_endpoint(data.get("source"))
target = _session_endpoint(data.get("target"))
source_session_key = _session_key(data.get("source_session_key"))
target_session_key = _session_key(data.get("target_session_key"))
if (
message_id is None
not isinstance(message_id, str)
or _MESSAGE_ID_RE.fullmatch(message_id) is None
or not isinstance(created_at_ms, int)
or isinstance(created_at_ms, bool)
or created_at_ms < 0
or not isinstance(expect_reply, bool)
or source is None
or target is None
or source_session_key is None
or target_session_key is None
):
return None
return {
"message_id": message_id,
"created_at_ms": created_at_ms,
"expect_reply": expect_reply,
"source": source,
"target": target,
"source_session_key": source_session_key,
"target_session_key": target_session_key,
}
def session_reply_timeout_envelope(
metadata: Mapping[str, Any] | None,
) -> SessionReplyTimeoutEnvelope | None:
"""Validate and normalize a session reply-timeout envelope."""
if not isinstance(metadata, Mapping):
def _session_key(value: object) -> str | None:
if not isinstance(value, str):
return None
raw = metadata.get(SESSION_REPLY_TIMEOUT_METADATA_KEY)
if not isinstance(raw, Mapping):
normalized_key = value.strip()
if not normalized_key or len(normalized_key) > _MAX_SESSION_KEY_CHARS:
return None
data = cast(Mapping[str, object], raw)
request = session_message_envelope({SESSION_MESSAGE_METADATA_KEY: data})
timeout_seconds = data.get("timeout_seconds")
if (
request is None
or not request["expect_reply"]
or not isinstance(timeout_seconds, int)
or isinstance(timeout_seconds, bool)
or not MIN_REPLY_TIMEOUT_SECONDS <= timeout_seconds <= MAX_REPLY_TIMEOUT_SECONDS
):
return None
return {
**request,
"timeout_seconds": timeout_seconds,
}
def session_message_inbound(msg: InboundMessage) -> SessionMessageEnvelope | None:
"""Return a session envelope only for the internal delivery shape we mint.
Metadata alone is not provenance: channel adapters may carry client-provided
metadata. Requiring the complete internal shape prevents forged session input.
"""
if (
msg.sender_id != SESSION_MESSAGE_SENDER_ID
or msg.session_key_override is None
):
return None
envelope = session_message_envelope(msg.metadata)
if envelope is None:
return None
target_key = envelope["target"]["session_key"]
raw_route = msg.channel == "system" and msg.chat_id == target_key
user_route = msg.channel == "websocket" and f"websocket:{msg.chat_id}" == target_key
if msg.session_key_override != target_key or not (raw_route or user_route):
return None
return envelope
def session_reply_timeout_inbound(
msg: InboundMessage,
) -> SessionReplyTimeoutEnvelope | None:
"""Return a timeout envelope only for the internal delivery shape we mint."""
if (
msg.sender_id != SESSION_REPLY_TIMEOUT_SENDER_ID
or msg.session_key_override is None
):
return None
envelope = session_reply_timeout_envelope(msg.metadata)
if envelope is None:
return None
waiter_key = envelope["source"]["session_key"]
raw_route = msg.channel == "system" and msg.chat_id == waiter_key
user_route = msg.channel == "websocket" and f"websocket:{msg.chat_id}" == waiter_key
if msg.session_key_override != waiter_key or not (raw_route or user_route):
return None
return envelope
def is_session_input(msg: InboundMessage) -> bool:
"""Return whether *msg* is a server-minted session input."""
return (
session_message_inbound(msg) is not None
or session_reply_timeout_inbound(msg) is not None
)
def session_input_history_extra(msg: InboundMessage) -> dict[str, Any]:
"""Return private history metadata for one validated session input."""
envelope = session_message_inbound(msg)
if envelope is not None:
return {SESSION_MESSAGE_METADATA_KEY: envelope}
timeout = session_reply_timeout_inbound(msg)
return {SESSION_REPLY_TIMEOUT_METADATA_KEY: timeout} if timeout is not None else {}
def session_message_public_metadata(envelope: SessionMessageEnvelope) -> dict[str, Any]:
"""Return public provenance without internal routing identifiers."""
source = envelope["source"]
return {
"direction": "incoming",
"message_id": envelope["message_id"],
"session": {
"id": source["handle_id"],
"name": source["name"],
"color_slot": source["color_slot"],
},
}
def _bounded_id(value: object) -> str | None:
return value if isinstance(value, str) and _MESSAGE_ID_RE.fullmatch(value) else None
def _session_endpoint(value: object) -> SessionMessageEndpoint | None:
if not isinstance(value, Mapping):
return None
data = cast(Mapping[str, object], value)
raw_name = data.get("name")
raw_key = data.get("session_key")
if not isinstance(raw_name, str) or not isinstance(raw_key, str):
return None
try:
name = normalize_session_handle(raw_name)
except SessionMessageError:
return None
session_key = raw_key.strip()
if not session_key or len(session_key) > _MAX_SESSION_KEY_CHARS:
return None
return {
"name": name,
"session_key": session_key,
}
def _session_source_endpoint(value: object) -> SessionMessageSourceEndpoint | None:
endpoint = _session_endpoint(value)
if endpoint is None:
return None
data = cast(Mapping[str, object], value)
handle_id = data.get("handle_id")
color_slot = data.get("color_slot")
if (
not isinstance(handle_id, str)
or _MESSAGE_ID_RE.fullmatch(handle_id) is None
or not isinstance(color_slot, int)
or isinstance(color_slot, bool)
or not 0 <= color_slot < 8
):
return None
return {
**endpoint,
"handle_id": handle_id,
"color_slot": color_slot,
}
def is_persisted_webui_session(
session_key: str,
payload: Mapping[str, Any],
) -> bool:
"""Return whether *payload* is a persisted WebUI conversation."""
raw_metadata = cast(object, payload.get("metadata"))
if not session_key.startswith("websocket:") or not isinstance(raw_metadata, Mapping):
return False
metadata = cast(Mapping[str, object], raw_metadata)
return metadata.get("webui") is True
return normalized_key
+72 -98
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
import re
import time
from collections.abc import Awaitable, Callable, Mapping
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, replace
from typing import Any, cast
from uuid import uuid4
@@ -19,10 +19,10 @@ from nanobot.bus.outbound_events import (
GoalStateSyncEvent,
GoalStatusEvent,
RuntimeModelUpdatedEvent,
SessionMessageInputEvent,
SessionUpdatedEvent,
TurnEndEvent,
TurnModelUpdatedEvent,
UserInputEvent,
outbound_message_for_event,
)
from nanobot.bus.queue import MessageBus
@@ -35,6 +35,7 @@ from nanobot.bus.runtime_events import (
TurnCompleted,
TurnRunStatusChanged,
TurnRuntimeAdmitted,
UserInputAccepted,
)
from nanobot.providers.base import LLMProvider
from nanobot.providers.fallback_provider import FallbackModelObserver
@@ -42,17 +43,15 @@ from nanobot.runtime_context import public_history_message
from nanobot.session.goal_state import goal_state_ws_blob
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import Session, SessionManager
from nanobot.session.session_handles import session_handle_for_key
from nanobot.session.session_messages import (
SESSION_MESSAGE_METADATA_KEY,
session_message_inbound,
session_message_public_metadata,
session_reply_timeout_inbound,
SessionMessageEnvelope,
session_message_envelope,
)
from nanobot.utils.helpers import strip_think, truncate_text
from nanobot.utils.llm_runtime import LLMRuntime
from nanobot.webui.metadata import (
WEBSOCKET_TURN_OWNER_METADATA_KEY,
WEBUI_MESSAGE_SOURCE_METADATA_KEY,
WEBUI_TURN_METADATA_KEY,
)
from nanobot.webui.transcript import append_session_message_input
@@ -83,6 +82,16 @@ class _WebsocketTurn:
_WEBSOCKET_ACTIVE_TURNS: dict[str, dict[str, _WebsocketTurn]] = {}
def _session_message_public_metadata(
envelope: SessionMessageEnvelope,
) -> dict[str, Any]:
source = session_handle_for_key(envelope["source_session_key"])
return {
"message_id": envelope["message_id"],
"session": source.public_payload(),
}
def _validated_llm_runtime(value: object) -> LLMRuntime | None:
"""Keep runtime-event consumers defensive if an external publisher violates the contract."""
return value if isinstance(value, LLMRuntime) else None
@@ -115,20 +124,6 @@ def mark_webui_session(session: Session, metadata: dict[str, Any]) -> bool:
return True
def _session_for_webui_lifecycle(
sessions: SessionManager,
msg: InboundMessage,
session_key: str,
) -> Session | None:
"""Resolve lifecycle state without reviving deleted internal-message targets."""
if (
session_message_inbound(msg) is not None
or session_reply_timeout_inbound(msg) is not None
):
return sessions.get_existing(session_key)
return sessions.get_or_create(session_key)
def clean_generated_title(raw: str | None) -> str:
text = (raw or "").strip()
if not text:
@@ -176,9 +171,7 @@ async def maybe_generate_webui_title(
model: str,
) -> bool:
"""Generate and persist a short title for WebUI-owned sessions only."""
session = sessions.get_existing(session_key)
if session is None:
return False
session = sessions.get_or_create(session_key)
if session.metadata.get(WEBUI_SESSION_METADATA_KEY) is not True:
return False
if session.metadata.get(WEBUI_TITLE_USER_EDITED_METADATA_KEY) is True:
@@ -426,8 +419,7 @@ class WebuiTurnRoutePolicy:
) -> TurnRoute:
"""Make an independently dispatched agent turn visible in WebUI."""
routed = route
session_message = session_message_inbound(msg)
reply_timeout = session_reply_timeout_inbound(msg)
internal_user_input = msg.channel == "system" and msg.is_user_input
if (
(
(
@@ -435,41 +427,19 @@ class WebuiTurnRoutePolicy:
and msg.sender_id == "subagent"
and msg.metadata.get("injected_event") == "subagent_result"
)
or session_message is not None
or reply_timeout is not None
or internal_user_input
)
and route.channel == "websocket"
):
if session_message is not None or reply_timeout is not None:
persisted = self.sessions.read_session_metadata(session_key)
raw_session_metadata = (
persisted.get("metadata") if persisted is not None else None
)
session_metadata: Mapping[str, Any] = (
cast(Mapping[str, Any], raw_session_metadata)
if isinstance(raw_session_metadata, Mapping)
else {}
)
else:
session_metadata = self.sessions.get_or_create(session_key).metadata
if session_metadata.get(WEBUI_SESSION_METADATA_KEY) is True:
session = self.sessions.get_or_create(session_key)
if session.metadata.get(WEBUI_SESSION_METADATA_KEY) is True:
metadata = dict(route.metadata)
turn_prefix = "subagent"
if session_message is not None:
turn_prefix = "session-message"
elif reply_timeout is not None:
turn_prefix = "session-reply-timeout"
turn_prefix = "session-input" if internal_user_input else "subagent"
metadata.update({
WEBUI_SESSION_METADATA_KEY: True,
"_wants_stream": True,
WEBUI_TURN_METADATA_KEY: f"{turn_prefix}:{uuid4().hex}",
})
if session_message is not None:
metadata[SESSION_MESSAGE_METADATA_KEY] = session_message
metadata[WEBUI_MESSAGE_SOURCE_METADATA_KEY] = {
"kind": "session",
"label": f"@{session_message['source']['name']}",
}
routed = replace(route, metadata=metadata, publish_lifecycle=True)
if routed.channel == "websocket" and routed.publish_lifecycle:
@@ -501,40 +471,6 @@ class WebuiTurnRoutePolicy:
return routed
async def project_session_message_input(
bus: MessageBus,
msg: InboundMessage,
session_key: str,
) -> None:
"""Persist and publish an incoming session message for WebUI clients."""
envelope = session_message_inbound(msg)
if envelope is None or msg.channel != "websocket":
return
public_metadata = session_message_public_metadata(envelope)
try:
append_session_message_input(
session_key,
content=msg.content,
created_at_ms=envelope["created_at_ms"],
session_message=public_metadata,
)
except (OSError, TypeError, ValueError):
logger.warning(
"Failed to persist session input {}",
envelope["message_id"],
exc_info=True,
)
await bus.publish_outbound(outbound_message_for_event(
channel="websocket",
chat_id=str(msg.chat_id),
event=SessionMessageInputEvent(
content=msg.content,
created_at_ms=envelope["created_at_ms"],
session_message=public_metadata,
),
))
def build_webui_fallback_model_observer(bus: MessageBus) -> FallbackModelObserver:
"""Translate provider fallback choices into chat-scoped WebUI events."""
@@ -575,6 +511,10 @@ class WebuiTurnCoordinator:
def subscribe(self, runtime_events: RuntimeEventBus) -> Callable[[], None]:
"""Subscribe this coordinator to runtime events."""
unsubscribe = [
runtime_events.subscribe(
self._handle_user_input_accepted,
UserInputAccepted,
),
runtime_events.subscribe(
self._handle_session_turn_started,
SessionTurnStarted,
@@ -622,17 +562,53 @@ class WebuiTurnCoordinator:
def _is_websocket_event(ctx: RuntimeEventContext) -> bool:
return ctx.channel == "websocket"
async def _handle_session_turn_started(self, event: SessionTurnStarted) -> None:
async def _handle_user_input_accepted(self, event: UserInputAccepted) -> None:
envelope = session_message_envelope(event.context.metadata)
session_key = event.context.session_key
if (
event.context.channel != "system"
or envelope is None
or envelope["target_session_key"] != session_key
or not session_key.startswith("websocket:")
):
return
persisted = self.sessions.read_session_metadata(session_key)
metadata_value: object = persisted.get("metadata") if persisted is not None else None
metadata = (
cast(dict[str, Any], metadata_value)
if isinstance(metadata_value, dict)
else None
)
if metadata is None or metadata.get(WEBUI_SESSION_METADATA_KEY) is not True:
return
public_metadata = _session_message_public_metadata(envelope)
try:
append_session_message_input(
session_key,
content=event.content,
created_at_ms=envelope["created_at_ms"],
session_message=public_metadata,
)
except (OSError, TypeError, ValueError):
logger.warning(
"Failed to persist session input {}",
envelope["message_id"],
exc_info=True,
)
await self.bus.publish_outbound(outbound_message_for_event(
channel="websocket",
chat_id=session_key.split(":", 1)[1],
event=UserInputEvent(
content=event.content,
created_at_ms=envelope["created_at_ms"],
provenance={"session_message": public_metadata},
),
))
def _handle_session_turn_started(self, event: SessionTurnStarted) -> None:
if not self._is_websocket_event(event.context):
return
msg = self._ctx_msg(event.context)
session = _session_for_webui_lifecycle(
self.sessions,
msg,
event.context.session_key,
)
if session is None:
return
session = self.sessions.get_or_create(event.context.session_key)
mark_webui_session(session, event.context.metadata)
async def _handle_run_status_changed(self, event: TurnRunStatusChanged) -> None:
@@ -726,9 +702,7 @@ class WebuiTurnCoordinator:
if msg.channel != "websocket":
return
session = _session_for_webui_lifecycle(self.sessions, msg, session_key)
if session is None:
return
session = self.sessions.get_or_create(session_key)
await self.bus.publish_outbound(
outbound_message_for_event(
channel=msg.channel,