refactor(session): centralize state ownership in SQLite (#5943)

* fix(session): move persistence off event loop

* refactor(session): isolate async persistence boundary

* refactor(session): keep a single session manager

* refactor(session): use stateless async adapters

* fix(session): serialize local persistence without file-lock contention

* refactor(session): own async persistence and snapshot commits

* refactor(session): narrow persistence changes to async adapters

* refactor(session): remove redundant async forwarding helpers

* fix(command): offload compact session persistence

* fix(session): adapt idle compaction to current main

* fix(webui): offload session metadata persistence

* refactor(session): centralize state ownership in SQLite

* fix(session): skip storage for non-recoverable followups

* test(webui): honor the full gateway event deadline

* perf(session): persist incremental changes and reuse owner snapshots

* test(agent): allow durable worker shutdown in burst test

* fix(gateway): drain session storage on Windows console shutdown

* fix(session): enforce bounded ownership and lifecycle-safe persistence

* fix: reject unresolved home paths and stabilize platform tests

* fix(session): preserve request context compatibility and owner-backed tests

* docs: focus configuration guide on user-facing behavior

* fix(session): adapt goal admission to async ownership after rebase

* fix(session): integrate current gateway and subagent contracts

* fix(session): align rebased workspace admission and async tests

* fix(session): support compatible SQLite schema evolution

* test(agent): use session owner in workspace context regressions

* test: stabilize Windows lifecycle and browser checks

* refactor(session): remove premature JSONL file export

* ci: bound Windows full-suite worker concurrency

* chore: remove session state refactor notes

* fix(session): queue writes and retain worker connections

* perf(webui): read detached metadata for session and task lists

* perf(agent): bound prompt preparation and local token counting

* docs: remove internal session storage guide

* perf(session): skip archived transcripts during idle scans

* fix(session): coordinate turns and isolate legacy session data

Bind WebUI input generations to the execution session and serialize idle
and SDK compaction with turns. Keep turn drafts through preparation so the
latest channel route persists.

Move imported workspace JSONL and checkpoints to durable private backups
before gateway admission, resuming cleanup after interruptions. Remove
committed child sessions when task creation is cancelled.

Validation: focused Python and frontend regressions, Ruff, BasedPyright,
import boundaries, WebUI build, and isolated gateway/browser flows.

* fix(agent): keep cancellation hooks independent of prompt preparation

* fix(session): preserve admission, delivery, and migration contracts

* fix(agent): preserve cancellation settlement after rebase

* fix(session): preserve request attribution through async ownership
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-16 17:28:47 +08:00
1 parent 33ff520d12
commit 8f6a5594fb
144 files changed
+8293 -4912

No files matched your search

+33 -34
View File
@@ -3,7 +3,7 @@
from __future__ import annotations
import asyncio
from collections.abc import Collection
from collections.abc import Awaitable, Collection
from datetime import datetime
from typing import TYPE_CHECKING, Any, Callable, Coroutine
@@ -14,7 +14,6 @@ from nanobot.session.keys import is_dream_session
from nanobot.session.manager import Session, SessionManager
from nanobot.session.summary import (
SessionSummary,
is_summary_checkpoint,
session_summary_from_metadata,
)
@@ -26,10 +25,15 @@ SessionEventFactory = Callable[[str], EventSink]
class AutoCompact:
def __init__(self, sessions: SessionManager, consolidator: Consolidator,
session_ttl_minutes: int = 0,
bind_events: SessionEventFactory | None = None,
*, session_lock: Callable[[str], asyncio.Lock]):
def __init__(
self,
sessions: SessionManager,
consolidator: Consolidator,
session_ttl_minutes: int = 0,
bind_events: SessionEventFactory | None = None,
*,
session_lock: Callable[[str], asyncio.Lock],
):
self.sessions = sessions
self.consolidator = consolidator
self._ttl = session_ttl_minutes
@@ -56,38 +60,30 @@ class AutoCompact:
return False
return idle_seconds >= self._ttl * 60
def _has_unarchived_messages(self, key: str) -> bool:
session = self.sessions.get_or_create(key)
return any(
not message.get("_command") and not is_summary_checkpoint(message)
for message in session.messages[session.last_archived:]
)
def check_expired(
async def check_expired(
self,
schedule_background: Callable[[Coroutine[Any, Any, None]], None],
resolve_runtime: Callable[[Session], LLMRuntime],
resolve_runtime: Callable[[Session], Awaitable[LLMRuntime]],
active_session_keys: Collection[str] = (),
) -> None:
"""Schedule archival for idle sessions, skipping those with in-flight agent tasks."""
"""Schedule idle archival without blocking the event loop."""
now = datetime.now()
for info in self.sessions.list_sessions():
active_keys = set(active_session_keys)
for info in await self.sessions.state.list_sessions():
key = info.get("key", "")
# Dream sessions are per-run; persistent maintenance sessions still compact.
if not key or is_dream_session(key) or key in self._archiving:
continue
if key in active_session_keys:
if key in active_keys or not self._is_expired(info.get("updated_at"), now):
continue
updated_at = info.get("updated_at")
if self._is_expired(updated_at, now) and self._has_unarchived_messages(key):
session = self.sessions.get_or_create(key)
try:
runtime = resolve_runtime(session)
except (KeyError, ValueError):
# Invalid session selections remain recoverable through /model.
continue
self._archiving.add(key)
schedule_background(self._archive(key, runtime=runtime))
if not await self.sessions.state.has_unarchived_messages(key):
continue
session = await self.sessions.state.get(key)
try:
runtime = await resolve_runtime(session)
except (KeyError, ValueError):
continue
self._archiving.add(key)
schedule_background(self._archive(key, runtime=runtime))
async def _archive(self, key: str, *, runtime: LLMRuntime) -> None:
if is_dream_session(key):
@@ -95,13 +91,14 @@ class AutoCompact:
return
try:
async with self._session_lock(key):
# Idle compaction and turns share one transcript boundary.
summary = await self.consolidator.compact_idle_session(
key,
runtime=runtime,
events=self._bind_events(key) if self._bind_events else NO_EVENTS,
)
if summary:
session = self.sessions.get_or_create(key)
session = await self.sessions.state.get(key)
stored = session_summary_from_metadata(
session.metadata,
fallback_last_active=session.updated_at,
@@ -113,14 +110,16 @@ class AutoCompact:
finally:
self._archiving.discard(key)
def prepare_session(self, session: Session, key: str) -> tuple[Session, SessionSummary | None]:
async def prepare_session(
self,
session: Session,
key: str,
) -> tuple[Session, SessionSummary | None]:
"""Resolve a summary while preserving the turn's owner-issued draft."""
if is_dream_session(key):
self._archiving.discard(key)
self._summaries.pop(key, None)
return session, None
if key in self._archiving or self._is_expired(session.updated_at):
logger.info("Auto-compact: reloading session {} (archiving={})", key, key in self._archiving)
session = self.sessions.get_or_create(key)
# Hot path: summary from in-memory dict (process hasn't restarted).
entry = self._summaries.pop(key, None)
if entry:
+3 -3
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
import asyncio
import dataclasses
from collections.abc import Callable, Iterable
from collections.abc import Awaitable, Callable, Iterable
from nanobot.bus.events import InboundMessage, OutboundMessage
@@ -19,7 +19,7 @@ class AutomationTurnCoordinator:
def __init__(
self,
*,
enqueue: Callable[[InboundMessage], None],
enqueue: Callable[[InboundMessage], Awaitable[None]],
turn_id: Callable[[InboundMessage], str | None],
pending_id: Callable[[InboundMessage], str | None],
should_defer_turn: Callable[[InboundMessage, str, Iterable[str]], bool],
@@ -54,7 +54,7 @@ class AutomationTurnCoordinator:
self._waiters[turn_id] = future
self._pending_messages_by_turn_id[turn_id] = msg
try:
self._enqueue(msg)
await self._enqueue(msg)
try:
return await future
except asyncio.CancelledError:
-12
View File
@@ -71,7 +71,6 @@ BACKFILL_CONTENT = "[Tool result unavailable — call was interrupted or lost]"
PLACEHOLDER_TEXTS = frozenset({
"[Previous assistant message omitted.]",
})
_PreparationArgs = ParamSpec("_PreparationArgs")
_PreparationResult = TypeVar("_PreparationResult")
@@ -234,17 +233,6 @@ class ContextCompactionState:
) -> list[dict[str, Any]]:
return deepcopy(request_messages[len(self.accepted_messages):])
def accept_request(
self,
model_messages: list[dict[str, Any]],
*,
raw_boundary: int,
) -> None:
"""Advance H after the provider has received one request."""
self.accepted_messages = deepcopy(model_messages)
self.raw_accepted_boundary = raw_boundary
@dataclass(slots=True)
class ModelRequestState:
"""Context state shared by every provider request in one runner turn."""
+2 -2
View File
@@ -2,7 +2,7 @@
from __future__ import annotations
from collections.abc import Callable, Iterable
from collections.abc import Awaitable, Callable, Iterable
from nanobot.agent.automation_turns import AutomationTurnCoordinator
from nanobot.bus.events import InboundMessage
@@ -19,7 +19,7 @@ class CronTurnCoordinator(AutomationTurnCoordinator):
def __init__(
self,
*,
enqueue: Callable[[InboundMessage], None],
enqueue: Callable[[InboundMessage], Awaitable[None]],
deferred_queues: dict[str, list[InboundMessage]] | None = None,
) -> None:
super().__init__(
+210 -137
View File
@@ -97,11 +97,12 @@ from nanobot.session.recovery import (
RequestOrigin,
acknowledge_pending_followups,
pending_followups,
record_pending_followup,
request_origin_from_metadata,
restore_pending_interruption,
restore_runtime_checkpoint,
)
from nanobot.session.sqlite_store import SessionConflictError
from nanobot.session.state import SessionOperationQueueFullError
from nanobot.session.summary import (
SessionSummary,
SessionSummaryCheckpoint,
@@ -181,6 +182,8 @@ class TurnContext:
provider_compaction_applied: bool = False
ephemeral: bool = False
# SDK temporary turns use an isolated draft; gateway temporary chats retain owner state.
commit_session: bool = True
run_extra_hooks_for_ephemeral: bool = False
hooks: list[AgentHook] = field(default_factory=list)
hook_factories: list[AgentTurnHookFactory] = field(default_factory=list)
@@ -543,13 +546,13 @@ class AgentLoop:
self._publish_runtime_selection(runtime)
return runtime
def runtime_for_session(
def _resolve_session_runtime(
self,
session: Session,
*,
recover_removed: bool = True,
) -> LLMRuntime:
"""Resolve the immutable runtime selected by one session."""
recover_removed: bool,
) -> LLMRuntime | None:
"""Return the selected runtime, or clear a removed preset for persistence."""
name = model_preset_from_metadata(session.metadata)
if name is None:
return self.llm_runtime()
@@ -564,19 +567,38 @@ class AgentLoop:
name,
)
session.metadata.pop(SESSION_MODEL_PRESET_METADATA_KEY, None)
self.sessions.save(session)
return self.llm_runtime()
return None
def set_session_model_preset(
async def runtime_for_session(
self,
session: Session,
*,
recover_removed: bool = True,
) -> LLMRuntime:
"""Resolve a session runtime without blocking on recovery persistence."""
runtime = self._resolve_session_runtime(session, recover_removed=recover_removed)
if runtime is not None:
return runtime
await self.sessions.state.update_metadata(
session.key,
{},
remove=(SESSION_MODEL_PRESET_METADATA_KEY,),
expected_generation=session.generation,
)
return self.llm_runtime()
async def set_session_model_preset(
self,
session_key: str,
name: str,
) -> LLMRuntime:
"""Validate and persist one session's preset selection."""
"""Validate and persist one session's preset selection without blocking."""
runtime = self.runtime_resolver.resolve_preset(name)
session = self.sessions.get_or_create(session_key)
session.metadata[SESSION_MODEL_PRESET_METADATA_KEY] = runtime.model_preset
self.sessions.save(session)
await self.sessions.state.update_metadata(
session_key,
{SESSION_MODEL_PRESET_METADATA_KEY: runtime.model_preset},
create_if_missing=True,
)
return runtime
def _publish_runtime_selection(
@@ -675,17 +697,14 @@ class AgentLoop:
def pending_local_trigger_ids_for_session(self, session_key: str) -> set[str]:
return self._local_trigger_turns.pending_trigger_ids_for_session(session_key)
def _persist_user_message_early(
async def _persist_user_message_early(
self,
msg: InboundMessage,
session: Session,
runtime_context_blocks: list[RuntimeContextBlock] | None = None,
**kwargs: Any,
) -> bool:
"""Persist the triggering user message before the turn starts.
Returns True if the message was persisted.
"""
"""Persist the triggering user message and recovery markers before running the turn."""
if not turn_continuation.should_persist_user_message(msg.metadata):
return False
media_paths = [
@@ -716,7 +735,7 @@ class AgentLoop:
followup_id = msg.metadata.get(PENDING_FOLLOWUP_ID_KEY)
if isinstance(followup_id, str) and followup_id:
acknowledge_pending_followups(session, [followup_id])
self.sessions.save(session)
await self.sessions.state.prepare_input(session)
return True
return False
@@ -743,7 +762,11 @@ class AgentLoop:
ctx.session.metadata[REQUEST_ORIGIN_METADATA_KEY] = origin
if ctx.original_user_text is None:
# No new user row will persist this turn's owner before execution.
self.sessions.save(ctx.session)
await self.sessions.state.update_metadata(
ctx.session.key,
{REQUEST_ORIGIN_METADATA_KEY: origin},
expected_generation=ctx.session.generation,
)
scope = await self.runner.prepare_prompt(
self.workspace_scopes.for_turn,
channel=ctx.delivery.route.channel,
@@ -755,6 +778,7 @@ class AgentLoop:
chat_id=ctx.delivery.route.chat_id,
message_id=origin["message_id"],
session_key=ctx.session_key,
session_generation=ctx.session.generation,
original_user_text=ctx.original_user_text,
runtime=ctx.runtime,
metadata=dict(ctx.msg.metadata or {}),
@@ -789,9 +813,10 @@ class AgentLoop:
]
blocks = runtime_context_blocks_from_metadata(request.metadata)
blocks.extend(await resolve_runtime_context(providers, request))
skill_context = await self.runner.prepare_prompt(
self.context.skills.build_explicit_skill_runtime_context,
request.original_user_text or "",
text = request.original_user_text or ""
skill_context = (
await self.runner.prepare_prompt(self.context.skills.build_explicit_skill_runtime_context, text)
if "$" in text else None
)
if skill_context is not None and skill_context not in blocks:
blocks.append(skill_context)
@@ -806,7 +831,7 @@ class AgentLoop:
) -> None:
"""Dispatch a command directly from the run() loop and publish the result."""
if self.commands.requires_session_queue(raw):
self._enqueue_session_message(msg)
await self._enqueue_session_message(msg)
return
async def dispatch_and_publish() -> None:
@@ -821,7 +846,7 @@ class AgentLoop:
)
result = await dispatch_fn(ctx)
if isinstance(result, InboundMessage):
self._enqueue_session_message(result)
await self._enqueue_session_message(result)
elif result is not None:
await self.bus.publish_outbound(result)
@@ -839,7 +864,7 @@ class AgentLoop:
if tool is None:
content = "Shell execution is disabled in this nanobot configuration."
else:
session = ctx.session or self.sessions.get_or_create(ctx.key)
session = ctx.session or await self.sessions.state.get(ctx.key)
scope = self.workspace_scopes.for_turn(
channel=ctx.msg.channel,
message_metadata=metadata,
@@ -850,6 +875,7 @@ class AgentLoop:
chat_id=ctx.msg.chat_id,
message_id=metadata.get("message_id"),
session_key=ctx.key,
session_generation=session.generation,
original_user_text=f"!{ctx.args.strip()}",
runtime=ctx.runtime,
metadata=metadata,
@@ -900,7 +926,7 @@ class AgentLoop:
Returns the total number of cancelled tasks, subagents, and exec sessions.
"""
journal_session = self.sessions.get_cached(key) or self.sessions.read_session_snapshot(key)
journal_session = await self.sessions.state.read(key)
journaled_followup_ids = (
tuple(
followup_id
@@ -928,9 +954,7 @@ class AgentLoop:
# Explicit session cancellation owns the follow-ups accepted before
# it began. Gateway shutdown uses aclose() directly and keeps this
# journal intact for startup recovery.
current_session = self.sessions.get_cached(key) or journal_session
acknowledge_pending_followups(current_session, journaled_followup_ids)
self.sessions.save(current_session)
await self.sessions.state.acknowledge_followups(key, journaled_followup_ids)
sub_cancelled = await self.subagents.cancel_by_session(key)
exec_cancelled = await self._exec_session_manager.terminate_by_owner(key)
return cancelled + sub_cancelled + exec_cancelled
@@ -939,7 +963,7 @@ class AgentLoop:
"""Stop active work for *key* and forget its cached session."""
self._discarding_sessions.add(key)
try:
self.sessions.invalidate(key)
await self.sessions.state.discard(key)
await self._cancel_active_tasks(key)
finally:
self.discard_session_file_state(key)
@@ -970,7 +994,9 @@ class AgentLoop:
session_key: str,
) -> EventSink:
"""Bind one idle compaction to its current user-facing destination."""
session = self.sessions.get_or_create(session_key)
session = self.sessions.state.peek_header(session_key)
if session is None:
return NO_EVENTS
return self.turn_delivery_factory.session_events(
session_key, session.metadata,
)
@@ -1042,7 +1068,7 @@ class AgentLoop:
public_payload[self._PROVIDER_STATE_CHECKPOINT_VERSION_KEY] = (
self._PROVIDER_STATE_CHECKPOINT_VERSION
)
self._set_runtime_checkpoint(session, public_payload)
await self._set_runtime_checkpoint(session, public_payload)
async def _drain_pending(
*,
@@ -1099,6 +1125,7 @@ class AgentLoop:
chat_id=pending_msg.chat_id,
message_id=metadata.get("message_id"),
session_key=active_session_key,
session_generation=session.generation if session is not None else None,
original_user_text=pending_msg.content,
runtime=runtime,
metadata=dict(metadata),
@@ -1222,6 +1249,9 @@ class AgentLoop:
request_ctx = dataclasses.replace(
request_ctx,
workspace_scope=effective_scope,
session_generation=(
session.generation if session is not None else request_ctx.session_generation
),
log_content=(
request_ctx.log_content and not ephemeral
and (session is None or session.policy.log_content)
@@ -1237,8 +1267,9 @@ class AgentLoop:
workspace_token = bind_workspace_scope(effective_scope)
turn_scope_stack = ExitStack()
# Compute lazily because create_goal may create goal metadata during this run.
def _goal_continue() -> str | None:
_goal_lines = goal_state_runtime_lines(session.metadata if session is not None else None)
async def _goal_continue() -> str | None:
current = await self.sessions.state.read_metadata(session.key) if session else None
_goal_lines = goal_state_runtime_lines(current["metadata"] if current else None)
if not _goal_lines:
return None
return (
@@ -1350,17 +1381,20 @@ class AgentLoop:
)
return result
def _check_expired_sessions_if_due(self) -> None:
"""Scan idle sessions no more often than the configured interval."""
async def _check_expired_sessions_if_due(self) -> None:
"""Scan idle sessions without blocking the event loop."""
now = time.monotonic()
if now < self._next_idle_compact_check_at:
return
self._next_idle_compact_check_at = now + self._idle_compact_check_interval_s
self.auto_compact.check_expired(
self.schedule_background,
self.runtime_for_session,
active_session_keys=self._pending_queues.keys(),
)
try:
await self.auto_compact.check_expired(
self.schedule_background,
self.runtime_for_session,
active_session_keys=self._pending_queues.keys(),
)
except SessionOperationQueueFullError:
logger.debug("Skipping idle archival while session storage is busy")
async def run(self) -> None:
"""Run the agent loop, dispatching messages as tasks to stay responsive to /stop."""
@@ -1372,7 +1406,7 @@ class AgentLoop:
try:
msg = await asyncio.wait_for(self.bus.consume_inbound(), timeout=1.0)
except asyncio.TimeoutError:
self._check_expired_sessions_if_due()
await self._check_expired_sessions_if_due()
continue
except asyncio.CancelledError:
# Preserve real task cancellation so shutdown can complete cleanly.
@@ -1387,55 +1421,66 @@ class AgentLoop:
logger.warning("Error consuming inbound message: {}, continuing...", e)
continue
raw = command_text(msg)
effective_key = self._effective_session_key(msg)
if msg.metadata.get(INBOUND_META_RUNTIME_CONTROL) == RUNTIME_CONTROL_SESSION_DISCARD:
await self.discard_session(msg.session_key)
continue
if (
msg.require_existing_session
and self.sessions.get_existing(effective_key) is None
):
continue
if msg.is_user_input:
await self.runtime_event_publisher.user_input_accepted(msg, effective_key)
if msg.channel != "system" and self.commands.is_priority(raw):
await self._dispatch_command_inline(
msg, effective_key, raw,
self.commands.dispatch_priority,
)
continue
routed_msg = msg
if effective_key != msg.session_key:
routed_msg = dataclasses.replace(
msg,
session_key_override=effective_key,
)
# A newer WebUI message must supersede an explicit recovery
# before it is injected into that recovery's pending queue.
# Without this admission point, a recovered turn could finish
# first and only then observe the user's newer request.
if (
effective_key in self._pending_queues
and msg.channel == "websocket"
and self._recovery_admission is not None
and not await self._recovery_admission.admit(routed_msg)
):
continue
# If this session already has an active pending queue (i.e. a task
# is processing this session), route the message there for mid-turn
# injection instead of creating a competing task.
if effective_key in self._pending_queues:
if msg.channel != "system" and self.commands.is_dispatchable_command(raw):
await self._dispatch_command_inline(
msg, effective_key, raw,
self.commands.dispatch,
)
continue
self._enqueue_session_message(routed_msg)
try:
await self._dispatch_inbound(msg)
except (SessionOperationQueueFullError, SessionConflictError) as exc:
key = self._effective_session_key(msg)
logger.warning("Session input rejected for {}: {}", key, exc)
if msg.is_user_input:
delivery = self.turn_delivery_factory.unrouted(msg, key)
await delivery.fail(publish_completion=key not in self._pending_queues)
finally:
await self.aclose()
async def _dispatch_inbound(self, msg: InboundMessage) -> None:
"""Route one input through command and session admission."""
raw = command_text(msg)
effective_key = self._effective_session_key(msg)
if msg.metadata.get(INBOUND_META_RUNTIME_CONTROL) == RUNTIME_CONTROL_SESSION_DISCARD:
await self.discard_session(msg.session_key)
return
if (
msg.require_existing_session
and await self.sessions.state.read_metadata(effective_key) is None
):
return
if msg.is_user_input:
await self.runtime_event_publisher.user_input_accepted(msg, effective_key)
if msg.channel != "system" and self.commands.is_priority(raw):
await self._dispatch_command_inline(
msg, effective_key, raw,
self.commands.dispatch_priority,
)
return
routed_msg = msg
if effective_key != msg.session_key:
routed_msg = dataclasses.replace(
msg,
session_key_override=effective_key,
)
# A newer WebUI message must supersede an explicit recovery
# before it is injected into that recovery's pending queue.
# Without this admission point, a recovered turn could finish
# first and only then observe the user's newer request.
if (
effective_key in self._pending_queues
and msg.channel == "websocket"
and self._recovery_admission is not None
and not await self._recovery_admission.admit(routed_msg)
):
return
# If this session already has an active pending queue (i.e. a task
# is processing this session), route the message there for mid-turn
# injection instead of creating a competing task.
if effective_key in self._pending_queues:
if msg.channel != "system" and self.commands.is_dispatchable_command(raw):
await self._dispatch_command_inline(
msg, effective_key, raw,
self.commands.dispatch,
)
return
await self._enqueue_session_message(routed_msg)
def preserve_inflight_turns_on_shutdown(self) -> None:
"""Keep durable checkpoints when the owning gateway exits.
@@ -1446,7 +1491,7 @@ class AgentLoop:
"""
self._preserve_inflight_turns_on_shutdown = True
def _journal_pending_message(
async def _journal_pending_message(
self,
session_key: str,
msg: InboundMessage,
@@ -1454,8 +1499,7 @@ class AgentLoop:
"""Persist a recoverable WebUI follow-up before adding it to the inbox."""
if not self._can_inject_message(msg):
return msg
session = self.sessions.get_or_create(session_key)
followup_id = record_pending_followup(session, msg)
followup_id = await self.sessions.state.queue_followup(session_key, msg)
if followup_id is None:
return msg
pending_msg = dataclasses.replace(
@@ -1465,10 +1509,9 @@ class AgentLoop:
PENDING_FOLLOWUP_ID_KEY: followup_id,
},
)
self.sessions.save(session)
return pending_msg
def _enqueue_session_message(self, msg: InboundMessage) -> None:
async def _enqueue_session_message(self, msg: InboundMessage) -> None:
"""Admit session work without waiting for its execution or result."""
session_key = self._effective_session_key(msg)
if not self.subagents.accepts_result(msg, session_key):
@@ -1484,9 +1527,11 @@ class AgentLoop:
):
return
if session_key in self._pending_queues:
msg = await self._journal_pending_message(session_key, msg)
pending = self._pending_queues.get(session_key)
if pending is not None:
pending.put_nowait(self._journal_pending_message(session_key, msg))
pending.put_nowait(msg)
return
new_pending: asyncio.Queue[InboundMessage] = asyncio.Queue()
@@ -1514,7 +1559,7 @@ class AgentLoop:
msg = deferred.pop(0)
if not deferred:
self._deferred_automation_turns.pop(session_key)
session = self.sessions.get_cached(session_key)
session = self.sessions.state.peek_header(session_key)
log_content = session is None or (
session.policy.persist and session.policy.log_content
)
@@ -1566,7 +1611,7 @@ class AgentLoop:
session_key = self._effective_session_key(msg)
# The request context is reset before errors reach this boundary, and
# discard may evict the session while a turn is still unwinding.
session = self.sessions.get_cached(session_key)
session = self.sessions.state.peek_header(session_key)
log_content = session is None or (
session.policy.persist and session.policy.log_content
)
@@ -1595,10 +1640,11 @@ class AgentLoop:
# A preceding user turn may have completed or blocked the goal
# while its older continuation was still waiting in the inbox.
if turn_continuation.sustained_goal_continuation_inbound(msg.metadata) and not (
sustained_goal_active(self.sessions.get_or_create(session_key).metadata)
sustained_goal_active((await self.sessions.state.get(session_key)).metadata)
):
return
try:
await self.sessions.state.read(session_key)
delivery = self.turn_delivery_factory.create(
msg,
session_key,
@@ -1637,10 +1683,10 @@ class AgentLoop:
raise
try:
key = self._effective_session_key(msg)
session = self.sessions.get_or_create(key)
session = await self.sessions.state.get(key)
if restore_runtime_checkpoint(session):
self._clear_pending_user_turn(session)
self.sessions.save(session)
await self.sessions.state.restore_interruption(session)
logger.info(
"Restored partial context for cancelled session {}",
key,
@@ -1727,6 +1773,7 @@ class AgentLoop:
self.subagents.close,
self._exec_session_manager.close_all,
self.runtime_resolver.aclose,
self.sessions.state.aclose,
)
for cleanup in cleanup_steps:
try:
@@ -1790,6 +1837,17 @@ class AgentLoop:
key = session_key or msg.session_key
if not self.subagents.accepts_result(msg, key):
return None
commit_session = session is None or session.policy.persist
if session is None:
session = (await self.sessions.state.read(key)
if msg.require_existing_session or msg.session_generation is not None
else await self.sessions.state.get(key))
if msg.require_existing_session and session is None:
raise RuntimeError("required session is not active")
if msg.session_generation is not None and (
session is None or session.generation != msg.session_generation
):
raise RuntimeError("required session generation was replaced")
if delivery is None:
delivery = self.turn_delivery_factory.create(msg, key)
elif delivery.session_key != key:
@@ -1823,6 +1881,7 @@ class AgentLoop:
on_runtime_admitted=on_runtime_admitted,
pending_queue=pending_queue,
ephemeral=ephemeral,
commit_session=commit_session,
run_extra_hooks_for_ephemeral=run_extra_hooks_for_ephemeral,
hooks=list(hooks or []),
hook_factories=list(hook_factories or []),
@@ -1980,13 +2039,19 @@ class AgentLoop:
msg = ctx.msg
if ctx.session is None:
if msg.require_existing_session:
ctx.session = self.sessions.get_existing(ctx.session_key)
if msg.require_existing_session or msg.session_generation is not None:
ctx.session = await self.sessions.state.read(ctx.session_key)
if ctx.session is None:
raise RuntimeError("required session is not active")
if (
msg.session_generation is not None
and ctx.session.generation != msg.session_generation
):
raise RuntimeError("required session generation was replaced")
else:
ctx.session = self.sessions.get_or_create(ctx.session_key)
ctx.session = await self.sessions.state.get(ctx.session_key)
session = ctx.session
ctx.delivery.bind_session_generation(session.generation)
ctx.ephemeral = ctx.ephemeral or not session.policy.persist
tools = ctx.tools if ctx.tools is not None else self.tools
if session.policy.disabled_tools:
@@ -2016,17 +2081,20 @@ class AgentLoop:
if ctx.kind is TurnKind.USER:
self.workspace_scopes.persist_message_scope(session, msg)
if restore_runtime_checkpoint(session):
self.sessions.save(session)
if restore_runtime_checkpoint(session) and ctx.commit_session:
await self.sessions.state.restore_interruption(session)
if (
RECOVERY_INBOUND_METADATA_KEY not in msg.metadata
and restore_pending_interruption(session)
and ctx.commit_session
):
self.sessions.save(session)
await self.sessions.state.restore_interruption(session)
async def _compact_session(self, ctx: TurnContext) -> None:
if not ctx.commit_session:
return
session = ctx.require_session()
ctx.session, pending = self.auto_compact.prepare_session(
ctx.session, pending = await self.auto_compact.prepare_session(
session,
ctx.session_key,
)
@@ -2068,15 +2136,15 @@ class AgentLoop:
# message. Mark messages with _command so get_history can filter
# them out of LLM context. /new is excluded because it
# intentionally clears the session.
if cmd_ctx.raw.lower() != "/new":
ctx.input_persisted_early = self._persist_user_message_early(
if cmd_ctx.raw.lower() != "/new" and ctx.commit_session:
ctx.input_persisted_early = await self._persist_user_message_early(
ctx.msg, session, _command=True
)
session.add_message(
"assistant", result.content, _command=True
)
self._clear_pending_user_turn(session)
self.sessions.save(session)
await self.sessions.state.prepare_input(session)
if not ctx.ephemeral:
await self.runtime_event_publisher.session_turn_persisted(
ctx.msg,
@@ -2091,7 +2159,7 @@ class AgentLoop:
session = ctx.require_session()
runtime = ctx.runtime
if runtime is None:
runtime = self.runtime_for_session(session)
runtime = await self.runtime_for_session(session)
ctx.runtime = runtime
if ctx.session_key.startswith("dream:"):
logger.info(
@@ -2101,22 +2169,10 @@ class AgentLoop:
)
if ctx.on_runtime_admitted is not None:
await ctx.on_runtime_admitted(runtime)
if not ctx.ephemeral:
ctx.session, ctx.pending_summary = self.auto_compact.prepare_session(
session,
ctx.session_key,
)
session = ctx.require_session()
is_subagent = ctx.kind is TurnKind.SYSTEM and ctx.msg.sender_id == "subagent"
# Capture replay inputs on the loop; the worker never sees the live Session/cache.
history_records = session.messages[session.last_archived:]
history_snapshot = Session(
key=session.key,
messages=await self.runner.copy_messages_on_loop(history_records),
)
ctx.history = await self.runner.prepare_prompt(
history_snapshot.get_history, extend_to_user=is_subagent,
session.get_history, extend_to_user=is_subagent,
)
stored_state = session.provider_state
subagent_followup_persisted = False
@@ -2136,7 +2192,7 @@ class AgentLoop:
# provider compatibility or prompt assembly work. A compatible
# staged state replaces this in a second atomic save below.
session.provider_state = None
self.sessions.save(session)
await self.sessions.state.prepare_input(session)
ctx.input_persisted_early = True
await ctx.delivery.runtime_admitted(runtime)
@@ -2189,8 +2245,8 @@ class AgentLoop:
staged_provider_state = True
elif stored_state is not None:
session.provider_state = None
if ctx.kind is TurnKind.USER:
ctx.input_persisted_early = self._persist_user_message_early(
if ctx.kind is TurnKind.USER and ctx.commit_session:
ctx.input_persisted_early = await self._persist_user_message_early(
ctx.msg,
session,
runtime_context_blocks=ctx.runtime_context_blocks,
@@ -2200,7 +2256,9 @@ class AgentLoop:
elif subagent_followup_persisted and staged_provider_state:
# Upgrade the replay-safe baseline to the resumable state before
# prompt assembly and the first model checkpoint.
self.sessions.save(session)
await self.sessions.state.prepare_input(session)
if not session.persisted and ctx.commit_session:
await self.sessions.state.prepare_input(session)
ctx.transcript_input = self._build_transcript_input(ctx)
@@ -2242,7 +2300,10 @@ class AgentLoop:
ctx.usage = result.usage
ctx.delivery.record_usage(result.round_usages)
if ctx.kind is TurnKind.USER:
await turn_continuation.maybe_continue_turn(ctx)
current = await self.sessions.state.read_metadata(ctx.session_key)
await turn_continuation.maybe_continue_turn(
ctx, session_metadata=current["metadata"] if current else {},
)
async def _persist_turn(self, ctx: TurnContext) -> None:
session = ctx.require_session()
@@ -2284,7 +2345,8 @@ class AgentLoop:
session.provider_state = None
self._clear_pending_user_turn(session)
self._clear_runtime_checkpoint(session)
self.sessions.save(session)
if ctx.commit_session:
await self.sessions.state.finish_turn(session)
if not ctx.ephemeral:
await self.runtime_event_publisher.session_turn_persisted(
ctx.msg,
@@ -2532,10 +2594,14 @@ class AgentLoop:
)
return True
def _set_runtime_checkpoint(self, session: Session, payload: dict[str, Any]) -> None:
"""Persist the latest in-flight turn state into session metadata."""
async def _set_runtime_checkpoint(
self,
session: Session,
payload: dict[str, Any],
) -> None:
"""Persist the latest in-flight turn state without blocking the event loop."""
session.metadata[self._RUNTIME_CHECKPOINT_KEY] = payload
self.sessions.save_runtime_checkpoint(session)
await self.sessions.state.checkpoint_view(session, payload)
def _mark_pending_user_turn(self, session: Session) -> None:
session.metadata[self._PENDING_USER_TURN_KEY] = True
@@ -2585,6 +2651,7 @@ class AgentLoop:
)
# Share the dispatch lock so direct calls serialize with bus turns.
lock = self._get_session_lock(session_key)
temporary_parent = False
try:
async with lock:
kwargs: dict[str, Any] = {
@@ -2597,7 +2664,10 @@ class AgentLoop:
if _session_policy is not None:
# Isolate per-run state before any early save or checkpoint;
# the cached conversation must survive a temporary SDK turn.
session = deepcopy(self.sessions.get_or_create(session_key))
session = (await self.sessions.state.read(session_key) or Session(key=session_key)
if not _session_policy.persist
else await self.sessions.state.get(session_key))
temporary_parent = not _session_policy.persist and not session.persisted
session.policy = SessionPolicy(
persist=session.policy.persist and _session_policy.persist,
log_content=session.policy.log_content and _session_policy.log_content,
@@ -2618,10 +2688,13 @@ class AgentLoop:
kwargs["on_runtime_admitted"] = on_runtime_admitted
if attributes is not None:
kwargs["attributes"] = dict(attributes)
return await self._process_message(
msg,
**kwargs,
)
try:
return await self._process_message(msg, **kwargs)
finally:
if temporary_parent:
parent = self.sessions.state.peek_header(session_key)
if parent is not None and not parent.policy.persist:
await self.sessions.state.delete(session_key, expected_generation=parent.generation)
finally:
await self.runtime_event_publisher.run_status_changed(msg, session_key, "idle")
self.runtime_event_publisher.clear_turn(session_key)
+4 -32
View File
@@ -25,7 +25,6 @@ from nanobot.llm_usage.context import llm_usage_source
from nanobot.providers.base import LLMResponse, ProviderConversationState
from nanobot.providers.conversation_state import ProviderConversationStateController
from nanobot.runtime_context import public_history_messages
from nanobot.session.keys import is_dream_session
from nanobot.session.manager import Session, SessionManager
from nanobot.session.summary import is_summary_checkpoint, session_summary_from_metadata
from nanobot.utils.gitstore import GitStore
@@ -722,28 +721,6 @@ class MemoryStore:
return prefix
return f"{prefix}\n\n{diff_body}"
@staticmethod
def prune_dream_sessions(sessions: SessionManager, *, keep: int = 10) -> None:
"""Remove the oldest Dream session files, keeping only the N most recent.
Only current base64url-encoded Dream session keys are considered.
Non-dream session files are never touched.
"""
with sessions.locked_session_files() as sessions_dir:
dream_files: list[tuple[Path, str]] = []
for path in sessions_dir.glob("*.jsonl"):
decoded_key = SessionManager.decode_storage_key(path.stem)
if decoded_key is not None and is_dream_session(decoded_key):
dream_files.append((path, decoded_key))
dream_files.sort(key=lambda item: item[0].stat().st_mtime)
for path, key in dream_files[: max(0, len(dream_files) - keep)]:
if sessions.delete_session(key):
logger.debug("Pruned old dream session: {}", path.stem)
else:
logger.warning("Failed to prune dream session {}", path)
# ---------------------------------------------------------------------------
# Memory ingestion and context-pressure coordination
# ---------------------------------------------------------------------------
@@ -1253,8 +1230,8 @@ class Consolidator:
"""
lock = self.get_lock(session_key)
async with lock:
self.sessions.invalidate(session_key)
session = self.sessions.get_or_create(session_key)
await self.sessions.state.discard(session_key)
session = await self.sessions.state.get(session_key)
archive_start = session.last_archived
messages_to_archive = list(session.messages[archive_start:])
@@ -1269,20 +1246,15 @@ class Consolidator:
await events.emit(
ContextCompactionEvent(compaction_id=compaction_id, phase="started", notify=notify),
)
last_active = session.updated_at
archive_end = archive_start + len(messages_to_archive)
try:
summary = await self.archive_session(
session, archive_end=archive_end, runtime=runtime,
)
if summary:
# Concurrent appends remain after the captured boundary.
session.commit_summary_checkpoint(
summary, insert_at=archive_end, last_active=last_active,
await self.sessions.state.commit_summary(
session, summary, archive_end=archive_end,
)
# Resume from the summary and retained transcript, not the old provider history.
session.provider_state = None
self.sessions.save(session)
except (Exception, asyncio.CancelledError) as exc:
await events.emit(
ContextCompactionEvent(
+14 -28
View File
@@ -68,7 +68,7 @@ def _raise_if_cancelling() -> None:
raise asyncio.CancelledError
ContinuationCallback = Callable[[], str | None]
ContinuationCallback = Callable[[], Awaitable[str | None]]
CheckpointCallback = Callable[[dict[str, Any]], Awaitable[None]]
InjectionCallback = Callable[[], Awaitable[Iterable[Any] | None]]
@@ -158,29 +158,15 @@ class AgentRunner:
self, operation: Callable[_PromptArgs, _PromptResult],
*args: _PromptArgs.args, **kwargs: _PromptArgs.kwargs,
) -> _PromptResult:
"""Share the bounded worker for read-only prompt preparation."""
"""Share the bounded context worker for prompt filesystem preparation."""
return await self.context_governor.prepare_in_background(operation, *args, **kwargs)
@staticmethod
async def copy_messages_on_loop(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Detach loop-owned records while yielding between bounded batches."""
copied: list[dict[str, Any]] = []
memo: dict[int, Any] = {id(messages): copied}
for start in range(0, len(messages), 64):
copied.extend(deepcopy(message, memo) for message in messages[start:start + 64])
await asyncio.sleep(0)
return copied
async def _run_context_snapshot(
self, messages: list[dict[str, Any]],
self, hook: AgentHook, messages: list[dict[str, Any]],
) -> list[dict[str, Any]]:
if not messages:
if not messages or not hook.has_run_hooks():
return []
task = asyncio.current_task()
if task is not None and task.cancelling():
# Cancellation cleanup must not queue behind its own unfinished worker.
return await self.copy_messages_on_loop(messages)
return await self.prepare_prompt(deepcopy, messages)
return await asyncio.to_thread(deepcopy, messages)
@staticmethod
def _append_injected_messages(
@@ -208,7 +194,7 @@ class AgentRunner:
injections = await self._drain_injections(spec) if drain_callback else []
real_injection = bool(injections)
if not injections and allow_continuation and assistant_message is not None:
continuation = self._build_continuation_message(spec)
continuation = await self._build_continuation_message(spec)
if continuation is not None:
injections = [continuation]
if (
@@ -260,12 +246,12 @@ class AgentRunner:
return True, injection_cycles
@staticmethod
def _build_continuation_message(spec: AgentRunSpec) -> dict[str, str] | None:
async def _build_continuation_message(spec: AgentRunSpec) -> dict[str, str] | None:
callback = spec.continuation_callback
if callback is None:
return None
try:
content = callback()
content = await callback()
except Exception:
logger.opt(exception=tool_log_content_allowed()).error("continuation_callback failed")
return None
@@ -332,18 +318,18 @@ class AgentRunner:
try:
try:
messages, compaction = await self.prepare_prompt(self._initial_transcript_and_compaction, spec)
context.messages = await self._run_context_snapshot(messages) if has_run_hooks else []
context.messages = await self._run_context_snapshot(hook, messages) if has_run_hooks else []
await hook.before_run(context)
result = await self._run_core(spec, hook, messages, compaction)
except Exception as exc:
context.messages = await self._run_context_snapshot(messages) if has_run_hooks else []
context.messages = await self._run_context_snapshot(hook, messages) if has_run_hooks else []
context.stop_reason = "error"
context.error = f"Error: {type(exc).__name__}: {exc}"
context.exception = exc
await hook.on_error(context)
raise
else:
context.messages = await self._run_context_snapshot(result.messages) if has_run_hooks else []
context.messages = await self._run_context_snapshot(hook, result.messages) if has_run_hooks else []
context.final_content = result.final_content
context.tools_used = list(result.tools_used)
context.usage = result.usage
@@ -365,14 +351,14 @@ class AgentRunner:
if has_run_hooks:
try:
if isinstance(context.exception, asyncio.CancelledError):
context.messages = await self.copy_messages_on_loop(messages)
context.messages = await self._run_context_snapshot(hook, messages)
else:
context.messages = await self._run_context_snapshot(messages)
context.messages = await self._run_context_snapshot(hook, messages)
except asyncio.CancelledError as exc:
context.stop_reason = "cancelled"
context.error = None
context.exception = exc
context.messages = await self.copy_messages_on_loop(messages)
context.messages = await self._run_context_snapshot(hook, messages)
raise
finally:
try:
+101 -41
View File
@@ -7,7 +7,7 @@ import json
import time
import uuid
import warnings
from collections.abc import Callable, Mapping
from collections.abc import Awaitable, Callable, Mapping
from copy import deepcopy
from dataclasses import dataclass, field, replace
from functools import partial
@@ -49,6 +49,7 @@ from nanobot.security.workspace_access import (
workspace_sandbox_status,
)
from nanobot.session.manager import Session, SessionManager, SessionPolicy
from nanobot.utils.cancellation import shield_and_drain
from nanobot.utils.llm_runtime import LLMRuntime
from nanobot.utils.prompt_templates import render_template
@@ -158,7 +159,7 @@ class _SubagentHook(AgentHook):
def __init__(self, status: SubagentStatus | None = None,
*, check_active: Callable[[], None] | None = None,
max_result_chars: int = 16000,
on_status: Callable[[SubagentStatus], None] | None = None) -> None:
on_status: Callable[[SubagentStatus], Awaitable[None]] | None = None) -> None:
super().__init__()
self._status = status
self._check_active = check_active
@@ -180,7 +181,7 @@ class _SubagentHook(AgentHook):
{"name": call.name, "status": "running"} for call in context.tool_calls
]
if self._status is not None and self._on_status is not None:
self._on_status(self._status)
await self._on_status(self._status)
async def before_execute_tool(
self, context: AgentHookContext, tool_call: ToolCallRequest,
@@ -199,7 +200,7 @@ class _SubagentHook(AgentHook):
if context.error:
self._status.error = str(context.error)
if self._on_status is not None:
self._on_status(self._status)
await self._on_status(self._status)
class SubagentManager:
@@ -273,6 +274,7 @@ class SubagentManager:
self._terminal_statuses: dict[str, SubagentStatus] = {}
self._closed = False
self._close_task: asyncio.Task[int] | None = None
self._admitting = 0
self.sessions = SubagentSessions(session_manager) if session_manager is not None else None
MAX_ACTIVE = 128
@@ -283,11 +285,11 @@ class SubagentManager:
CANCEL_WAIT_SECONDS = 5.0
def _save_status(
self, status: SubagentStatus, *, fsync: bool = False,
async def _save_status(
self, status: SubagentStatus,
) -> None:
status.revision += 1
if self.sessions is not None and not self.sessions.save(status, fsync=fsync):
if self.sessions is not None and not await self.sessions.save(status):
return
self._publish_status(status)
@@ -300,10 +302,10 @@ class SubagentManager:
task_id=status.task_id,
))
def recover_interrupted(self) -> None:
async def recover_interrupted(self) -> None:
"""Recover observations only after the host has claimed execution ownership."""
if self.sessions is not None:
self.sessions.interrupt_pending()
await self.sessions.interrupt_pending()
def _start_cleanup(self, record: _SubagentTask, *, retry: bool = False) -> asyncio.Task[int]:
cleanup = record.cleanup_task
@@ -326,10 +328,11 @@ class SubagentManager:
and not cleanup.cancelled() and cleanup.exception() is None):
self._tasks.pop(record.status.task_id, None)
def _finish(self, record: _SubagentTask,
async def _finish(self, record: _SubagentTask,
cleanup_error: str | None = None) -> _SubagentOutcome:
outcome = record.finish(self.max_tool_result_chars, cleanup_error)
self._save_status(record.status, fsync=True)
await self._save_transcript(record)
await self._save_status(record.status)
self._terminal_statuses[record.status.task_id] = record.snapshot()
while len(self._terminal_statuses) > self.MAX_TERMINAL:
del self._terminal_statuses[next(iter(self._terminal_statuses))]
@@ -341,7 +344,7 @@ class SubagentManager:
for message_id, _ in snapshot:
record.status.receipts[message_id] = "delivered"
if snapshot:
self._save_status(record.status)
await self._save_status(record.status)
return [{"role": "user", "content": content} for _, content in snapshot]
def _owned_status(self, task_id: str, owner: str | None) -> SubagentStatus:
@@ -377,7 +380,7 @@ class SubagentManager:
raise SubagentControlError("task unavailable")
return status, child
def send(self, task_id: str, owner: str | None,
async def send(self, task_id: str, owner: str | None,
message: str | None) -> SubagentMessageReceipt:
"""Accept a bounded follow-up only while execution is open."""
status = self._owned_status(task_id, owner)
@@ -391,7 +394,7 @@ class SubagentManager:
message_id = str(uuid.uuid4())
record.inbox.append((message_id, message))
status.receipts[message_id] = "accepted"
self._save_status(status)
await self._save_status(status)
return {"task_id": task_id, "message_id": message_id,
"receipt": "accepted", "delivered": False}
@@ -410,7 +413,7 @@ class SubagentManager:
task_id = record.status.task_id
task = self._running_tasks.get(task_id)
if record.decide(_SubagentOutcome("cancelled", "Task cancelled.", "cancelled")):
self._save_status(record.status, fsync=True)
await self._save_status(record.status)
if task is not None and record.begun and not task.done():
task.cancel()
if record.status.finished_at is None:
@@ -428,21 +431,44 @@ class SubagentManager:
**deepcopy(self._terminal_statuses),
}
def _runtime_statuses_for_session(self, session_key: str) -> dict[str, SubagentStatus]:
return {
**{tid: record.snapshot() for tid, record in self._tasks.items()
if record.status.owner == session_key and record.status.finished_at is None},
**{tid: deepcopy(status) for tid, status in self._terminal_statuses.items()
if status.owner == session_key},
}
def _merge_session_statuses(
self, session_key: str, runtime: Mapping[str, SubagentStatus], *, include_history: bool,
) -> Mapping[str, SubagentStatus]:
if self.sessions is not None and not self.sessions.exists(session_key):
return {}
statuses = self.sessions.load(session_key) if include_history and self.sessions is not None else {}
for task_id, status in runtime.items():
if self.sessions is not None and not self.sessions.contains(task_id, session_key):
continue
persisted = statuses.get(task_id)
if persisted is None or status.revision >= persisted.revision:
statuses[task_id] = status
return statuses
def statuses_for_session(
self, session_key: str | None, *, include_history: bool = True,
) -> Mapping[str, SubagentStatus]:
"""Return only tasks owned by the given session, never a global fallback."""
if not session_key or (self.sessions is not None and not self.sessions.exists(session_key)):
if not session_key:
return {}
return {
**(self.sessions.load(session_key) if include_history and self.sessions is not None else {}),
**{tid: record.snapshot() for tid, record in self._tasks.items()
if record.status.owner == session_key and record.status.finished_at is None
and (self.sessions is None or self.sessions.contains(tid, session_key))},
**{tid: deepcopy(status) for tid, status in self._terminal_statuses.items()
if status.owner == session_key
and (self.sessions is None or self.sessions.contains(tid, session_key))},
}
return self._merge_session_statuses(
session_key, self._runtime_statuses_for_session(session_key), include_history=include_history,
)
async def read_statuses_for_session(self, session_key: str) -> Mapping[str, SubagentStatus]:
"""Capture runtime observations on the owner loop; read stored metadata on a worker."""
runtime = self._runtime_statuses_for_session(session_key)
return await asyncio.to_thread(
self._merge_session_statuses, session_key, runtime, include_history=True,
)
def set_provider(self, provider: LLMProvider, model: str) -> None:
"""Update the deprecated runtime source used by legacy ``spawn`` calls."""
@@ -511,7 +537,7 @@ class SubagentManager:
ToolLoader().load(ctx, registry, scope="subagent")
return registry
def _create_task(
async def _create_task(
self, task: str, label: str | None, origin_channel: str, origin_chat_id: str,
session_key: str | None, origin_message_id: str | None,
temperature: float | None, workspace_scope: WorkspaceScope | None,
@@ -523,7 +549,7 @@ class SubagentManager:
if temperature is not None:
runtime = runtime.with_generation_overrides(temperature=temperature)
# A failed cleanup owns admission even after its status has been evicted.
if self._closed or len(self._tasks) >= self.MAX_ACTIVE:
if self._closed or len(self._tasks) + self._admitting >= self.MAX_ACTIVE:
raise SubagentControlError("subagent manager is closed or at task capacity")
owner = session_key or f"{origin_channel}:{origin_chat_id}"
task_id = str(uuid.uuid4())
@@ -537,11 +563,28 @@ class SubagentManager:
origin_message_id=origin_message_id,
origin_turn_id=origin_turn_id,
)
if self.sessions is not None:
child = self.sessions.create(status, policy=session_policy)
else:
child = Session(key=SubagentSessions.key(task_id), policy=session_policy or SessionPolicy())
child.add_message("user", task)
self._admitting += 1
try:
if self.sessions is not None:
admission = asyncio.create_task(self.sessions.create(status, policy=session_policy))
try:
child = await shield_and_drain(admission)
except asyncio.CancelledError:
if not admission.cancelled() and admission.exception() is None:
child = admission.result()
await shield_and_drain(self.sessions.sessions.state.delete(
child.key, expected_generation=child.generation,
))
raise
else:
child = Session(key=SubagentSessions.key(task_id), policy=session_policy or SessionPolicy())
child.add_message("user", task)
finally:
self._admitting -= 1
if self._closed:
if self.sessions is not None:
await self.sessions.sessions.state.delete(child.key, expected_generation=child.generation)
raise SubagentControlError("subagent manager is closed")
record = _SubagentTask(
status=status,
session=child,
@@ -580,7 +623,7 @@ class SubagentManager:
) -> str:
"""Start background work and route its terminal result to the parent."""
try:
record = self._create_task(
record = await self._create_task(
task, label, origin_channel, origin_chat_id, session_key,
origin_message_id, temperature, workspace_scope, runtime, announce=True, origin_turn_id=origin_turn_id,
session_policy=session_policy,
@@ -607,7 +650,7 @@ class SubagentManager:
) -> str:
"""Wait for the same task lifecycle without a background notice."""
try:
record = self._create_task(
record = await self._create_task(
task, label, origin_channel, origin_chat_id, session_key,
origin_message_id, temperature, workspace_scope, runtime, announce=False, origin_turn_id=origin_turn_id,
session_policy=session_policy,
@@ -647,9 +690,25 @@ class SubagentManager:
else _SubagentOutcome("cancelled", "Task cancelled.", "cancelled")
)
self._start_cleanup(record)
self._finish(record)
settlement = asyncio.create_task(self._settle_unfinished_task(record))
self._running_tasks[record.status.task_id] = settlement
settlement.add_done_callback(partial(self._task_done, record))
self._release_task(record)
async def _save_transcript(self, record: _SubagentTask) -> None:
if self.sessions is not None:
from nanobot.session.sqlite_store import SessionConflictError
try:
await self.sessions.sessions.state.finish_turn(record.session)
except SessionConflictError:
# A removed child must not be recreated by a late observation.
return
async def _settle_unfinished_task(self, record: _SubagentTask) -> str:
outcome = await self._finish(record)
return outcome.result
async def _run_subagent(self, record: _SubagentTask) -> str:
"""Execute once, seal the outcome, then clean up and publish once."""
status = record.status
@@ -661,7 +720,7 @@ class SubagentManager:
record.raise_if_stopping()
status.state = "running"
status.phase = "initializing"
self._save_status(status)
await self._save_status(status)
outcome = await self._run_admitted_subagent(record)
record.decide(outcome)
except asyncio.CancelledError:
@@ -677,7 +736,7 @@ class SubagentManager:
"Subagent [{}] exec cleanup failed", status.task_id,
)
cleanup_error = f"Error cleaning up task processes: {exc}"
outcome = self._finish(record, cleanup_error)
outcome = await self._finish(record, cleanup_error)
if record.announce and not record.suppress_notice and not self._closed:
await self._announce_result(
status.task_id, label, task_text, outcome.result, record.origin,
@@ -703,7 +762,7 @@ class SubagentManager:
iteration = payload.get("iteration", status.iteration)
if (phase, iteration) != (status.phase, status.iteration):
status.phase, status.iteration = phase, iteration
self._save_status(status)
await self._save_status(status)
root = workspace_scope.project_path if workspace_scope is not None else self.workspace
cfg = None
@@ -719,13 +778,14 @@ class SubagentManager:
]
activity = SessionActivity()
def save_observation(status: SubagentStatus) -> None:
async def save_observation(status: SubagentStatus) -> None:
record.session.messages = activity.transcript()
self._save_status(status)
await self._save_transcript(record)
await self._save_status(status)
async def publish_activity(event: AgentEvent) -> None:
if activity.remember(event):
save_observation(status)
await save_observation(status)
events = EventSink(publish_activity)
hook = build_agent_turn_hook(AgentTurnHookSpec(
+39 -49
View File
@@ -4,7 +4,6 @@ from __future__ import annotations
import math
import time
from copy import deepcopy
from typing import Any, cast
from loguru import logger
@@ -13,6 +12,7 @@ from pydantic import TypeAdapter, ValidationError
from nanobot.agent.subagent_status import SubagentSessionError as SubagentSessionError
from nanobot.agent.subagent_status import SubagentStatus
from nanobot.session.manager import Session, SessionManager, SessionPolicy
from nanobot.session.sqlite_store import SessionConflictError
from nanobot.session.types import PARENT_SESSION_KEY, SESSION_TYPE_KEY, SessionType
SUBAGENT = SessionType("subagent", needs_handle=False, public_history=False)
@@ -33,21 +33,23 @@ class SubagentSessions:
return f"subagent:{task_id}"
def exists(self, owner: str) -> bool:
return self.sessions.get_cached(owner) is not None or self.sessions.read_session_metadata(owner) is not None
return (
self.sessions.get_cached_metadata(owner) is not None
or self.sessions.read_session_metadata(owner) is not None
)
def contains(self, task_id: str, owner: str) -> bool:
key = self.key(task_id)
child = self.sessions.get_cached(key)
metadata = child.metadata if child is not None else (self.sessions.read_session_metadata(key) or {}).get("metadata", {})
metadata = self.sessions.get_cached_metadata(key)
if metadata is None:
metadata = (self.sessions.read_session_metadata(key) or {}).get("metadata", {})
return metadata.get(SESSION_TYPE_KEY) == SUBAGENT.name and metadata.get(PARENT_SESSION_KEY) == owner
def snapshot(self, task_id: str, owner: str) -> Session | None:
"""Read a detached child only while its parent still owns it."""
with self.sessions.locked_session_files():
if not self.exists(owner) or not self.contains(task_id, owner):
return None
child = self.sessions.get_cached(self.key(task_id))
return deepcopy(child) if child is not None else self.sessions.read_session_snapshot(self.key(task_id))
if not self.exists(owner) or not self.contains(task_id, owner):
return None
return self.sessions.get_existing(self.key(task_id))
@staticmethod
def _payload(status: SubagentStatus) -> dict[str, Any]:
@@ -56,49 +58,36 @@ class SubagentSessions:
"elapsed_seconds": status.as_dict()["elapsed_seconds"],
}
def create(self, status: SubagentStatus, *, policy: SessionPolicy | None = None) -> Session:
with self.sessions.locked_session_files():
parent = self.sessions.get_existing(status.owner)
if parent is None:
parent = self.sessions.get_or_create(status.owner)
requested = policy or SessionPolicy()
effective = SessionPolicy(
persist=parent.policy.persist and requested.persist,
log_content=parent.policy.log_content and requested.log_content,
)
if effective.persist and self.sessions.read_session_metadata(parent.key) is None:
self.sessions.save(parent, fsync=True)
key = self.key(status.task_id)
child = (self.sessions.get_or_create(key) if effective.persist
else self.sessions.get_or_create_transient(key))
child.policy = effective
child.metadata.update({
SESSION_TYPE_KEY: SUBAGENT.name,
PARENT_SESSION_KEY: status.owner,
TASK_METADATA_KEY: self._payload(status),
})
child.add_message("user", status.task_description)
self.sessions.save(child, fsync=True)
return child
async def create(self, status: SubagentStatus, *, policy: SessionPolicy | None = None) -> Session:
return await self.sessions.state.create_child(
status.owner, self.key(status.task_id),
metadata={SESSION_TYPE_KEY: SUBAGENT.name, TASK_METADATA_KEY: self._payload(status)},
content=status.task_description, policy=policy or SessionPolicy(),
)
def save(self, status: SubagentStatus, *, fsync: bool = False) -> bool:
with self.sessions.locked_session_files():
if not self.exists(status.owner):
return False
child = self.sessions.get_existing(self.key(status.task_id))
if child is None or not self.contains(status.task_id, status.owner):
return False
child.metadata[TASK_METADATA_KEY] = self._payload(status)
# Only create() establishes identity. Progress and late completion
# cannot recreate a child removed with its parent.
self.sessions.save(child, fsync=fsync)
return True
async def save(self, status: SubagentStatus) -> bool:
try:
await self.sessions.state.update_metadata(
self.key(status.task_id), {TASK_METADATA_KEY: self._payload(status)},
)
except SessionConflictError:
return False
return True
def status(self, task_id: str, owner: str) -> SubagentStatus | None:
payload = self.sessions.read_session_metadata(self.key(task_id))
if payload is None:
metadata = self.sessions.get_cached_metadata(self.key(task_id))
payload = {"metadata": metadata} if metadata is not None else None
if payload is None:
return None
metadata = payload.get("metadata", {})
return self._status_from_metadata(task_id, owner, metadata)
@staticmethod
def _status_from_metadata(
task_id: str, owner: str, metadata: dict[str, Any],
) -> SubagentStatus | None:
if metadata.get(SESSION_TYPE_KEY) != SUBAGENT.name or metadata.get(PARENT_SESSION_KEY) != owner:
return None
raw: object = metadata.get(TASK_METADATA_KEY)
@@ -123,16 +112,17 @@ class SubagentSessions:
def load(self, owner: str) -> dict[str, SubagentStatus]:
result: dict[str, SubagentStatus] = {}
for key in self.sessions.child_session_keys(owner):
for row in self.sessions.list_child_session_metadata(owner):
key = row["key"]
task_id = key.removeprefix("subagent:")
if key != self.key(task_id):
continue
status = self.status(task_id, owner)
status = self._status_from_metadata(task_id, owner, row["metadata"])
if status is not None:
result[task_id] = status
return result
def interrupt_pending(self) -> None:
async def interrupt_pending(self) -> None:
"""Seal abandoned work after the gateway acquires execution ownership."""
for row in self.sessions.list_sessions():
key = row["key"]
@@ -156,6 +146,6 @@ class SubagentSessions:
status.tool_events = []
status.receipts = {key: "undelivered" if receipt == "accepted" else receipt
for key, receipt in status.receipts.items()}
self.save(status, fsync=True)
await self.save(status)
except (OSError, SubagentSessionError):
logger.exception("Could not recover subagent session {}", key)
+1
View File
@@ -33,6 +33,7 @@ class RequestContext:
chat_id: str
message_id: str | None = None
session_key: str | None = None
session_generation: str | None = field(default=None, kw_only=True)
original_user_text: str | None = None
runtime: LLMRuntime | None = None
metadata: dict[str, Any] = field(default_factory=dict)
+39 -28
View File
@@ -29,10 +29,11 @@ from nanobot.session.goal_state import (
sustained_goal_active,
)
from nanobot.session.turn_continuation import reset_goal_continuation_rounds
from nanobot.utils.cancellation import shield_and_drain
from nanobot.utils.prompt_templates import render_template
if TYPE_CHECKING:
from nanobot.session.manager import SessionManager
from nanobot.session.manager import Session, SessionManager
_GOAL_ACTIONS = ("complete", "cancel", "block", "replace")
@@ -61,36 +62,47 @@ class _GoalToolsMixin:
self._sessions = sessions
self._bus = bus
def _session(self):
async def _session(self) -> Session | None:
request_ctx = current_request_context()
if request_ctx is None:
return None
key = request_ctx.session_key
if not key:
return None
return self._sessions.get_or_create(key)
return await self._sessions.state.get_header(key)
def _goal_mutation_allowed(self) -> bool:
return current_request_context() is not None and goal_mutation_allowed()
def _save_goal_state(
async def _save_goal_state(
self,
sess: Any,
sess: Session,
blob: dict[str, Any],
*,
reset_continuation: bool = False,
revoke_permission: bool = False,
) -> None:
previous_metadata = deepcopy(sess.metadata)
sess.metadata[GOAL_STATE_KEY] = blob
discard_legacy_goal_state_key(sess.metadata)
if reset_continuation:
reset_goal_continuation_rounds(sess.metadata)
saved = False
async def save_and_publish() -> None:
nonlocal saved
def change(metadata: dict[str, Any]) -> None:
metadata[GOAL_STATE_KEY] = deepcopy(blob)
discard_legacy_goal_state_key(metadata)
if reset_continuation:
reset_goal_continuation_rounds(metadata)
_, sess.metadata = await self._sessions.state.mutate_metadata(
sess.key, change, expected_generation=sess.generation,
)
saved = True
await self._publish_goal_state_changed(sess.metadata)
try:
self._sessions.save(sess)
except BaseException:
sess.metadata.clear()
sess.metadata.update(previous_metadata)
raise
await shield_and_drain(save_and_publish())
finally:
# This ContextVar belongs to the caller task, not the settlement task.
if revoke_permission and saved:
revoke_goal_mutation_permission()
async def _publish_goal_state_changed(self, metadata: dict[str, Any]) -> None:
bus = self._bus
@@ -171,11 +183,14 @@ class CreateGoalTool(Tool, _GoalToolsMixin):
self,
request: RequestContext,
) -> RuntimeContextBlock | None:
if not request.session_key:
if not request.session_key or not request.persist_session:
return None
session = self._sessions.get_or_create(request.session_key)
payload = await self._sessions.state.read_metadata(request.session_key)
if payload is None:
return None
metadata = payload["metadata"]
goal_start_requested = explicit_goal_requested(request.metadata)
goal_active = sustained_goal_active(session.metadata)
goal_active = sustained_goal_active(metadata)
if not goal_start_requested and not goal_active:
return None
@@ -185,7 +200,7 @@ class CreateGoalTool(Tool, _GoalToolsMixin):
goal_start_requested=goal_start_requested,
goal_active=goal_active,
)
state = wrap_runtime_context_lines(goal_state_runtime_lines(session.metadata))
state = wrap_runtime_context_lines(goal_state_runtime_lines(metadata))
content = "\n\n".join(part for part in (guidance, state) if part)
return RuntimeContextBlock(source="goal", content=content)
@@ -195,7 +210,7 @@ class CreateGoalTool(Tool, _GoalToolsMixin):
ui_summary: str | None = None,
**kwargs: Any,
) -> str:
sess = self._session()
sess = await self._session()
if sess is None:
return ToolResult.error(
"Error: create_goal requires an active chat session (missing routing context)."
@@ -223,8 +238,7 @@ class CreateGoalTool(Tool, _GoalToolsMixin):
"ui_summary": summary,
"started_at": _iso_now(),
}
self._save_goal_state(sess, blob, reset_continuation=True)
await self._publish_goal_state_changed(sess.metadata)
await self._save_goal_state(sess, blob, reset_continuation=True)
extra = f"\nSummary line: {summary}" if summary else ""
return (
"Goal recorded. Keep working toward the objective using ordinary tools. "
@@ -303,7 +317,7 @@ class UpdateGoalTool(Tool, _GoalToolsMixin):
ui_summary: str | None = None,
**kwargs: Any,
) -> str:
sess = self._session()
sess = await self._session()
if sess is None:
return ToolResult.error("Error: update_goal requires an active chat session.")
prior = parse_goal_state(goal_state_raw(sess.metadata))
@@ -338,8 +352,7 @@ class UpdateGoalTool(Tool, _GoalToolsMixin):
"previous_objective": str(prior.get("objective") or ""),
"recap": (recap or "").strip(),
}
self._save_goal_state(sess, blob, reset_continuation=True)
await self._publish_goal_state_changed(sess.metadata)
await self._save_goal_state(sess, blob, reset_continuation=True)
extra = f"\nSummary line: {summary}" if summary else ""
return "Goal replaced. Continue toward the new objective using ordinary tools." + extra
@@ -357,9 +370,7 @@ class UpdateGoalTool(Tool, _GoalToolsMixin):
}
if normalized == "complete":
blob["completed_at"] = ended
self._save_goal_state(sess, blob)
revoke_goal_mutation_permission()
await self._publish_goal_state_changed(sess.metadata)
await self._save_goal_state(sess, blob, revoke_permission=True)
tail = (recap or "").strip()
label = {
+3
View File
@@ -225,6 +225,9 @@ class MessageTool(Tool):
metadata["message_id"] = message_id
if media:
metadata["_record_channel_delivery"] = True
if same_target and request_ctx is not None and request_ctx.session_generation is not None:
metadata["_session_key"] = request_ctx.session_key
metadata["_session_generation"] = request_ctx.session_generation
msg = OutboundMessage(
channel=channel,
+8 -4
View File
@@ -100,7 +100,7 @@ class RuntimeControl(Protocol):
def set_model(self, model: str) -> LLMRuntime: ...
def set_model_preset(
async def set_model_preset(
self,
name: str,
*,
@@ -156,7 +156,11 @@ class _RuntimeControlTarget(Protocol):
def set_model_preset(self, name: str | None) -> LLMRuntime: ...
def set_session_model_preset(self, session_key: str, name: str) -> LLMRuntime: ...
async def set_session_model_preset(
self,
session_key: str,
name: str,
) -> LLMRuntime: ...
class AgentRuntimeControl:
@@ -227,14 +231,14 @@ class AgentRuntimeControl:
def set_model(self, model: str) -> LLMRuntime:
return self.__target.set_runtime_model(model)
def set_model_preset(
async def set_model_preset(
self,
name: str,
*,
session_key: str | None,
) -> LLMRuntime:
if session_key is not None:
return self.__target.set_session_model_preset(session_key, name)
return await self.__target.set_session_model_preset(session_key, name)
return self.__target.set_model_preset(name)
def set_max_iterations(self, value: int) -> None:
+5 -5
View File
@@ -252,7 +252,7 @@ class MyTool(Tool):
if not self._modify_allowed:
return ToolResult.error("Error: set is disabled (tools.my.allow_set is false)")
if action in ("modify", "set"):
return self._modify(key, value)
return await self._modify(key, value)
return f"Unknown action: {action}"
# -- inspect --
@@ -335,7 +335,7 @@ class MyTool(Tool):
# -- modify --
def _modify(self, key: str | None, value: Any) -> str:
async def _modify(self, key: str | None, value: Any) -> str:
if err := self._validate_key(key):
return err
key = cast(str, key)
@@ -361,7 +361,7 @@ class MyTool(Tool):
self._audit("modify", f"READ_ONLY {key}")
return ToolResult.error(f"Error: '{key}' is read-only and cannot be modified")
if key == "model_preset":
return self._modify_model_preset(value)
return await self._modify_model_preset(value)
if key in self.RESTRICTED:
return self._modify_restricted(key, value)
if key in RUNTIME_COMMAND_KEYS:
@@ -371,14 +371,14 @@ class MyTool(Tool):
return ToolResult.error(f"Error: '{key}' is read-only and cannot be modified")
return self._modify_scratchpad(key, value)
def _modify_model_preset(self, value: Any) -> str:
async def _modify_model_preset(self, value: Any) -> str:
if not isinstance(value, str) or not value.strip():
return ToolResult.error("Error: 'model_preset' must be a non-empty string")
name = value.strip()
session_key = current_request_session_key()
old = self._runtime_control.snapshot().model_preset
try:
runtime = self._runtime_control.set_model_preset(
runtime = await self._runtime_control.set_model_preset(
name,
session_key=session_key,
)
+3 -6
View File
@@ -88,7 +88,7 @@ class ListSessionsTool(Tool):
request = current_request_context()
if request is None or not request.session_key:
return ToolResult.error("Error: session context is unavailable")
handles = await asyncio.to_thread(self._handles.list_all)
handles = await self._handles.alist_all()
return json.dumps(
[
f"@{handle.name}"
@@ -219,14 +219,11 @@ class SendSessionMessageTool(Tool):
target_name = normalize_session_handle(target_handle)
except ValueError as exc:
raise SessionMessageError(str(exc)) from exc
target = await asyncio.to_thread(self._handles.resolve, target_name)
target = await self._handles.aresolve(target_name)
if target is None:
raise SessionMessageError(f"session @{target_name} was not found")
source = await asyncio.to_thread(
self._handles.handle_for_session,
source_session_key,
)
source = await self._handles.ahandle_for_session(source_session_key)
if source is None:
raise SessionMessageError("source session was not found")
envelope: SessionMessageEnvelope = {
+1 -4
View File
@@ -186,10 +186,7 @@ class ReadSessionTool(_SessionTool):
handle_name = normalize_session_handle(session_key)
except ValueError as exc:
return ToolResult.error(f"Error: {exc}")
handle = await asyncio.to_thread(
self._handles.resolve,
handle_name,
)
handle = await self._handles.aresolve(handle_name)
if handle is None:
return ToolResult.error(f"Error: session @{handle_name} was not found")
session_handle = f"@{handle_name}"
+1 -1
View File
@@ -109,7 +109,7 @@ class SubagentTool(Tool):
if not task_id:
return ToolResult.error(f"Error: {action} requires task_id")
if action == "send":
return json.dumps(self._manager.send(task_id, owner, message))
return json.dumps(await self._manager.send(task_id, owner, message))
status = await self._manager.cancel(task_id, owner)
return json.dumps(status.as_dict(), ensure_ascii=False)
return ToolResult.error("Error: unknown subagent action")
+5
View File
@@ -231,6 +231,11 @@ class TurnDelivery:
def streaming(self) -> bool:
return self._stream_base_id is not None
def bind_session_generation(self, generation: str) -> None:
"""Attach the admitted session identity to all later lifecycle events."""
self.delivery_message.session_generation = generation
self.lifecycle_message.session_generation = generation
def remember_session_route(self, session_metadata: dict[str, Any]) -> None:
"""Keep only routing fields needed to deliver a later idle notification."""
if is_internal_session(self.session_key):