feat(subagent): add session-owned task messaging and cancellation (#5985)

let's go!
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-05 05:16:33 +08:00
1 parent f75470e72f
commit 6ff96f2a8f
93 files changed
+5632 -1156

No files matched your search

+9
View File
@@ -95,6 +95,13 @@ class SessionHistoryReader:
key = row.get("key")
if not isinstance(key, str) or key == exclude_session_key:
continue
payload = self._sessions.read_session_metadata(key)
if payload is None:
continue
raw_metadata = cast(object, payload.get("metadata"))
metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {}
if not self._sessions.types.public_history(metadata):
continue
title = _text(row.get("title"))
folded = title.casefold()
rank = (
@@ -139,6 +146,8 @@ class SessionHistoryReader:
return None
raw_metadata = cast(object, payload.get("metadata"))
metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {}
if not self._sessions.types.public_history(metadata):
return None
updated = payload.get("updated_at")
return {
"session_key": session_key,
+54 -8
View File
@@ -30,6 +30,7 @@ from nanobot.runtime_context import (
from nanobot.session.history_visibility import HIDDEN_HISTORY_META, is_hidden_history_message
from nanobot.session.model_selection import SESSION_MODEL_PRESET_METADATA_KEY
from nanobot.session.summary import SUMMARY_CONTINUATION_TEXT, is_summary_checkpoint
from nanobot.session.types import PARENT_SESSION_KEY, SESSION_TYPE_KEY, SessionTypes
from nanobot.utils.helpers import (
atomic_write_lines,
content_with_media_breadcrumbs,
@@ -59,6 +60,8 @@ _RUNTIME_CHECKPOINT_KEY = "runtime_checkpoint"
_RUNTIME_CHECKPOINT_VERSION = 1
_RUNTIME_CHECKPOINT_SUFFIX = ".checkpoint.json"
_FORK_VOLATILE_METADATA_KEYS = {
PARENT_SESSION_KEY,
SESSION_TYPE_KEY,
"goal_state",
"pending_user_turn",
"pending_user_followups",
@@ -170,9 +173,9 @@ class SessionPolicy:
@dataclass
class Session:
"""A conversation session."""
"""Message history, runtime state, and metadata for one agent session."""
key: str # channel:chat_id
key: str # namespace:identity
messages: list[dict[str, Any]] = field(default_factory=list)
created_at: datetime = field(default_factory=datetime.now)
updated_at: datetime = field(default_factory=datetime.now)
@@ -1534,6 +1537,7 @@ class SessionManager:
self._overflow_cache: WeakValueDictionary[str, Session] = WeakValueDictionary()
self._max_cached_sessions = SESSION_CACHE_MAX_SIZE
self._delete_observer: Callable[[str], None] | None = None
self.types = SessionTypes()
def _remember(self, session: Session) -> None:
"""Keep recent sessions strongly cached without duplicating live objects."""
@@ -1631,6 +1635,32 @@ class SessionManager:
self._remember(session)
return session
def get_existing(self, key: str) -> Session | None:
"""Load an existing session without creating a deleted conversation."""
session = self._cached(key) or self._load(key)
if session is not None:
self._remember(session)
return session
def child_session_keys(self, parent_key: str) -> list[str]:
"""Find persisted and active children through their declared parent."""
return [key for key, parent in self._session_parents().items() if parent == parent_key]
def _session_parents(self) -> dict[str, str]:
keys = {row["key"] for row in self.list_sessions()}
cached = {**self._overflow_cache, **self._cache}
keys.update(cached)
parents: dict[str, str] = {}
for key in sorted(keys):
session = cached.get(key)
metadata = session.metadata if session is not None else (
(self.read_session_metadata(key) or {}).get("metadata", {})
)
parent = metadata.get(PARENT_SESSION_KEY)
if isinstance(parent, str):
parents[key] = parent
return parents
def get_or_create_transient(
self,
key: str,
@@ -1741,12 +1771,28 @@ class SessionManager:
self._overflow_cache.pop(key, None)
def delete_session(self, key: str) -> bool:
"""Delete a persisted session and invalidate its cache entry."""
self.invalidate(key)
deleted = self._store.delete(key)
if self._delete_observer is not None:
self._delete_observer(key)
return deleted
"""Delete a session and its descendants, invalidating their cache entries."""
# Collect descendants before deletion; the common file lock also keeps
# handle allocation and child-session saves outside this boundary.
with self.locked_session_files():
children: dict[str, list[str]] = {}
for child, parent in self._session_parents().items():
children.setdefault(parent, []).append(child)
pending = [key]
collected: set[str] = set()
while pending:
current = pending.pop()
if current in collected:
continue
collected.add(current)
pending.extend(children.get(current, ()))
deleted = False
for current in collected:
self.invalidate(current)
deleted = self._store.delete(current) or deleted
if self._delete_observer is not None:
self._delete_observer(current)
return deleted
def restore_sessions_to_workspace(self) -> SessionRestoreResult:
"""Restore session files to the pre-relocation path for an explicit rollback."""
+2
View File
@@ -172,6 +172,8 @@ class SessionHandleResolver:
if isinstance(raw_metadata, dict)
else {}
)
if not self._sessions.types.needs_handle(metadata):
continue
raw_name = metadata.get(SESSION_HANDLE_METADATA_KEY)
try:
name = normalize_session_handle(raw_name) if isinstance(raw_name, str) else ""
+46
View File
@@ -0,0 +1,46 @@
"""Session kinds declare their public identity and history access."""
from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass
SESSION_TYPE_KEY = "session_type"
PARENT_SESSION_KEY = "parent_session_key"
@dataclass(frozen=True, slots=True)
class SessionType:
name: str
needs_handle: bool
public_history: bool
CONVERSATION = SessionType("conversation", needs_handle=True, public_history=True)
class SessionTypes:
"""Consume declarations from session owners without importing those owners."""
def __init__(self) -> None:
self._types: dict[str, SessionType] = {CONVERSATION.name: CONVERSATION}
def register(self, session_type: SessionType) -> None:
previous = self._types.get(session_type.name)
if previous is not None and previous != session_type:
raise ValueError(f"session type already registered: {session_type.name}")
self._types[session_type.name] = session_type
def resolve(self, metadata: Mapping[str, object]) -> SessionType | None:
# Legacy sessions are ordinary conversations. Explicit unknown kinds
# remain private until their owner registers the access contract.
name = metadata.get(SESSION_TYPE_KEY, CONVERSATION.name)
return self._types.get(name) if isinstance(name, str) else None
def needs_handle(self, metadata: Mapping[str, object]) -> bool:
kind = self.resolve(metadata)
return kind is not None and kind.needs_handle
def public_history(self, metadata: Mapping[str, object]) -> bool:
kind = self.resolve(metadata)
return kind is not None and kind.public_history
+10 -2
View File
@@ -31,6 +31,7 @@ from nanobot.bus.runtime_events import (
RuntimeEventContext,
RuntimeModelChanged,
SessionTurnStarted,
SubagentTaskChanged,
TurnCompleted,
TurnRunStatusChanged,
TurnRuntimeAdmitted,
@@ -55,7 +56,7 @@ from nanobot.webui.metadata import (
WEBSOCKET_TURN_OWNER_METADATA_KEY,
WEBUI_TURN_METADATA_KEY,
)
from nanobot.webui.session_identity import is_webui_session_key
from nanobot.webui.session_identity import is_webui_session_key, webui_session_key
from nanobot.webui.star_prompt import update_star_prompt
from nanobot.webui.transcript import append_session_message_input
@@ -502,7 +503,7 @@ class WebuiTurnRoutePolicy:
else uuid4().hex
)
metadata[WEBSOCKET_TURN_OWNER_METADATA_KEY] = owner
routed = replace(routed, metadata=metadata)
routed = replace(routed, metadata=metadata, turn_id=current_turn_id)
# Direct websocket turns publish their final idle transition from
# the original input message. Carry the same server-owned identity
# there, overwriting any untrusted client-supplied value.
@@ -578,6 +579,7 @@ class WebuiTurnCoordinator:
self._handle_goal_state_changed,
GoalStateChanged,
),
self.bus.subscribe(self._handle_subagent_task_changed, SubagentTaskChanged),
self.bus.subscribe(
self._handle_runtime_model_changed,
RuntimeModelChanged,
@@ -734,6 +736,12 @@ class WebuiTurnCoordinator:
),
)
async def _handle_subagent_task_changed(self, event: SubagentTaskChanged) -> None:
ctx = event.context
if not self._is_websocket_event(ctx) or ctx.session_key != webui_session_key(ctx.chat_id):
return
await self.bus.publish_event(event, channel=ctx.channel, chat_id=ctx.chat_id)
async def _handle_runtime_model_changed(self, event: RuntimeModelChanged) -> None:
await self.bus.publish_outbound(
outbound_message_for_event(