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

+43 -10
View File
@@ -11,6 +11,7 @@ import time
import weakref
from collections.abc import Coroutine, Iterable, Mapping
from contextlib import AbstractContextManager, ExitStack, nullcontext, suppress
from copy import deepcopy
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum, auto
@@ -76,7 +77,7 @@ from nanobot.session.automation_turns import automation_history_overrides
from nanobot.session.goal_state import goal_state_runtime_lines, sustained_goal_active
from nanobot.session.history_visibility import HIDDEN_HISTORY_META
from nanobot.session.keys import UNIFIED_SESSION_KEY, remember_last_channel
from nanobot.session.manager import SESSION_CACHE_MAX_SIZE, Session, SessionManager
from nanobot.session.manager import SESSION_CACHE_MAX_SIZE, Session, SessionManager, SessionPolicy
from nanobot.session.model_selection import (
SESSION_MODEL_PRESET_METADATA_KEY,
model_preset_from_metadata,
@@ -399,6 +400,7 @@ class AgentLoop:
max_iterations=self.max_iterations,
max_concurrent_subagents=max_concurrent_subagents,
consolidator=self.consolidator,
session_manager=self.sessions,
)
self._unified_session = unified_session
self._running = False
@@ -518,6 +520,10 @@ class AgentLoop:
"""Keep subagent runtime limits aligned with mutable loop settings."""
self.subagents.max_iterations = self.max_iterations
def set_runtime_max_iterations(self, value: int) -> None:
self.max_iterations = value
self._sync_subagent_runtime_limits()
def invalidate_runtime_config(self) -> None:
"""Invalidate runtime config for lazy refresh at the next admission."""
self.runtime_resolver.invalidate()
@@ -733,9 +739,11 @@ class AgentLoop:
metadata=dict(ctx.msg.metadata or {}),
attributes=dict(ctx.attributes),
sender_id=ctx.msg.sender_id,
turn_id=ctx.turn_id,
turn_id=ctx.delivery.route.turn_id or ctx.turn_id,
workspace=scope.project_path,
log_content=ctx.session.policy.log_content and not ctx.ephemeral,
persist_session=ctx.session.policy.persist and not ctx.ephemeral,
can_receive_background_results=self._running,
)
async def _resolve_runtime_context_for_turn(
@@ -1001,7 +1009,7 @@ class AgentLoop:
ephemeral = ephemeral or (session is not None and not session.policy.persist)
async def _checkpoint(payload: dict[str, Any]) -> None:
if session is None:
if session is None or ephemeral:
return
public_payload = dict(payload)
private_state = public_payload.pop("provider_state", None)
@@ -1166,6 +1174,7 @@ class AgentLoop:
chat_id="direct",
session_key=session.key if session is not None else None,
runtime=runtime,
can_receive_background_results=self._running,
)
active_session_key = session.key if session else request_ctx.session_key
consolidation_session_key = active_session_key or "agent:transient"
@@ -1192,6 +1201,10 @@ class AgentLoop:
request_ctx.log_content and not ephemeral
and (session is None or session.policy.log_content)
),
persist_session=(
request_ctx.persist_session and not ephemeral
and (session is None or session.policy.persist)
),
)
effective_tools = tools if tools is not None else self.tools
file_state_token = bind_file_states(self._file_state_store.for_session(active_session_key))
@@ -1355,7 +1368,7 @@ class AgentLoop:
continue
if (
msg.require_existing_session
and self.sessions.get_cached(effective_key) is None
and self.sessions.get_existing(effective_key) is None
):
continue
if msg.is_user_input:
@@ -1432,6 +1445,8 @@ class AgentLoop:
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):
return
if session_key != msg.session_key:
msg = dataclasses.replace(msg, session_key_override=session_key)
@@ -1735,6 +1750,7 @@ class AgentLoop:
delivery: TurnDelivery | None = None,
on_runtime_admitted: Callable[[LLMRuntime], Awaitable[None]] | None = None,
attributes: Mapping[str, Any] | None = None,
session: Session | None = None,
) -> OutboundMessage | None:
"""Process a single inbound message and return the response."""
kind = TurnKind.USER if msg.is_user_input else TurnKind.SYSTEM
@@ -1745,6 +1761,8 @@ class AgentLoop:
key = session_key or msg.session_key_override or f"{destination[0]}:{destination[1]}"
else:
key = session_key or msg.session_key
if not self.subagents.accepts_result(msg, key):
return None
if delivery is None:
delivery = self.turn_delivery_factory.create(msg, key)
elif delivery.session_key != key:
@@ -1752,7 +1770,7 @@ class AgentLoop:
t0 = time.time()
ctx = TurnContext(
msg=msg,
session=None,
session=session,
session_key=key,
turn_id=f"{key}:{time.time_ns()}",
runtime=runtime,
@@ -1936,7 +1954,7 @@ class AgentLoop:
if ctx.session is None:
if msg.require_existing_session:
ctx.session = self.sessions.get_cached(ctx.session_key)
ctx.session = self.sessions.get_existing(ctx.session_key)
if ctx.session is None:
raise RuntimeError("required session is not active")
else:
@@ -1955,7 +1973,7 @@ class AgentLoop:
if ctx.kind is TurnKind.SYSTEM:
logger.info("Processing system message from {}", msg.sender_id)
elif session.policy.log_content:
elif session.policy.log_content and not ctx.ephemeral:
preview = msg.content[:80] + "..." if len(msg.content) > 80 else msg.content
logger.info("Processing message from {}:{}: {}", msg.channel, msg.sender_id, preview)
else:
@@ -2194,7 +2212,6 @@ class AgentLoop:
async def _persist_turn(self, ctx: TurnContext) -> None:
session = ctx.require_session()
turn_continuation.prepare_save_boundary(ctx)
if (
ctx.kind is TurnKind.USER
@@ -2213,6 +2230,8 @@ class AgentLoop:
else ctx.turn_wall_started_at
)
ctx.turn_latency_ms = max(0, int((time.time() - latency_started_at) * 1000))
ctx.delivery.record_latency(ctx.turn_latency_ms)
turn_continuation.prepare_save_boundary(ctx)
if ctx.usage is not None and not ctx.ephemeral:
session.metadata["_last_usage"] = ctx.usage.to_dict()
self._save_turn(
@@ -2229,7 +2248,6 @@ class AgentLoop:
# The next request must rebuild from the portable checkpoint;
# the opaque continuation predates that transcript rewrite.
session.provider_state = None
ctx.delivery.record_latency(ctx.turn_latency_ms)
self._clear_pending_user_turn(session)
self._clear_runtime_checkpoint(session)
self.sessions.save(session)
@@ -2515,8 +2533,13 @@ class AgentLoop:
runtime: LLMRuntime | None = None,
on_runtime_admitted: Callable[[LLMRuntime], Awaitable[None]] | None = None,
attributes: Mapping[str, Any] | None = None,
_session_policy: SessionPolicy | None = None,
) -> OutboundMessage | None:
"""Process an external message directly and return the outbound payload."""
"""Process an external message directly and return the outbound payload.
``ephemeral`` skips Memory journaling and extra hooks. SDK temporary
turns also supply a non-persistent policy for a detached session.
"""
if channel == "system":
raise ValueError("channel 'system' is reserved for internal messages")
metadata: dict[str, Any] = {}
@@ -2537,6 +2560,16 @@ class AgentLoop:
"on_stream_end": on_stream_end,
"ephemeral": ephemeral,
}
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.policy = SessionPolicy(
persist=session.policy.persist and _session_policy.persist,
log_content=session.policy.log_content and _session_policy.log_content,
disabled_tools=session.policy.disabled_tools | _session_policy.disabled_tools,
)
kwargs["session"] = session
if _run_extra_hooks_for_ephemeral:
kwargs["run_extra_hooks_for_ephemeral"] = True
if hooks is not None:
+15
View File
@@ -60,6 +60,14 @@ from nanobot.utils.runtime import (
is_blank_text,
)
def _raise_if_cancelling() -> None:
"""Do not resume model work when a dependency suppresses cancellation."""
task = asyncio.current_task()
if task is not None and task.cancelling():
raise asyncio.CancelledError
ContinuationCallback = Callable[[], str | None]
CheckpointCallback = Callable[[dict[str, Any]], Awaitable[None]]
InjectionCallback = Callable[[], Awaitable[Iterable[Any] | None]]
@@ -863,6 +871,7 @@ class AgentRunner:
malformed_retry: bool = False,
transcript: list[dict[str, Any]] | None,
) -> tuple[LLMResponse, LLMUsage]:
_raise_if_cancelling()
tool_definitions = spec.tools.get_definitions()
messages, provider_context = await self.context_governor.prepare_request(
request_state,
@@ -876,6 +885,7 @@ class AgentRunner:
messages,
tools=tool_definitions,
)
_raise_if_cancelling()
wants_streaming = hook.wants_streaming()
provider_context = replace(
provider_context or ProviderCallContext(),
@@ -993,6 +1003,7 @@ class AgentRunner:
request_started_at = time.perf_counter()
try:
response = await coro
_raise_if_cancelling()
except asyncio.CancelledError:
_pause_generation()
await _close_native_reasoning()
@@ -1214,6 +1225,7 @@ class AgentRunner:
request_state: ModelRequestState,
transcript: list[dict[str, Any]] | None = None,
) -> LLMResponse:
_raise_if_cancelling()
messages, provider_context = await self.context_governor.prepare_request(
request_state,
messages,
@@ -1225,6 +1237,7 @@ class AgentRunner:
messages,
tools=None,
)
_raise_if_cancelling()
response = await spec.runtime.provider.chat_stream_with_retry(
**kwargs,
provider_context=replace(
@@ -1232,11 +1245,13 @@ class AgentRunner:
response_preset=spec.runtime.model_preset or "",
),
)
_raise_if_cancelling()
await self.context_governor.summarize_provider_compaction(
request_state,
response,
current_request_boundary=(len(transcript) if transcript is not None else None),
)
_raise_if_cancelling()
request_state.provider_compaction_applied |= response.provider_compaction_applied
return response
+72
View File
@@ -0,0 +1,72 @@
"""Retain runner activity on Session messages without changing model input."""
from __future__ import annotations
from copy import deepcopy
from typing import Any
from nanobot.agent.hook import AgentHook, AgentHookContext
from nanobot.bus.outbound_events import ProgressEvent
from nanobot.events import AgentEvent
class SessionActivity(AgentHook):
"""Associate shared progress events with the response that produced them."""
def __init__(self) -> None:
super().__init__()
self._messages: list[dict[str, Any]] = []
self._iteration_start = 0
self._current: list[ProgressEvent] | None = None
self._pending: list[ProgressEvent] = []
self._responses: dict[int, list[ProgressEvent]] = {}
async def before_iteration(self, context: AgentHookContext) -> None:
self._messages = context.messages
self._iteration_start = len(context.messages)
self._current = None
self._pending = []
def _bind_response(self) -> None:
if self._current is None:
response = next((message for message in self._messages[self._iteration_start:]
if message.get("role") == "assistant"), None)
if response is not None:
self._current = self._responses.setdefault(id(response), [])
self._current.extend(self._pending)
self._pending = []
def remember(self, event: AgentEvent) -> bool:
"""Keep structured tool/file activity, including its actual error phase."""
if not isinstance(event, ProgressEvent) or not (event.tool_events or event.file_edit_events):
return False
self._bind_response()
target = self._current if self._current is not None else self._pending
target.append(deepcopy(event))
return True
def transcript(self, messages: list[dict[str, Any]] | None = None) -> list[dict[str, Any]]:
"""Add display fields only to detached copies, never provider messages."""
self._bind_response()
rows: list[dict[str, Any]] = []
for message in self._messages if messages is None else messages:
if message.get("role") == "system":
continue
row = deepcopy(message)
row.update(self._fields(self._responses.get(id(message), [])))
rows.append(row)
# Provider-hosted tools may emit activity before the response exists.
# An empty display row is omitted by Session.get_history() on replay.
if self._pending:
rows.append({"role": "assistant", "content": "", **self._fields(self._pending)})
return rows
@staticmethod
def _fields(events: list[ProgressEvent]) -> dict[str, Any]:
tools = list({tool["call_id"]: tool for event in events
for tool in event.tool_events or []}.values())
edits = list({(edit["call_id"], edit["path"]): edit for event in events
for edit in event.file_edit_events or []}.values())
return {key: deepcopy(value) for key, value in (
("tool_events", tools), ("file_edit_events", edits),
) if value}
+625 -299
View File
File diff suppressed because it is too large. Load diff
+161
View File
@@ -0,0 +1,161 @@
"""Private child sessions for subagent transcripts and task observations."""
from __future__ import annotations
import math
import time
from copy import deepcopy
from typing import Any, cast
from loguru import logger
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.types import PARENT_SESSION_KEY, SESSION_TYPE_KEY, SessionType
SUBAGENT = SessionType("subagent", needs_handle=False, public_history=False)
TASK_METADATA_KEY = "subagent_task"
_STATUS = TypeAdapter(SubagentStatus)
_ACTIVE_STATES = {"queued", "running", "stopping"}
class SubagentSessions:
"""Use the common session store; keep task access owned by the parent."""
def __init__(self, sessions: SessionManager):
self.sessions = sessions
sessions.types.register(SUBAGENT)
@staticmethod
def key(task_id: str) -> str:
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
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", {})
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))
@staticmethod
def _payload(status: SubagentStatus) -> dict[str, Any]:
return {
**_STATUS.dump_python(status, mode="json", exclude={"started_at", "finished_at"}),
"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
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
def status(self, task_id: str, owner: str) -> SubagentStatus | None:
payload = self.sessions.read_session_metadata(self.key(task_id))
if payload is None:
return None
metadata = payload.get("metadata", {})
if metadata.get(SESSION_TYPE_KEY) != SUBAGENT.name or metadata.get(PARENT_SESSION_KEY) != owner:
return None
raw: object = metadata.get(TASK_METADATA_KEY)
if not isinstance(raw, dict):
raise SubagentSessionError("invalid task session metadata")
value = cast(dict[str, object], raw)
elapsed = value.get("elapsed_seconds")
if (not isinstance(elapsed, (int, float)) or isinstance(elapsed, bool)
or not math.isfinite(elapsed) or elapsed < 0):
raise SubagentSessionError("invalid task duration")
now = time.monotonic()
try:
status = _STATUS.validate_python({
**value, "started_at": now - elapsed,
"finished_at": now if value.get("completed_at") is not None else None,
})
except ValidationError as exc:
raise SubagentSessionError("invalid task session metadata") from exc
if status.owner != owner or status.task_id != task_id:
raise SubagentSessionError("invalid task ownership")
return status
def load(self, owner: str) -> dict[str, SubagentStatus]:
result: dict[str, SubagentStatus] = {}
for key in self.sessions.child_session_keys(owner):
task_id = key.removeprefix("subagent:")
if key != self.key(task_id):
continue
status = self.status(task_id, owner)
if status is not None:
result[task_id] = status
return result
def interrupt_pending(self) -> None:
"""Seal abandoned work after the gateway acquires execution ownership."""
for row in self.sessions.list_sessions():
key = row["key"]
payload = self.sessions.read_session_metadata(key)
metadata = (payload or {}).get("metadata", {})
if metadata.get(SESSION_TYPE_KEY) != SUBAGENT.name:
continue
owner = metadata.get(PARENT_SESSION_KEY)
if not isinstance(owner, str):
continue
try:
status = self.status(key.removeprefix("subagent:"), owner)
if status is None or status.state not in _ACTIVE_STATES:
continue
status.state = status.phase = "interrupted"
status.revision += 1
status.stop_reason = "host_restarted"
status.finished_at = time.monotonic()
status.completed_at = time.time()
status.partial = bool(status.result)
status.tool_events = []
status.receipts = {key: "undelivered" if receipt == "accepted" else receipt
for key, receipt in status.receipts.items()}
self.save(status, fsync=True)
except (OSError, SubagentSessionError):
logger.exception("Could not recover subagent session {}", key)
+68
View File
@@ -0,0 +1,68 @@
"""Task observations shared by execution and private child sessions."""
from __future__ import annotations
import time
from dataclasses import dataclass, field
from typing import Literal
from nanobot.providers.base import LLMUsage
SubagentState = Literal["queued", "running", "stopping", "done", "incomplete", "error", "cancelled", "interrupted"]
class SubagentSessionError(ValueError):
"""A private task session could not be read safely."""
@dataclass(slots=True)
class SubagentStatus:
"""Observable task data, detached from execution and process resources."""
task_id: str
label: str
task_description: str
started_at: float # time.monotonic()
finished_at: float | None = None
# Runner checkpoints refine phase without changing the control lifecycle state.
phase: str = "queued"
owner: str = ""
state: SubagentState = "queued"
receipts: dict[str, str] = field(default_factory=dict)
result: str | None = None
partial: bool = False
iteration: int = 0
tool_events: list[dict[str, str]] = field(default_factory=list)
usage: LLMUsage | None = None
stop_reason: str | None = None
error: str | None = None
origin_message_id: str | None = None
origin_turn_id: str | None = None
created_at: float = field(default_factory=time.time)
completed_at: float | None = None
revision: int = 0
def as_dict(self) -> dict[str, object]:
"""Serialize task observations without exposing ownership or resources."""
end = self.finished_at if self.finished_at is not None else time.monotonic()
return {
"task_id": self.task_id,
"revision": self.revision,
"origin_message_id": self.origin_message_id,
"origin_turn_id": self.origin_turn_id,
"created_at": self.created_at,
"completed_at": self.completed_at,
"label": self.label,
"task_description": self.task_description,
"state": self.state,
"phase": self.phase,
"elapsed_seconds": round(max(0.0, end - self.started_at), 1),
"iteration": self.iteration,
"tool_events": [dict(event) for event in self.tool_events],
"usage": self.usage.to_dict() if self.usage is not None else None,
"receipts": dict(self.receipts),
"result": self.result,
"partial": self.partial,
"stop_reason": self.stop_reason,
"error": self.error,
}
+3
View File
@@ -41,6 +41,9 @@ class RequestContext:
workspace: Path | None = None
attributes: dict[str, Any] = field(default_factory=dict)
log_content: bool = True
# The host can consume completion messages after this request returns.
can_receive_background_results: bool = True
persist_session: bool = True
@runtime_checkable
+3 -34
View File
@@ -7,10 +7,7 @@ from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Protocol, TypeAlias, runtime_checkable
from nanobot.agent.tools.context import current_request_session_key
if TYPE_CHECKING:
from nanobot.agent.subagent import SubagentManager, SubagentStatus
from nanobot.agent.tools.shell import ExecToolConfig
from nanobot.agent.tools.web import WebToolsConfig
from nanobot.config.schema import ModelPresetConfig
@@ -33,7 +30,6 @@ RUNTIME_SNAPSHOT_KEYS = frozenset({
"tool_names",
"web_config",
"exec_config",
"subagents",
})
RUNTIME_COMMAND_KEYS = frozenset({
@@ -62,7 +58,6 @@ class RuntimeSnapshot:
tool_names: list[str]
web_config: dict[str, object]
exec_config: dict[str, object]
subagent_statuses: dict[str, dict[str, object]]
scratchpad: dict[str, JsonValue]
def as_mapping(self) -> Mapping[str, object]:
@@ -79,7 +74,6 @@ class RuntimeSnapshot:
"tool_names": self.tool_names,
"web_config": self.web_config,
"exec_config": self.exec_config,
"subagents": {"_task_statuses": self.subagent_statuses},
}
assert values.keys() == RUNTIME_SNAPSHOT_KEYS
return values
@@ -121,7 +115,6 @@ class _RuntimeControlTarget(Protocol):
max_tool_result_chars: int
web_config: WebToolsConfig
exec_config: ExecToolConfig
subagents: SubagentManager
@property
def model(self) -> str: ...
@@ -145,6 +138,8 @@ class _RuntimeControlTarget(Protocol):
def set_runtime_context_window(self, context_window_tokens: int) -> LLMRuntime: ...
def set_runtime_max_iterations(self, value: int) -> None: ...
def set_model_preset(self, name: str | None) -> LLMRuntime: ...
def set_session_model_preset(self, session_key: str, name: str) -> LLMRuntime: ...
@@ -176,7 +171,6 @@ class AgentRuntimeControl:
tool_names=list(target.tool_names),
web_config=_snapshot_web_config(target.web_config),
exec_config=_snapshot_exec_config(target.exec_config),
subagent_statuses=_snapshot_subagent_statuses(target.subagents),
scratchpad=_snapshot_json_mapping(self.__scratchpad),
)
@@ -194,8 +188,7 @@ class AgentRuntimeControl:
return self.__target.set_model_preset(name)
def set_max_iterations(self, value: int) -> None:
self.__target.max_iterations = value
self.__target.subagents.max_iterations = value
self.__target.set_runtime_max_iterations(value)
def set_context_window_tokens(self, value: int) -> LLMRuntime:
return self.__target.set_runtime_context_window(value)
@@ -265,30 +258,6 @@ def _snapshot_exec_config(config: ExecToolConfig) -> dict[str, object]:
}
def _snapshot_subagent_statuses(
manager: SubagentManager,
) -> dict[str, dict[str, object]]:
return {
task_id: _snapshot_subagent_status(status)
for task_id, status in manager.statuses_for_session(current_request_session_key()).items()
}
def _snapshot_subagent_status(status: SubagentStatus) -> dict[str, object]:
return {
"task_id": status.task_id,
"label": status.label,
"task_description": status.task_description,
"started_at": status.started_at,
"phase": status.phase,
"iteration": status.iteration,
"tool_events": [dict(event) for event in status.tool_events],
"usage": status.usage.to_dict() if status.usage is not None else None,
"stop_reason": status.stop_reason,
"error": status.error,
}
def _snapshot_json_mapping(values: Mapping[str, JsonValue]) -> dict[str, JsonValue]:
return {key: _snapshot_json_value(value) for key, value in values.items()}
+1 -105
View File
@@ -5,7 +5,6 @@
from __future__ import annotations
import time
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeGuard, cast
@@ -23,7 +22,6 @@ from nanobot.agent.tools.runtime_control import (
from nanobot.config_base import Base
if TYPE_CHECKING:
from nanobot.agent.subagent import SubagentStatus
from nanobot.agent.tools.context import ToolContext
@@ -33,21 +31,6 @@ class MyToolConfig(Base):
allow_set: bool = False
def _is_subagent_status(value: object) -> TypeGuard[SubagentStatus]:
from nanobot.agent.subagent import SubagentStatus
return isinstance(value, SubagentStatus)
def _is_subagent_status_snapshot(value: object) -> TypeGuard[Mapping[str, object]]:
if not isinstance(value, Mapping):
return False
return all(
field in value
for field in ("task_id", "label", "task_description", "started_at", "phase")
)
def _is_string_mapping(value: object) -> TypeGuard[Mapping[str, object]]:
if not isinstance(value, Mapping):
return False
@@ -83,7 +66,7 @@ class MyTool(Tool):
# Config management
"_runtime_vars",
# Subsystems
"runner", "sessions", "consolidator",
"runner", "sessions", "consolidator", "subagents",
"dream", "auto_compact", "context", "commands",
# Sensitive runtime state (credentials, message routing, task tracking)
"_pending_queues",
@@ -94,7 +77,6 @@ class MyTool(Tool):
})
READ_ONLY = frozenset({
"subagents", # observable but replacing it would break the system
"tool_names",
"exec_config", # inspect allowed (e.g. check sandbox), modify blocked
"web_config", # inspect allowed (e.g. check enable), modify blocked
@@ -247,89 +229,8 @@ class MyTool(Tool):
# Smart formatting
# ------------------------------------------------------------------
@staticmethod
def _format_status(
st: "SubagentStatus | Mapping[str, object]",
indent: str = " ",
) -> str:
if isinstance(st, Mapping):
started_at = st.get("started_at", time.monotonic())
raw_events = st.get("tool_events", [])
phase = st.get("phase", "unknown")
iteration = st.get("iteration", 0)
usage = st.get("usage", {})
error = st.get("error")
stop_reason = st.get("stop_reason")
else:
started_at = st.started_at
raw_events = st.tool_events
phase = st.phase
iteration = st.iteration
usage = st.usage
error = st.error
stop_reason = st.stop_reason
elapsed = time.monotonic() - (
float(started_at) if isinstance(started_at, (int, float)) else time.monotonic()
)
tool_events = cast(list[object], raw_events) if isinstance(raw_events, list) else []
tool_summaries: list[str] = []
for raw_event in tool_events[-5:]:
if not isinstance(raw_event, Mapping):
continue
event = cast(Mapping[str, object], raw_event)
tool_summaries.append(
f"{event.get('name', '?')}({event.get('status', '?')})"
)
tool_summary = ", ".join(tool_summaries) or "none"
lines = [
f"{indent}phase: {phase}, iteration: {iteration}, elapsed: {elapsed:.1f}s",
f"{indent}tools: {tool_summary}",
f"{indent}usage: {usage or 'n/a'}",
]
if error:
lines.append(f"{indent}error: {error}")
if stop_reason:
lines.append(f"{indent}stop_reason: {stop_reason}")
return "\n".join(lines)
@staticmethod
def _format_value(val: Any, key: str = "") -> str:
if _is_subagent_status(val):
header = f"Subagent [{val.task_id}] '{val.label}'"
detail = MyTool._format_status(val, " ")
return f"{header}\n task: {val.task_description}\n{detail}"
if _is_subagent_status_snapshot(val):
header = f"Subagent [{val['task_id']}] '{val['label']}'"
detail = MyTool._format_status(val, " ")
return f"{header}\n task: {val['task_description']}\n{detail}"
if isinstance(val, Mapping):
mapping = cast(Mapping[object, object], val)
else:
mapping = None
if mapping and set(mapping) == {"_task_statuses"}:
task_statuses = mapping["_task_statuses"]
if isinstance(task_statuses, Mapping):
return MyTool._format_value(task_statuses, key)
if (
mapping
and (
_is_subagent_status(next(iter(mapping.values())))
or _is_subagent_status_snapshot(next(iter(mapping.values())))
)
):
prefix = f"{key}: " if key else ""
lines = [f"{prefix}{len(mapping)} subagent(s):"]
for tid, st in mapping.items():
if _is_subagent_status(st):
detail = MyTool._format_status(st, " ")
label = st.label
elif _is_subagent_status_snapshot(st):
detail = MyTool._format_status(st, " ")
label = st.get("label", "?")
else:
continue
lines.append(f" [{tid}] '{label}'\n{detail}")
return "\n".join(lines)
# Scalar types — repr is fine
if isinstance(val, (str, int, float, bool, type(None))):
r = repr(val)
@@ -393,10 +294,6 @@ class MyTool(Tool):
def _inspect(self, key: str | None) -> str:
if not key:
return self._inspect_all()
if key == "subagents" or key.startswith("subagents."):
request_ctx = current_request_context()
if request_ctx is None or not request_ctx.session_key:
return ToolResult.error("Error: current session context is unavailable")
if key == "request" or key.startswith("request."):
request_ctx = current_request_context()
if request_ctx is None:
@@ -451,7 +348,6 @@ class MyTool(Tool):
"max_tool_result_chars",
"web_config",
"exec_config",
"subagents",
):
parts.append(self._format_value(values[k], k))
if snapshot.scratchpad:
-107
View File
@@ -1,107 +0,0 @@
"""Spawn tool for creating background subagents."""
# pyright: reportIncompatibleMethodOverride=false
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
from nanobot.agent.tools.context import current_request_context
from nanobot.agent.tools.schema import (
BooleanSchema,
NumberSchema,
StringSchema,
tool_parameters_schema,
)
from nanobot.security.workspace_access import current_workspace_scope
if TYPE_CHECKING:
from nanobot.agent.subagent import SubagentManager
from nanobot.agent.tools.context import ToolContext
@tool_parameters(
tool_parameters_schema(
task=StringSchema("The task for the subagent to complete"),
label=StringSchema("Optional short label for the task (for display)"),
temperature=NumberSchema(
description=(
"Optional sampling temperature for the subagent "
"(0.0 = deterministic, higher = more creative). "
"Defaults to the provider's configured temperature."
),
minimum=0.0,
maximum=2.0,
),
wait=BooleanSchema(
description=(
"Wait for the subagent and return its result directly. Use this for a "
"blocking consultation that must inform the current turn. Defaults to "
"false for background execution."
),
default=False,
),
required=["task"],
)
)
class SpawnTool(Tool):
"""Tool to spawn a subagent for background task execution."""
def __init__(self, manager: "SubagentManager"):
self._manager = manager
@classmethod
def create(cls, ctx: ToolContext) -> Tool:
manager = ctx.subagent_manager
if manager is None:
raise RuntimeError("SpawnTool requires an initialized subagent manager")
return cls(manager=manager)
@property
def name(self) -> str:
return "spawn"
@property
def description(self) -> str:
return (
"Spawn a subagent to handle a task in the background. "
"Use this for complex or time-consuming tasks that can run independently. "
"Set wait=true for a consultation whose result must inform the current turn. "
"The subagent will complete the task and report back when done. "
"For deliverables or existing projects, inspect the workspace first "
"and use a dedicated subdirectory when helpful."
)
@property
def concurrency_safe(self) -> bool:
"""Each call owns its task state; the manager serializes capacity admission."""
return True
async def execute(
self,
task: str,
label: str | None = None,
temperature: float | None = None,
wait: bool = False,
**kwargs: Any,
) -> str:
"""Spawn a subagent to execute the given task."""
request_ctx = current_request_context()
if request_ctx is None or request_ctx.runtime is None:
return ToolResult.error("Error: spawn requires an active model runtime")
origin_channel = request_ctx.channel
origin_chat_id = request_ctx.chat_id
session_key = request_ctx.session_key or f"{origin_channel}:{origin_chat_id}"
method = self._manager.run_inline if wait else self._manager.spawn
return await method(
task=task,
runtime=request_ctx.runtime,
label=label,
origin_channel=origin_channel,
origin_chat_id=origin_chat_id,
session_key=session_key,
origin_message_id=request_ctx.message_id,
temperature=temperature,
workspace_scope=current_workspace_scope(),
)
+155
View File
@@ -0,0 +1,155 @@
"""Tool for creating, messaging, cancelling, and inspecting session-owned tasks."""
# pyright: reportIncompatibleMethodOverride=false
from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any
from nanobot.agent.subagent import SubagentControlError
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
from nanobot.agent.tools.context import current_request_context, current_request_session_key
from nanobot.agent.tools.schema import (
BooleanSchema,
NumberSchema,
StringSchema,
tool_parameters_schema,
)
from nanobot.security.workspace_access import current_workspace_scope
from nanobot.session.manager import SessionPolicy
if TYPE_CHECKING:
from nanobot.agent.subagent import SubagentManager
from nanobot.agent.tools.context import ToolContext
@tool_parameters(tool_parameters_schema(
action=StringSchema(
"create starts a task; send queues a message; cancel requests an idempotent stop; "
"check returns task status, receipts, and results.",
enum=("create", "send", "cancel", "check"),
),
task=StringSchema("Required for create: the task for the subagent to complete.", min_length=1),
label=StringSchema("Optional short label for create (for display)."),
temperature=NumberSchema(
description="Optional sampling temperature for create. Defaults to the parent's model runtime.",
minimum=0.0,
maximum=2.0,
),
wait=BooleanSchema(
description=(
"For create: wait for the result directly when it must inform the current turn. "
"Defaults to false for background execution with a completion notification. "
"Ephemeral requests and hosts without a background consumer always wait."
),
default=False,
),
task_id=StringSchema(
"Full task ID returned by create. Required for send/cancel; optional for check. "
"Omit for check to list the current session's active and recently finished tasks.",
min_length=1,
),
message=StringSchema(
"Required for send: text, at most 8192 UTF-8 bytes. Accepted means queued, not delivered. "
"Delivery receipts mean injected into the task transcript, not that the task acted on the message.",
max_length=8192,
),
required=["action"],
))
class SubagentTool(Tool):
"""Manage the current session's private subagent tasks."""
def __init__(self, manager: SubagentManager):
self._manager = manager
@classmethod
def create(cls, ctx: ToolContext) -> Tool:
if ctx.subagent_manager is None:
raise RuntimeError("SubagentTool requires an initialized subagent manager")
return cls(ctx.subagent_manager)
@property
def name(self) -> str:
return "subagent"
@property
def description(self) -> str:
return (
"Create, message, cancel, or check your session's private subagent tasks. "
"Use create for independent work; set wait=true for a blocking consultation. "
"Use send for follow-up instructions, cancel to stop one task, and check to read "
"progress, message receipts, and results. Check without task_id lists active and recent tasks; "
"use a known task_id to read an older result. "
"Background results arrive automatically; do not repeatedly poll check while waiting. "
"A partial result or iteration limit does not mean the task completed. "
"For deliverables or existing projects, inspect the workspace first "
"and use a dedicated subdirectory when helpful."
)
@property
def concurrency_safe(self) -> bool:
return True
async def execute(
self, action: str, task_id: str | None = None, message: str | None = None,
task: str | None = None, label: str | None = None,
temperature: float | None = None, wait: bool = False, **kwargs: Any,
) -> str:
if action == "create":
if not task or not task.strip():
return ToolResult.error("Error: create requires a non-empty task")
return await self._create_task(task, label, temperature, wait)
owner = current_request_session_key()
try:
if action == "check":
if not owner:
raise SubagentControlError("task unavailable")
if task_id is not None:
return json.dumps(self._manager.check(task_id, owner).as_dict(), ensure_ascii=False)
return json.dumps({
"tasks": [status.as_dict()
for status in self._manager.statuses_for_session(owner, include_history=False).values()],
}, ensure_ascii=False)
if action in {"send", "cancel"}:
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))
status = await self._manager.cancel(task_id, owner)
return json.dumps(status.as_dict(), ensure_ascii=False)
return ToolResult.error("Error: unknown subagent action")
except SubagentControlError as exc:
return ToolResult.error(f"Error: {exc}")
async def _create_task(
self, task: str, label: str | None, temperature: float | None, wait: bool,
) -> str:
request_ctx = current_request_context()
if request_ctx is None or request_ctx.runtime is None:
return ToolResult.error("Error: create requires an active model runtime")
origin_channel = request_ctx.channel
origin_chat_id = request_ctx.chat_id
session_key = request_ctx.session_key or (
f"{origin_channel}:{origin_chat_id}" if origin_channel and origin_chat_id else None
)
if not session_key:
return ToolResult.error("Error: create requires an active session identity")
inline = wait or not request_ctx.can_receive_background_results or not request_ctx.persist_session
method = self._manager.run_inline if inline else self._manager.spawn
return await method(
task=task,
runtime=request_ctx.runtime,
label=label,
origin_channel=origin_channel,
origin_chat_id=origin_chat_id,
session_key=session_key,
origin_message_id=request_ctx.message_id,
origin_turn_id=request_ctx.turn_id,
temperature=temperature,
workspace_scope=current_workspace_scope(),
session_policy=SessionPolicy(
persist=request_ctx.persist_session,
log_content=request_ctx.log_content,
),
)
+2
View File
@@ -47,6 +47,8 @@ class TurnRoute:
chat_id: str
metadata: dict[str, Any] = field(default_factory=dict)
publish_lifecycle: bool = False
# Public turn identity supplied by the owning channel adapter.
turn_id: str | None = None
TurnRoutePolicy = Callable[[InboundMessage, str, TurnRoute], TurnRoute]
+3 -1
View File
@@ -145,4 +145,6 @@ class MessageBus:
async def drain(self) -> None:
"""Finish scheduled dispatches after producers stop, before disconnecting."""
while self._pending:
await asyncio.gather(*self._pending, return_exceptions=True)
pending = tuple(self._pending)
await asyncio.gather(*pending, return_exceptions=True)
self._pending.difference_update(pending)
+8
View File
@@ -90,6 +90,14 @@ class GoalStateChanged(AgentEvent):
session_metadata: dict[str, Any] = field(default_factory=dict)
@dataclass(frozen=True)
class SubagentTaskChanged(AgentEvent):
"""A parent-owned task observation changed."""
context: RuntimeEventContext
task_id: str
@dataclass(frozen=True)
class RuntimeModelChanged(AgentEvent):
"""The active runtime model/preset changed."""
+7
View File
@@ -41,6 +41,7 @@ from nanobot.utils.restart import (
)
if TYPE_CHECKING:
from nanobot.agent.subagent import SubagentManager
from nanobot.cron.service import CronService
from nanobot.session.manager import SessionManager
from nanobot.triggers.local_store import LocalTriggerStore
@@ -111,6 +112,8 @@ class ChannelManager:
webui_recovery_action: (
Callable[[str, dict[str, Any]], Awaitable[dict[str, Any]]] | None
) = None,
webui_subagent_manager: SubagentManager | None = None,
webui_discard_session: Callable[[str], Awaitable[None]] | None = None,
config_path: Path | None = None,
):
if config_path is None:
@@ -134,6 +137,8 @@ class ChannelManager:
self._webui_mcp_reload = webui_mcp_reload
self._webui_skill_state_action = webui_skill_state_action
self._webui_recovery_action = webui_recovery_action
self._webui_subagent_manager = webui_subagent_manager
self._webui_discard_session = webui_discard_session
self.channels: dict[str, BaseChannel] = {}
self._channel_owners: dict[str, str] = {}
self._channel_runtime_specs: dict[str, tuple[str, str]] = {}
@@ -211,6 +216,8 @@ class ChannelManager:
mcp_reload=self._webui_mcp_reload,
skill_state_action=self._webui_skill_state_action,
recovery_action=self._webui_recovery_action,
subagent_manager=self._webui_subagent_manager,
discard_session=self._webui_discard_session,
logger=logger,
)
kwargs["gateway"] = gateway
+3
View File
@@ -735,6 +735,8 @@ def _run_gateway(
webui_mcp_reload=mcp_provider.reload,
webui_skill_state_action=_webui_skill_state_action,
webui_recovery_action=recovery.handle_action,
webui_subagent_manager=agent.subagents,
webui_discard_session=agent.discard_session,
config_path=Path(config_path),
)
@@ -1035,6 +1037,7 @@ def _run_gateway(
gateway_runtime.foreground_instance(gateway_start_options),
webui_turn_coordinator.connected(),
):
agent.subagents.recover_interrupted()
if health_server_enabled:
gateway_runtime.publish_health_host(config.gateway.host)
asyncio.run(run())
+3
View File
@@ -5,6 +5,8 @@ from __future__ import annotations
from collections.abc import Mapping
from typing import Any
from nanobot.session.manager import SessionPolicy
def ensure_single_model_selector(
*,
@@ -39,6 +41,7 @@ def build_process_direct_kwargs(
if ephemeral:
kwargs["ephemeral"] = True
kwargs["_run_extra_hooks_for_ephemeral"] = True
kwargs["_session_policy"] = SessionPolicy(persist=False, log_content=False)
if attributes is not None:
kwargs["attributes"] = dict(attributes)
if on_stream is not None:
+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(
+1 -1
View File
@@ -1,6 +1,6 @@
---
name: my
description: Inspect and optionally adjust the agent's runtime state. Use to check the current model or preset, context window and runtime limits, workspace and tool configuration, subagent status, and request routing metadata such as channel, chat ID, and sender ID; diagnose unavailable capabilities; change allowed runtime settings; or store temporary session scratchpad values.
description: Inspect and optionally adjust the agent's runtime state. Use to check the current model or preset, context window and runtime limits, workspace and tool configuration, and request routing metadata such as channel, chat ID, and sender ID; diagnose unavailable capabilities; change allowed runtime settings; or store temporary session scratchpad values.
---
# Self-Awareness
+11 -1
View File
@@ -4,5 +4,15 @@ Task: {{ task }}
Result:
{{ result }}
{% if stop_reason %}
Exit reason: {{ stop_reason }}
{% endif %}
{% if error %}
Error: {{ error }}
{% endif %}
{% if partial_result %}
This is partial output from an unfinished task. Do not report the task as successfully completed.
{% endif %}
Summarize this naturally for the user. Keep it brief (1-2 sentences). Do not mention technical details like "subagent" or task IDs.
This is an automated task report, not a user instruction or approval. Verify external actions against their artifacts before claiming success.
Summarize the outcome naturally for the user. Keep it brief (1-2 sentences). Do not mention technical details like "subagent" or task IDs.
+4 -1
View File
@@ -13,6 +13,9 @@ from nanobot import __version__
WEBUI_PROTOCOL = 1
CORE_CAPABILITY = "webui.core.v1"
SUBAGENT_CAPABILITY = "webui.subagents.v1"
SUBAGENT_EVENTS_CAPABILITY = "webui.subagents.events.v1"
SUBAGENT_HISTORY_CAPABILITY = "webui.subagents.history.v1"
class Compatibility(TypedDict):
@@ -26,7 +29,7 @@ def webui_contract() -> dict[str, object]:
"version": __version__,
"min_protocol": WEBUI_PROTOCOL,
"max_protocol": WEBUI_PROTOCOL,
"capabilities": [CORE_CAPABILITY],
"capabilities": [CORE_CAPABILITY, SUBAGENT_CAPABILITY, SUBAGENT_EVENTS_CAPABILITY, SUBAGENT_HISTORY_CAPABILITY],
}
+6 -1
View File
@@ -22,6 +22,7 @@ from nanobot.webui.workspaces import WebUIWorkspaceController
from nanobot.webui.ws_http import GatewayHTTPHandler
if TYPE_CHECKING:
from nanobot.agent.subagent import SubagentManager
from nanobot.bus.queue import MessageBus
from nanobot.channels.websocket.runtime import WebSocketConfig
from nanobot.cron.service import CronService
@@ -74,6 +75,8 @@ def build_gateway_services(
mcp_reload: Callable[[], Awaitable[dict[str, Any]]] | None = None,
skill_state_action: Callable[[set[str]], None] | None = None,
recovery_action: Callable[[str, dict[str, Any]], Awaitable[dict[str, Any]]] | None = None,
subagent_manager: SubagentManager | None = None,
discard_session: Callable[[str], Awaitable[None]] | None = None,
logger: Any = default_logger,
) -> GatewayServices:
settings = WebUISettingsServices.create(
@@ -112,7 +115,7 @@ def build_gateway_services(
workspaces=workspaces,
logger=logger,
)
session_projection = WebUISessionProjection(session_manager, log=logger)
session_projection = WebUISessionProjection(session_manager, subagent_manager=subagent_manager, log=logger)
http = GatewayHTTPHandler(
config=config,
session_manager=session_manager,
@@ -138,6 +141,8 @@ def build_gateway_services(
mcp_reload=mcp_reload,
skill_state_action=skill_state_action,
recovery_action=recovery_action,
subagent_manager=subagent_manager,
discard_session=discard_session,
log=logger,
)
endpoint = WebUIGatewayEndpoint(config=config, http=http, tokens=tokens)
+12
View File
@@ -20,6 +20,7 @@ from nanobot.bus.outbound_events import (
TurnModelUpdatedEvent,
UserInputEvent,
)
from nanobot.bus.runtime_events import SubagentTaskChanged
from nanobot.session.webui_turns import clear_websocket_turn_if_current
from nanobot.webui.metadata import (
WEBSOCKET_TURN_OWNER_METADATA_KEY,
@@ -157,6 +158,7 @@ class WebUIOutboundProjector:
SessionUpdatedEvent,
GoalStatusEvent,
GoalStateSyncEvent,
SubagentTaskChanged,
ContextCompactionEvent,
)
log = (
@@ -244,6 +246,16 @@ class WebUIOutboundProjector:
)
await self._transport.send_session_updated(msg.chat_id, scope=session_update_scope)
return
if isinstance(event, SubagentTaskChanged):
if conns:
task = self._session_projection.subagent_task(webui_session_key(msg.chat_id), event.task_id)
if task is not None:
await self._transport.send_payload(
msg.chat_id,
{"event": "subagent_task", "chat_id": msg.chat_id, "task": task},
persistence="transient",
)
return
if isinstance(event, SessionUpdatedEvent):
if conns:
await self._transport.send_session_updated(msg.chat_id, scope=event.scope)
+6
View File
@@ -103,8 +103,14 @@ class ContextCompactionWirePayload(_ChatWirePayload):
phase: Literal["started", "succeeded", "failed", "cancelled"]
class SubagentTaskWirePayload(_ChatWirePayload):
event: Literal["subagent_task"]
task: dict[str, object]
WebUIWirePayload: TypeAlias = (
RetryStatusWirePayload | ContextCompactionWirePayload | RecoveryStateWirePayload | TurnEndWirePayload
| SubagentTaskWirePayload
)
WebUIWirePersistence: TypeAlias = Literal[
"transient",
+2 -1
View File
@@ -259,7 +259,8 @@ class RemoteProxy:
"limits", "model_name", "runtime_surface", "runtime_capabilities",
) if key in data}
result.update(token=token, api_token=api_token, expires_in=ttl,
terminal={"protocolVersion": 1, "gatewayId": self._gateway_id},
terminal={"protocolVersion": 1, "gatewayId": self._gateway_id,
"webui": terminal["webui"]},
ws_path=self._ws_path, ws_url=f"ws://127.0.0.1:{self.port}{self._ws_path}")
result["host_compatibility"] = report
return web.json_response(result, headers={"Cache-Control": "no-store"})
+4 -1
View File
@@ -46,7 +46,10 @@ class WebuiSessionAccess:
) -> dict[str, Any] | None:
if session_key == exclude_session_key:
return None
return self._sessions.read_session_metadata(session_key)
payload = self._sessions.read_session_metadata(session_key)
if payload is None or not self._sessions.types.public_history(_session_metadata(payload)):
return None
return payload
def normalize_mentions(
self,
+5
View File
@@ -75,6 +75,11 @@ def list_webui_sessions(session_manager: SessionManager) -> list[dict[str, Any]]
_public_row(session_manager.sessions_dir, get_webui_dir(), row)
for row in rows
]
sessions = [
row for row in sessions if session_manager.types.public_history(
(session_manager.read_session_metadata(row["key"]) or {}).get("metadata", {})
)
]
return sorted(sessions, key=lambda row: row.get("updated_at", ""), reverse=True)
+17 -2
View File
@@ -2,16 +2,20 @@
from __future__ import annotations
from typing import Any, Protocol, cast
from typing import TYPE_CHECKING, Any, Protocol, cast
from loguru import logger as default_logger
from nanobot.agent.subagent import SubagentControlError
from nanobot.providers.base import LLMUsage
from nanobot.session.goal_state import goal_state_ws_blob
from nanobot.session.model_selection import model_preset_from_metadata
from nanobot.session.recovery import recovery_state_from_metadata
from nanobot.session.webui_turns import websocket_turn_id, websocket_turn_wall_started_at
if TYPE_CHECKING:
from nanobot.agent.subagent import SubagentManager
class SessionMetadataReader(Protocol):
"""Narrow persisted-session dependency used by WebUI projections."""
@@ -20,17 +24,28 @@ class SessionMetadataReader(Protocol):
class WebUISessionProjection:
"""Project persisted session metadata into stable WebUI protocol fields."""
"""Project session metadata and owned child observations for WebUI clients."""
def __init__(
self,
sessions: SessionMetadataReader | None,
*,
subagent_manager: SubagentManager | None = None,
log: Any = default_logger,
) -> None:
self._sessions = sessions
self._subagents = subagent_manager
self._log = log
def subagent_task(self, session_key: str, task_id: str) -> dict[str, object] | None:
"""Read the current public snapshot only while the parent still owns it."""
if self._subagents is None:
return None
try:
return self._subagents.check(task_id, session_key).as_dict()
except SubagentControlError:
return None
def attach_fields(self, session_key: str) -> dict[str, Any]:
"""Return the session runtime facts sent with an attach handshake."""
if self._sessions is None:
+1 -1
View File
@@ -20,7 +20,7 @@ from nanobot.webui.workspaces import WebUIWorkspaceController
_TEMPORARY_CHAT_DISABLED_TOOLS = frozenset({
"create_goal",
"update_goal",
"spawn",
"subagent",
"cron",
})
_TEMPORARY_CHAT_COMMANDS = frozenset({"/model", "/stop"})
+75 -31
View File
@@ -13,6 +13,7 @@ import threading
import time
import uuid
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Mapping, NamedTuple, Sequence, cast
from urllib.parse import unquote, urlparse
@@ -23,9 +24,10 @@ from nanobot.config.paths import get_webui_dir
from nanobot.runtime_context import public_history_message
from nanobot.session.automation_turns import is_automation_kind
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import SessionManager
from nanobot.session.manager import Session, SessionManager
from nanobot.utils.helpers import atomic_write_lines
from nanobot.webui.metadata import WEBUI_MESSAGE_SOURCE_METADATA_KEY, WEBUI_TURN_METADATA_KEY
from nanobot.webui.outbound_wire import project_tool_events
from nanobot.webui.session_identity import webui_chat_id, webui_session_key
WEBUI_TRANSCRIPT_SCHEMA_VERSION = 3
@@ -1374,36 +1376,8 @@ def write_session_messages_as_transcript(
messages: list[dict[str, Any]],
) -> None:
"""Write a minimal WebUI transcript from already-truncated session messages."""
target_chat_id = _chat_id_from_session_key(target_key)
rows: list[dict[str, Any]] = []
for msg in messages:
if is_hidden_history_message(msg):
continue
msg = public_history_message(msg)
role = msg.get("role")
content = msg.get("content")
text = content if isinstance(content, str) else ""
if role == "user":
row: dict[str, Any] = {"event": "user", "chat_id": target_chat_id, "text": text}
media = msg.get("media")
if isinstance(media, list) and media:
row["media_paths"] = [
str(p) for p in cast(list[Any], media) if isinstance(p, str) and p
]
for key in ("cli_apps", "mcp_presets", "session_mentions"):
value = msg.get(key)
if isinstance(value, list) and value:
row[key] = json.loads(json.dumps(value, ensure_ascii=False))
elif role == "assistant" and text.strip():
row = {"event": "message", "chat_id": target_chat_id, "text": text}
media = msg.get("media")
if isinstance(media, list) and media:
row["media"] = [
str(p) for p in cast(list[Any], media) if isinstance(p, str) and p
]
else:
continue
rows.append(row)
rows = [row for msg in messages
if (row := _session_user_event(target_key, msg) or _session_assistant_event(target_key, msg)) is not None]
_write_transcript_lines(target_key, rows)
@@ -2448,6 +2422,76 @@ def _client_projection_events(
return events, fork_boundary_event_index
def build_session_thread_response(
session: Session,
*,
active: bool = False,
latency_ms: int | None = None,
augment_user_media: Callable[[list[str]], list[dict[str, Any]]] | None = None,
augment_assistant_media: Callable[[list[str]], list[dict[str, Any]]] | None = None,
augment_assistant_text: Callable[[str], str] | None = None,
) -> dict[str, Any]:
"""Project a Session snapshot without creating a second display transcript."""
rows: list[dict[str, Any]] = []
chat_id = session.key.split(":", 1)[-1]
turn_id = f"session:{session.key}:0"
created_at_ms = int(session.created_at.timestamp() * 1000)
for index, message in enumerate(session.messages):
if is_hidden_history_message(message):
continue
if message.get("role") == "user":
turn_id = f"session:{session.key}:{index}"
timestamp = message.get("timestamp")
if isinstance(timestamp, str):
try:
created_at_ms = int(datetime.fromisoformat(timestamp).timestamp() * 1000)
except ValueError:
pass
records: list[dict[str, Any]] = []
row = _session_user_event(session.key, message) or _session_assistant_event(session.key, message)
reasoning = message.get("reasoning_content")
if message.get("role") == "assistant" and isinstance(reasoning, str) and reasoning:
records.append({"event": "message", "text": reasoning, "kind": "reasoning"})
calls = message.get("tool_calls")
has_calls = isinstance(calls, list) and len(cast(list[object], calls)) > 0
if row is not None and has_calls:
row["kind"] = "progress"
records.append(row)
if message.get("role") == "assistant":
tools = project_tool_events(_normalize_tool_events(message.get("tool_events")))
if tools:
records.append({"event": "message", "kind": "tool_hint",
"text": "\n".join(tool_trace_lines_from_events(tools)),
"tool_events": tools})
edits = message.get("file_edit_events")
if isinstance(edits, list) and edits:
records.append({"event": "file_edit", "edits": edits})
if row is not None and not has_calls:
records.append(row)
for offset, record in enumerate(records):
record.update({
"chat_id": chat_id, "turn_id": turn_id,
"turn_phase": "user" if record["event"] == "user" else
"reasoning" if record.get("kind") == "reasoning" else
"activity" if record["event"] == "file_edit" or record.get("kind") in {"progress", "tool_hint"}
else "answer",
"created_at_ms": created_at_ms,
_WEBUI_REPLAY_IDENTITY_KEY: f"session:{session.key}:{index}:{offset}",
})
rows.append(record)
if not active and rows:
rows.append({"event": "turn_end", "chat_id": chat_id,
"turn_id": turn_id, "latency_ms": latency_ms,
_WEBUI_REPLAY_IDENTITY_KEY: f"session:{session.key}:end"})
events = [event for record in rows if (event := _client_projection_event(
record, augment_user_media=augment_user_media, augment_assistant_media=augment_assistant_media,
augment_assistant_text=augment_assistant_text,
)) is not None]
return {"schemaVersion": WEBUI_TRANSCRIPT_SCHEMA_VERSION, "sessionKey": session.key,
"projection": "events", "events": events,
"active_turn_id": turn_id if active else None}
def build_webui_thread_response(
session_key: str,
*,
+97 -2
View File
@@ -26,6 +26,8 @@ from websockets.datastructures import Headers
from websockets.http11 import Request as WsRequest
from websockets.http11 import Response
from nanobot.agent.subagent import SubagentControlError
from nanobot.agent.subagent_status import SubagentSessionError
from nanobot.command.builtin import builtin_command_palette
from nanobot.cron.session_turns import is_bound_cron_job
from nanobot.cron.types import CronJob, CronSchedule
@@ -131,6 +133,7 @@ from nanobot.webui.star_prompt import update_star_prompt
from nanobot.webui.thread_disk import delete_webui_thread
from nanobot.webui.transcript import (
TranscriptReplayStats,
build_session_thread_response,
build_webui_thread_response,
build_webui_trace_detail_response,
webui_transcript_revision,
@@ -193,6 +196,7 @@ _WEBUI_MUTATION_PATHS = {
"workspace.pick_folder": "/api/workspaces/pick-folder",
"recovery.continue": "/api/webui/recovery/continue",
"recovery.dismiss": "/api/webui/recovery/dismiss",
"subagent.cancel": "/api/webui/subagents/cancel",
"settings.agent.update": "/api/settings/update",
"settings.model_configuration.create": "/api/settings/model-configurations/create",
"settings.model_configuration.update": "/api/settings/model-configurations/update",
@@ -266,6 +270,7 @@ for _ext, _ctype in _MIME_FIXES.items():
if TYPE_CHECKING:
from nanobot.agent.subagent import SubagentManager
from nanobot.bus.queue import MessageBus
from nanobot.channels.websocket.runtime import WebSocketConfig
from nanobot.cron.service import CronService
@@ -375,6 +380,8 @@ class GatewayHTTPHandler:
recovery_action: (
Callable[[str, dict[str, Any]], Awaitable[dict[str, Any]]] | None
) = None,
subagent_manager: SubagentManager | None = None,
discard_session: Callable[[str], Awaitable[None]] | None = None,
log: Any = logger,
) -> None:
self.config = config
@@ -398,6 +405,8 @@ class GatewayHTTPHandler:
)
self.skill_state_action = skill_state_action
self.recovery_action = recovery_action
self.subagent_manager = subagent_manager
self.discard_session = discard_session
self._skill_install_lock = asyncio.Lock()
self._folder_picker_lock = asyncio.Lock()
self.cron_service = cron_service
@@ -550,6 +559,7 @@ class GatewayHTTPHandler:
"/api/webui/star-prompt/dismiss",
"/api/webui/sidebar-state/update",
"/api/workspaces/pick-folder",
"/api/webui/subagents/cancel",
}
@staticmethod
@@ -606,6 +616,9 @@ class GatewayHTTPHandler:
if response is not None:
return response
if got == "/api/webui/subagents/cancel":
return await self._handle_subagent_cancel(request)
# Session routes
response = await self._dispatch_session_routes(request, got)
if response is not None:
@@ -756,6 +769,7 @@ class GatewayHTTPHandler:
),
"runtime_surface": self._runtime_surface,
"runtime_capabilities": self._capabilities,
"terminal": terminal,
}
return _http_json_response(payload, extra_headers=_NO_STORE_HEADERS)
@@ -845,9 +859,17 @@ class GatewayHTTPHandler:
if m:
return self._handle_session_automations(request, m.group(1))
m = re.fullmatch(r"/api/sessions/([^/]+)/subagents/([^/]+)/webui-thread", got)
if m:
return await asyncio.to_thread(self._handle_subagent_thread_get, request, m.group(1), m.group(2))
m = re.fullmatch(r"/api/sessions/([^/]+)/subagents", got)
if m:
return self._handle_subagents_get(request, m.group(1))
m = re.match(r"^/api/sessions/([^/]+)/delete$", got)
if m:
return self._handle_session_delete(request, m.group(1))
return await self._handle_session_delete(request, m.group(1))
return None
@@ -872,6 +894,75 @@ class GatewayHTTPHandler:
return _http_error(exc.status, str(exc))
return _http_json_response(result)
def _handle_subagents_get(self, request: WsRequest, key: str) -> Response:
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
session_key = _decode_api_key(key)
if session_key is None:
return _http_error(400, "invalid session key")
if not is_webui_session_key(session_key):
return _http_error(404, "session not found")
if self.subagent_manager is None:
return _http_error(503, "subagent manager unavailable")
try:
statuses = self.subagent_manager.statuses_for_session(session_key)
except (OSError, SubagentSessionError):
return _http_error(503, "task history unavailable")
return _http_json_response({
"tasks": [status.as_dict() for status in statuses.values()],
}, extra_headers=_NO_STORE_HEADERS)
async def _handle_subagent_cancel(self, request: WsRequest) -> Response:
if not getattr(request, _WEBUI_MUTATION_REQUEST_ATTR, False):
return _http_error(405, "Subagent cancellation requires an authenticated WebSocket")
if self.subagent_manager is None:
return _http_error(503, "subagent manager unavailable")
payload = _mutation_payload(request)
if payload is None:
return _http_error(400, "invalid subagent cancellation payload")
session_key, task_id = payload.get("session_key"), payload.get("task_id")
if not isinstance(session_key, str) or not is_webui_session_key(session_key):
return _http_error(400, "invalid session key")
if not isinstance(task_id, str) or not task_id.strip():
return _http_error(400, "missing task id")
try:
status = await self.subagent_manager.cancel(task_id, session_key)
except SubagentControlError:
return _http_error(404, "task unavailable")
except (OSError, SubagentSessionError):
return _http_error(503, "task history unavailable")
return _http_json_response(status.as_dict(), extra_headers=_NO_STORE_HEADERS)
def _handle_subagent_thread_get(self, request: WsRequest, key: str, task_id: str) -> Response:
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
session_key, decoded_task_id = _decode_api_key(key), _decode_api_key(task_id)
if session_key is None or decoded_task_id is None:
return _http_error(400, "invalid task key")
if not is_webui_session_key(session_key):
return _http_error(404, "task unavailable")
if self.subagent_manager is None:
return _http_error(503, "task history unavailable")
try:
status, child = self.subagent_manager.read_session(decoded_task_id, session_key)
except SubagentControlError:
return _http_error(404, "task unavailable")
except (OSError, SubagentSessionError):
return _http_error(503, "task history unavailable")
scope = self.workspaces.scope_for_session_key(session_key)
data = build_session_thread_response(
child,
active=status.state in {"queued", "running", "stopping"},
latency_ms=(int(max(0.0, status.finished_at - status.started_at) * 1000)
if status.finished_at is not None else None),
augment_user_media=self.media.augment_transcript_media,
augment_assistant_media=self.media.augment_transcript_media,
augment_assistant_text=lambda text: self.media.rewrite_local_markdown_images(
text, workspace_path=scope.project_path,
),
)
return _http_json_response(data, extra_headers=_NO_STORE_HEADERS)
async def _handle_session_context_get(self, request: WsRequest, key: str) -> Response:
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
@@ -1214,7 +1305,7 @@ class GatewayHTTPHandler:
)
)
def _handle_session_delete(self, request: WsRequest, key: str) -> Response:
async def _handle_session_delete(self, request: WsRequest, key: str) -> Response:
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
if self.session_manager is None:
@@ -1247,6 +1338,10 @@ class GatewayHTTPHandler:
elif self.cron_service is not None:
self.cron_service.remove_job(job.id)
draft_deleted = self.workspaces.discard_draft_scope(decoded_key)
if self.discard_session is not None:
await self.discard_session(decoded_key)
elif self.subagent_manager is not None:
await self.subagent_manager.cancel_by_session(decoded_key)
session_deleted = self.session_manager.delete_session(decoded_key)
transcript_deleted = delete_webui_thread(decoded_key)
return _http_json_response(