Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
refactor: isolate runtime contracts and enforce import boundaries (#6166)
chengyongru328e933d3654
diff --git a/.agent/design.md b/.agent/design.mdindex e60039ead..9ad59896f 100644--- a/.agent/design.md+++ b/.agent/design.md@@ -8,6 +8,18 @@ New capabilities should be added via `channels/`, `tools/`, skills, or MCP serveRuntime state fan-out follows the same boundary. `MessageBus.publish` awaits local subscribers for turn/run/model/goal state changes; `MessageBus.publish_event` queues routed channel delivery without waiting for network sends. Both carry `AgentEvent` values. Runner hooks publish typed output through the turn's scoped `EventSink`; direct-call callbacks are adapted at the execution boundary. WebUI/WebSocket wire details, title refreshes, and goal-state sync belong in `nanobot.session.webui_turns.WebuiTurnCoordinator` or the relevant channel adapter.+Tools and channels own their configuration, metadata, and activation behavior. Tool configuration models live beside their implementations in `agent/tools/*_config.py`; channel descriptors and configuration stay in their channel packages. The root schema in `config/schema.py` assembles these contracts without importing their runtime implementations. Tool classes expose their configuration through `config_key` and `config_cls()`.++Generic recovery checkpoints belong in `session/recovery.py`; WebUI recovery and turn coordination belong in `webui/recovery.py` and `session/webui_turns.py`. Gateway startup supplies WebUI turn policy. Channels own the pure address contract in `channels/notification_routes.py`, which core turn delivery consumes for default replies and durable notifications without loading channel runtime implementations.++## Executable import boundaries++Core execution, session storage, and security primitives stay independent of API, channel, CLI, and WebUI adapter implementations. Core may consume channel-owned pure address contracts, which must stay independent of runtime implementations. Shared client contracts stay independent of UI implementations, and client initialization dependencies must be acyclic.++Python rules live in [scripts/check_import_boundaries.py](../scripts/check_import_boundaries.py); run `python -m scripts.check_import_boundaries` from the repository root. Client rules live in [scripts/check_client_import_boundaries.mjs](../scripts/check_client_import_boundaries.mjs); run `bun run check:imports` and `bun run test:imports` from `webui/` or `tui/` for that project. These scripts are the source of truth for checked modules, dependency rules, and exceptions.++The checks cover selected direct imports and client initialization dependencies. They do not establish a complete runtime dependency graph; execution, state ownership, and security contracts still require behavioral verification.+## Prefer duplication over premature abstractionChannels and providers are allowed to repeat similar logic (send retries, media handling, message splitting). Do not introduce complex base classes or shared helpers just to eliminate duplication across channel files. Each channel file should remain self-contained and readable on its own. The same applies to provider implementations.@@ -22,4 +34,4 @@ Every new cast must be supported by a boundary check or an invariant established## Explicit over magical-Configuration belongs in `config/schema.py` Pydantic models. Provider auto-detection must remain traceable from the factory to the concrete provider class.+Provider auto-detection must remain traceable from the factory to the concrete provider class.diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 8b2c7f94d..8869159f8 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -104,6 +104,10 @@ jobs:python_required=truedocker_required=true;;+ scripts/check_client_import_boundaries.*)+ webui_required=true+ tui_required=true+ ;;tests/*|conftest.py|uv.lock|scripts/*)python_required=true;;@@ -172,6 +176,10 @@ jobs:with:python-version: ${{ matrix.python-version }}+ - name: Check Python import boundaries+ if: matrix.coverage+ run: python -m scripts.check_import_boundaries+- name: Install uvuses: astral-sh/setup-uv@v4with:@@ -195,7 +203,7 @@ jobs:# later uv run sync pruning the packages installed by the previous step.- name: Lint with ruffif: matrix.coverage- run: uv run --no-sync ruff check nanobot tests conftest.py+ run: uv run --no-sync ruff check nanobot tests conftest.py scripts/check_import_boundaries.py- name: Type check with BasedPyright (strict)if: matrix.coverage@@ -290,6 +298,14 @@ jobs:working-directory: webuirun: bun install --frozen-lockfile+ - name: Check WebUI import boundaries+ working-directory: webui+ run: bun run check:imports++ - name: Test client import checker with WebUI dependencies+ working-directory: webui+ run: bun run test:imports+- name: Lint WebUIworking-directory: webuirun: bun run lint@@ -331,6 +347,14 @@ jobs:working-directory: tuirun: bun install --frozen-lockfile+ - name: Check TUI import boundaries+ working-directory: tui+ run: bun run check:imports++ - name: Test client import checker with TUI dependencies+ working-directory: tui+ run: bun run test:imports+- name: Check TUIworking-directory: tuirun: bun run checkdiff --git a/conftest.py b/conftest.pyindex 1db713017..e7ddcd636 100644--- a/conftest.py+++ b/conftest.py@@ -63,7 +63,7 @@ def _isolate_sessions_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Idef _isolate_llm_usage_stores(tmp_path: Path, monkeypatch: pytest.MonkeyPatch,) -> Iterator[None]:- from nanobot import llm_usage+ import nanobot.llm_usage.service as llm_usagestores: dict[Path, llm_usage.LLMUsageStore] = {}monkeypatch.setattr(llm_usage, "_STORES", stores)diff --git a/nanobot/__init__.py b/nanobot/__init__.pyindex ac09e67e1..d562b7902 100644--- a/nanobot/__init__.py+++ b/nanobot/__init__.py@@ -57,7 +57,7 @@ __logo__ = "🐈"_LAZY_EXPORTS = {"Nanobot": ".nanobot",- "LLMUsage": ".nanobot",+ "LLMUsage": ".llm_usage.types","RunStream": ".nanobot","RunResult": ".nanobot","RequestContext": ".agent.tools.context",diff --git a/nanobot/agent/__init__.py b/nanobot/agent/__init__.pyindex 8b4a0548a..1464d8a3f 100644--- a/nanobot/agent/__init__.py+++ b/nanobot/agent/__init__.py@@ -1,18 +1,53 @@"""Agent core module."""-from nanobot.agent.context import ContextBuilder-from nanobot.agent.hook import (- AgentHook,- AgentHookContext,- AgentRunHookContext,- AgentTurnHookContext,- AgentTurnHookFactory,- CompositeHook,-)-from nanobot.agent.loop import AgentLoop-from nanobot.agent.memory import MemoryStore-from nanobot.agent.skills import SkillsLoader-from nanobot.agent.subagent import SubagentManager+from __future__ import annotations++from importlib import import_module+from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ from nanobot.agent.context import ContextBuilder+ from nanobot.agent.hook import (+ AgentHook,+ AgentHookContext,+ AgentRunHookContext,+ AgentTurnHookContext,+ AgentTurnHookFactory,+ CompositeHook,+ )+ from nanobot.agent.loop import AgentLoop+ from nanobot.agent.memory import MemoryStore+ from nanobot.agent.skills import SkillsLoader+ from nanobot.agent.subagent import SubagentManager+++_EXPORTS = {+ "AgentHook": "nanobot.agent.hook",+ "AgentHookContext": "nanobot.agent.hook",+ "AgentRunHookContext": "nanobot.agent.hook",+ "AgentTurnHookContext": "nanobot.agent.hook",+ "AgentTurnHookFactory": "nanobot.agent.hook",+ "AgentLoop": "nanobot.agent.loop",+ "CompositeHook": "nanobot.agent.hook",+ "ContextBuilder": "nanobot.agent.context",+ "MemoryStore": "nanobot.agent.memory",+ "SkillsLoader": "nanobot.agent.skills",+ "SubagentManager": "nanobot.agent.subagent",+}+++def __getattr__(name: str) -> Any:+ module_name = _EXPORTS.get(name)+ if module_name is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ value = getattr(import_module(module_name), name)+ globals()[name] = value+ return value+++def __dir__() -> list[str]:+ return sorted(set(globals()) | set(_EXPORTS))+__all__ = ["AgentHook",diff --git a/nanobot/agent/memory.py b/nanobot/agent/memory.pyindex 567d213c4..ebdac8b20 100644--- a/nanobot/agent/memory.py+++ b/nanobot/agent/memory.py@@ -500,7 +500,7 @@ class MemoryStore:@staticmethoddef default_dream_prompt() -> str:- from nanobot.agent.skills import BUILTIN_SKILLS_DIR+ from nanobot.agent.skill_metadata import BUILTIN_SKILLS_DIRreturn render_template("agent/dream.md",@@ -558,7 +558,7 @@ class MemoryStore:def build_dream_tools(self) -> ToolRegistry:"""Build the restricted tool registry used by Dream runs."""- from nanobot.agent.skills import BUILTIN_SKILLS_DIR+ from nanobot.agent.skill_metadata import BUILTIN_SKILLS_DIRfrom nanobot.agent.tools.apply_patch import ApplyPatchToolfrom nanobot.agent.tools.file_state import FileStatesfrom nanobot.agent.tools.filesystem import EditFileTool, ReadFileTool, WriteFileTooldiff --git a/nanobot/agent/plugins.py b/nanobot/agent/plugins.pyindex e369e1479..5713108b9 100644--- a/nanobot/agent/plugins.py+++ b/nanobot/agent/plugins.py@@ -13,7 +13,7 @@ from typing import castfrom loguru import loggerfrom pydantic import ValidationError-from nanobot.agent.skills import parse_skill_metadata, valid_skill_metadata+from nanobot.agent.skill_metadata import parse_skill_metadata, valid_skill_metadatafrom nanobot.config.loader import get_config_pathfrom nanobot.config.schema import MCPServerConfigdiff --git a/nanobot/agent/skill_metadata.py b/nanobot/agent/skill_metadata.pynew file mode 100644index 000000000..3d7f927ed--- /dev/null+++ b/nanobot/agent/skill_metadata.py@@ -0,0 +1,43 @@+"""Skill resource locations and validated YAML identity metadata."""++import re+from pathlib import Path+from typing import cast++import yaml++BUILTIN_SKILLS_DIR = Path(__file__).parent.parent / "skills"+++SKILL_FRONTMATTER = re.compile(+ r"^---\s*\r?\n(.*?)\r?\n---\s*\r?\n?",+ re.DOTALL,+)+++SKILL_NAME = re.compile(r"^(?!.*--)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$")+++def parse_skill_metadata(content: str) -> dict[str, object] | None:+ """Parse a skill document's YAML frontmatter."""+ if not (match := SKILL_FRONTMATTER.match(content)):+ return None+ try:+ parsed = yaml.safe_load(match.group(1))+ except yaml.YAMLError:+ return None+ if not isinstance(parsed, dict):+ return None+ return {str(key): value for key, value in cast(dict[object, object], parsed).items()}+++def valid_skill_metadata(metadata: dict[str, object], name: str) -> bool:+ """Return whether metadata satisfies the Agent Skills identity contract."""+ description = metadata.get("description")+ return (+ metadata.get("name") == name+ and len(name) <= 64+ and SKILL_NAME.fullmatch(name) is not None+ and isinstance(description, str)+ and 1 <= len(description.strip()) <= 1024+ )diff --git a/nanobot/agent/skills.py b/nanobot/agent/skills.pyindex e862826bf..e25599c39 100644--- a/nanobot/agent/skills.py+++ b/nanobot/agent/skills.py@@ -7,47 +7,23 @@ import shutilfrom pathlib import Pathfrom typing import Any, cast-import yaml-+from nanobot.agent.skill_metadata import (+ BUILTIN_SKILLS_DIR as BUILTIN_SKILLS_DIR,+)+from nanobot.agent.skill_metadata import (+ SKILL_FRONTMATTER as _STRIP_SKILL_FRONTMATTER,+)+from nanobot.agent.skill_metadata import (+ parse_skill_metadata as parse_skill_metadata,+)+from nanobot.agent.skill_metadata import (+ valid_skill_metadata as valid_skill_metadata,+)from nanobot.runtime_context import RuntimeContextBlock-# Default builtin skills directory (relative to this file)-BUILTIN_SKILLS_DIR = Path(__file__).parent.parent / "skills"--# Opening ---, YAML body (group 1), closing --- on its own line; supports CRLF.-_STRIP_SKILL_FRONTMATTER = re.compile(- r"^---\s*\r?\n(.*?)\r?\n---\s*\r?\n?",- re.DOTALL,-)-_SKILL_NAME = re.compile(r"^(?!.*--)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$")_SKILL_REFERENCE = re.compile(r"(?<![\w$])\$([A-Za-z0-9_-]+)")-def parse_skill_metadata(content: str) -> dict[str, object] | None:- """Parse a skill document's YAML frontmatter."""- if not (match := _STRIP_SKILL_FRONTMATTER.match(content)):- return None- try:- parsed = yaml.safe_load(match.group(1))- except yaml.YAMLError:- return None- if not isinstance(parsed, dict):- return None- return {str(key): value for key, value in cast(dict[object, object], parsed).items()}---def valid_skill_metadata(metadata: dict[str, object], name: str) -> bool:- """Return whether metadata satisfies the Agent Skills identity contract."""- description = metadata.get("description")- return (- metadata.get("name") == name- and len(name) <= 64- and _SKILL_NAME.fullmatch(name) is not None- and isinstance(description, str)- and 1 <= len(description.strip()) <= 1024- )--class SkillsLoader:"""Loader for agent skills.diff --git a/nanobot/agent/tools/__init__.py b/nanobot/agent/tools/__init__.pyindex 882a482b1..75cfcb88c 100644--- a/nanobot/agent/tools/__init__.py+++ b/nanobot/agent/tools/__init__.py@@ -1,18 +1,56 @@-"""Agent tools module."""--from nanobot.agent.tools.base import Schema, Tool, ToolResult, tool_parameters-from nanobot.agent.tools.context import ToolContext-from nanobot.agent.tools.loader import ToolLoader-from nanobot.agent.tools.registry import ToolRegistry-from nanobot.agent.tools.schema import (- ArraySchema,- BooleanSchema,- IntegerSchema,- NumberSchema,- ObjectSchema,- StringSchema,- tool_parameters_schema,-)+"""Public tool contracts and discovery interfaces."""++from __future__ import annotations++from importlib import import_module+from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ from nanobot.agent.tools.base import Schema, Tool, ToolResult, tool_parameters+ from nanobot.agent.tools.context import ToolContext+ from nanobot.agent.tools.loader import ToolLoader+ from nanobot.agent.tools.registry import ToolRegistry+ from nanobot.agent.tools.schema import (+ ArraySchema,+ BooleanSchema,+ IntegerSchema,+ NumberSchema,+ ObjectSchema,+ StringSchema,+ tool_parameters_schema,+ )+++_EXPORTS = {+ "Schema": "nanobot.agent.tools.base",+ "ArraySchema": "nanobot.agent.tools.schema",+ "BooleanSchema": "nanobot.agent.tools.schema",+ "IntegerSchema": "nanobot.agent.tools.schema",+ "NumberSchema": "nanobot.agent.tools.schema",+ "ObjectSchema": "nanobot.agent.tools.schema",+ "StringSchema": "nanobot.agent.tools.schema",+ "Tool": "nanobot.agent.tools.base",+ "ToolContext": "nanobot.agent.tools.context",+ "ToolLoader": "nanobot.agent.tools.loader",+ "ToolResult": "nanobot.agent.tools.base",+ "ToolRegistry": "nanobot.agent.tools.registry",+ "tool_parameters": "nanobot.agent.tools.base",+ "tool_parameters_schema": "nanobot.agent.tools.schema",+}+++def __getattr__(name: str) -> Any:+ module_name = _EXPORTS.get(name)+ if module_name is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ value = getattr(import_module(module_name), name)+ globals()[name] = value+ return value+++def __dir__() -> list[str]:+ return sorted(set(globals()) | set(_EXPORTS))+__all__ = ["Schema",diff --git a/nanobot/agent/tools/cli_apps.py b/nanobot/agent/tools/cli_apps.pyindex 76758a386..382257a45 100644--- a/nanobot/agent/tools/cli_apps.py+++ b/nanobot/agent/tools/cli_apps.py@@ -6,9 +6,8 @@ from __future__ import annotationsfrom pathlib import Path-from pydantic import Field-from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters+from nanobot.agent.tools.cli_apps_config import CliAppsToolConfigfrom nanobot.agent.tools.context import RequestContext, ToolContextfrom nanobot.agent.tools.schema import (ArraySchema,@@ -19,20 +18,10 @@ from nanobot.agent.tools.schema import ()from nanobot.apps.cli import CliAppError, CliAppManager, CliAppsRuntimeConfigfrom nanobot.apps.cli.utils import runtime_lines_for_request-from nanobot.config_base import Basefrom nanobot.runtime_context import RuntimeContextBlock, wrap_runtime_context_linesfrom nanobot.security.workspace_access import current_tool_workspace-class CliAppsToolConfig(Base):- """CLI Apps tool configuration."""-- enable: bool = True- install_timeout: int = Field(default=300, ge=1, le=3600)- run_timeout: int = Field(default=60, ge=1, le=600)- catalog_ttl_seconds: int = Field(default=3600, ge=60, le=86_400)--@tool_parameters(tool_parameters_schema(required=["name"],diff --git a/nanobot/agent/tools/cli_apps_config.py b/nanobot/agent/tools/cli_apps_config.pynew file mode 100644index 000000000..5eaecc997--- /dev/null+++ b/nanobot/agent/tools/cli_apps_config.py@@ -0,0 +1,14 @@+"""CLI Apps configuration shared by the tool and root schema."""++from pydantic import Field++from nanobot.config_base import Base+++class CliAppsToolConfig(Base):+ """CLI Apps tool configuration."""++ enable: bool = True+ install_timeout: int = Field(default=300, ge=1, le=3600)+ run_timeout: int = Field(default=60, ge=1, le=600)+ catalog_ttl_seconds: int = Field(default=3600, ge=60, le=86_400)diff --git a/nanobot/agent/tools/exec_session.py b/nanobot/agent/tools/exec_session.pyindex c75d4fa51..28452de79 100644--- a/nanobot/agent/tools/exec_session.py+++ b/nanobot/agent/tools/exec_session.py@@ -26,6 +26,7 @@ from nanobot.agent.tools.schema import (StringSchema,tool_parameters_schema,)+from nanobot.agent.tools.shell_config import ExecToolConfigDEFAULT_YIELD_MS = 1000MAX_YIELD_MS = 30_000@@ -583,8 +584,6 @@ class ExecSessionTool(Tool):@classmethoddef config_cls(cls):- from nanobot.agent.tools.shell import ExecToolConfig-return ExecToolConfig@classmethod@@ -744,8 +743,6 @@ class ListExecSessionsTool(Tool):@classmethoddef config_cls(cls):- from nanobot.agent.tools.shell import ExecToolConfig-return ExecToolConfig@classmethoddiff --git a/nanobot/agent/tools/filesystem.py b/nanobot/agent/tools/filesystem.pyindex dd6c1b87b..d133143e0 100644--- a/nanobot/agent/tools/filesystem.py+++ b/nanobot/agent/tools/filesystem.py@@ -12,6 +12,7 @@ from typing import Anyfrom nanobot.agent.tools.base import Tool, ToolResult, tool_parametersfrom nanobot.agent.tools.context import ToolContextfrom nanobot.agent.tools.file_state import FileStates, current_file_states+from nanobot.agent.tools.filesystem_config import FileToolsConfigfrom nanobot.agent.tools.path_utils import resolve_workspace_pathfrom nanobot.agent.tools.schema import (BooleanSchema,@@ -19,18 +20,11 @@ from nanobot.agent.tools.schema import (StringSchema,tool_parameters_schema,)-from nanobot.config_base import Basefrom nanobot.security.workspace_access import current_tool_workspacefrom nanobot.utils.file_edit_events import FileDiff, FileEditResult, display_file_edit_pathfrom nanobot.utils.helpers import build_image_content_blocks, detect_image_mime-class FileToolsConfig(Base):- """Filesystem tools configuration."""-- enable: bool = True # built-in file tools on by default--class _FsTool(Tool):"""Shared base for filesystem tools — common init and path resolution."""@@ -82,7 +76,7 @@ class _FsTool(Tool):@classmethoddef create(cls, ctx: ToolContext) -> Tool:- from nanobot.agent.skills import BUILTIN_SKILLS_DIR+ from nanobot.agent.skill_metadata import BUILTIN_SKILLS_DIRagent_workspace = Path(ctx.workspace)resolved_agent_workspace = agent_workspace.expanduser().resolve(strict=False)@@ -233,7 +227,7 @@ def _is_blocked_device(path: str | Path) -> bool:def _builtin_skill_read_path(path: str) -> Path | None:"""Map workspace-relative skills/<name>/... reads onto bundled skills."""- from nanobot.agent.skills import BUILTIN_SKILLS_DIR+ from nanobot.agent.skill_metadata import BUILTIN_SKILLS_DIRrequested = Path(path)if requested.is_absolute():diff --git a/nanobot/agent/tools/filesystem_config.py b/nanobot/agent/tools/filesystem_config.pynew file mode 100644index 000000000..576d4c2e1--- /dev/null+++ b/nanobot/agent/tools/filesystem_config.py@@ -0,0 +1,9 @@+"""Filesystem configuration shared by the tools and root schema."""++from nanobot.config_base import Base+++class FileToolsConfig(Base):+ """Filesystem tools configuration."""++ enable: bool = Truediff --git a/nanobot/agent/tools/image_generation.py b/nanobot/agent/tools/image_generation.pyindex 4422b3dc4..9abbe16f2 100644--- a/nanobot/agent/tools/image_generation.py+++ b/nanobot/agent/tools/image_generation.py@@ -7,9 +7,9 @@ from pathlib import Pathfrom typing import TYPE_CHECKING, Anyfrom loguru import logger-from pydantic import Fieldfrom nanobot.agent.tools.base import Tool, ToolResult, tool_parameters+from nanobot.agent.tools.image_generation_config import ImageGenerationToolConfigfrom nanobot.agent.tools.registry import ToolRegistryfrom nanobot.agent.tools.schema import (ArraySchema,@@ -18,7 +18,6 @@ from nanobot.agent.tools.schema import (tool_parameters_schema,)from nanobot.config.paths import get_media_dir-from nanobot.config_base import Basefrom nanobot.providers.image_generation import (ImageGenerationError,ImageGenerationProvider,@@ -39,19 +38,6 @@ if TYPE_CHECKING:from nanobot.config.schema import Config, ProviderConfig-class ImageGenerationToolConfig(Base):- """Image generation tool configuration."""- enabled: bool = False- provider: str = "openrouter"- model: str = "openai/gpt-5.4-image-2"- default_aspect_ratio: str = "1:1"- default_image_size: str = "1K"- max_images_per_turn: int = Field(default=4, ge=1, le=8)- save_dir: str = "generated"- extra_headers: dict[str, str] | None = Field(default=None, repr=False)- extra_body: dict[str, Any] | None = Field(default=None, repr=False)--@tool_parameters(tool_parameters_schema(prompt=StringSchema(diff --git a/nanobot/agent/tools/image_generation_config.py b/nanobot/agent/tools/image_generation_config.pynew file mode 100644index 000000000..66cdc100b--- /dev/null+++ b/nanobot/agent/tools/image_generation_config.py@@ -0,0 +1,20 @@+"""Image generation configuration shared by the tool and root schema."""++from typing import Any++from pydantic import Field++from nanobot.config_base import Base+++class ImageGenerationToolConfig(Base):+ """Image generation tool configuration."""+ enabled: bool = False+ provider: str = "openrouter"+ model: str = "openai/gpt-5.4-image-2"+ default_aspect_ratio: str = "1:1"+ default_image_size: str = "1K"+ max_images_per_turn: int = Field(default=4, ge=1, le=8)+ save_dir: str = "generated"+ extra_headers: dict[str, str] | None = Field(default=None, repr=False)+ extra_body: dict[str, Any] | None = Field(default=None, repr=False)diff --git a/nanobot/agent/tools/self.py b/nanobot/agent/tools/self.pyindex e7155cb55..cf74b2683 100644--- a/nanobot/agent/tools/self.py+++ b/nanobot/agent/tools/self.py@@ -19,18 +19,12 @@ from nanobot.agent.tools.runtime_control import (RuntimeControl,RuntimeSnapshot,)-from nanobot.config_base import Base+from nanobot.agent.tools.self_config import MyToolConfigif TYPE_CHECKING:from nanobot.agent.tools.context import ToolContext-class MyToolConfig(Base):- """Self-inspection tool configuration."""- enable: bool = True- allow_set: bool = False--def _is_string_mapping(value: object) -> TypeGuard[Mapping[str, object]]:if not isinstance(value, Mapping):return Falsediff --git a/nanobot/agent/tools/self_config.py b/nanobot/agent/tools/self_config.pynew file mode 100644index 000000000..167b6469d--- /dev/null+++ b/nanobot/agent/tools/self_config.py@@ -0,0 +1,9 @@+"""Self-inspection configuration shared by the tool and root schema."""++from nanobot.config_base import Base+++class MyToolConfig(Base):+ """Self-inspection tool configuration."""+ enable: bool = True+ allow_set: bool = Falsediff --git a/nanobot/agent/tools/shell.py b/nanobot/agent/tools/shell.pyindex 98524d662..24eabdfe0 100644--- a/nanobot/agent/tools/shell.py+++ b/nanobot/agent/tools/shell.py@@ -17,7 +17,6 @@ from typing import Any, Protocol, castfrom urllib.parse import unquotefrom loguru import logger-from pydantic import Fieldfrom nanobot.agent.tools.base import Tool, ToolResult, tool_parametersfrom nanobot.agent.tools.context import ToolContext, current_request_session_key@@ -38,8 +37,8 @@ from nanobot.agent.tools.schema import (StringSchema,tool_parameters_schema,)+from nanobot.agent.tools.shell_config import ExecToolConfigfrom nanobot.config.paths import get_media_dir-from nanobot.config_base import Basefrom nanobot.security.workspace_access import current_scope_allows_loopback, current_tool_workspacefrom nanobot.security.workspace_policy import is_path_within@@ -91,20 +90,6 @@ _WORKSPACE_BOUNDARY_NOTE = ()-class ExecToolConfig(Base):- """Shell exec tool configuration."""- enable: bool = True- timeout: int = Field(default=60, ge=0) # Hard timeout (s); 0 = no limit. Not capped by the per-call max.- path_prepend: str = ""- path_append: str = ""- sandbox: str = ""- sandbox_ro_binds: list[str] = Field(default_factory=list)- sandbox_rw_binds: list[str] = Field(default_factory=list)- allowed_env_keys: list[str] = Field(default_factory=list)- allow_patterns: list[str] = Field(default_factory=list)- deny_patterns: list[str] = Field(default_factory=list)--@dataclass(slots=True)class _PreparedCommand:command: str | list[str]diff --git a/nanobot/agent/tools/shell_config.py b/nanobot/agent/tools/shell_config.pynew file mode 100644index 000000000..8010c85a9--- /dev/null+++ b/nanobot/agent/tools/shell_config.py@@ -0,0 +1,19 @@+"""Execution configuration shared by shell/session tools and the root schema."""++from pydantic import Field++from nanobot.config_base import Base+++class ExecToolConfig(Base):+ """Shell exec tool configuration."""+ enable: bool = True+ timeout: int = Field(default=60, ge=0) # Hard timeout (s); 0 = no limit. Not capped by the per-call max.+ path_prepend: str = ""+ path_append: str = ""+ sandbox: str = ""+ sandbox_ro_binds: list[str] = Field(default_factory=list)+ sandbox_rw_binds: list[str] = Field(default_factory=list)+ allowed_env_keys: list[str] = Field(default_factory=list)+ allow_patterns: list[str] = Field(default_factory=list)+ deny_patterns: list[str] = Field(default_factory=list)diff --git a/nanobot/agent/tools/web.py b/nanobot/agent/tools/web.pyindex f7bea1f19..d2650c9c6 100644--- a/nanobot/agent/tools/web.py+++ b/nanobot/agent/tools/web.py@@ -15,7 +15,6 @@ from urllib.parse import parse_qsl, quote, urljoin, urlparseimport httpxfrom loguru import logger-from pydantic import Fieldfrom nanobot.agent.tools.base import Tool, ToolResult, tool_parametersfrom nanobot.agent.tools.context import ToolContext, tool_log_content_allowed@@ -25,7 +24,7 @@ from nanobot.agent.tools.schema import (StringSchema,tool_parameters_schema,)-from nanobot.config_base import Base+from nanobot.agent.tools.web_config import WebFetchConfig, WebSearchConfig, WebToolsConfigfrom nanobot.utils.helpers import build_image_content_blocks# Shared constants@@ -60,29 +59,6 @@ SEARCH_PROVIDER_OPTIONS: tuple[dict[str, str], ...] = ()-class WebSearchConfig(Base):- """Web search configuration."""- provider: str = "duckduckgo"- api_key: str = ""- base_url: str = ""- max_results: int = 5- timeout: int = 30---class WebFetchConfig(Base):- """Web fetch tool configuration."""- use_jina_reader: bool = True---class WebToolsConfig(Base):- """Web tools configuration."""- enable: bool = True- proxy: str | None = None- user_agent: str | None = None- search: WebSearchConfig = Field(default_factory=WebSearchConfig)- fetch: WebFetchConfig = Field(default_factory=WebFetchConfig)--def _strip_tags(text: str) -> str:"""Remove HTML tags and decode entities."""text = re.sub(r'<script[\s\S]*?</script>', '', text, flags=re.I)diff --git a/nanobot/agent/tools/web_config.py b/nanobot/agent/tools/web_config.pynew file mode 100644index 000000000..761e5cb88--- /dev/null+++ b/nanobot/agent/tools/web_config.py@@ -0,0 +1,28 @@+"""Web configuration shared by search/fetch tools and the root schema."""++from pydantic import Field++from nanobot.config_base import Base+++class WebSearchConfig(Base):+ """Web search configuration."""+ provider: str = "duckduckgo"+ api_key: str = ""+ base_url: str = ""+ max_results: int = 5+ timeout: int = 30+++class WebFetchConfig(Base):+ """Web fetch tool configuration."""+ use_jina_reader: bool = True+++class WebToolsConfig(Base):+ """Web tools configuration."""+ enable: bool = True+ proxy: str | None = None+ user_agent: str | None = None+ search: WebSearchConfig = Field(default_factory=WebSearchConfig)+ fetch: WebFetchConfig = Field(default_factory=WebFetchConfig)diff --git a/nanobot/agent/turn_delivery.py b/nanobot/agent/turn_delivery.pyindex e8d274140..a3204e31a 100644--- a/nanobot/agent/turn_delivery.py+++ b/nanobot/agent/turn_delivery.py@@ -19,7 +19,7 @@ from nanobot.bus.outbound_events import ()from nanobot.bus.queue import MessageBusfrom nanobot.bus.runtime_events import RuntimeEventPublisher-from nanobot.channels.notification_routes import notification_metadata+from nanobot.channels.notification_routes import notification_metadata, system_reply_metadatafrom nanobot.events import (AgentEvent,ContextCompactionEvent,@@ -180,13 +180,7 @@ class TurnDeliveryFactory:channel, chat_id = (msg.chat_id.split(":", 1) if ":" in msg.chat_id else ("cli", msg.chat_id))- metadata: dict[str, Any] = {}- if (- channel == "slack"- and session_key.startswith("slack:")- and session_key.count(":") >= 2- ):- metadata["slack"] = {"thread_ts": session_key.split(":", 2)[2]}+ metadata = system_reply_metadata(channel, session_key)if origin_message_id := msg.metadata.get("origin_message_id"):metadata["origin_message_id"] = origin_message_idreturn TurnRoute(channel=channel, chat_id=chat_id, metadata=metadata)diff --git a/nanobot/apps/cli/service.py b/nanobot/apps/cli/service.pyindex e58260c4b..3131df9ef 100644--- a/nanobot/apps/cli/service.py+++ b/nanobot/apps/cli/service.py@@ -20,7 +20,7 @@ from urllib.parse import urlparseimport httpxfrom loguru import logger-from nanobot.agent.skills import parse_skill_metadata, valid_skill_metadata+from nanobot.agent.skill_metadata import parse_skill_metadata, valid_skill_metadatafrom nanobot.apps.protocol import app_manifest, compact_dictfrom nanobot.config.paths import get_runtime_subdirfrom nanobot.security.workspace_policy import is_path_withindiff --git a/nanobot/bus/events.py b/nanobot/bus/events.pyindex 8c228a92a..788029f03 100644--- a/nanobot/bus/events.py+++ b/nanobot/bus/events.py@@ -18,6 +18,9 @@ INBOUND_META_RUNTIME_CONTROL = "_runtime_control"INBOUND_META_USER_SHELL = "_user_shell"RUNTIME_CONTROL_SESSION_DISCARD = "session_discard"+# Transport-provided turn correlation; the persisted spelling is retained for clients.+INBOUND_META_TURN_ID = "webui_turn_id"+@dataclassclass InboundMessage:diff --git a/nanobot/channels/dingtalk/runtime.py b/nanobot/channels/dingtalk/runtime.pyindex 9018d7271..86d0a1cbd 100644--- a/nanobot/channels/dingtalk/runtime.py+++ b/nanobot/channels/dingtalk/runtime.py@@ -20,7 +20,7 @@ from pydantic import Fieldfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannel-from nanobot.config.schema import Base+from nanobot.config_base import Basefrom nanobot.events import ContextCompactionEventfrom nanobot.security.network import validate_resolved_url, validate_url_targetdiff --git a/nanobot/channels/dingtalk/webui/index.ts b/nanobot/channels/dingtalk/webui/index.tsindex 26a02e23d..0c4bb8f5d 100644--- a/nanobot/channels/dingtalk/webui/index.ts+++ b/nanobot/channels/dingtalk/webui/index.ts@@ -1,5 +1,5 @@import type { ChannelUiContribution } from "@/channel-plugins/types";-import { chatAppGuideUrl } from "@/components/settings/channels/catalog";+import { chatAppGuideUrl } from "@/channel-plugins/catalog";export default {presentation: {diff --git a/nanobot/channels/discord/runtime.py b/nanobot/channels/discord/runtime.pyindex e74ec97d5..7257b515a 100644--- a/nanobot/channels/discord/runtime.py+++ b/nanobot/channels/discord/runtime.py@@ -19,7 +19,7 @@ from nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannelfrom nanobot.command.builtin import build_help_textfrom nanobot.config.paths import get_media_dir-from nanobot.config.schema import Base+from nanobot.config_base import Basefrom nanobot.utils.helpers import safe_filename, split_messageDISCORD_AVAILABLE = importlib.util.find_spec("discord") is not Nonediff --git a/nanobot/channels/discord/webui/index.ts b/nanobot/channels/discord/webui/index.tsindex f59324dee..3c5b129da 100644--- a/nanobot/channels/discord/webui/index.ts+++ b/nanobot/channels/discord/webui/index.ts@@ -1,5 +1,5 @@import type { ChannelUiContribution } from "@/channel-plugins/types";-import { chatAppGuideUrl } from "@/components/settings/channels/catalog";+import { chatAppGuideUrl } from "@/channel-plugins/catalog";export default {presentation: {diff --git a/nanobot/channels/email/runtime.py b/nanobot/channels/email/runtime.pyindex 6aa0912d8..6ee202f1e 100644--- a/nanobot/channels/email/runtime.py+++ b/nanobot/channels/email/runtime.py@@ -28,7 +28,7 @@ from nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannelfrom nanobot.config.paths import get_media_dir-from nanobot.config.schema import Base+from nanobot.config_base import Basefrom nanobot.events import ContextCompactionEventfrom nanobot.utils.helpers import safe_filenamediff --git a/nanobot/channels/email/webui/index.ts b/nanobot/channels/email/webui/index.tsindex 2952ee7d1..6baa2c203 100644--- a/nanobot/channels/email/webui/index.ts+++ b/nanobot/channels/email/webui/index.ts@@ -4,7 +4,7 @@ import type { ChannelUiContribution } from "@/channel-plugins/types";import {type ChannelProviderPresetDefinition,chatAppGuideUrl,-} from "@/components/settings/channels/catalog";+} from "@/channel-plugins/catalog";const EMAIL_PROVIDER_PRESETS: ChannelProviderPresetDefinition[] = [{diff --git a/nanobot/channels/feishu/config.py b/nanobot/channels/feishu/config.pyindex 37e4aa3e5..4b208bfa4 100644--- a/nanobot/channels/feishu/config.py+++ b/nanobot/channels/feishu/config.py@@ -4,7 +4,7 @@ from typing import Literalfrom pydantic import Field-from nanobot.config.schema import Base+from nanobot.config_base import Baseclass FeishuConfig(Base):diff --git a/nanobot/channels/feishu/webui/index.tsx b/nanobot/channels/feishu/webui/index.tsxindex eb6902d17..0243c58c5 100644--- a/nanobot/channels/feishu/webui/index.tsx+++ b/nanobot/channels/feishu/webui/index.tsx@@ -1,7 +1,7 @@import { lazy } from "react";import type { ChannelUiContribution } from "@/channel-plugins/types";-import { chatAppGuideUrl } from "@/components/settings/channels/catalog";+import { chatAppGuideUrl } from "@/channel-plugins/catalog";const FeishuAssistantsPanel = lazy(() =>import("./FeishuAssistantsPanel").then(({ FeishuAssistantsPanel: component }) => ({diff --git a/nanobot/channels/linear/webui/LinearResetConnection.tsx b/nanobot/channels/linear/webui/LinearResetConnection.tsxindex d1f4a2a59..ebc4e3635 100644--- a/nanobot/channels/linear/webui/LinearResetConnection.tsx+++ b/nanobot/channels/linear/webui/LinearResetConnection.tsx@@ -3,7 +3,7 @@ import { Loader2 } from "lucide-react";import { useTranslation } from "react-i18next";import { channelTranslator } from "@/channel-plugins/i18n";-import type { ChannelConfigField } from "@/components/settings/channels/catalog";+import type { ChannelConfigField } from "@/channel-plugins/catalog";import { channelFieldInputId, defaultChannelFieldValues } from "@/components/settings/channels/CredentialForm";import { Button } from "@/components/ui/button";import {diff --git a/nanobot/channels/linear/webui/LinearSecretField.tsx b/nanobot/channels/linear/webui/LinearSecretField.tsxindex 2d5b0fd75..38d896e74 100644--- a/nanobot/channels/linear/webui/LinearSecretField.tsx+++ b/nanobot/channels/linear/webui/LinearSecretField.tsx@@ -3,7 +3,7 @@ import { Eye, EyeOff } from "lucide-react";import { useTranslation } from "react-i18next";import { channelTranslator } from "@/channel-plugins/i18n";-import type { ChannelConfigField } from "@/components/settings/channels/catalog";+import type { ChannelConfigField } from "@/channel-plugins/catalog";import { channelFieldInputId } from "@/components/settings/channels/CredentialForm";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";diff --git a/nanobot/channels/linear/webui/index.tsx b/nanobot/channels/linear/webui/index.tsxindex e9aa1893d..86b41a419 100644--- a/nanobot/channels/linear/webui/index.tsx+++ b/nanobot/channels/linear/webui/index.tsx@@ -1,7 +1,7 @@import { lazy } from "react";import type { ChannelUiContribution } from "@/channel-plugins/types";-import { chatAppGuideUrl } from "@/components/settings/channels/catalog";+import { chatAppGuideUrl } from "@/channel-plugins/catalog";import { LinearHelpContent } from "./LinearHelpContent";diff --git a/nanobot/channels/matrix/runtime.py b/nanobot/channels/matrix/runtime.pyindex f208ce8c0..8eb9b94dd 100644--- a/nanobot/channels/matrix/runtime.py+++ b/nanobot/channels/matrix/runtime.py@@ -63,7 +63,7 @@ from nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannelfrom nanobot.config.paths import get_data_dir, get_media_dir-from nanobot.config.schema import Base+from nanobot.config_base import Basefrom nanobot.events import ContextCompactionEventfrom nanobot.utils.helpers import safe_filenamefrom nanobot.utils.logging_bridge import redirect_lib_loggingdiff --git a/nanobot/channels/matrix/webui/index.ts b/nanobot/channels/matrix/webui/index.tsindex 8a45162a3..803bd6c7a 100644--- a/nanobot/channels/matrix/webui/index.ts+++ b/nanobot/channels/matrix/webui/index.ts@@ -1,5 +1,5 @@import type { ChannelUiContribution } from "@/channel-plugins/types";-import { chatAppGuideUrl } from "@/components/settings/channels/catalog";+import { chatAppGuideUrl } from "@/channel-plugins/catalog";export default {presentation: {diff --git a/nanobot/channels/mattermost/webui/index.ts b/nanobot/channels/mattermost/webui/index.tsindex d18eb84b5..459b69c86 100644--- a/nanobot/channels/mattermost/webui/index.ts+++ b/nanobot/channels/mattermost/webui/index.ts@@ -1,5 +1,5 @@import type { ChannelUiContribution } from "@/channel-plugins/types";-import { chatAppGuideUrl } from "@/components/settings/channels/catalog";+import { chatAppGuideUrl } from "@/channel-plugins/catalog";export default {presentation: {diff --git a/nanobot/channels/mochat/runtime.py b/nanobot/channels/mochat/runtime.pyindex 477e491f8..4c60321d8 100644--- a/nanobot/channels/mochat/runtime.py+++ b/nanobot/channels/mochat/runtime.py@@ -19,7 +19,7 @@ from nanobot.bus.events import OutboundMessagefrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannelfrom nanobot.config.paths import get_runtime_subdir-from nanobot.config.schema import Base+from nanobot.config_base import Basefrom nanobot.events import ContextCompactionEventtry:diff --git a/nanobot/channels/mochat/webui/index.ts b/nanobot/channels/mochat/webui/index.tsindex c37358589..363a02cb9 100644--- a/nanobot/channels/mochat/webui/index.ts+++ b/nanobot/channels/mochat/webui/index.ts@@ -1,5 +1,5 @@import type { ChannelUiContribution } from "@/channel-plugins/types";-import { chatAppGuideUrl } from "@/components/settings/channels/catalog";+import { chatAppGuideUrl } from "@/channel-plugins/catalog";export default {presentation: {diff --git a/nanobot/channels/msteams/runtime.py b/nanobot/channels/msteams/runtime.pyindex a298f4a09..ae8a06828 100644--- a/nanobot/channels/msteams/runtime.py+++ b/nanobot/channels/msteams/runtime.py@@ -39,7 +39,7 @@ from nanobot.bus.events import OutboundMessagefrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannelfrom nanobot.config.paths import get_workspace_path-from nanobot.config.schema import Base+from nanobot.config_base import Basefrom nanobot.events import ContextCompactionEventMSTEAMS_AVAILABLE = (diff --git a/nanobot/channels/msteams/webui/index.ts b/nanobot/channels/msteams/webui/index.tsindex 378a5619f..a1dfc5b55 100644--- a/nanobot/channels/msteams/webui/index.ts+++ b/nanobot/channels/msteams/webui/index.ts@@ -1,5 +1,5 @@import type { ChannelUiContribution } from "@/channel-plugins/types";-import { chatAppGuideUrl } from "@/components/settings/channels/catalog";+import { chatAppGuideUrl } from "@/channel-plugins/catalog";export default {presentation: {diff --git a/nanobot/channels/napcat/runtime.py b/nanobot/channels/napcat/runtime.pyindex 4df45357c..3a57f190b 100644--- a/nanobot/channels/napcat/runtime.py+++ b/nanobot/channels/napcat/runtime.py@@ -23,7 +23,7 @@ from nanobot.bus.events import OutboundMessagefrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannelfrom nanobot.config.paths import get_media_dir-from nanobot.config.schema import Base+from nanobot.config_base import Basefrom nanobot.events import ContextCompactionEventfrom nanobot.security.network import validate_url_targetfrom nanobot.utils.helpers import safe_filenamediff --git a/nanobot/channels/napcat/webui/index.ts b/nanobot/channels/napcat/webui/index.tsindex 22a16202e..53e5b0024 100644--- a/nanobot/channels/napcat/webui/index.ts+++ b/nanobot/channels/napcat/webui/index.ts@@ -1,5 +1,5 @@import type { ChannelUiContribution } from "@/channel-plugins/types";-import { chatAppGuideUrl } from "@/components/settings/channels/catalog";+import { chatAppGuideUrl } from "@/channel-plugins/catalog";export default {presentation: {diff --git a/nanobot/channels/notification_routes.py b/nanobot/channels/notification_routes.pyindex d07429b29..1629f8a11 100644--- a/nanobot/channels/notification_routes.py+++ b/nanobot/channels/notification_routes.py@@ -21,3 +21,14 @@ def notification_metadata(channel: str, source: Mapping[str, Any]) -> dict[str,fields = ("thread_ts",) if channel_type == "slack" else ("root_id", "thread_ts")metadata[channel_type] = {key: nested[key] for key in fields if key in nested}return deepcopy(metadata)+++def system_reply_metadata(channel: str, session_key: str) -> dict[str, Any]:+ """Restore the thread address for an independently dispatched system reply."""+ if (+ channel == "slack"+ and session_key.startswith("slack:")+ and session_key.count(":") >= 2+ ):+ return {"slack": {"thread_ts": session_key.split(":", 2)[2]}}+ return {}diff --git a/nanobot/channels/qq/runtime.py b/nanobot/channels/qq/runtime.pyindex 505bef2d8..a144ef0b2 100644--- a/nanobot/channels/qq/runtime.py+++ b/nanobot/channels/qq/runtime.py@@ -41,7 +41,7 @@ from nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import ContextCompactionEventfrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannel-from nanobot.config.schema import Base+from nanobot.config_base import Basefrom nanobot.security.network import validate_url_targetfrom nanobot.utils.logging_bridge import redirect_lib_loggingdiff --git a/nanobot/channels/qq/webui/index.ts b/nanobot/channels/qq/webui/index.tsindex 877a82aa7..dc0e3214c 100644--- a/nanobot/channels/qq/webui/index.ts+++ b/nanobot/channels/qq/webui/index.ts@@ -1,5 +1,5 @@import type { ChannelUiContribution } from "@/channel-plugins/types";-import { chatAppGuideUrl } from "@/components/settings/channels/catalog";+import { chatAppGuideUrl } from "@/channel-plugins/catalog";export default {presentation: {diff --git a/nanobot/channels/signal/runtime.py b/nanobot/channels/signal/runtime.pyindex 5dfd1aaa9..4a13d34fa 100644--- a/nanobot/channels/signal/runtime.py+++ b/nanobot/channels/signal/runtime.py@@ -22,7 +22,7 @@ from nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannelfrom nanobot.config.paths import get_media_dir-from nanobot.config.schema import Base+from nanobot.config_base import Basefrom nanobot.events import ContextCompactionEventfrom nanobot.pairing import is_approvedfrom nanobot.utils.helpers import safe_filename, split_messagediff --git a/nanobot/channels/signal/webui/index.ts b/nanobot/channels/signal/webui/index.tsindex 26aeea231..a2d40a562 100644--- a/nanobot/channels/signal/webui/index.ts+++ b/nanobot/channels/signal/webui/index.ts@@ -1,5 +1,5 @@import type { ChannelUiContribution } from "@/channel-plugins/types";-import { chatAppGuideUrl } from "@/components/settings/channels/catalog";+import { chatAppGuideUrl } from "@/channel-plugins/catalog";export default {presentation: {diff --git a/nanobot/channels/slack/runtime.py b/nanobot/channels/slack/runtime.pyindex 5e61c7bff..e14e5d7a5 100644--- a/nanobot/channels/slack/runtime.py+++ b/nanobot/channels/slack/runtime.py@@ -19,7 +19,7 @@ from nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannelfrom nanobot.config.paths import get_media_dir-from nanobot.config.schema import Base+from nanobot.config_base import Basefrom nanobot.events import ContextCompactionEventfrom nanobot.pairing import is_approvedfrom nanobot.security.network import (diff --git a/nanobot/channels/slack/webui/index.ts b/nanobot/channels/slack/webui/index.tsindex c2d0368a1..7b40a5581 100644--- a/nanobot/channels/slack/webui/index.ts+++ b/nanobot/channels/slack/webui/index.ts@@ -1,5 +1,5 @@import type { ChannelUiContribution } from "@/channel-plugins/types";-import { chatAppGuideUrl } from "@/components/settings/channels/catalog";+import { chatAppGuideUrl } from "@/channel-plugins/catalog";const SLACK_SOCKET_MODE_MANIFEST = `display_information:name: nanobotdiff --git a/nanobot/channels/telegram/runtime.py b/nanobot/channels/telegram/runtime.pyindex 1824930fc..22dd9462b 100644--- a/nanobot/channels/telegram/runtime.py+++ b/nanobot/channels/telegram/runtime.py@@ -35,7 +35,7 @@ from nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannelfrom nanobot.command.builtin import build_help_textfrom nanobot.config.paths import get_media_dir-from nanobot.config.schema import Base+from nanobot.config_base import Basefrom nanobot.events import ContextCompactionEventfrom nanobot.security.network import validate_url_targetfrom nanobot.utils.helpers import split_messagediff --git a/nanobot/channels/telegram/webui/index.ts b/nanobot/channels/telegram/webui/index.tsindex 4def46c0b..3a8c3df31 100644--- a/nanobot/channels/telegram/webui/index.ts+++ b/nanobot/channels/telegram/webui/index.ts@@ -1,5 +1,5 @@import type { ChannelUiContribution } from "@/channel-plugins/types";-import { chatAppGuideUrl } from "@/components/settings/channels/catalog";+import { chatAppGuideUrl } from "@/channel-plugins/catalog";export default {presentation: {diff --git a/nanobot/channels/websocket/runtime.py b/nanobot/channels/websocket/runtime.pyindex 1ccc38e10..6b035d6d4 100644--- a/nanobot/channels/websocket/runtime.py+++ b/nanobot/channels/websocket/runtime.py@@ -28,7 +28,7 @@ from nanobot.bus.events import (from nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannelfrom nanobot.channels.websocket.binary_http import BinaryHTTPBridge-from nanobot.config.schema import Base+from nanobot.config_base import Basefrom nanobot.session.webui_turns import (clear_websocket_turn_if_current,mark_websocket_turn_transcript_persistence_failed,diff --git a/nanobot/channels/websocket/webui/index.ts b/nanobot/channels/websocket/webui/index.tsindex ef055a513..e3c00eee6 100644--- a/nanobot/channels/websocket/webui/index.ts+++ b/nanobot/channels/websocket/webui/index.ts@@ -1,5 +1,5 @@import type { ChannelUiContribution } from "@/channel-plugins/types";-import { chatAppGuideUrl } from "@/components/settings/channels/catalog";+import { chatAppGuideUrl } from "@/channel-plugins/catalog";import { WebSocketIcon } from "./WebSocketIcon";diff --git a/nanobot/channels/wecom/runtime.py b/nanobot/channels/wecom/runtime.pyindex d4bdfdf15..db5982af7 100644--- a/nanobot/channels/wecom/runtime.py+++ b/nanobot/channels/wecom/runtime.py@@ -17,7 +17,7 @@ from nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannelfrom nanobot.config.paths import get_media_dir-from nanobot.config.schema import Base+from nanobot.config_base import Basefrom nanobot.events import ContextCompactionEventWECOM_AVAILABLE = importlib.util.find_spec("wecom_aibot_sdk") is not Nonediff --git a/nanobot/channels/wecom/webui/index.ts b/nanobot/channels/wecom/webui/index.tsindex d8829be7a..099406f77 100644--- a/nanobot/channels/wecom/webui/index.ts+++ b/nanobot/channels/wecom/webui/index.ts@@ -1,5 +1,5 @@import type { ChannelUiContribution } from "@/channel-plugins/types";-import { chatAppGuideUrl } from "@/components/settings/channels/catalog";+import { chatAppGuideUrl } from "@/channel-plugins/catalog";export default {presentation: {diff --git a/nanobot/channels/weixin/runtime.py b/nanobot/channels/weixin/runtime.pyindex 51948a9fe..e03939f1a 100644--- a/nanobot/channels/weixin/runtime.py+++ b/nanobot/channels/weixin/runtime.py@@ -36,7 +36,7 @@ from nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannelfrom nanobot.config.paths import get_media_dir, get_runtime_subdir-from nanobot.config.schema import Base+from nanobot.config_base import Basefrom nanobot.events import ContextCompactionEventfrom nanobot.utils.logging_bridge import redirect_lib_loggingdiff --git a/nanobot/channels/weixin/webui/WeixinPanel.tsx b/nanobot/channels/weixin/webui/WeixinPanel.tsxindex 64df53b1b..959f287a7 100644--- a/nanobot/channels/weixin/webui/WeixinPanel.tsx+++ b/nanobot/channels/weixin/webui/WeixinPanel.tsx@@ -7,7 +7,7 @@ import { channelLocaleMessages } from "@/channel-plugins/locale-registry";import type { ChannelPluginPanelProps } from "@/channel-plugins/types";import {type ChannelConfigField,-} from "@/components/settings/channels/catalog";+} from "@/channel-plugins/catalog";import {CredentialForm,channelValuesForSave,diff --git a/nanobot/channels/weixin/webui/index.tsx b/nanobot/channels/weixin/webui/index.tsxindex 35ef192cf..415f3910e 100644--- a/nanobot/channels/weixin/webui/index.tsx+++ b/nanobot/channels/weixin/webui/index.tsx@@ -1,7 +1,7 @@import { lazy } from "react";import type { ChannelUiContribution } from "@/channel-plugins/types";-import { chatAppGuideUrl } from "@/components/settings/channels/catalog";+import { chatAppGuideUrl } from "@/channel-plugins/catalog";import {WEIXIN_ADVANCED_FIELD_KEYS,diff --git a/nanobot/channels/whatsapp/manifest.py b/nanobot/channels/whatsapp/manifest.pyindex 00535ae0b..7e7f9716a 100644--- a/nanobot/channels/whatsapp/manifest.py+++ b/nanobot/channels/whatsapp/manifest.py@@ -32,6 +32,8 @@ PLUGIN = ChannelPlugin(management=ChannelManagementSpec(local_state_present=local_state_present),dependencies=("neonize>=0.4.3.post0,<0.5.0",+ "python-magic>=0.4.27; sys_platform != 'win32'",+ "python-magic-bin>=0.4.14; sys_platform == 'win32'","segno>=1.6.1,<2.0.0",),webui="webui/index.tsx",diff --git a/nanobot/channels/whatsapp/runtime.py b/nanobot/channels/whatsapp/runtime.pyindex 9ffd6588b..b8f2bc46c 100644--- a/nanobot/channels/whatsapp/runtime.py+++ b/nanobot/channels/whatsapp/runtime.py@@ -22,7 +22,7 @@ from nanobot.bus.events import OutboundMessagefrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannelfrom nanobot.config.paths import get_media_dir, get_runtime_subdir-from nanobot.config.schema import Base+from nanobot.config_base import Basefrom nanobot.events import ContextCompactionEventfrom nanobot.security.network import PinnedDNSAsyncTransportdiff --git a/nanobot/channels/whatsapp/webui/index.tsx b/nanobot/channels/whatsapp/webui/index.tsxindex fe18712b1..d22761c13 100644--- a/nanobot/channels/whatsapp/webui/index.tsx+++ b/nanobot/channels/whatsapp/webui/index.tsx@@ -1,7 +1,7 @@import { MessageCircle } from "lucide-react";import type { ChannelUiContribution } from "@/channel-plugins/types";-import { chatAppGuideUrl } from "@/components/settings/channels/catalog";+import { chatAppGuideUrl } from "@/channel-plugins/catalog";import { WhatsAppConnectFlow } from "./WhatsAppConnectFlow";diff --git a/nanobot/cli/gateway_runtime.py b/nanobot/cli/gateway_runtime.pyindex 15c6dd858..7112ed6dc 100644--- a/nanobot/cli/gateway_runtime.py+++ b/nanobot/cli/gateway_runtime.py@@ -382,7 +382,6 @@ def _run_gateway()from nanobot.providers.fallback_provider import FallbackProviderfrom nanobot.session.manager import SessionManager- from nanobot.session.recovery import RecoveryCoordinatorfrom nanobot.session.webui_turns import (WebuiTurnCoordinator,WebuiTurnRoutePolicy,@@ -390,6 +389,7 @@ def _run_gateway()from nanobot.triggers.local_runner import run_local_trigger_queuefrom nanobot.triggers.local_store import LocalTriggerStore+ from nanobot.webui.recovery import RecoveryCoordinatorport = port if port is not None else config.gateway.portwebui_url = _webui_browser_url(config)diff --git a/nanobot/config/__init__.py b/nanobot/config/__init__.pyindex 1b0b62bbf..215a8eb09 100644--- a/nanobot/config/__init__.py+++ b/nanobot/config/__init__.py@@ -1,20 +1,59 @@"""Configuration module for nanobot."""-from nanobot.config.errors import ConfigIssue, ConfigLoadError-from nanobot.config.loader import get_config_path, load_config-from nanobot.config.paths import (- get_cli_history_path,- get_cron_dir,- get_data_dir,- get_legacy_sessions_dir,- get_logs_dir,- get_media_dir,- get_runtime_subdir,- get_webui_dir,- get_workspace_path,- is_default_workspace,-)-from nanobot.config.schema import Config+from __future__ import annotations++from importlib import import_module+from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ from nanobot.config.errors import ConfigIssue, ConfigLoadError+ from nanobot.config.loader import get_config_path, load_config+ from nanobot.config.paths import (+ get_cli_history_path,+ get_cron_dir,+ get_data_dir,+ get_legacy_sessions_dir,+ get_logs_dir,+ get_media_dir,+ get_runtime_subdir,+ get_webui_dir,+ get_workspace_path,+ is_default_workspace,+ )+ from nanobot.config.schema import Config+++_EXPORTS = {+ "Config": "nanobot.config.schema",+ "ConfigIssue": "nanobot.config.errors",+ "ConfigLoadError": "nanobot.config.errors",+ "load_config": "nanobot.config.loader",+ "get_config_path": "nanobot.config.loader",+ "get_data_dir": "nanobot.config.paths",+ "get_runtime_subdir": "nanobot.config.paths",+ "get_media_dir": "nanobot.config.paths",+ "get_cron_dir": "nanobot.config.paths",+ "get_logs_dir": "nanobot.config.paths",+ "get_webui_dir": "nanobot.config.paths",+ "get_workspace_path": "nanobot.config.paths",+ "is_default_workspace": "nanobot.config.paths",+ "get_cli_history_path": "nanobot.config.paths",+ "get_legacy_sessions_dir": "nanobot.config.paths",+}+++def __getattr__(name: str) -> Any:+ module_name = _EXPORTS.get(name)+ if module_name is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ value = getattr(import_module(module_name), name)+ globals()[name] = value+ return value+++def __dir__() -> list[str]:+ return sorted(set(globals()) | set(_EXPORTS))+__all__ = ["Config",diff --git a/nanobot/config/loader.py b/nanobot/config/loader.pyindex ff9a81c84..5d6c72bf5 100644--- a/nanobot/config/loader.py+++ b/nanobot/config/loader.py@@ -11,15 +11,11 @@ from pydantic_settings import SettingsErrorfrom nanobot.config.errors import ConfigIssue, ConfigLoadError, validation_issuesfrom nanobot.config.home import get_home_path-from nanobot.config.schema import (- Config,- _resolve_tool_config_refs, # pyright: ignore[reportPrivateUsage]-)-from nanobot.utils.helpers import _write_text_atomic # pyright: ignore[reportPrivateUsage]+from nanobot.config.schema import Config+from nanobot.utils.file_io import write_text_atomic# Global variable to store current config path (for multi-instance support)_current_config_path: Path | None = None-_schema_refs_ready = Falsedef _as_config_object(value: object) -> dict[str, Any] | None:@@ -50,11 +46,6 @@ def load_config(config_path: Path | None = None) -> Config:Returns:Loaded configuration object."""- global _schema_refs_ready- if not _schema_refs_ready:- _resolve_tool_config_refs()- _schema_refs_ready = True-path = config_path or get_config_path()if not path.exists():@@ -172,7 +163,7 @@ def save_config(config: Config, config_path: Path | None = None) -> None:data.setdefault("providers", {})[alias] = settings# Temp + replace so a crash mid-write cannot leave a truncated config.json.- _write_text_atomic(path, json.dumps(data, indent=2, ensure_ascii=False))+ write_text_atomic(path, json.dumps(data, indent=2, ensure_ascii=False))def merge_missing_defaults(existing: object, defaults: object) -> object:diff --git a/nanobot/config/paths.py b/nanobot/config/paths.pyindex ec2766697..3d8163307 100644--- a/nanobot/config/paths.py+++ b/nanobot/config/paths.py@@ -5,7 +5,7 @@ from __future__ import annotationsfrom pathlib import Pathfrom nanobot.config.home import get_home_path-from nanobot.utils.helpers import ensure_dir+from nanobot.utils.file_io import ensure_dirdef get_config_path() -> Path:diff --git a/nanobot/config/schema.py b/nanobot/config/schema.pyindex ceb14be6d..1f0c93a58 100644--- a/nanobot/config/schema.py+++ b/nanobot/config/schema.py@@ -2,26 +2,31 @@from __future__ import annotationsfrom pathlib import Path-from typing import TYPE_CHECKING, Any, ClassVar, Literal, cast+from typing import Any, ClassVar, Literal, castfrom pydantic import AliasChoices, ConfigDict, Field, PrivateAttr, field_validator, model_validatorfrom pydantic_settings import BaseSettings, SettingsConfigDict+from nanobot.agent.tools.cli_apps_config import CliAppsToolConfig+from nanobot.agent.tools.filesystem_config import FileToolsConfig+from nanobot.agent.tools.image_generation_config import ImageGenerationToolConfig+from nanobot.agent.tools.self_config import MyToolConfig+from nanobot.agent.tools.shell_config import ExecToolConfig+from nanobot.agent.tools.web_config import (+ WebFetchConfig as WebFetchConfig,+)+from nanobot.agent.tools.web_config import (+ WebSearchConfig as WebSearchConfig,+)+from nanobot.agent.tools.web_config import WebToolsConfigfrom nanobot.config.home import get_default_workspacefrom nanobot.config.provider_api_migration import migrate_legacy_provider_apifrom nanobot.config.timezone import detect_system_timezonefrom nanobot.config_base import Basefrom nanobot.cron.types import CronSchedule+from nanobot.providers.generation import GenerationSettingsfrom nanobot.providers.model_api import ModelAPICapabilities, RequestAPI-if TYPE_CHECKING:- from nanobot.agent.tools.cli_apps import CliAppsToolConfig- from nanobot.agent.tools.filesystem import FileToolsConfig- from nanobot.agent.tools.image_generation import ImageGenerationToolConfig- from nanobot.agent.tools.self import MyToolConfig- from nanobot.agent.tools.shell import ExecToolConfig- from nanobot.agent.tools.web import WebToolsConfig-class ChannelsConfig(Base):"""Configuration for chat channels.@@ -149,8 +154,7 @@ class ModelPresetConfig(RequestOverrides):reasoning_effort: str | None = Noneapi: ModelAPIConfig | None = None- def to_generation_settings(self) -> Any:- from nanobot.providers.base import GenerationSettings+ def to_generation_settings(self) -> GenerationSettings:return GenerationSettings(temperature=self.temperature,max_tokens=self.max_tokens,@@ -420,28 +424,16 @@ class MCPServerConfig(Base):enabled_tools: list[str] = Field(default_factory=lambda: ["*"]) # Only register these tools; accepts raw MCP names or wrapped mcp_<server>_<tool> names; ["*"] = all capabilities (tools, resources, prompts); any restriction = only listed tools, no resources/prompts-def _lazy_default(module_path: str, class_name: str) -> Any:- """Deferred import helper for ToolsConfig default factories."""- import importlib- module = importlib.import_module(module_path)- return getattr(module, class_name)()--class ToolsConfig(Base):- """Tools configuration.-- Field types for tool-specific sub-configs are resolved via model_rebuild()- at the bottom of this file so tool config classes can stay next to their- tool implementations.- """+ """Root settings assembled from tool-owned configuration models."""- web: WebToolsConfig = Field(default_factory=lambda: _lazy_default("nanobot.agent.tools.web", "WebToolsConfig"))- exec: ExecToolConfig = Field(default_factory=lambda: _lazy_default("nanobot.agent.tools.shell", "ExecToolConfig"))- file: FileToolsConfig = Field(default_factory=lambda: _lazy_default("nanobot.agent.tools.filesystem", "FileToolsConfig"))- cli_apps: CliAppsToolConfig = Field(default_factory=lambda: _lazy_default("nanobot.agent.tools.cli_apps", "CliAppsToolConfig"))- my: MyToolConfig = Field(default_factory=lambda: _lazy_default("nanobot.agent.tools.self", "MyToolConfig"))+ web: WebToolsConfig = Field(default_factory=WebToolsConfig)+ exec: ExecToolConfig = Field(default_factory=ExecToolConfig)+ file: FileToolsConfig = Field(default_factory=FileToolsConfig)+ cli_apps: CliAppsToolConfig = Field(default_factory=CliAppsToolConfig)+ my: MyToolConfig = Field(default_factory=MyToolConfig)image_generation: ImageGenerationToolConfig = Field(- default_factory=lambda: _lazy_default("nanobot.agent.tools.image_generation", "ImageGenerationToolConfig"),+ default_factory=ImageGenerationToolConfig,)max_session_messages_per_minute: int = Field(default=6, ge=1)restrict_to_workspace: bool = False # policy intent: keep tool access inside workspace when possible@@ -483,11 +475,6 @@ class Config(BaseSettings):serialization_alias="modelPresets",)- def __init__(self, **values: Any) -> None:- if not type(self).__pydantic_complete__:- _resolve_tool_config_refs()- super().__init__(**values)-def bind_source_path(self, path: Path) -> None:"""Record the config file that owns instance-level runtime data."""self._source_path = path.expanduser().resolve(strict=False)@@ -711,43 +698,3 @@ class Config(BaseSettings):env_prefix="NANOBOT_",env_nested_delimiter="__",)---def _resolve_tool_config_refs() -> None:- """Resolve forward references in ToolsConfig by importing tool config classes.-- Must be called after all modules are loaded (breaks circular imports).- Re-exports the classes into this module's namespace so existing imports- like ``from nanobot.config.schema import ExecToolConfig`` continue to work.- """- import sys-- from nanobot.agent.tools.cli_apps import CliAppsToolConfig- from nanobot.agent.tools.filesystem import FileToolsConfig- from nanobot.agent.tools.image_generation import ImageGenerationToolConfig- from nanobot.agent.tools.self import MyToolConfig- from nanobot.agent.tools.shell import ExecToolConfig- from nanobot.agent.tools.web import WebFetchConfig, WebSearchConfig, WebToolsConfig-- # Re-export into this module's namespace- mod = sys.modules[__name__]- mod.ExecToolConfig = ExecToolConfig # type: ignore[attr-defined]- mod.FileToolsConfig = FileToolsConfig # type: ignore[attr-defined]- mod.CliAppsToolConfig = CliAppsToolConfig # type: ignore[attr-defined]- mod.WebToolsConfig = WebToolsConfig # type: ignore[attr-defined]- mod.WebSearchConfig = WebSearchConfig # type: ignore[attr-defined]- mod.WebFetchConfig = WebFetchConfig # type: ignore[attr-defined]- mod.MyToolConfig = MyToolConfig # type: ignore[attr-defined]- mod.ImageGenerationToolConfig = ImageGenerationToolConfig # type: ignore[attr-defined]-- ToolsConfig.model_rebuild()- Config.model_rebuild()---# Eagerly resolve when the import chain allows it (no circular deps at this-# point). If it fails (first import triggers a cycle), the rebuild will-# happen lazily when Config/ToolsConfig is first used at runtime.-try:- _resolve_tool_config_refs()-except ImportError:- passdiff --git a/nanobot/cron/session_turns.py b/nanobot/cron/session_turns.pyindex b0c9e847f..d63c40de2 100644--- a/nanobot/cron/session_turns.py+++ b/nanobot/cron/session_turns.py@@ -5,7 +5,7 @@ from __future__ import annotationsfrom typing import Any, Mappingfrom nanobot.cron.types import CronJob-from nanobot.session.automation_turns import (+from nanobot.session.automation_spec import (AutomationTurnSpec,automation_trigger,)diff --git a/nanobot/llm_usage/__init__.py b/nanobot/llm_usage/__init__.pyindex 95d51a9c5..a41f65799 100644--- a/nanobot/llm_usage/__init__.py+++ b/nanobot/llm_usage/__init__.py@@ -1,78 +1,43 @@-"""Unified, content-free LLM usage backend."""+"""Public LLM usage records and persistence services."""from __future__ import annotations-import threading-from pathlib import Path-from typing import Any--from loguru import logger--from nanobot.config.paths import get_data_dir-from nanobot.llm_usage.models import LLMCallRecord-from nanobot.llm_usage.store import LLMUsageStore--_STORES_LOCK = threading.Lock()-_STORES: dict[Path, LLMUsageStore] = {}---def empty_usage_payload() -> dict[str, Any]:- return {- "days": [],- "total_tokens": 0,- "total_tokens_30d": 0,- "total_tokens_365d": 0,- "reported_tokens_30d": 0,- "estimated_tokens_30d": 0,- "cache_read_tokens_30d": 0,- "cache_read_observed_input_tokens_30d": 0,- "cache_read_rate_30d": None,- "peak_day_tokens": 0,- "current_streak_days": 0,- "longest_streak_days": 0,- "active_days_30d": 0,- "requests_30d": 0,- "failed_requests_30d": 0,- "providers_30d": [],- "updated_at": None,- }---def llm_usage_store_path() -> Path:- return get_data_dir() / "llm_usage.sqlite3"---def get_llm_usage_store(path: Path | None = None) -> LLMUsageStore:- resolved = (path or llm_usage_store_path()).resolve(strict=False)- with _STORES_LOCK:- store = _STORES.get(resolved)- if store is None:- store = LLMUsageStore(resolved)- _STORES[resolved] = store- return store---def record_llm_call(call: LLMCallRecord) -> None:- """Default fail-open callback attached to gateway provider snapshots."""- try:- get_llm_usage_store().record(call)- except Exception:- logger.exception("failed to record LLM usage")---def llm_usage_payload(- *,- days: int = 371,- timezone_name: str | None = None,-) -> dict[str, Any]:- try:- return get_llm_usage_store().usage_payload(- days=days,- timezone_name=timezone_name,- )- except Exception:- logger.exception("failed to query LLM usage")- return empty_usage_payload()+from importlib import import_module+from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ from nanobot.llm_usage.models import LLMCallRecord+ from nanobot.llm_usage.service import (+ empty_usage_payload,+ get_llm_usage_store,+ llm_usage_payload,+ llm_usage_store_path,+ record_llm_call,+ )+ from nanobot.llm_usage.store import LLMUsageStore++_EXPORTS = {+ "LLMCallRecord": "nanobot.llm_usage.models",+ "LLMUsageStore": "nanobot.llm_usage.store",+ "empty_usage_payload": "nanobot.llm_usage.service",+ "get_llm_usage_store": "nanobot.llm_usage.service",+ "record_llm_call": "nanobot.llm_usage.service",+ "llm_usage_store_path": "nanobot.llm_usage.service",+ "llm_usage_payload": "nanobot.llm_usage.service",+}+++def __getattr__(name: str) -> Any:+ module_name = _EXPORTS.get(name)+ if module_name is None:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ value = getattr(import_module(module_name), name)+ globals()[name] = value+ return value+++def __dir__() -> list[str]:+ return sorted(set(globals()) | set(_EXPORTS))__all__ = [diff --git a/nanobot/llm_usage/models.py b/nanobot/llm_usage/models.pyindex 7ceb6f5c0..b6b983bbb 100644--- a/nanobot/llm_usage/models.py+++ b/nanobot/llm_usage/models.py@@ -5,7 +5,7 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom nanobot.llm_usage.context import LLMUsageSource-from nanobot.providers.base import LLMUsage+from nanobot.llm_usage.types import LLMUsage@dataclass(frozen=True, slots=True)diff --git a/nanobot/llm_usage/service.py b/nanobot/llm_usage/service.pynew file mode 100644index 000000000..34db72c81--- /dev/null+++ b/nanobot/llm_usage/service.py@@ -0,0 +1,75 @@+"""Unified, content-free LLM usage backend."""++from __future__ import annotations++import threading+from pathlib import Path+from typing import Any++from loguru import logger++from nanobot.config.paths import get_data_dir+from nanobot.llm_usage.models import LLMCallRecord+from nanobot.llm_usage.store import LLMUsageStore++_STORES_LOCK = threading.Lock()+_STORES: dict[Path, LLMUsageStore] = {}+++def empty_usage_payload() -> dict[str, Any]:+ return {+ "days": [],+ "total_tokens": 0,+ "total_tokens_30d": 0,+ "total_tokens_365d": 0,+ "reported_tokens_30d": 0,+ "estimated_tokens_30d": 0,+ "cache_read_tokens_30d": 0,+ "cache_read_observed_input_tokens_30d": 0,+ "cache_read_rate_30d": None,+ "peak_day_tokens": 0,+ "current_streak_days": 0,+ "longest_streak_days": 0,+ "active_days_30d": 0,+ "requests_30d": 0,+ "failed_requests_30d": 0,+ "providers_30d": [],+ "updated_at": None,+ }+++def llm_usage_store_path() -> Path:+ return get_data_dir() / "llm_usage.sqlite3"+++def get_llm_usage_store(path: Path | None = None) -> LLMUsageStore:+ resolved = (path or llm_usage_store_path()).resolve(strict=False)+ with _STORES_LOCK:+ store = _STORES.get(resolved)+ if store is None:+ store = LLMUsageStore(resolved)+ _STORES[resolved] = store+ return store+++def record_llm_call(call: LLMCallRecord) -> None:+ """Default fail-open callback attached to gateway provider snapshots."""+ try:+ get_llm_usage_store().record(call)+ except Exception:+ logger.exception("failed to record LLM usage")+++def llm_usage_payload(+ *,+ days: int = 371,+ timezone_name: str | None = None,+) -> dict[str, Any]:+ try:+ return get_llm_usage_store().usage_payload(+ days=days,+ timezone_name=timezone_name,+ )+ except Exception:+ logger.exception("failed to query LLM usage")+ return empty_usage_payload()diff --git a/nanobot/llm_usage/types.py b/nanobot/llm_usage/types.pynew file mode 100644index 000000000..bf09bf5b4--- /dev/null+++ b/nanobot/llm_usage/types.py@@ -0,0 +1,291 @@+"""Normalized usage values shared by providers and usage records."""++from __future__ import annotations++from dataclasses import dataclass+from typing import Literal, cast+++@dataclass(frozen=True, slots=True)+class LLMUsage:+ """Canonical token usage reported by, or estimated for, one or more LLM calls.++ ``input_tokens`` is the logical input total and therefore includes cache reads+ and writes. ``None`` cache counts mean the wire protocol did not report that+ metric, while zero means it explicitly reported no cache activity.++ ``total_tokens`` preserves a provider-reported total when it exceeds the+ visible input plus output (for example, hidden reasoning or tool usage). It+ must be at least ``input_tokens + output_tokens``. The reported and estimated+ totals partition it exactly, including after multi-call aggregation.+ """++ input_tokens: int+ output_tokens: int+ total_tokens: int+ cache_read_tokens: int | None = None+ cache_write_tokens: int | None = None+ reported_tokens: int = 0+ estimated_tokens: int = 0+ generation_ms: int = 0+ measured_output_tokens: int = 0+ ttft_ms: int = 0+ timed_requests: int = 0+ context_tokens: int | None = None+ request_count: int = 0++ def __post_init__(self) -> None:+ token_fields = {+ "input_tokens": self.input_tokens,+ "output_tokens": self.output_tokens,+ "total_tokens": self.total_tokens,+ "reported_tokens": self.reported_tokens,+ "estimated_tokens": self.estimated_tokens,+ "generation_ms": self.generation_ms,+ "measured_output_tokens": self.measured_output_tokens,+ "ttft_ms": self.ttft_ms,+ "timed_requests": self.timed_requests,+ "request_count": self.request_count,+ }+ for name, value in token_fields.items():+ runtime_value = cast(object, value)+ if (+ not isinstance(runtime_value, int)+ or isinstance(runtime_value, bool)+ or runtime_value < 0+ ):+ raise ValueError(f"{name} must be a non-negative integer")+ for name, value in (+ ("cache_read_tokens", self.cache_read_tokens),+ ("cache_write_tokens", self.cache_write_tokens),+ ("context_tokens", self.context_tokens),+ ):+ runtime_value = cast(object, value)+ if runtime_value is not None and (+ not isinstance(runtime_value, int)+ or isinstance(runtime_value, bool)+ or runtime_value < 0+ ):+ raise ValueError(f"{name} must be None or a non-negative integer")++ visible_total = self.input_tokens + self.output_tokens+ if self.total_tokens < visible_total:+ raise ValueError("total_tokens must be at least input_tokens + output_tokens")+ if self.reported_tokens + self.estimated_tokens != self.total_tokens:+ raise ValueError("reported_tokens + estimated_tokens must equal total_tokens")+ cache_total = (self.cache_read_tokens or 0) + (self.cache_write_tokens or 0)+ if cache_total > self.input_tokens:+ raise ValueError("cache token counts cannot exceed logical input_tokens")++ @classmethod+ def reported(+ cls,+ *,+ input_tokens: int,+ output_tokens: int,+ total_tokens: int | None = None,+ cache_read_tokens: int | None = None,+ cache_write_tokens: int | None = None,+ ) -> LLMUsage:+ """Build usage normalized from a provider response."""+ visible_total = input_tokens + output_tokens+ normalized_total = (+ visible_total if total_tokens is None else max(visible_total, total_tokens)+ )+ return cls(+ input_tokens=input_tokens,+ output_tokens=output_tokens,+ total_tokens=normalized_total,+ cache_read_tokens=cache_read_tokens,+ cache_write_tokens=cache_write_tokens,+ reported_tokens=normalized_total,+ context_tokens=input_tokens,+ request_count=1,+ )++ @classmethod+ def estimated(cls, *, input_tokens: int, output_tokens: int) -> LLMUsage:+ """Build usage estimated locally because the provider omitted it."""+ return cls(+ input_tokens=input_tokens,+ output_tokens=output_tokens,+ total_tokens=input_tokens + output_tokens,+ estimated_tokens=input_tokens + output_tokens,+ context_tokens=input_tokens,+ request_count=1,+ )++ @classmethod+ def empty_request(cls) -> LLMUsage:+ """Represent a completed model request with no measurable token usage."""+ return cls(+ input_tokens=0,+ output_tokens=0,+ total_tokens=0,+ request_count=1,+ )++ @property+ def source(self) -> Literal["reported", "estimated", "mixed"]:+ if self.estimated_tokens == 0:+ return "reported"+ if self.reported_tokens == 0:+ return "estimated"+ return "mixed"++ def with_timing(+ self,+ *,+ generation_ms: int | None,+ ttft_ms: int | None,+ ) -> LLMUsage:+ """Attach locally measured streaming telemetry to this usage value."""+ return LLMUsage(+ input_tokens=self.input_tokens,+ output_tokens=self.output_tokens,+ total_tokens=self.total_tokens,+ cache_read_tokens=self.cache_read_tokens,+ cache_write_tokens=self.cache_write_tokens,+ reported_tokens=self.reported_tokens,+ estimated_tokens=self.estimated_tokens,+ generation_ms=max(0, generation_ms or 0),+ measured_output_tokens=self.output_tokens if generation_ms is not None else 0,+ ttft_ms=max(0, ttft_ms or 0),+ timed_requests=1 if ttft_ms is not None else 0,+ context_tokens=self.context_tokens,+ request_count=self.request_count,+ )++ def __add__(self, other: LLMUsage) -> LLMUsage:+ """Aggregate calls without turning partially reported cache data into a count."""++ def _sum_cache(left: int | None, right: int | None) -> int | None:+ return left + right if left is not None and right is not None else None++ return LLMUsage(+ input_tokens=self.input_tokens + other.input_tokens,+ output_tokens=self.output_tokens + other.output_tokens,+ total_tokens=self.total_tokens + other.total_tokens,+ cache_read_tokens=_sum_cache(self.cache_read_tokens, other.cache_read_tokens),+ cache_write_tokens=_sum_cache(self.cache_write_tokens, other.cache_write_tokens),+ reported_tokens=self.reported_tokens + other.reported_tokens,+ estimated_tokens=self.estimated_tokens + other.estimated_tokens,+ generation_ms=self.generation_ms + other.generation_ms,+ measured_output_tokens=(+ self.measured_output_tokens + other.measured_output_tokens+ ),+ ttft_ms=self.ttft_ms + other.ttft_ms,+ timed_requests=self.timed_requests + other.timed_requests,+ context_tokens=(+ other.context_tokens+ if other.context_tokens is not None+ else self.context_tokens+ ),+ request_count=self.request_count + other.request_count,+ )++ def to_dict(self) -> dict[str, int | str | None]:+ """Serialize the canonical contract at JSON/persistence boundaries."""+ return {+ "input_tokens": self.input_tokens,+ "output_tokens": self.output_tokens,+ "total_tokens": self.total_tokens,+ "cache_read_tokens": self.cache_read_tokens,+ "cache_write_tokens": self.cache_write_tokens,+ "reported_tokens": self.reported_tokens,+ "estimated_tokens": self.estimated_tokens,+ "source": self.source,+ "generation_ms": self.generation_ms,+ "measured_output_tokens": self.measured_output_tokens,+ "ttft_ms": self.ttft_ms,+ "timed_requests": self.timed_requests,+ "context_tokens": self.context_tokens,+ "request_count": self.request_count,+ }++ def to_turn_dict(self) -> dict[str, int]:+ """Project canonical usage into the compact WebUI/TUI per-turn shape."""+ result: dict[str, int] = {+ "prompt_tokens": self.input_tokens,+ "completion_tokens": self.output_tokens,+ "total_tokens": self.total_tokens,+ "request_count": self.request_count,+ "estimated_tokens": self.estimated_tokens,+ }+ if self.context_tokens is not None:+ result["context_tokens"] = self.context_tokens+ if self.cache_read_tokens is not None:+ result["cached_tokens"] = self.cache_read_tokens+ if self.cache_write_tokens is not None:+ result["cache_write_tokens"] = self.cache_write_tokens+ if self.generation_ms > 0 and self.measured_output_tokens > 0:+ result["generation_ms"] = self.generation_ms+ result["measured_completion_tokens"] = self.measured_output_tokens+ if self.timed_requests > 0:+ result["ttft_ms"] = self.ttft_ms+ result["timed_requests"] = self.timed_requests+ return result++ @classmethod+ def from_dict(cls, value: object) -> LLMUsage | None:+ """Validate the exact first-party serialized contract."""+ if not isinstance(value, dict):+ return None+ data = cast(dict[object, object], value)+ integer_fields = (+ "input_tokens",+ "output_tokens",+ "reported_tokens",+ "estimated_tokens",+ "generation_ms",+ "measured_output_tokens",+ "ttft_ms",+ "timed_requests",+ "request_count",+ )+ serialized_fields = {+ *integer_fields,+ "total_tokens",+ "cache_read_tokens",+ "cache_write_tokens",+ "context_tokens",+ "source",+ }+ if set(data) != serialized_fields:+ return None+ if any(+ not isinstance(item := data.get(name), int) or isinstance(item, bool)+ for name in integer_fields+ ):+ return None+ cache_read = data.get("cache_read_tokens")+ cache_write = data.get("cache_write_tokens")+ context_tokens = data.get("context_tokens")+ total = data.get("total_tokens")+ source = data.get("source")+ if any(+ item is not None and (not isinstance(item, int) or isinstance(item, bool))+ for item in (cache_read, cache_write, context_tokens)+ ) or not isinstance(total, int) or isinstance(total, bool):+ return None+ try:+ usage = cls(+ input_tokens=cast(int, data["input_tokens"]),+ output_tokens=cast(int, data["output_tokens"]),+ total_tokens=total,+ cache_read_tokens=cast(int | None, cache_read),+ cache_write_tokens=cast(int | None, cache_write),+ reported_tokens=cast(int, data["reported_tokens"]),+ estimated_tokens=cast(int, data["estimated_tokens"]),+ generation_ms=cast(int, data["generation_ms"]),+ measured_output_tokens=cast(int, data["measured_output_tokens"]),+ ttft_ms=cast(int, data["ttft_ms"]),+ timed_requests=cast(int, data["timed_requests"]),+ context_tokens=cast(int | None, context_tokens),+ request_count=cast(int, data["request_count"]),+ )+ except (KeyError, ValueError):+ return None+ if source != usage.source:+ return None+ return usagediff --git a/nanobot/providers/__init__.py b/nanobot/providers/__init__.pyindex 0d12ace8e..c6d9dc1cf 100644--- a/nanobot/providers/__init__.py+++ b/nanobot/providers/__init__.py@@ -5,8 +5,6 @@ from __future__ import annotationsfrom importlib import import_modulefrom typing import TYPE_CHECKING-from nanobot.providers.base import LLMProvider, LLMResponse, LLMUsage-__all__ = ["LLMProvider","LLMResponse",@@ -21,6 +19,9 @@ __all__ = []_LAZY_IMPORTS = {+ "LLMProvider": ".base",+ "LLMResponse": ".base",+ "LLMUsage": ".base","AnthropicProvider": ".anthropic_provider","OpenAICompatProvider": ".openai_compat_provider","OpenAICodexProvider": ".openai_codex_provider",@@ -33,6 +34,7 @@ _LAZY_IMPORTS = {if TYPE_CHECKING:from nanobot.providers.anthropic_provider import AnthropicProviderfrom nanobot.providers.azure_openai_provider import AzureOpenAIProvider+ from nanobot.providers.base import LLMProvider, LLMResponse, LLMUsagefrom nanobot.providers.bedrock_provider import BedrockProviderfrom nanobot.providers.github_copilot_provider import GitHubCopilotProviderfrom nanobot.providers.openai_codex_provider import OpenAICodexProviderdiff --git a/nanobot/providers/base.py b/nanobot/providers/base.pyindex d381f4d5f..299ce7c30 100644--- a/nanobot/providers/base.py+++ b/nanobot/providers/base.py@@ -27,6 +27,8 @@ from nanobot.events import (RetryStatusEvent,RetryWaitEvent,)+from nanobot.llm_usage.types import LLMUsage as LLMUsage+from nanobot.providers.generation import GenerationSettings as GenerationSettingsfrom nanobot.utils.helpers import sanitize_surrogates_deepif TYPE_CHECKING:@@ -278,291 +280,6 @@ class ProviderCallContext:compaction_input_budget: int | None = None-@dataclass(frozen=True, slots=True)-class LLMUsage:- """Canonical token usage reported by, or estimated for, one or more LLM calls.-- ``input_tokens`` is the logical input total and therefore includes cache reads- and writes. ``None`` cache counts mean the wire protocol did not report that- metric, while zero means it explicitly reported no cache activity.-- ``total_tokens`` preserves a provider-reported total when it exceeds the- visible input plus output (for example, hidden reasoning or tool usage). It- must be at least ``input_tokens + output_tokens``. The reported and estimated- totals partition it exactly, including after multi-call aggregation.- """-- input_tokens: int- output_tokens: int- total_tokens: int- cache_read_tokens: int | None = None- cache_write_tokens: int | None = None- reported_tokens: int = 0- estimated_tokens: int = 0- generation_ms: int = 0- measured_output_tokens: int = 0- ttft_ms: int = 0- timed_requests: int = 0- context_tokens: int | None = None- request_count: int = 0-- def __post_init__(self) -> None:- token_fields = {- "input_tokens": self.input_tokens,- "output_tokens": self.output_tokens,- "total_tokens": self.total_tokens,- "reported_tokens": self.reported_tokens,- "estimated_tokens": self.estimated_tokens,- "generation_ms": self.generation_ms,- "measured_output_tokens": self.measured_output_tokens,- "ttft_ms": self.ttft_ms,- "timed_requests": self.timed_requests,- "request_count": self.request_count,- }- for name, value in token_fields.items():- runtime_value = cast(object, value)- if (- not isinstance(runtime_value, int)- or isinstance(runtime_value, bool)- or runtime_value < 0- ):- raise ValueError(f"{name} must be a non-negative integer")- for name, value in (- ("cache_read_tokens", self.cache_read_tokens),- ("cache_write_tokens", self.cache_write_tokens),- ("context_tokens", self.context_tokens),- ):- runtime_value = cast(object, value)- if runtime_value is not None and (- not isinstance(runtime_value, int)- or isinstance(runtime_value, bool)- or runtime_value < 0- ):- raise ValueError(f"{name} must be None or a non-negative integer")-- visible_total = self.input_tokens + self.output_tokens- if self.total_tokens < visible_total:- raise ValueError("total_tokens must be at least input_tokens + output_tokens")- if self.reported_tokens + self.estimated_tokens != self.total_tokens:- raise ValueError("reported_tokens + estimated_tokens must equal total_tokens")- cache_total = (self.cache_read_tokens or 0) + (self.cache_write_tokens or 0)- if cache_total > self.input_tokens:- raise ValueError("cache token counts cannot exceed logical input_tokens")-- @classmethod- def reported(- cls,- *,- input_tokens: int,- output_tokens: int,- total_tokens: int | None = None,- cache_read_tokens: int | None = None,- cache_write_tokens: int | None = None,- ) -> LLMUsage:- """Build usage normalized from a provider response."""- visible_total = input_tokens + output_tokens- normalized_total = (- visible_total if total_tokens is None else max(visible_total, total_tokens)- )- return cls(- input_tokens=input_tokens,- output_tokens=output_tokens,- total_tokens=normalized_total,- cache_read_tokens=cache_read_tokens,- cache_write_tokens=cache_write_tokens,- reported_tokens=normalized_total,- context_tokens=input_tokens,- request_count=1,- )-- @classmethod- def estimated(cls, *, input_tokens: int, output_tokens: int) -> LLMUsage:- """Build usage estimated locally because the provider omitted it."""- return cls(- input_tokens=input_tokens,- output_tokens=output_tokens,- total_tokens=input_tokens + output_tokens,- estimated_tokens=input_tokens + output_tokens,- context_tokens=input_tokens,- request_count=1,- )-- @classmethod- def empty_request(cls) -> LLMUsage:- """Represent a completed model request with no measurable token usage."""- return cls(- input_tokens=0,- output_tokens=0,- total_tokens=0,- request_count=1,- )-- @property- def source(self) -> Literal["reported", "estimated", "mixed"]:- if self.estimated_tokens == 0:- return "reported"- if self.reported_tokens == 0:- return "estimated"- return "mixed"-- def with_timing(- self,- *,- generation_ms: int | None,- ttft_ms: int | None,- ) -> LLMUsage:- """Attach locally measured streaming telemetry to this usage value."""- return LLMUsage(- input_tokens=self.input_tokens,- output_tokens=self.output_tokens,- total_tokens=self.total_tokens,- cache_read_tokens=self.cache_read_tokens,- cache_write_tokens=self.cache_write_tokens,- reported_tokens=self.reported_tokens,- estimated_tokens=self.estimated_tokens,- generation_ms=max(0, generation_ms or 0),- measured_output_tokens=self.output_tokens if generation_ms is not None else 0,- ttft_ms=max(0, ttft_ms or 0),- timed_requests=1 if ttft_ms is not None else 0,- context_tokens=self.context_tokens,- request_count=self.request_count,- )-- def __add__(self, other: LLMUsage) -> LLMUsage:- """Aggregate calls without turning partially reported cache data into a count."""-- def _sum_cache(left: int | None, right: int | None) -> int | None:- return left + right if left is not None and right is not None else None-- return LLMUsage(- input_tokens=self.input_tokens + other.input_tokens,- output_tokens=self.output_tokens + other.output_tokens,- total_tokens=self.total_tokens + other.total_tokens,- cache_read_tokens=_sum_cache(self.cache_read_tokens, other.cache_read_tokens),- cache_write_tokens=_sum_cache(self.cache_write_tokens, other.cache_write_tokens),- reported_tokens=self.reported_tokens + other.reported_tokens,- estimated_tokens=self.estimated_tokens + other.estimated_tokens,- generation_ms=self.generation_ms + other.generation_ms,- measured_output_tokens=(- self.measured_output_tokens + other.measured_output_tokens- ),- ttft_ms=self.ttft_ms + other.ttft_ms,- timed_requests=self.timed_requests + other.timed_requests,- context_tokens=(- other.context_tokens- if other.context_tokens is not None- else self.context_tokens- ),- request_count=self.request_count + other.request_count,- )-- def to_dict(self) -> dict[str, int | str | None]:- """Serialize the canonical contract at JSON/persistence boundaries."""- return {- "input_tokens": self.input_tokens,- "output_tokens": self.output_tokens,- "total_tokens": self.total_tokens,- "cache_read_tokens": self.cache_read_tokens,- "cache_write_tokens": self.cache_write_tokens,- "reported_tokens": self.reported_tokens,- "estimated_tokens": self.estimated_tokens,- "source": self.source,- "generation_ms": self.generation_ms,- "measured_output_tokens": self.measured_output_tokens,- "ttft_ms": self.ttft_ms,- "timed_requests": self.timed_requests,- "context_tokens": self.context_tokens,- "request_count": self.request_count,- }-- def to_turn_dict(self) -> dict[str, int]:- """Project canonical usage into the compact WebUI/TUI per-turn shape."""- result: dict[str, int] = {- "prompt_tokens": self.input_tokens,- "completion_tokens": self.output_tokens,- "total_tokens": self.total_tokens,- "request_count": self.request_count,- "estimated_tokens": self.estimated_tokens,- }- if self.context_tokens is not None:- result["context_tokens"] = self.context_tokens- if self.cache_read_tokens is not None:- result["cached_tokens"] = self.cache_read_tokens- if self.cache_write_tokens is not None:- result["cache_write_tokens"] = self.cache_write_tokens- if self.generation_ms > 0 and self.measured_output_tokens > 0:- result["generation_ms"] = self.generation_ms- result["measured_completion_tokens"] = self.measured_output_tokens- if self.timed_requests > 0:- result["ttft_ms"] = self.ttft_ms- result["timed_requests"] = self.timed_requests- return result-- @classmethod- def from_dict(cls, value: object) -> LLMUsage | None:- """Validate the exact first-party serialized contract."""- if not isinstance(value, dict):- return None- data = cast(dict[object, object], value)- integer_fields = (- "input_tokens",- "output_tokens",- "reported_tokens",- "estimated_tokens",- "generation_ms",- "measured_output_tokens",- "ttft_ms",- "timed_requests",- "request_count",- )- serialized_fields = {- *integer_fields,- "total_tokens",- "cache_read_tokens",- "cache_write_tokens",- "context_tokens",- "source",- }- if set(data) != serialized_fields:- return None- if any(- not isinstance(item := data.get(name), int) or isinstance(item, bool)- for name in integer_fields- ):- return None- cache_read = data.get("cache_read_tokens")- cache_write = data.get("cache_write_tokens")- context_tokens = data.get("context_tokens")- total = data.get("total_tokens")- source = data.get("source")- if any(- item is not None and (not isinstance(item, int) or isinstance(item, bool))- for item in (cache_read, cache_write, context_tokens)- ) or not isinstance(total, int) or isinstance(total, bool):- return None- try:- usage = cls(- input_tokens=cast(int, data["input_tokens"]),- output_tokens=cast(int, data["output_tokens"]),- total_tokens=total,- cache_read_tokens=cast(int | None, cache_read),- cache_write_tokens=cast(int | None, cache_write),- reported_tokens=cast(int, data["reported_tokens"]),- estimated_tokens=cast(int, data["estimated_tokens"]),- generation_ms=cast(int, data["generation_ms"]),- measured_output_tokens=cast(int, data["measured_output_tokens"]),- ttft_ms=cast(int, data["ttft_ms"]),- timed_requests=cast(int, data["timed_requests"]),- context_tokens=cast(int | None, context_tokens),- request_count=cast(int, data["request_count"]),- )- except (KeyError, ValueError):- return None- if source != usage.source:- return None- return usage--@dataclassclass LLMResponse:"""Response from an LLM provider."""@@ -621,15 +338,6 @@ class LLMResponse:return self.finish_reason in ("tool_calls", "function_call", "stop")-@dataclass(frozen=True)-class GenerationSettings:- """Default generation settings."""-- temperature: float = 0.7- max_tokens: int = 4096- reasoning_effort: str | None = None--_SYNTHETIC_USER_CONTENT = "(conversation continued)"diff --git a/nanobot/providers/fallback_provider.py b/nanobot/providers/fallback_provider.pyindex a2de5f96f..3d80661fb 100644--- a/nanobot/providers/fallback_provider.py+++ b/nanobot/providers/fallback_provider.py@@ -23,7 +23,7 @@ from nanobot.providers.base import (RetryEventCallback,RetryStatusCallback,)-from nanobot.providers.oauth_model_catalog import oauth_catalog_auth_rejected+from nanobot.providers.oauth_catalog_cache import oauth_catalog_auth_rejectedfrom nanobot.providers.registry import find_by_name# Circuit breaker tuned to match OpenAICompatProvider's Responses API breaker.diff --git a/nanobot/providers/generation.py b/nanobot/providers/generation.pynew file mode 100644index 000000000..7af1bc0e9--- /dev/null+++ b/nanobot/providers/generation.py@@ -0,0 +1,12 @@+"""Provider-independent generation defaults."""++from dataclasses import dataclass+++@dataclass(frozen=True)+class GenerationSettings:+ """Default generation settings."""++ temperature: float = 0.7+ max_tokens: int = 4096+ reasoning_effort: str | None = Nonediff --git a/nanobot/providers/github_copilot_provider.py b/nanobot/providers/github_copilot_provider.pyindex 98487a80e..b813896d0 100644--- a/nanobot/providers/github_copilot_provider.py+++ b/nanobot/providers/github_copilot_provider.py@@ -20,7 +20,7 @@ from oauth_cli_kit.storage import FileTokenStoragefrom nanobot.providers.base import LLMResponse, ProviderCallContextfrom nanobot.providers.model_api import ModelAPICapabilities, RequestAPI-from nanobot.providers.oauth_model_catalog import (+from nanobot.providers.oauth_catalog_cache import (OAuthCatalogAuthRequiredError,OAuthModelCatalog,OAuthModelCatalogSnapshot,diff --git a/nanobot/providers/oauth_catalog_cache.py b/nanobot/providers/oauth_catalog_cache.pynew file mode 100644index 000000000..872819a6c--- /dev/null+++ b/nanobot/providers/oauth_catalog_cache.py@@ -0,0 +1,241 @@+"""Shared cache seam for OAuth provider model discovery."""++from __future__ import annotations++import threading+import time+from collections.abc import Callable, Sequence+from dataclasses import dataclass, replace+from typing import Literal, cast++import httpx+from loguru import logger++from nanobot.providers.registry import ProviderModelSpec++CatalogSource = Literal["remote", "cache", "stale", "fallback"]+CatalogErrorKind = Literal["auth_required", "unavailable"]+++class OAuthCatalogAuthRequiredError(RuntimeError):+ """The provider's credentials are missing or were explicitly rejected."""+++def oauth_catalog_auth_rejected(status: int, payload: object = None) -> bool:+ """Classify only explicit credential failures, never arbitrary response text."""+ if status == 401:+ return True+ if status not in {400, 403} or not isinstance(payload, dict):+ return False+ error = cast(dict[object, object], payload).get("error")+ code = cast(dict[object, object], error).get("code") if isinstance(error, dict) else error+ return isinstance(code, str) and code in {+ "invalid_grant", "invalid_token", "token_revoked", "refresh_token_expired",+ "refresh_token_reused", "refresh_token_invalidated",+ }+++def _catalog_error_kind(exc: Exception) -> CatalogErrorKind:+ if isinstance(exc, OAuthCatalogAuthRequiredError):+ return "auth_required"+ if isinstance(exc, httpx.HTTPStatusError):+ payload: object = None+ if len(exc.response.content) <= 16_384:+ try:+ payload = exc.response.json()+ except ValueError:+ pass+ if oauth_catalog_auth_rejected(exc.response.status_code, payload):+ return "auth_required"+ return "unavailable"+++@dataclass(frozen=True, slots=True)+class OAuthModelCatalogSnapshot:+ """One usable catalog view, including where it came from."""++ models: tuple[ProviderModelSpec, ...]+ source: CatalogSource+ fetched_at: float+ message: str | None = None+ error_kind: CatalogErrorKind | None = None++ def find(self, model: str) -> ProviderModelSpec | None:+ wire_id = model.split("/", 1)[-1]+ return next(+ (item for item in self.models if item.id.split("/", 1)[-1] == wire_id),+ None,+ )+++@dataclass(frozen=True, slots=True)+class _CacheEntry:+ snapshot: OAuthModelCatalogSnapshot+ stored_at: float+++@dataclass(frozen=True, slots=True)+class _FailureEntry:+ retry_at: float+ error_kind: CatalogErrorKind+++class OAuthModelCatalog:+ """Cache one provider's discovery behind a small failure-tolerant interface."""++ def __init__(+ self,+ *,+ fallback_models: Sequence[ProviderModelSpec],+ fetch: Callable[[str | None], Sequence[ProviderModelSpec]],+ fresh_ttl_s: float = 5 * 60,+ stale_ttl_s: float = 24 * 60 * 60,+ failure_ttl_s: float = 30,+ max_entries: int = 8,+ monotonic: Callable[[], float] = time.monotonic,+ wall_clock: Callable[[], float] = time.time,+ ) -> None:+ if fresh_ttl_s < 0 or stale_ttl_s < fresh_ttl_s or failure_ttl_s < 0:+ raise ValueError("catalog cache TTLs are invalid")+ if max_entries < 1:+ raise ValueError("catalog cache must allow at least one entry")+ self._fallback_models = tuple(fallback_models)+ self._fetch = fetch+ self._fresh_ttl_s = fresh_ttl_s+ self._stale_ttl_s = stale_ttl_s+ self._failure_ttl_s = failure_ttl_s+ self._max_entries = max_entries+ self._monotonic = monotonic+ self._wall_clock = wall_clock+ self._condition = threading.Condition()+ self._entries: dict[str, _CacheEntry] = {}+ self._failures: dict[str, _FailureEntry] = {}+ self._inflight: set[str] = set()+ self._generation = 0++ def get(+ self, *, cache_key: str, proxy: str | None = None, refresh: bool = False,+ ) -> OAuthModelCatalogSnapshot:+ """Reuse cached discovery unless explicitly refreshed, retaining fallback models."""+ with self._condition:+ generation = self._generation+ if not refresh:+ cached = self._cached_result(cache_key)+ if cached is not None:+ return cached+ if cache_key in self._inflight:+ while cache_key in self._inflight:+ self._condition.wait()+ if generation != self._generation:+ return self._stale_or_fallback(None, self._monotonic())+ cached = self._cached_result(cache_key)+ if cached is not None:+ return cached+ self._inflight.add(cache_key)++ try:+ models = tuple(self._fetch(proxy))+ if not models:+ raise ValueError("provider returned an empty model catalog")+ except Exception as exc:+ error_kind = _catalog_error_kind(exc)+ logger.warning("OAuth model catalog refresh failed: kind={}", error_kind)+ with self._condition:+ result = (+ self._stale_or_fallback(None, self._monotonic())+ if generation != self._generation+ else self._failure_result(cache_key, error_kind)+ )+ else:+ now = self._monotonic()+ result = OAuthModelCatalogSnapshot(+ models=models,+ source="remote",+ fetched_at=self._wall_clock(),+ )+ with self._condition:+ if generation != self._generation:+ result = self._stale_or_fallback(None, now)+ else:+ self._store(cache_key, _CacheEntry(snapshot=result, stored_at=now))+ self._failures.pop(cache_key, None)+ finally:+ with self._condition:+ self._inflight.discard(cache_key)+ self._condition.notify_all()++ return result++ def invalidate(self) -> None:+ """Drop cached work and prevent an older identity refresh from being stored."""+ with self._condition:+ self._generation += 1+ self._entries.clear()+ self._failures.clear()+ self._condition.notify_all()++ def peek(self, *, cache_key: str) -> OAuthModelCatalogSnapshot | None:+ """Read the last successful metadata for this identity without discovery."""+ with self._condition:+ entry = self._entries.get(cache_key)+ return entry.snapshot if entry is not None else None++ def _cached_result(self, cache_key: str) -> OAuthModelCatalogSnapshot | None:+ now = self._monotonic()+ entry = self._entries.get(cache_key)+ failure = self._failures.get(cache_key)+ if failure is not None and failure.retry_at <= now:+ self._failures.pop(cache_key, None)+ elif failure is not None:+ return self._stale_or_fallback(entry, now, failure.error_kind)+ if entry is not None and now - entry.stored_at < self._fresh_ttl_s:+ return replace(entry.snapshot, source="cache")+ return None++ def _failure_result(+ self, cache_key: str, error_kind: CatalogErrorKind,+ ) -> OAuthModelCatalogSnapshot:+ now = self._monotonic()+ self._reserve(cache_key)+ self._failures[cache_key] = _FailureEntry(now + self._failure_ttl_s, error_kind)+ return self._stale_or_fallback(self._entries.get(cache_key), now, error_kind)++ def _stale_or_fallback(+ self,+ entry: _CacheEntry | None,+ now: float,+ error_kind: CatalogErrorKind = "unavailable",+ ) -> OAuthModelCatalogSnapshot:+ if entry is not None and now - entry.stored_at < self._stale_ttl_s:+ return replace(+ entry.snapshot,+ source="stale",+ message="Could not refresh the online model list; showing cached models.",+ error_kind=error_kind,+ )+ return OAuthModelCatalogSnapshot(+ models=self._fallback_models,+ source="fallback",+ fetched_at=self._wall_clock(),+ message="Could not load the online model list; showing built-in fallback models.",+ error_kind=error_kind,+ )++ def _store(self, cache_key: str, entry: _CacheEntry) -> None:+ self._reserve(cache_key)+ self._entries[cache_key] = entry++ def _reserve(self, cache_key: str) -> None:+ known = set(self._entries) | set(self._failures)+ if cache_key in known or len(known) < self._max_entries:+ return+ oldest = min(+ known,+ key=lambda key: (+ self._entries[key].stored_at+ if key in self._entries+ else self._failures[key].retry_at - self._failure_ttl_s+ ),+ )+ self._entries.pop(oldest, None)+ self._failures.pop(oldest, None)diff --git a/nanobot/providers/oauth_model_catalog.py b/nanobot/providers/oauth_model_catalog.pyindex fe6daffdd..5e9b819a4 100644--- a/nanobot/providers/oauth_model_catalog.py+++ b/nanobot/providers/oauth_model_catalog.py@@ -1,244 +1,25 @@-"""Shared cache seam for OAuth provider model discovery."""+"""Dispatch OAuth model discovery to the owning provider."""from __future__ import annotations-import threading-import time-from collections.abc import Callable, Sequence-from dataclasses import dataclass, replace-from typing import Literal, cast--import httpx-from loguru import logger--from nanobot.providers.registry import ProviderModelSpec--CatalogSource = Literal["remote", "cache", "stale", "fallback"]-CatalogErrorKind = Literal["auth_required", "unavailable"]---class OAuthCatalogAuthRequiredError(RuntimeError):- """The provider's credentials are missing or were explicitly rejected."""---def oauth_catalog_auth_rejected(status: int, payload: object = None) -> bool:- """Classify only explicit credential failures, never arbitrary response text."""- if status == 401:- return True- if status not in {400, 403} or not isinstance(payload, dict):- return False- error = cast(dict[object, object], payload).get("error")- code = cast(dict[object, object], error).get("code") if isinstance(error, dict) else error- return isinstance(code, str) and code in {- "invalid_grant", "invalid_token", "token_revoked", "refresh_token_expired",- "refresh_token_reused", "refresh_token_invalidated",- }---def _catalog_error_kind(exc: Exception) -> CatalogErrorKind:- if isinstance(exc, OAuthCatalogAuthRequiredError):- return "auth_required"- if isinstance(exc, httpx.HTTPStatusError):- payload: object = None- if len(exc.response.content) <= 16_384:- try:- payload = exc.response.json()- except ValueError:- pass- if oauth_catalog_auth_rejected(exc.response.status_code, payload):- return "auth_required"- return "unavailable"---@dataclass(frozen=True, slots=True)-class OAuthModelCatalogSnapshot:- """One usable catalog view, including where it came from."""-- models: tuple[ProviderModelSpec, ...]- source: CatalogSource- fetched_at: float- message: str | None = None- error_kind: CatalogErrorKind | None = None-- def find(self, model: str) -> ProviderModelSpec | None:- wire_id = model.split("/", 1)[-1]- return next(- (item for item in self.models if item.id.split("/", 1)[-1] == wire_id),- None,- )---@dataclass(frozen=True, slots=True)-class _CacheEntry:- snapshot: OAuthModelCatalogSnapshot- stored_at: float---@dataclass(frozen=True, slots=True)-class _FailureEntry:- retry_at: float- error_kind: CatalogErrorKind---class OAuthModelCatalog:- """Cache one provider's discovery behind a small failure-tolerant interface."""-- def __init__(- self,- *,- fallback_models: Sequence[ProviderModelSpec],- fetch: Callable[[str | None], Sequence[ProviderModelSpec]],- fresh_ttl_s: float = 5 * 60,- stale_ttl_s: float = 24 * 60 * 60,- failure_ttl_s: float = 30,- max_entries: int = 8,- monotonic: Callable[[], float] = time.monotonic,- wall_clock: Callable[[], float] = time.time,- ) -> None:- if fresh_ttl_s < 0 or stale_ttl_s < fresh_ttl_s or failure_ttl_s < 0:- raise ValueError("catalog cache TTLs are invalid")- if max_entries < 1:- raise ValueError("catalog cache must allow at least one entry")- self._fallback_models = tuple(fallback_models)- self._fetch = fetch- self._fresh_ttl_s = fresh_ttl_s- self._stale_ttl_s = stale_ttl_s- self._failure_ttl_s = failure_ttl_s- self._max_entries = max_entries- self._monotonic = monotonic- self._wall_clock = wall_clock- self._condition = threading.Condition()- self._entries: dict[str, _CacheEntry] = {}- self._failures: dict[str, _FailureEntry] = {}- self._inflight: set[str] = set()- self._generation = 0-- def get(- self, *, cache_key: str, proxy: str | None = None, refresh: bool = False,- ) -> OAuthModelCatalogSnapshot:- """Reuse cached discovery unless explicitly refreshed, retaining fallback models."""- with self._condition:- generation = self._generation- if not refresh:- cached = self._cached_result(cache_key)- if cached is not None:- return cached- if cache_key in self._inflight:- while cache_key in self._inflight:- self._condition.wait()- if generation != self._generation:- return self._stale_or_fallback(None, self._monotonic())- cached = self._cached_result(cache_key)- if cached is not None:- return cached- self._inflight.add(cache_key)-- try:- models = tuple(self._fetch(proxy))- if not models:- raise ValueError("provider returned an empty model catalog")- except Exception as exc:- error_kind = _catalog_error_kind(exc)- logger.warning("OAuth model catalog refresh failed: kind={}", error_kind)- with self._condition:- result = (- self._stale_or_fallback(None, self._monotonic())- if generation != self._generation- else self._failure_result(cache_key, error_kind)- )- else:- now = self._monotonic()- result = OAuthModelCatalogSnapshot(- models=models,- source="remote",- fetched_at=self._wall_clock(),- )- with self._condition:- if generation != self._generation:- result = self._stale_or_fallback(None, now)- else:- self._store(cache_key, _CacheEntry(snapshot=result, stored_at=now))- self._failures.pop(cache_key, None)- finally:- with self._condition:- self._inflight.discard(cache_key)- self._condition.notify_all()-- return result-- def invalidate(self) -> None:- """Drop cached work and prevent an older identity refresh from being stored."""- with self._condition:- self._generation += 1- self._entries.clear()- self._failures.clear()- self._condition.notify_all()-- def peek(self, *, cache_key: str) -> OAuthModelCatalogSnapshot | None:- """Read the last successful metadata for this identity without discovery."""- with self._condition:- entry = self._entries.get(cache_key)- return entry.snapshot if entry is not None else None-- def _cached_result(self, cache_key: str) -> OAuthModelCatalogSnapshot | None:- now = self._monotonic()- entry = self._entries.get(cache_key)- failure = self._failures.get(cache_key)- if failure is not None and failure.retry_at <= now:- self._failures.pop(cache_key, None)- elif failure is not None:- return self._stale_or_fallback(entry, now, failure.error_kind)- if entry is not None and now - entry.stored_at < self._fresh_ttl_s:- return replace(entry.snapshot, source="cache")- return None-- def _failure_result(- self, cache_key: str, error_kind: CatalogErrorKind,- ) -> OAuthModelCatalogSnapshot:- now = self._monotonic()- self._reserve(cache_key)- self._failures[cache_key] = _FailureEntry(now + self._failure_ttl_s, error_kind)- return self._stale_or_fallback(self._entries.get(cache_key), now, error_kind)-- def _stale_or_fallback(- self,- entry: _CacheEntry | None,- now: float,- error_kind: CatalogErrorKind = "unavailable",- ) -> OAuthModelCatalogSnapshot:- if entry is not None and now - entry.stored_at < self._stale_ttl_s:- return replace(- entry.snapshot,- source="stale",- message="Could not refresh the online model list; showing cached models.",- error_kind=error_kind,- )- return OAuthModelCatalogSnapshot(- models=self._fallback_models,- source="fallback",- fetched_at=self._wall_clock(),- message="Could not load the online model list; showing built-in fallback models.",- error_kind=error_kind,- )-- def _store(self, cache_key: str, entry: _CacheEntry) -> None:- self._reserve(cache_key)- self._entries[cache_key] = entry-- def _reserve(self, cache_key: str) -> None:- known = set(self._entries) | set(self._failures)- if cache_key in known or len(known) < self._max_entries:- return- oldest = min(- known,- key=lambda key: (- self._entries[key].stored_at- if key in self._entries- else self._failures[key].retry_at - self._failure_ttl_s- ),- )- self._entries.pop(oldest, None)- self._failures.pop(oldest, None)+from nanobot.providers.oauth_catalog_cache import (+ CatalogErrorKind as CatalogErrorKind,+)+from nanobot.providers.oauth_catalog_cache import (+ CatalogSource as CatalogSource,+)+from nanobot.providers.oauth_catalog_cache import (+ OAuthCatalogAuthRequiredError as OAuthCatalogAuthRequiredError,+)+from nanobot.providers.oauth_catalog_cache import (+ OAuthModelCatalog as OAuthModelCatalog,+)+from nanobot.providers.oauth_catalog_cache import (+ OAuthModelCatalogSnapshot as OAuthModelCatalogSnapshot,+)+from nanobot.providers.oauth_catalog_cache import (+ oauth_catalog_auth_rejected as oauth_catalog_auth_rejected,+)def get_oauth_model_catalog(diff --git a/nanobot/providers/openai_codex_provider.py b/nanobot/providers/openai_codex_provider.pyindex 39911a43a..4f91cd8d9 100644--- a/nanobot/providers/openai_codex_provider.py+++ b/nanobot/providers/openai_codex_provider.py@@ -27,7 +27,7 @@ from nanobot.providers.base import (ProviderConversationState,)from nanobot.providers.images import prepare_inline_images-from nanobot.providers.oauth_model_catalog import (+from nanobot.providers.oauth_catalog_cache import (OAuthCatalogAuthRequiredError,OAuthModelCatalog,OAuthModelCatalogSnapshot,diff --git a/nanobot/providers/xai_grok_provider.py b/nanobot/providers/xai_grok_provider.pyindex e88c77674..bad91d2e4 100644--- a/nanobot/providers/xai_grok_provider.py+++ b/nanobot/providers/xai_grok_provider.py@@ -21,7 +21,7 @@ from nanobot.providers.base import (LLMUsage,ToolCallRequest,)-from nanobot.providers.oauth_model_catalog import (+from nanobot.providers.oauth_catalog_cache import (OAuthCatalogAuthRequiredError,OAuthModelCatalog,OAuthModelCatalogSnapshot,diff --git a/nanobot/session/automation_spec.py b/nanobot/session/automation_spec.pynew file mode 100644index 000000000..cfc31f925--- /dev/null+++ b/nanobot/session/automation_spec.py@@ -0,0 +1,51 @@+"""Shared contracts for session-bound automation sources."""++from __future__ import annotations++from collections.abc import Callable, Mapping+from dataclasses import dataclass, field+from typing import Any, cast++AUTOMATION_HISTORY_META = "_automation_turn"+++@dataclass(frozen=True)+class AutomationTurnSpec:+ """Source-specific wiring for one session-bound automation turn type."""++ kind: str+ trigger_meta_key: str+ legacy_history_meta_key: str | None = None+ history_fields: Mapping[str, str] = field(default_factory=dict[str, str])+ text_builder: Callable[[Mapping[str, Any]], str | None] | None = None+++def automation_trigger(+ metadata: Mapping[str, Any] | None,+ spec: AutomationTurnSpec,+) -> dict[str, Any] | None:+ """Return source trigger metadata for *spec* when present."""+ raw = (metadata or {}).get(spec.trigger_meta_key)+ return cast(dict[str, Any], raw) if isinstance(raw, dict) else None+++def automation_history_overrides_for_spec(+ metadata: Mapping[str, Any] | None,+ spec: AutomationTurnSpec,+) -> tuple[str | None, dict[str, Any]]:+ """Return hidden session-history text/metadata overrides for *spec*."""+ trigger = automation_trigger(metadata, spec)+ if not trigger:+ return None, {}++ details: dict[str, Any] = {"kind": spec.kind}+ extra: dict[str, Any] = {AUTOMATION_HISTORY_META: details}+ if spec.legacy_history_meta_key:+ extra[spec.legacy_history_meta_key] = True+ for history_key, trigger_key in spec.history_fields.items():+ value = trigger.get(trigger_key)+ extra[history_key] = value+ details[history_key] = value++ text = spec.text_builder(trigger) if spec.text_builder else None+ return text, extradiff --git a/nanobot/session/automation_turns.py b/nanobot/session/automation_turns.pyindex 336f9f491..b401eb71e 100644--- a/nanobot/session/automation_turns.py+++ b/nanobot/session/automation_turns.py@@ -2,59 +2,26 @@from __future__ import annotations-from collections.abc import Callable, Mapping-from dataclasses import dataclass, field+from collections.abc import Mappingfrom functools import lru_cache-from typing import Any, cast--AUTOMATION_HISTORY_META = "_automation_turn"---@dataclass(frozen=True)-class AutomationTurnSpec:- """Source-specific wiring for one session-bound automation turn type."""-- kind: str- trigger_meta_key: str- legacy_history_meta_key: str | None = None- history_fields: Mapping[str, str] = field(default_factory=dict[str, str])- text_builder: Callable[[Mapping[str, Any]], str | None] | None = None---def automation_trigger(- metadata: Mapping[str, Any] | None,- spec: AutomationTurnSpec,-) -> dict[str, Any] | None:- """Return source trigger metadata for *spec* when present."""- raw = (metadata or {}).get(spec.trigger_meta_key)- return cast(dict[str, Any], raw) if isinstance(raw, dict) else None---def automation_history_overrides_for_spec(- metadata: Mapping[str, Any] | None,- spec: AutomationTurnSpec,-) -> tuple[str | None, dict[str, Any]]:- """Return hidden session-history text/metadata overrides for *spec*."""- trigger = automation_trigger(metadata, spec)- if not trigger:- return None, {}-- details: dict[str, Any] = {"kind": spec.kind}- extra: dict[str, Any] = {AUTOMATION_HISTORY_META: details}- if spec.legacy_history_meta_key:- extra[spec.legacy_history_meta_key] = True- for history_key, trigger_key in spec.history_fields.items():- value = trigger.get(trigger_key)- extra[history_key] = value- details[history_key] = value-- text = spec.text_builder(trigger) if spec.text_builder else None- return text, extra+from typing import Any++from nanobot.session.automation_spec import (+ AUTOMATION_HISTORY_META as AUTOMATION_HISTORY_META,+)+from nanobot.session.automation_spec import (+ AutomationTurnSpec as AutomationTurnSpec,+)+from nanobot.session.automation_spec import (+ automation_history_overrides_for_spec as automation_history_overrides_for_spec,+)+from nanobot.session.automation_spec import (+ automation_trigger as automation_trigger,+)@lru_cache(maxsize=1)def _automation_specs() -> tuple[AutomationTurnSpec, ...]:- # Source modules import the generic helpers above, so keep spec loading lazy.from nanobot.cron.session_turns import CRON_AUTOMATION_SPECfrom nanobot.triggers.local_session_turns import LOCAL_TRIGGER_AUTOMATION_SPECdiff --git a/nanobot/session/recovery.py b/nanobot/session/recovery.pyindex b77a5b60c..c61dcf306 100644--- a/nanobot/session/recovery.py+++ b/nanobot/session/recovery.py@@ -1,14 +1,8 @@-"""Durable, side-effect-safe recovery for interrupted WebUI turns.--The coordinator owns restart policy. Checkpoint materialization is a session-operation shared with AgentLoop lifecycle boundaries, so transport code never-has to guess whether an interrupted tool call is safe to replay.-"""+"""Durable session checkpoints and pending-turn recovery state."""from __future__ import annotationsimport asyncio-import dataclassesimport jsonfrom collections.abc import Iterable, Mappingfrom datetime import datetime@@ -18,17 +12,7 @@ from uuid import uuid4from loguru import loggerfrom nanobot.bus.events import InboundMessage-from nanobot.bus.outbound_events import (- RecoveryStateEvent,- SessionUpdatedEvent,- outbound_message_for_event,-)-from nanobot.bus.queue import MessageBus-from nanobot.session import turn_continuation-from nanobot.session.keys import UNIFIED_SESSION_KEY, last_channel_from_metadata-from nanobot.session.manager import Session, SessionManager-from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY-from nanobot.webui.session_identity import webui_chat_id, webui_session_key+from nanobot.session.manager import SessionRUNTIME_CHECKPOINT_KEY = "runtime_checkpoint"PENDING_USER_TURN_KEY = "pending_user_turn"@@ -40,20 +24,12 @@ PROVIDER_STATE_CHECKPOINT_VERSION_KEY = "provider_state_checkpoint_version"PROVIDER_STATE_CHECKPOINT_VERSION = "v1"_RECOVERY_STATUSES = frozenset({"resuming", "awaiting_user", "recovered", "failed"})-_UNCERTAIN_TOOL_PHASES = frozenset({"awaiting_tools"})-_KNOWN_CHECKPOINT_PHASES = frozenset(+UNCERTAIN_TOOL_PHASES = frozenset({"awaiting_tools"})+KNOWN_CHECKPOINT_PHASES = frozenset({"final_response", "tools_completed", "awaiting_tools", "error"})-class RecoveryActionError(ValueError):- """A stale or malformed recovery action from an authenticated WebUI."""-- def __init__(self, message: str, *, status: int = 400) -> None:- super().__init__(message)- self.status = status--class RecoveryAdmission(Protocol):"""Narrow AgentLoop boundary for explicit recovery validation."""@@ -211,7 +187,7 @@ def _checkpoint_tool_call_ids(return ids if len(ids) == len(set(ids)) else None-def _runtime_checkpoint_is_well_formed(checkpoint: Mapping[str, Any]) -> bool:+def runtime_checkpoint_is_well_formed(checkpoint: Mapping[str, Any]) -> bool:"""Return whether a checkpoint is safe to offer for continuation.Restoration stays tolerant so Dismiss can always clear corrupt state.@@ -371,7 +347,7 @@ def restore_runtime_checkpoint(session: Session) -> bool:return True-def _discard_runtime_checkpoint(session: Session) -> bool:+def discard_runtime_checkpoint(session: Session) -> bool:"""Drop checkpoint state that cannot be projected into valid history."""if RUNTIME_CHECKPOINT_KEY not in session.metadata:return False@@ -446,495 +422,3 @@ def recovery_state_from_metadata(metadata: Mapping[str, Any] | None) -> dict[strif isinstance(can_continue, bool):payload["can_continue"] = can_continuereturn payload--[email protected](slots=True)-class RecoveryCoordinator:- """Classify, announce, and gate durable WebUI turn recovery."""-- sessions: SessionManager- bus: MessageBus- unified_session: bool = False- _active_recovery_tasks: dict[str, asyncio.Task[Any]] = dataclasses.field(- default_factory=dict,- init=False,- repr=False,- )-- def register_recovery_task(self, session_key: str, task: asyncio.Task[Any]) -> None:- """Track the task that owns an explicit recovery continuation."""- self._active_recovery_tasks[session_key] = task-- def unregister_recovery_task(self, session_key: str, task: asyncio.Task[Any]) -> None:- """Drop a recovery task without removing a newer task for the same session."""- if self._active_recovery_tasks.get(session_key) is task:- self._active_recovery_tasks.pop(session_key, None)-- async def _cancel_active_recovery(self, session_key: str) -> None:- """Stop an explicit continuation before accepting newer user input."""- task = self._active_recovery_tasks.get(session_key)- if task is None or task is asyncio.current_task() or task.done():- return- task.cancel()- # AgentLoop's cancellation path materializes any partial checkpoint and- # releases its pending queue. Wait for that ownership to be released- # before the newer message is routed.- await asyncio.gather(task, return_exceptions=True)-- async def scan(self) -> None:- """Recover every interrupted WebUI session once at gateway startup."""- for key in self._recovery_candidates():- metadata_payload = self.sessions.read_session_metadata(key)- raw_metadata = metadata_payload.get("metadata") if metadata_payload else None- metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {}- route = self._websocket_route_for(key, metadata)- if route is None:- continue- unfinished = self._has_unfinished_webui_transcript(key)- if not self._needs_recovery(metadata) and not unfinished:- continue- session = self.sessions.get_or_create(key)- try:- await self._recover_session(session, route[1])- await self._requeue_pending_followups(session)- except Exception:- logger.exception("failed to recover interrupted WebUI session {}", session.key)- state = recovery_state_from_metadata(session.metadata)- failed = self._set_state(- session,- status="failed",- recovery_id=cast(str, state["recovery_id"]) if state else uuid4().hex,- attempts=cast(int, state.get("attempts", 0)) if state else 0,- reason="recovery_failed",- can_continue=False,- )- self.sessions.save(session)- await self._publish(route[1], failed)-- def _recovery_candidates(self) -> list[str]:- """Discover canonical and transcript-only WebUI sessions cheaply."""- candidates = dict.fromkeys(- key- for item in self.sessions.list_sessions()- if isinstance((key := item.get("key")), str)- )- try:- # Imported lazily because the sidebar index also projects recovery- # metadata. The index is the owner of transcript-only discovery;- # duplicating its filename and migration rules here would drift.- from nanobot.webui.session_list_index import list_webui_sessions-- for item in list_webui_sessions(self.sessions):- key = item.get("key")- if isinstance(key, str):- candidates.setdefault(key, None)- except Exception:- # Canonical checkpoint recovery remains available even if the- # optional display-history index is corrupt or unavailable.- logger.exception("failed to discover transcript-only WebUI sessions")- return list(candidates)-- @staticmethod- def _needs_recovery(metadata: Mapping[str, Any]) -> bool:- if metadata.get(PENDING_USER_TURN_KEY) is True:- return True- if isinstance(metadata.get(RUNTIME_CHECKPOINT_KEY), dict):- return True- followups = metadata.get(PENDING_FOLLOWUPS_KEY)- if isinstance(followups, list) and len(cast(list[object], followups)) > 0:- return True- state = recovery_state_from_metadata(metadata)- return bool(state and state["status"] in {"resuming", "awaiting_user", "failed"})-- async def admit(self, message: InboundMessage) -> bool:- """Reject stale queued recoveries and let new user input supersede them."""- recovery_id = message.metadata.get(RECOVERY_INBOUND_METADATA_KEY)- if isinstance(recovery_id, str):- session = self.sessions.get_or_create(message.session_key)- state = recovery_state_from_metadata(session.metadata)- return bool(- state- and state["status"] == "resuming"- and state["recovery_id"] == recovery_id- )- if message.channel != "websocket":- return True- session = self.sessions.get_or_create(message.session_key)- state = recovery_state_from_metadata(session.metadata)- if state and state["status"] in {"resuming", "awaiting_user", "failed"}:- await self._cancel_active_recovery(message.session_key)- restore_runtime_checkpoint(session)- if not restore_pending_interruption(session, superseded=True):- append_recovery_interruption(session, superseded=True)- recovered = self._set_state(- session,- status="recovered",- recovery_id=cast(str, state["recovery_id"]),- attempts=cast(int, state.get("attempts", 0)),- reason="superseded",- )- self.sessions.save(session)- await self._publish(message.chat_id, recovered)- return True-- async def turn_completed(self, session_key: str) -> None:- """Resolve a resuming state after the recovered turn commits."""- session = self.sessions.get_or_create(session_key)- state = recovery_state_from_metadata(session.metadata)- if not state or state["status"] != "resuming":- return- route = self._websocket_route(session)- if route is None:- return- recovered = self._set_state(- session,- status="recovered",- recovery_id=cast(str, state["recovery_id"]),- attempts=cast(int, state.get("attempts", 0)),- reason="continued",- )- self.sessions.save(session)- await self._publish(route[1], recovered)-- async def handle_action(self, action: str, payload: dict[str, Any]) -> dict[str, Any]:- """Apply an authenticated continue/dismiss operation."""- chat_id = payload.get("chat_id")- recovery_id = payload.get("recovery_id")- if not isinstance(chat_id, str) or not chat_id:- raise RecoveryActionError("missing chat_id")- if not isinstance(recovery_id, str) or not recovery_id:- raise RecoveryActionError("missing recovery_id")- session = self.sessions.get_or_create(self._session_key(chat_id))- state = recovery_state_from_metadata(session.metadata)- if not state or state["recovery_id"] != recovery_id:- raise RecoveryActionError("recovery state is stale", status=409)-- if action == "dismiss":- restore_runtime_checkpoint(session)- restore_pending_interruption(session)- next_state = self._set_state(- session,- status="recovered",- recovery_id=recovery_id,- attempts=cast(int, state.get("attempts", 0)),- reason="dismissed",- )- self.sessions.save(session)- await self._publish(chat_id, next_state)- return next_state- if action != "continue":- raise RecoveryActionError("unknown recovery action")- if state["status"] not in {"awaiting_user", "failed"}:- raise RecoveryActionError("recovery is not waiting for confirmation", status=409)- if state.get("can_continue") is False:- raise RecoveryActionError("recovery context is unavailable", status=409)- next_state = self._set_state(- session,- status="resuming",- recovery_id=recovery_id,- attempts=cast(int, state.get("attempts", 0)) + 1,- reason="user_confirmed",- resume_message_count=len(session.messages),- )- self.sessions.save(session)- await self._publish(chat_id, next_state)- await self._queue_continuation(session, chat_id, next_state)- return next_state-- async def _recover_session(self, session: Session, chat_id: str) -> None:- checkpoint_value = cast(object, session.metadata.get(RUNTIME_CHECKPOINT_KEY))- checkpoint = (- cast(dict[str, Any], checkpoint_value)- if isinstance(checkpoint_value, dict)- else None- )- pending = session.metadata.get(PENDING_USER_TURN_KEY) is True- state = recovery_state_from_metadata(session.metadata)- if not pending and checkpoint is None:- if state and state["status"] == "resuming":- resume_count = self._resume_message_count(session)- if resume_count is not None and len(session.messages) > resume_count:- next_state = self._set_state(- session,- status="recovered",- recovery_id=cast(str, state["recovery_id"]),- attempts=cast(int, state.get("attempts", 0)),- reason="committed",- )- else:- next_state = self._set_state(- session,- status="awaiting_user",- recovery_id=cast(str, state["recovery_id"]),- attempts=cast(int, state.get("attempts", 1)),- reason="loop_guard",- )- self.sessions.save(session)- await self._publish(chat_id, next_state)- elif self._has_unfinished_webui_transcript(session.key):- # A normal last-client shutdown can materialize the checkpoint- # before the process exits. In that path there is no pending- # marker left to classify, but the append-only transcript still- # contains an activity row without a turn_end. Treat it as an- # interrupted turn instead of letting the UI resurrect it as a- # forever-running spinner.- can_continue = self._has_saved_continuation_context(session)- waiting = self._set_state(- session,- status="awaiting_user",- recovery_id=uuid4().hex,- attempts=0,- reason=(- "interrupted_with_saved_context"- if can_continue- else "interrupted_without_checkpoint"- ),- can_continue=can_continue,- )- self.sessions.save(session)- await self._publish(chat_id, waiting)- return- if state and state["status"] in {"awaiting_user", "failed"}:- await self._publish(chat_id, state)- return- if state and state["status"] == "resuming":- restore_runtime_checkpoint(session)- restore_pending_interruption(session)- waiting = self._set_state(- session,- status="awaiting_user",- recovery_id=cast(str, state["recovery_id"]),- attempts=cast(int, state.get("attempts", 1)),- reason="loop_guard",- )- self.sessions.save(session)- await self._publish(chat_id, waiting)- return-- recovery_id = uuid4().hex- phase = checkpoint.get("phase") if checkpoint is not None else None- pending_calls = checkpoint.get("pending_tool_calls") if checkpoint is not None else None- if checkpoint is not None and phase not in _KNOWN_CHECKPOINT_PHASES:- _discard_runtime_checkpoint(session)- restore_pending_interruption(session)- waiting = self._set_state(- session,- status="awaiting_user",- recovery_id=recovery_id,- attempts=0,- reason="checkpoint_unknown",- can_continue=False,- )- self.sessions.save(session)- await self._publish(chat_id, waiting)- return- if checkpoint is not None and not _runtime_checkpoint_is_well_formed(checkpoint):- _discard_runtime_checkpoint(session)- restore_pending_interruption(session)- waiting = self._set_state(- session,- status="awaiting_user",- recovery_id=recovery_id,- attempts=0,- reason="checkpoint_invalid",- can_continue=False,- )- self.sessions.save(session)- await self._publish(chat_id, waiting)- return- if phase == "final_response":- restore_runtime_checkpoint(session)- recovered = self._set_state(- session,- status="recovered",- recovery_id=recovery_id,- attempts=0,- reason="answer_restored",- )- self.sessions.save(session)- await self._publish(chat_id, recovered)- return- if phase in _UNCERTAIN_TOOL_PHASES or pending_calls:- restore_runtime_checkpoint(session)- waiting = self._set_state(- session,- status="awaiting_user",- recovery_id=recovery_id,- attempts=0,- reason="tool_state_unknown",- )- self.sessions.save(session)- await self._publish(chat_id, waiting)- return- # A gateway restart is a lifecycle boundary. Never enqueue model work- # implicitly: even a synchronized checkpoint may sit next to an- # external side effect that the user should review first. The final- # answer path above only restores persisted output; it never executes.- restore_runtime_checkpoint(session)- waiting = self._set_state(- session,- status="awaiting_user",- recovery_id=recovery_id,- attempts=0,- reason="restart_requires_confirmation",- )- self.sessions.save(session)- await self._publish(chat_id, waiting)-- async def _queue_continuation(- self,- session: Session,- chat_id: str,- state: Mapping[str, Any],- ) -> None:- recovery_id = cast(str, state["recovery_id"])- await self.bus.publish_inbound(- InboundMessage(- channel="websocket",- sender_id="system:recovery",- chat_id=chat_id,- content=(- "Continue the interrupted request from the saved conversation context. "- "Do not repeat completed work or mention the restart unless it affects the answer."- ),- metadata={- "webui": True,- "_wants_stream": True,- WEBUI_TURN_METADATA_KEY: f"recovery:{recovery_id}",- RECOVERY_INBOUND_METADATA_KEY: recovery_id,- turn_continuation.INTERNAL_CONTINUATION_META: True,- turn_continuation.SKIP_USER_PERSIST_META: True,- },- session_key_override=session.key,- require_existing_session=True,- )- )-- async def _requeue_pending_followups(self, session: Session) -> None:- """Return durable live-turn follow-ups to the bus after a restart."""- for message in pending_followups(session):- await self.bus.publish_inbound(message)-- @staticmethod- def _resume_message_count(session: Session) -> int | None:- raw_value = cast(object, session.metadata.get(RECOVERY_METADATA_KEY))- value = cast(dict[str, Any], raw_value) if isinstance(raw_value, dict) else None- if value is None:- return None- count = value.get("resume_message_count")- return count if isinstance(count, int) and count >= 0 else None-- async def _publish(- self,- chat_id: str,- state: Mapping[str, Any],- ) -> None:- """Publish the recovery state and invalidate its sidebar projection."""- await self.bus.publish_outbound(- outbound_message_for_event(- channel="websocket",- chat_id=chat_id,- event=RecoveryStateEvent(- status=cast(str, state["status"]),- recovery_id=cast(str, state["recovery_id"]),- reason=cast(str | None, state.get("reason")),- attempts=cast(int, state.get("attempts", 0)),- can_continue=cast(bool | None, state.get("can_continue")),- ),- )- )- await self.bus.publish_outbound(- outbound_message_for_event(- channel="websocket",- chat_id=chat_id,- event=SessionUpdatedEvent(scope="thread"),- )- )-- @staticmethod- def _set_state(- session: Session,- *,- status: str,- recovery_id: str,- attempts: int,- reason: str,- resume_message_count: int | None = None,- can_continue: bool = True,- ) -> dict[str, Any]:- state = {- "status": status,- "recovery_id": recovery_id,- "attempts": max(0, attempts),- "reason": reason,- "updated_at": datetime.now().isoformat(),- }- if not can_continue:- state["can_continue"] = False- if resume_message_count is not None:- state["resume_message_count"] = max(0, resume_message_count)- session.metadata[RECOVERY_METADATA_KEY] = state- session.updated_at = datetime.now()- return state-- def _session_key(self, chat_id: str) -> str:- return UNIFIED_SESSION_KEY if self.unified_session else webui_session_key(chat_id)-- @staticmethod- def _has_unfinished_webui_transcript(session_key: str) -> bool:- """Detect a stale WebUI activity tail after an unclean gateway stop.-- The transcript is intentionally consulted only as a last-resort signal:- a durable pending turn or runtime checkpoint always takes precedence.- This keeps browser disconnects harmless while preventing a materialized- partial turn from being presented as active forever after a restart.- """- try:- from nanobot.webui.transcript import has_unfinished_transcript_tail-- return has_unfinished_transcript_tail(session_key)- except (OSError, ValueError, TypeError):- # Recovery must fail closed if the optional display transcript is- # corrupt or unavailable; the normal checkpoint path still applies.- return False-- @staticmethod- def _has_saved_continuation_context(session: Session) -> bool:- """Whether an interrupted turn left model-visible context to continue from."""- last_user = next(- (- index- for index in range(len(session.messages) - 1, -1, -1)- if session.messages[index].get("role") == "user"- ),- None,- )- if last_user is None:- return False- tail = session.messages[last_user + 1 :]- return bool(tail) and (- tail[-1].get("role") == "tool"- or any(message.get("_recovery_interrupted") is True for message in tail)- or any(- message.get("role") == "assistant" and bool(message.get("tool_calls"))- for message in tail- )- )-- @staticmethod- def _websocket_route(session: Session) -> tuple[str, str] | None:- return RecoveryCoordinator._websocket_route_for(session.key, session.metadata)-- @staticmethod- def _websocket_route_for(- session_key: str,- metadata: Mapping[str, Any],- ) -> tuple[str, str] | None:- chat_id = webui_chat_id(session_key)- if chat_id is not None:- return ("websocket", chat_id)- if session_key == UNIFIED_SESSION_KEY:- route = last_channel_from_metadata(metadata)- if route and route[0] == "websocket":- return route- return Nonediff --git a/nanobot/session/webui_turns.py b/nanobot/session/webui_turns.pyindex aeedb90fe..566b53448 100644--- a/nanobot/session/webui_turns.py+++ b/nanobot/session/webui_turns.py@@ -44,7 +44,6 @@ from nanobot.runtime_context import public_history_messagefrom nanobot.session.goal_state import goal_state_ws_blobfrom nanobot.session.history_visibility import is_hidden_history_messagefrom nanobot.session.manager import Session, SessionManager-from nanobot.session.recovery import RecoveryCoordinatorfrom nanobot.session.session_handles import session_handle_for_namefrom nanobot.session.session_messages import (SessionMessageEnvelope,@@ -56,6 +55,7 @@ from nanobot.webui.metadata import (WEBSOCKET_TURN_OWNER_METADATA_KEY,WEBUI_TURN_METADATA_KEY,)+from nanobot.webui.recovery import RecoveryCoordinatorfrom nanobot.webui.session_identity import is_webui_session_key, webui_session_keyfrom nanobot.webui.star_prompt import update_star_promptfrom nanobot.webui.transcript import append_session_message_inputdiff --git a/nanobot/triggers/local_session_turns.py b/nanobot/triggers/local_session_turns.pyindex 8ac456bdf..a8bde71ad 100644--- a/nanobot/triggers/local_session_turns.py+++ b/nanobot/triggers/local_session_turns.py@@ -4,7 +4,7 @@ from __future__ import annotationsfrom typing import Any, Mapping-from nanobot.session.automation_turns import (+from nanobot.session.automation_spec import (AutomationTurnSpec,automation_trigger,)diff --git a/nanobot/utils/__init__.py b/nanobot/utils/__init__.pyindex 15dbe2e98..c2f8d13f7 100644--- a/nanobot/utils/__init__.py+++ b/nanobot/utils/__init__.py@@ -6,7 +6,7 @@ import sysfrom importlib import import_modulefrom types import ModuleType-from nanobot.utils.helpers import ensure_dir+from nanobot.utils.file_io import ensure_dirfrom nanobot.utils.path import abbreviate_path__all__ = ["ensure_dir", "abbreviate_path"]diff --git a/nanobot/utils/file_io.py b/nanobot/utils/file_io.pynew file mode 100644index 000000000..725326c8f--- /dev/null+++ b/nanobot/utils/file_io.py@@ -0,0 +1,37 @@+"""Filesystem primitives shared by configuration and runtime storage."""++import os+import stat+import uuid+from contextlib import suppress+from pathlib import Path+++def ensure_dir(path: Path) -> Path:+ """Ensure directory exists, return it."""+ path.mkdir(parents=True, exist_ok=True)+ return path+++def write_text_atomic(path: Path, content: str) -> None:+ tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")+ existing_mode: int | None = None+ with suppress(OSError):+ existing_mode = stat.S_IMODE(path.stat().st_mode)+ try:+ with open(tmp, "w", encoding="utf-8") as f:+ if existing_mode is not None:+ os.chmod(tmp, existing_mode)+ f.write(content)+ f.flush()+ os.fsync(f.fileno())+ tmp.replace(path)+ with suppress(OSError, NotImplementedError):+ dfd = os.open(path.parent, os.O_RDONLY)+ try:+ os.fsync(dfd)+ finally:+ os.close(dfd)+ finally:+ if tmp.exists():+ tmp.unlink(missing_ok=True)diff --git a/nanobot/utils/helpers.py b/nanobot/utils/helpers.pyindex d8552e66f..829bfeb90 100644--- a/nanobot/utils/helpers.py+++ b/nanobot/utils/helpers.py@@ -8,7 +8,6 @@ import jsonimport osimport reimport shutil-import statimport timeimport uuidfrom collections.abc import Iterable@@ -19,6 +18,8 @@ from typing import TYPE_CHECKING, Any, TypeVar, cast, overloadfrom loguru import logger+from nanobot.utils.file_io import ensure_dir as ensure_dir+from nanobot.utils.file_io import write_text_atomic as _write_text_atomicfrom nanobot.utils.token_encoding import get_token_encoding as _get_token_encodingif TYPE_CHECKING:@@ -351,12 +352,6 @@ def build_image_content_blocks(]-def ensure_dir(path: Path) -> Path:- """Ensure directory exists, return it."""- path.mkdir(parents=True, exist_ok=True)- return path--def timestamp() -> str:"""Current ISO timestamp."""return datetime.now().isoformat()@@ -597,30 +592,6 @@ def _fsync_directory_after_replace(directory: Path) -> None:os.close(fd)-def _write_text_atomic(path: Path, content: str) -> None:- tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")- existing_mode: int | None = None- with suppress(OSError):- existing_mode = stat.S_IMODE(path.stat().st_mode)- try:- with open(tmp, "w", encoding="utf-8") as f:- if existing_mode is not None:- os.chmod(tmp, existing_mode)- f.write(content)- f.flush()- os.fsync(f.fileno())- tmp.replace(path)- with suppress(OSError, NotImplementedError):- dfd = os.open(path.parent, os.O_RDONLY)- try:- os.fsync(dfd)- finally:- os.close(dfd)- finally:- if tmp.exists():- tmp.unlink(missing_ok=True)--def maybe_persist_tool_result(workspace: Path | None,session_key: str | None,diff --git a/nanobot/utils/restart.py b/nanobot/utils/restart.pyindex 03cbf8b1f..99dccf504 100644--- a/nanobot/utils/restart.py+++ b/nanobot/utils/restart.py@@ -9,7 +9,7 @@ from contextlib import suppressfrom dataclasses import dataclass, fieldfrom typing import Any, cast-from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY+from nanobot.bus.events import INBOUND_META_TURN_IDRESTART_NOTIFY_CHANNEL_ENV = "NANOBOT_RESTART_NOTIFY_CHANNEL"RESTART_NOTIFY_CHAT_ID_ENV = "NANOBOT_RESTART_NOTIFY_CHAT_ID"@@ -43,7 +43,7 @@ def set_restart_notice_to_env(os.environ[RESTART_NOTIFY_CHAT_ID_ENV] = chat_idos.environ[RESTART_STARTED_AT_ENV] = str(time.time())persisted_metadata = dict(metadata or {})- persisted_metadata.pop(WEBUI_TURN_METADATA_KEY, None)+ persisted_metadata.pop(INBOUND_META_TURN_ID, None)if persisted_metadata:try:os.environ[RESTART_NOTIFY_METADATA_ENV] = json.dumps(diff --git a/nanobot/webui/metadata.py b/nanobot/webui/metadata.pyindex 81b098ee9..32346c5d1 100644--- a/nanobot/webui/metadata.py+++ b/nanobot/webui/metadata.py@@ -1,6 +1,8 @@"""Shared WebUI metadata keys."""-WEBUI_TURN_METADATA_KEY = "webui_turn_id"+from nanobot.bus.events import INBOUND_META_TURN_ID++WEBUI_TURN_METADATA_KEY = INBOUND_META_TURN_IDWEBUI_SYSTEM_COMMAND_TURN_PREFIX = "webui-system:"# Set by authenticated WebUI ingress, never copied from an envelope's metadata.WEBUI_RESTART_CONTROL_METADATA_KEY = "_webui_restart_control"diff --git a/nanobot/webui/recovery.py b/nanobot/webui/recovery.pynew file mode 100644index 000000000..40e00e5a0--- /dev/null+++ b/nanobot/webui/recovery.py@@ -0,0 +1,541 @@+"""WebUI restart recovery over durable session checkpoints."""++from __future__ import annotations++import asyncio+import dataclasses+from collections.abc import Mapping+from datetime import datetime+from typing import Any, cast+from uuid import uuid4++from loguru import logger++from nanobot.bus.events import InboundMessage+from nanobot.bus.outbound_events import (+ RecoveryStateEvent,+ SessionUpdatedEvent,+ outbound_message_for_event,+)+from nanobot.bus.queue import MessageBus+from nanobot.session import turn_continuation+from nanobot.session.keys import UNIFIED_SESSION_KEY, last_channel_from_metadata+from nanobot.session.manager import Session, SessionManager+from nanobot.session.recovery import (+ KNOWN_CHECKPOINT_PHASES,+ PENDING_FOLLOWUPS_KEY,+ PENDING_USER_TURN_KEY,+ RECOVERY_INBOUND_METADATA_KEY,+ RECOVERY_METADATA_KEY,+ RUNTIME_CHECKPOINT_KEY,+ UNCERTAIN_TOOL_PHASES,+ append_recovery_interruption,+ discard_runtime_checkpoint,+ pending_followups,+ recovery_state_from_metadata,+ restore_pending_interruption,+ restore_runtime_checkpoint,+ runtime_checkpoint_is_well_formed,+)+from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY+from nanobot.webui.session_identity import webui_chat_id, webui_session_key+++class RecoveryActionError(ValueError):+ """A stale or malformed recovery action from an authenticated WebUI."""++ def __init__(self, message: str, *, status: int = 400) -> None:+ super().__init__(message)+ self.status = status++[email protected](slots=True)+class RecoveryCoordinator:+ """Classify, announce, and gate durable WebUI turn recovery."""++ sessions: SessionManager+ bus: MessageBus+ unified_session: bool = False+ _active_recovery_tasks: dict[str, asyncio.Task[Any]] = dataclasses.field(+ default_factory=dict,+ init=False,+ repr=False,+ )++ def register_recovery_task(self, session_key: str, task: asyncio.Task[Any]) -> None:+ """Track the task that owns an explicit recovery continuation."""+ self._active_recovery_tasks[session_key] = task++ def unregister_recovery_task(self, session_key: str, task: asyncio.Task[Any]) -> None:+ """Drop a recovery task without removing a newer task for the same session."""+ if self._active_recovery_tasks.get(session_key) is task:+ self._active_recovery_tasks.pop(session_key, None)++ async def _cancel_active_recovery(self, session_key: str) -> None:+ """Stop an explicit continuation before accepting newer user input."""+ task = self._active_recovery_tasks.get(session_key)+ if task is None or task is asyncio.current_task() or task.done():+ return+ task.cancel()+ # AgentLoop's cancellation path materializes any partial checkpoint and+ # releases its pending queue. Wait for that ownership to be released+ # before the newer message is routed.+ await asyncio.gather(task, return_exceptions=True)++ async def scan(self) -> None:+ """Recover every interrupted WebUI session once at gateway startup."""+ for key in self._recovery_candidates():+ metadata_payload = self.sessions.read_session_metadata(key)+ raw_metadata = metadata_payload.get("metadata") if metadata_payload else None+ metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {}+ route = self._websocket_route_for(key, metadata)+ if route is None:+ continue+ unfinished = self._has_unfinished_webui_transcript(key)+ if not self._needs_recovery(metadata) and not unfinished:+ continue+ session = self.sessions.get_or_create(key)+ try:+ await self._recover_session(session, route[1])+ await self._requeue_pending_followups(session)+ except Exception:+ logger.exception("failed to recover interrupted WebUI session {}", session.key)+ state = recovery_state_from_metadata(session.metadata)+ failed = self._set_state(+ session,+ status="failed",+ recovery_id=cast(str, state["recovery_id"]) if state else uuid4().hex,+ attempts=cast(int, state.get("attempts", 0)) if state else 0,+ reason="recovery_failed",+ can_continue=False,+ )+ self.sessions.save(session)+ await self._publish(route[1], failed)++ def _recovery_candidates(self) -> list[str]:+ """Discover canonical and transcript-only WebUI sessions cheaply."""+ candidates = dict.fromkeys(+ key+ for item in self.sessions.list_sessions()+ if isinstance((key := item.get("key")), str)+ )+ try:+ # Imported lazily because the sidebar index also projects recovery+ # metadata. The index is the owner of transcript-only discovery;+ # duplicating its filename and migration rules here would drift.+ from nanobot.webui.session_list_index import list_webui_sessions++ for item in list_webui_sessions(self.sessions):+ key = item.get("key")+ if isinstance(key, str):+ candidates.setdefault(key, None)+ except Exception:+ # Canonical checkpoint recovery remains available even if the+ # optional display-history index is corrupt or unavailable.+ logger.exception("failed to discover transcript-only WebUI sessions")+ return list(candidates)++ @staticmethod+ def _needs_recovery(metadata: Mapping[str, Any]) -> bool:+ if metadata.get(PENDING_USER_TURN_KEY) is True:+ return True+ if isinstance(metadata.get(RUNTIME_CHECKPOINT_KEY), dict):+ return True+ followups = metadata.get(PENDING_FOLLOWUPS_KEY)+ if isinstance(followups, list) and len(cast(list[object], followups)) > 0:+ return True+ state = recovery_state_from_metadata(metadata)+ return bool(state and state["status"] in {"resuming", "awaiting_user", "failed"})++ async def admit(self, message: InboundMessage) -> bool:+ """Reject stale queued recoveries and let new user input supersede them."""+ recovery_id = message.metadata.get(RECOVERY_INBOUND_METADATA_KEY)+ if isinstance(recovery_id, str):+ session = self.sessions.get_or_create(message.session_key)+ state = recovery_state_from_metadata(session.metadata)+ return bool(+ state+ and state["status"] == "resuming"+ and state["recovery_id"] == recovery_id+ )+ if message.channel != "websocket":+ return True+ session = self.sessions.get_or_create(message.session_key)+ state = recovery_state_from_metadata(session.metadata)+ if state and state["status"] in {"resuming", "awaiting_user", "failed"}:+ await self._cancel_active_recovery(message.session_key)+ restore_runtime_checkpoint(session)+ if not restore_pending_interruption(session, superseded=True):+ append_recovery_interruption(session, superseded=True)+ recovered = self._set_state(+ session,+ status="recovered",+ recovery_id=cast(str, state["recovery_id"]),+ attempts=cast(int, state.get("attempts", 0)),+ reason="superseded",+ )+ self.sessions.save(session)+ await self._publish(message.chat_id, recovered)+ return True++ async def turn_completed(self, session_key: str) -> None:+ """Resolve a resuming state after the recovered turn commits."""+ session = self.sessions.get_or_create(session_key)+ state = recovery_state_from_metadata(session.metadata)+ if not state or state["status"] != "resuming":+ return+ route = self._websocket_route(session)+ if route is None:+ return+ recovered = self._set_state(+ session,+ status="recovered",+ recovery_id=cast(str, state["recovery_id"]),+ attempts=cast(int, state.get("attempts", 0)),+ reason="continued",+ )+ self.sessions.save(session)+ await self._publish(route[1], recovered)++ async def handle_action(self, action: str, payload: dict[str, Any]) -> dict[str, Any]:+ """Apply an authenticated continue/dismiss operation."""+ chat_id = payload.get("chat_id")+ recovery_id = payload.get("recovery_id")+ if not isinstance(chat_id, str) or not chat_id:+ raise RecoveryActionError("missing chat_id")+ if not isinstance(recovery_id, str) or not recovery_id:+ raise RecoveryActionError("missing recovery_id")+ session = self.sessions.get_or_create(self._session_key(chat_id))+ state = recovery_state_from_metadata(session.metadata)+ if not state or state["recovery_id"] != recovery_id:+ raise RecoveryActionError("recovery state is stale", status=409)++ if action == "dismiss":+ restore_runtime_checkpoint(session)+ restore_pending_interruption(session)+ next_state = self._set_state(+ session,+ status="recovered",+ recovery_id=recovery_id,+ attempts=cast(int, state.get("attempts", 0)),+ reason="dismissed",+ )+ self.sessions.save(session)+ await self._publish(chat_id, next_state)+ return next_state+ if action != "continue":+ raise RecoveryActionError("unknown recovery action")+ if state["status"] not in {"awaiting_user", "failed"}:+ raise RecoveryActionError("recovery is not waiting for confirmation", status=409)+ if state.get("can_continue") is False:+ raise RecoveryActionError("recovery context is unavailable", status=409)+ next_state = self._set_state(+ session,+ status="resuming",+ recovery_id=recovery_id,+ attempts=cast(int, state.get("attempts", 0)) + 1,+ reason="user_confirmed",+ resume_message_count=len(session.messages),+ )+ self.sessions.save(session)+ await self._publish(chat_id, next_state)+ await self._queue_continuation(session, chat_id, next_state)+ return next_state++ async def _recover_session(self, session: Session, chat_id: str) -> None:+ checkpoint_value = cast(object, session.metadata.get(RUNTIME_CHECKPOINT_KEY))+ checkpoint = (+ cast(dict[str, Any], checkpoint_value)+ if isinstance(checkpoint_value, dict)+ else None+ )+ pending = session.metadata.get(PENDING_USER_TURN_KEY) is True+ state = recovery_state_from_metadata(session.metadata)+ if not pending and checkpoint is None:+ if state and state["status"] == "resuming":+ resume_count = self._resume_message_count(session)+ if resume_count is not None and len(session.messages) > resume_count:+ next_state = self._set_state(+ session,+ status="recovered",+ recovery_id=cast(str, state["recovery_id"]),+ attempts=cast(int, state.get("attempts", 0)),+ reason="committed",+ )+ else:+ next_state = self._set_state(+ session,+ status="awaiting_user",+ recovery_id=cast(str, state["recovery_id"]),+ attempts=cast(int, state.get("attempts", 1)),+ reason="loop_guard",+ )+ self.sessions.save(session)+ await self._publish(chat_id, next_state)+ elif self._has_unfinished_webui_transcript(session.key):+ # A normal last-client shutdown can materialize the checkpoint+ # before the process exits. In that path there is no pending+ # marker left to classify, but the append-only transcript still+ # contains an activity row without a turn_end. Treat it as an+ # interrupted turn instead of letting the UI resurrect it as a+ # forever-running spinner.+ can_continue = self._has_saved_continuation_context(session)+ waiting = self._set_state(+ session,+ status="awaiting_user",+ recovery_id=uuid4().hex,+ attempts=0,+ reason=(+ "interrupted_with_saved_context"+ if can_continue+ else "interrupted_without_checkpoint"+ ),+ can_continue=can_continue,+ )+ self.sessions.save(session)+ await self._publish(chat_id, waiting)+ return+ if state and state["status"] in {"awaiting_user", "failed"}:+ await self._publish(chat_id, state)+ return+ if state and state["status"] == "resuming":+ restore_runtime_checkpoint(session)+ restore_pending_interruption(session)+ waiting = self._set_state(+ session,+ status="awaiting_user",+ recovery_id=cast(str, state["recovery_id"]),+ attempts=cast(int, state.get("attempts", 1)),+ reason="loop_guard",+ )+ self.sessions.save(session)+ await self._publish(chat_id, waiting)+ return++ recovery_id = uuid4().hex+ phase = checkpoint.get("phase") if checkpoint is not None else None+ pending_calls = checkpoint.get("pending_tool_calls") if checkpoint is not None else None+ if checkpoint is not None and phase not in KNOWN_CHECKPOINT_PHASES:+ discard_runtime_checkpoint(session)+ restore_pending_interruption(session)+ waiting = self._set_state(+ session,+ status="awaiting_user",+ recovery_id=recovery_id,+ attempts=0,+ reason="checkpoint_unknown",+ can_continue=False,+ )+ self.sessions.save(session)+ await self._publish(chat_id, waiting)+ return+ if checkpoint is not None and not runtime_checkpoint_is_well_formed(checkpoint):+ discard_runtime_checkpoint(session)+ restore_pending_interruption(session)+ waiting = self._set_state(+ session,+ status="awaiting_user",+ recovery_id=recovery_id,+ attempts=0,+ reason="checkpoint_invalid",+ can_continue=False,+ )+ self.sessions.save(session)+ await self._publish(chat_id, waiting)+ return+ if phase == "final_response":+ restore_runtime_checkpoint(session)+ recovered = self._set_state(+ session,+ status="recovered",+ recovery_id=recovery_id,+ attempts=0,+ reason="answer_restored",+ )+ self.sessions.save(session)+ await self._publish(chat_id, recovered)+ return+ if phase in UNCERTAIN_TOOL_PHASES or pending_calls:+ restore_runtime_checkpoint(session)+ waiting = self._set_state(+ session,+ status="awaiting_user",+ recovery_id=recovery_id,+ attempts=0,+ reason="tool_state_unknown",+ )+ self.sessions.save(session)+ await self._publish(chat_id, waiting)+ return+ # A gateway restart is a lifecycle boundary. Never enqueue model work+ # implicitly: even a synchronized checkpoint may sit next to an+ # external side effect that the user should review first. The final+ # answer path above only restores persisted output; it never executes.+ restore_runtime_checkpoint(session)+ waiting = self._set_state(+ session,+ status="awaiting_user",+ recovery_id=recovery_id,+ attempts=0,+ reason="restart_requires_confirmation",+ )+ self.sessions.save(session)+ await self._publish(chat_id, waiting)++ async def _queue_continuation(+ self,+ session: Session,+ chat_id: str,+ state: Mapping[str, Any],+ ) -> None:+ recovery_id = cast(str, state["recovery_id"])+ await self.bus.publish_inbound(+ InboundMessage(+ channel="websocket",+ sender_id="system:recovery",+ chat_id=chat_id,+ content=(+ "Continue the interrupted request from the saved conversation context. "+ "Do not repeat completed work or mention the restart unless it affects the answer."+ ),+ metadata={+ "webui": True,+ "_wants_stream": True,+ WEBUI_TURN_METADATA_KEY: f"recovery:{recovery_id}",+ RECOVERY_INBOUND_METADATA_KEY: recovery_id,+ turn_continuation.INTERNAL_CONTINUATION_META: True,+ turn_continuation.SKIP_USER_PERSIST_META: True,+ },+ session_key_override=session.key,+ require_existing_session=True,+ )+ )++ async def _requeue_pending_followups(self, session: Session) -> None:+ """Return durable live-turn follow-ups to the bus after a restart."""+ for message in pending_followups(session):+ await self.bus.publish_inbound(message)++ @staticmethod+ def _resume_message_count(session: Session) -> int | None:+ raw_value = cast(object, session.metadata.get(RECOVERY_METADATA_KEY))+ value = cast(dict[str, Any], raw_value) if isinstance(raw_value, dict) else None+ if value is None:+ return None+ count = value.get("resume_message_count")+ return count if isinstance(count, int) and count >= 0 else None++ async def _publish(+ self,+ chat_id: str,+ state: Mapping[str, Any],+ ) -> None:+ """Publish the recovery state and invalidate its sidebar projection."""+ await self.bus.publish_outbound(+ outbound_message_for_event(+ channel="websocket",+ chat_id=chat_id,+ event=RecoveryStateEvent(+ status=cast(str, state["status"]),+ recovery_id=cast(str, state["recovery_id"]),+ reason=cast(str | None, state.get("reason")),+ attempts=cast(int, state.get("attempts", 0)),+ can_continue=cast(bool | None, state.get("can_continue")),+ ),+ )+ )+ await self.bus.publish_outbound(+ outbound_message_for_event(+ channel="websocket",+ chat_id=chat_id,+ event=SessionUpdatedEvent(scope="thread"),+ )+ )++ @staticmethod+ def _set_state(+ session: Session,+ *,+ status: str,+ recovery_id: str,+ attempts: int,+ reason: str,+ resume_message_count: int | None = None,+ can_continue: bool = True,+ ) -> dict[str, Any]:+ state = {+ "status": status,+ "recovery_id": recovery_id,+ "attempts": max(0, attempts),+ "reason": reason,+ "updated_at": datetime.now().isoformat(),+ }+ if not can_continue:+ state["can_continue"] = False+ if resume_message_count is not None:+ state["resume_message_count"] = max(0, resume_message_count)+ session.metadata[RECOVERY_METADATA_KEY] = state+ session.updated_at = datetime.now()+ return state++ def _session_key(self, chat_id: str) -> str:+ return UNIFIED_SESSION_KEY if self.unified_session else webui_session_key(chat_id)++ @staticmethod+ def _has_unfinished_webui_transcript(session_key: str) -> bool:+ """Detect a stale WebUI activity tail after an unclean gateway stop.++ The transcript is intentionally consulted only as a last-resort signal:+ a durable pending turn or runtime checkpoint always takes precedence.+ This keeps browser disconnects harmless while preventing a materialized+ partial turn from being presented as active forever after a restart.+ """+ try:+ from nanobot.webui.transcript import has_unfinished_transcript_tail++ return has_unfinished_transcript_tail(session_key)+ except (OSError, ValueError, TypeError):+ # Recovery must fail closed if the optional display transcript is+ # corrupt or unavailable; the normal checkpoint path still applies.+ return False++ @staticmethod+ def _has_saved_continuation_context(session: Session) -> bool:+ """Whether an interrupted turn left model-visible context to continue from."""+ last_user = next(+ (+ index+ for index in range(len(session.messages) - 1, -1, -1)+ if session.messages[index].get("role") == "user"+ ),+ None,+ )+ if last_user is None:+ return False+ tail = session.messages[last_user + 1 :]+ return bool(tail) and (+ tail[-1].get("role") == "tool"+ or any(message.get("_recovery_interrupted") is True for message in tail)+ or any(+ message.get("role") == "assistant" and bool(message.get("tool_calls"))+ for message in tail+ )+ )++ @staticmethod+ def _websocket_route(session: Session) -> tuple[str, str] | None:+ return RecoveryCoordinator._websocket_route_for(session.key, session.metadata)++ @staticmethod+ def _websocket_route_for(+ session_key: str,+ metadata: Mapping[str, Any],+ ) -> tuple[str, str] | None:+ chat_id = webui_chat_id(session_key)+ if chat_id is not None:+ return ("websocket", chat_id)+ if session_key == UNIFIED_SESSION_KEY:+ route = last_channel_from_metadata(metadata)+ if route and route[0] == "websocket":+ return route+ return Nonediff --git a/nanobot/webui/remote_mux.py b/nanobot/webui/remote_mux.pyindex 193770865..5c06c7662 100644--- a/nanobot/webui/remote_mux.py+++ b/nanobot/webui/remote_mux.py@@ -21,7 +21,7 @@ class SSHMaster:self._lock = asyncio.Lock()async def arguments(self, channel: list[str]) -> list[str]:- from nanobot.webui.remote_ssh import RemoteError, ssh_error+ from nanobot.webui.ssh_process import RemoteError, ssh_errorasync with self._lock:if self._process is None or self._process.returncode is not None:@@ -76,7 +76,7 @@ class SSHMaster:return [channel[0], "-S", str(Path(self._directory.name) / "s"), *channel[1:]]async def close(self) -> None:- from nanobot.webui.remote_ssh import stop_process+ from nanobot.webui.ssh_process import stop_processif self._process is not None:await stop_process(self._process)diff --git a/nanobot/webui/remote_ssh.py b/nanobot/webui/remote_ssh.pyindex 5c94b1b25..e63af21bc 100644--- a/nanobot/webui/remote_ssh.py+++ b/nanobot/webui/remote_ssh.py@@ -21,14 +21,13 @@ from typing import Any, castfrom pydantic import BaseModel, ConfigDict, Field, field_validatorfrom nanobot.webui.remote_mux import SSHMaster+from nanobot.webui.ssh_process import RemoteError as RemoteError+from nanobot.webui.ssh_process import ssh_error as ssh_error+from nanobot.webui.ssh_process import stop_process as stop_process_BRIDGE_READY = b"NANOBOT_REMOTE_BRIDGE_2\n"-class RemoteError(Exception):- """A stable, non-secret error code for the connection UI."""--class RemoteProfile(BaseModel):model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)@@ -138,55 +137,6 @@ def ssh_arguments(profile: RemoteProfile, known_hosts: Path | None = None) -> lireturn args-def ssh_error(stderr: bytes) -> str:- text = stderr.decode("utf-8", errors="replace").lower()- if "host identification has changed" in text:- return "host_key_changed"- if "host key verification failed" in text or "no ed25519 host key is known" in text:- return "host_key_unknown"- if "sudo:" in text:- return "runtime_user_denied"- if "unprotected private key file" in text or "bad permissions" in text:- return "ssh_key_permissions"- if "agent refused operation" in text or "signing failed" in text:- return "ssh_agent_refused"- if "bad configuration option" in text or "terminating, 1 bad configuration" in text:- return "ssh_config_invalid"- if "administratively prohibited" in text:- return "ssh_forwarding_denied"- if "open failed: connect failed" in text:- return "remote_unreachable"- if "too many authentication failures" in text:- return "ssh_too_many_keys"- if "permission denied" in text:- return "ssh_auth_failed"- if "connection refused" in text:- return "ssh_refused"- if "could not resolve hostname" in text:- return "ssh_host_not_found"- if "connection closed" in text or "connection reset" in text:- return "ssh_connection_closed"- if "python3" in text and "not found" in text:- return "python_unavailable"- return "ssh_unreachable"---async def stop_process(process: asyncio.subprocess.Process) -> None:- if process.returncode is None:- try:- process.terminate()- except ProcessLookupError:- pass- try:- await asyncio.wait_for(process.wait(), 3)- except TimeoutError:- try:- process.kill()- except ProcessLookupError:- pass- await process.wait()--async def run_check(profile: RemoteProfile, program: str, known_hosts: Path | None = None,) -> dict[str, Any]:diff --git a/nanobot/webui/ssh_process.py b/nanobot/webui/ssh_process.pynew file mode 100644index 000000000..c0a623c04--- /dev/null+++ b/nanobot/webui/ssh_process.py@@ -0,0 +1,58 @@+"""Shared SSH errors and owned subprocess shutdown."""++from __future__ import annotations++import asyncio+++class RemoteError(Exception):+ """A stable, non-secret error code for the connection UI."""+++def ssh_error(stderr: bytes) -> str:+ text = stderr.decode("utf-8", errors="replace").lower()+ if "host identification has changed" in text:+ return "host_key_changed"+ if "host key verification failed" in text or "no ed25519 host key is known" in text:+ return "host_key_unknown"+ if "sudo:" in text:+ return "runtime_user_denied"+ if "unprotected private key file" in text or "bad permissions" in text:+ return "ssh_key_permissions"+ if "agent refused operation" in text or "signing failed" in text:+ return "ssh_agent_refused"+ if "bad configuration option" in text or "terminating, 1 bad configuration" in text:+ return "ssh_config_invalid"+ if "administratively prohibited" in text:+ return "ssh_forwarding_denied"+ if "open failed: connect failed" in text:+ return "remote_unreachable"+ if "too many authentication failures" in text:+ return "ssh_too_many_keys"+ if "permission denied" in text:+ return "ssh_auth_failed"+ if "connection refused" in text:+ return "ssh_refused"+ if "could not resolve hostname" in text:+ return "ssh_host_not_found"+ if "connection closed" in text or "connection reset" in text:+ return "ssh_connection_closed"+ if "python3" in text and "not found" in text:+ return "python_unavailable"+ return "ssh_unreachable"+++async def stop_process(process: asyncio.subprocess.Process) -> None:+ if process.returncode is None:+ try:+ process.terminate()+ except ProcessLookupError:+ pass+ try:+ await asyncio.wait_for(process.wait(), 3)+ except TimeoutError:+ try:+ process.kill()+ except ProcessLookupError:+ pass+ await process.wait()diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.pyindex 09aa43b0e..5ed4dd3f5 100644--- a/nanobot/webui/ws_http.py+++ b/nanobot/webui/ws_http.py@@ -34,7 +34,6 @@ from nanobot.cron.session_turns import is_bound_cron_jobfrom nanobot.cron.types import CronJob, CronSchedulefrom nanobot.security.workspace_access import WorkspaceScope, WorkspaceScopeErrorfrom nanobot.session.manager import SessionManager-from nanobot.session.recovery import RecoveryActionErrorfrom nanobot.session.session_handles import (SessionHandleResolver,)@@ -95,6 +94,7 @@ from nanobot.webui.http_utils import ()from nanobot.webui.ingress_policy import WebUIIngressPolicyfrom nanobot.webui.media_gateway import WebUIMediaGateway+from nanobot.webui.recovery import RecoveryActionErrorfrom nanobot.webui.session_automations import (all_automations_payload,serialize_automation_jobs,diff --git a/pyproject.toml b/pyproject.tomlindex da9efdc28..720bba7a9 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -31,6 +31,7 @@ dependencies = ["websockets>=15.0,<17.0","httpx[socks]>=0.28.0,<1.0.0","aiohttp>=3.14.3,<4.0.0",+ "yarl>=1.17.0,<2.0.0","cryptography>=46.0.0","ddgs>=9.5.5,<10.0.0","oauth-cli-kit>=0.1.6,<1.0.0",@@ -74,6 +75,7 @@ azure = []bedrock = ["boto3>=1.43.0",+ "botocore>=1.43.0,<2.0.0",]documents = [# Compatibility extra: document readers are bundled since v0.2.3.diff --git a/scripts/check_client_import_boundaries.mjs b/scripts/check_client_import_boundaries.mjsnew file mode 100644index 000000000..2f004d7a7--- /dev/null+++ b/scripts/check_client_import_boundaries.mjs@@ -0,0 +1,315 @@+/** Check client imports without loading application or channel modules. */+import { Glob } from "bun";+import { readFileSync, readdirSync } from "node:fs";+import { createRequire } from "node:module";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { parseArgs } from "node:util";++const REPO_ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));+const UI_PACKAGES = ["react", "react-dom", "react-i18next", "@radix-ui", "lucide-react", "@opentui"];+const WEBUI_VIEWS = ["webui/src/components", "webui/src/hooks", "webui/src/providers"];+const TUI_VIEWS = ["tui/src/app", "tui/src/views", "tui/src/rendering", "tui/src/composer", "tui/src/menus"];+const CHANNEL_CONTRACTS = ["webui/src/channel-plugins/types.ts", "webui/src/channel-plugins/catalog.ts"];++function slash(value) {+ return value.replaceAll("\\", "/");+}++function within(value, prefix) {+ if (process.platform === "win32") {+ value = value.toLowerCase();+ prefix = prefix.toLowerCase();+ }+ return value === prefix || value.startsWith(`${prefix}/`);+}++function channelUi(value) {+ return /^nanobot\/channels\/[^/]+\/webui\//.test(process.platform === "win32" ? value.toLowerCase() : value);+}++function sourcePath(root, file) {+ return slash(path.relative(root, file));+}++function uiPackage(specifier) {+ return UI_PACKAGES.some((prefix) => within(specifier, prefix));+}++export function loadCompiler(project) {+ return createRequire(path.join(REPO_ROOT, project, "package.json"))("typescript");+}++function projectOptions(compiler, root, project) {+ const configPath = path.join(root, project, "tsconfig.json");+ const config = compiler.readConfigFile(configPath, compiler.sys.readFile);+ if (config.error) throw new Error(compiler.flattenDiagnosticMessageText(config.error.messageText, "\n"));+ const parsed = compiler.parseJsonConfigFileContent(config.config, compiler.sys, path.dirname(configPath));+ if (parsed.errors.length) {+ throw new Error(parsed.errors.map((error) => compiler.flattenDiagnosticMessageText(error.messageText, "\n")).join("\n"));+ }+ return parsed.options;+}++function targets(root, file, specifier, options, project) {+ if (specifier.startsWith(".")) return [path.resolve(path.dirname(file), specifier)];+ if (specifier.startsWith("/")) return [path.resolve(root, project, specifier.slice(1))];+ for (const [pattern, replacements] of Object.entries(options.paths ?? {})) {+ const wildcard = pattern.indexOf("*");+ const prefix = wildcard < 0 ? pattern : pattern.slice(0, wildcard);+ const suffix = wildcard < 0 ? "" : pattern.slice(wildcard + 1);+ if (wildcard < 0 ? specifier !== pattern : !specifier.startsWith(prefix) || !specifier.endsWith(suffix)) continue;+ const capture = wildcard < 0 ? "" : specifier.slice(prefix.length, specifier.length - suffix.length);+ const base = options.baseUrl ?? path.join(root, project);+ return replacements.map((replacement) => path.resolve(base, replacement.replace("*", capture)));+ }+ return [];+}++function stringValue(compiler, node) {+ return node && (compiler.isStringLiteral(node) || compiler.isNoSubstitutionTemplateLiteral(node))+ ? node.text+ : null;+}++function globTargets(compiler, argument, root, file, options, project) {+ const nodes = compiler.isArrayLiteralExpression(argument) ? argument.elements : [argument];+ const patterns = nodes.map((node) => stringValue(compiler, node));+ if (patterns.some((pattern) => pattern === null)) return [];+ const positive = [];+ const negative = [];+ for (const pattern of patterns) {+ const excluded = pattern.startsWith("!");+ for (const target of targets(root, file, excluded ? pattern.slice(1) : pattern, options, project)) {+ const relative = sourcePath(root, target);+ if (relative.startsWith("../")) throw new Error(`${sourcePath(root, file)}: glob resolves outside the repository`);+ (excluded ? negative : positive).push(new Glob(relative));+ }+ }+ const matches = new Set();+ for (const pattern of positive) {+ for (const match of pattern.scanSync({ cwd: root, onlyFiles: true })) {+ const relative = slash(match);+ if (!negative.some((excluded) => excluded.match(relative))) matches.add(relative);+ }+ }+ return [...matches];+}++export function findViolations(compiler, root, file, source, options, project) {+ const relative = sourcePath(root, file);+ const tree = compiler.createSourceFile(file, source, compiler.ScriptTarget.Latest, true);+ if (tree.parseDiagnostics.length) {+ const error = tree.parseDiagnostics[0];+ const line = tree.getLineAndCharacterOfPosition(error.start).line + 1;+ throw new Error(`${relative}:${line}: ${compiler.flattenDiagnosticMessageText(error.messageText, "\n")}`);+ }+ const violations = [];+ const reported = new Set();++ function check(specifier, target, node) {+ const rules = [];+ const targetPath = target === null ? null : sourcePath(root, target);+ if (within(relative, "packages/client-events")) {+ if ((targetPath !== null && !within(targetPath, "packages/client-events")) || uiPackage(specifier)) {+ rules.push("shared-client-contracts");+ }+ }+ if (within(relative, "tui/src/client")) {+ if (TUI_VIEWS.some((prefix) => targetPath !== null && within(targetPath, prefix)) || uiPackage(specifier)) {+ rules.push("tui-client");+ }+ }+ if (within(relative, "webui/src/lib") && WEBUI_VIEWS.some((prefix) => targetPath !== null && within(targetPath, prefix))) {+ rules.push("webui-lib");+ }+ const comparableTarget = process.platform === "win32" ? targetPath?.toLowerCase() : targetPath;+ if (within(relative, "webui/src/lib")+ && /^webui\/src\/i18n(?:\/index(?:\.[cm]?[jt]sx?)?)?$/.test(comparableTarget ?? "")) {+ rules.push("webui-lib-bootstrap");+ }+ if (within(relative, "webui/src/lib/format.ts") && ["i18next", "react-i18next"].includes(specifier)) {+ rules.push("pure-format-utils");+ }+ if (CHANNEL_CONTRACTS.includes(relative) && WEBUI_VIEWS.some((prefix) => targetPath !== null && within(targetPath, prefix))) {+ rules.push("channel-ui-contracts");+ }+ if (targetPath !== null) {+ const webuiSource = within(relative, "webui/src") || channelUi(relative);+ const tuiSource = within(relative, "tui/src");+ if ((webuiSource && within(targetPath, "tui"))+ || (tuiSource && (within(targetPath, "webui") || channelUi(targetPath)))) {+ rules.push("client-app-isolation");+ }+ }+ const line = tree.getLineAndCharacterOfPosition(node.getStart(tree)).line + 1;+ for (const rule of rules) {+ const message = `${relative}:${line}: [${rule}] must not import ${targetPath ?? specifier}`;+ if (!reported.has(message)) {+ reported.add(message);+ violations.push(message);+ }+ }+ }++ function add(specifier, node) {+ if (specifier === null) return;+ const resolved = targets(root, file, specifier, options, project);+ if (resolved.length) {+ for (const target of resolved) check(specifier, target, node);+ } else {+ check(specifier, null, node);+ }+ }++ function visit(node) {+ if (compiler.isImportDeclaration(node) || compiler.isExportDeclaration(node)) {+ add(stringValue(compiler, node.moduleSpecifier), node);+ } else if (compiler.isImportTypeNode(node) && compiler.isLiteralTypeNode(node.argument)) {+ add(stringValue(compiler, node.argument.literal), node);+ } else if (compiler.isImportEqualsDeclaration(node) && compiler.isExternalModuleReference(node.moduleReference)) {+ add(stringValue(compiler, node.moduleReference.expression), node);+ } else if (compiler.isCallExpression(node) && node.arguments.length) {+ if (node.expression.kind === compiler.SyntaxKind.ImportKeyword+ || (compiler.isIdentifier(node.expression) && node.expression.text === "require")) {+ add(stringValue(compiler, node.arguments[0]), node);+ } else if (compiler.isPropertyAccessExpression(node.expression)+ && node.expression.name.text === "glob"+ && compiler.isMetaProperty(node.expression.expression)+ && node.expression.expression.keywordToken === compiler.SyntaxKind.ImportKeyword) {+ for (const target of globTargets(compiler, node.arguments[0], root, file, options, project)) {+ check(target, path.join(root, target), node);+ }+ }+ }+ compiler.forEachChild(node, visit);+ }++ visit(tree);+ return violations;+}++function productionSources(directory) {+ const files = [];+ for (const entry of readdirSync(directory, { withFileTypes: true })) {+ if (entry.isDirectory() && !["tests", "__tests__"].includes(entry.name)) {+ files.push(...productionSources(path.join(directory, entry.name)));+ } else if (entry.isFile() && /\.(?:[cm]?[jt]s|[jt]sx)$/.test(entry.name) && !/\.(?:test|spec)\./.test(entry.name)) {+ files.push(path.join(directory, entry.name));+ }+ }+ return files;+}++export function findRuntimeCycles(compiler, root, project, files, options) {+ files = files.filter((file) => !/\.d\.[cm]?ts$/.test(file));+ const key = (file) => process.platform === "win32" ? path.resolve(file).toLowerCase() : path.resolve(file);+ const sources = new Map(files.map((file) => [key(file), file]));+ const graph = new Map(files.map((file) => [key(file), new Set()]));++ for (const file of files) {+ // TypeScript's emitter removes type-only dependencies, including value-spelled type imports.+ const { outputText } = compiler.transpileModule(readFileSync(file, "utf8"), {+ fileName: file,+ compilerOptions: { ...options, noEmit: false, module: compiler.ModuleKind.ESNext },+ });+ const tree = compiler.createSourceFile(file, outputText, compiler.ScriptTarget.Latest, true);+ const outgoing = graph.get(key(file));+ function add(specifier) {+ if (specifier === null) return;+ const resolved = compiler.resolveModuleName(specifier, file, options, compiler.sys).resolvedModule;+ if (resolved && sources.has(key(resolved.resolvedFileName))) outgoing.add(key(resolved.resolvedFileName));+ }+ function visit(node, deferred = false) {+ if (compiler.isImportDeclaration(node) || compiler.isExportDeclaration(node)) {+ add(stringValue(compiler, node.moduleSpecifier));+ } else if (!deferred && compiler.isCallExpression(node) && node.arguments.length+ && compiler.isIdentifier(node.expression) && node.expression.text === "require") {+ add(stringValue(compiler, node.arguments[0]));+ } else if (compiler.isCallExpression(node) && node.arguments.length > 1+ && compiler.isPropertyAccessExpression(node.expression) && node.expression.name.text === "glob"+ && compiler.isMetaProperty(node.expression.expression)+ && node.expression.expression.keywordToken === compiler.SyntaxKind.ImportKeyword) {+ const settings = node.arguments[1];+ const eager = compiler.isObjectLiteralExpression(settings) && settings.properties.some((property) =>+ compiler.isPropertyAssignment(property)+ && (compiler.isIdentifier(property.name) ? property.name.text : stringValue(compiler, property.name)) === "eager"+ && property.initializer.kind === compiler.SyntaxKind.TrueKeyword);+ if (eager) {+ for (const target of globTargets(compiler, node.arguments[0], root, file, options, project)) {+ const resolved = key(path.join(root, target));+ if (sources.has(resolved)) outgoing.add(resolved);+ }+ }+ }+ compiler.forEachChild(node, (child) => visit(child, deferred || compiler.isFunctionLike(node)));+ }+ visit(tree);+ }++ const visited = new Set();+ const active = new Map();+ const stack = [];+ const violations = [];+ function visit(file) {+ if (active.has(file)) {+ const cycle = [...stack.slice(active.get(file)), file].map((node) => sourcePath(root, sources.get(node)));+ violations.push(`${cycle[0]}: [client-runtime-cycle] eager dependencies form a cycle: ${cycle.join(" -> ")}`);+ return;+ }+ if (visited.has(file)) return;+ active.set(file, stack.length);+ stack.push(file);+ for (const target of [...graph.get(file)].sort()) visit(target);+ stack.pop();+ active.delete(file);+ visited.add(file);+ }+ for (const file of [...graph.keys()].sort()) visit(file);+ return violations;+}++export function checkRepository(compiler, root, project) {+ const options = projectOptions(compiler, root, project);+ const files = [+ ...productionSources(path.join(root, project, "src")),+ ...productionSources(path.join(root, "packages/client-events")),+ ];+ if (project === "webui") {+ const channels = path.join(root, "nanobot/channels");+ for (const entry of readdirSync(channels, { withFileTypes: true })) {+ if (!entry.isDirectory()) continue;+ const channelRoot = path.join(channels, entry.name);+ if (readdirSync(channelRoot).includes("webui")) files.push(...productionSources(path.join(channelRoot, "webui")));+ }+ }+ const violations = files.sort().flatMap((file) => findViolations(+ compiler, root, file, readFileSync(file, "utf8"), options, project,+ ));+ violations.push(...findRuntimeCycles(compiler, root, project, files, options));+ return { checked: files.length, violations };+}++export function main() {+ const { values } = parseArgs({+ options: { project: { type: "string" }, root: { type: "string", default: REPO_ROOT } },+ });+ if (!["webui", "tui"].includes(values.project)) throw new Error("--project must be webui or tui");+ const root = path.resolve(values.root);+ const result = checkRepository(loadCompiler(values.project), root, values.project);+ if (result.violations.length) {+ for (const violation of result.violations) console.error(violation);+ return 1;+ }+ console.log(`Client import boundaries passed (${values.project}, ${result.checked} files).`);+ return 0;+}++if (import.meta.main) {+ try {+ process.exitCode = main();+ } catch (error) {+ console.error(error.message);+ process.exitCode = 2;+ }+}diff --git a/scripts/check_client_import_boundaries.test.mjs b/scripts/check_client_import_boundaries.test.mjsnew file mode 100644index 000000000..0498e7bd0--- /dev/null+++ b/scripts/check_client_import_boundaries.test.mjs@@ -0,0 +1,202 @@+import { afterEach, beforeEach, expect, test } from "bun:test";+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import os from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";++import { findViolations, loadCompiler } from "./check_client_import_boundaries.mjs";++const project = path.basename(process.cwd());+const compiler = loadCompiler(project);+const script = fileURLToPath(new URL("./check_client_import_boundaries.mjs", import.meta.url));+const temporaryPrefix = path.resolve(os.tmpdir(), "nanobot-client-imports-");+let root;++function write(relative, source = "export {};\n") {+ const file = path.join(root, relative);+ mkdirSync(path.dirname(file), { recursive: true });+ writeFileSync(file, source);+ return file;+}++beforeEach(() => {+ root = path.resolve(mkdtempSync(temporaryPrefix));+ for (const name of ["webui", "tui"]) {+ write(`${name}/tsconfig.json`, JSON.stringify({+ compilerOptions: { baseUrl: ".", paths: { "@/*": ["src/*"] } },+ include: ["src"],+ }));+ }+ for (const file of [+ "webui/src/lib/model.ts", "webui/src/components/View.tsx",+ "webui/src/channel-plugins/types.ts", "webui/src/channel-plugins/registry.ts",+ "tui/src/client/api.ts", "tui/src/app/app.ts",+ "packages/client-events/notifications.ts", "packages/client-events/delivery.ts",+ "nanobot/channels/example/webui/index.ts",+ ]) write(file);+});++afterEach(() => {+ if (!root.startsWith(temporaryPrefix)) throw new Error("Fixture root is outside the allocated temporary directory");+ rmSync(root, { recursive: true });+});++function inspect(relative, source) {+ return findViolations(compiler, root, path.join(root, relative), source, {+ baseUrl: path.join(root, "webui"), paths: { "@/*": ["src/*"] },+ }, relative.startsWith("tui/") ? "tui" : "webui");+}++test.each([+ 'import { View } from "@/components/View";',+ 'import type { View } from "../components/View";',+ 'import "@/components/View";',+ 'export { View } from "@/components/View";',+ 'export type { View } from "@/components/View";',+ 'export * from "@/components/View";',+ 'type View = import("@/components/View").View;',+ 'function load() { return import("@/components/View"); }',+ 'const load = () => import(`@/components/View`);',+ 'const view = require("@/components/View");',+])("WebUI library rejects a view dependency: %s", (source) => {+ expect(inspect("webui/src/lib/model.ts", source)).toEqual([+ "webui/src/lib/model.ts:1: [webui-lib] must not import webui/src/components/View",+ ]);+});++test.skipIf(process.platform !== "win32")("checks Windows imports that differ in directory casing", () => {+ expect(existsSync(path.join(root, "webui/src/Components/View.tsx"))).toBe(true);+ expect(inspect("webui/src/lib/model.ts", 'import type { View } from "../Components/View";')).toEqual([+ "webui/src/lib/model.ts:1: [webui-lib] must not import webui/src/Components/View",+ ]);+});++test.each([+ ["packages/client-events/notifications.ts", 'import "../../webui/src/components/View";', "shared-client-contracts"],+ ["packages/client-events/notifications.ts", 'import type { ReactNode } from "react";', "shared-client-contracts"],+ ["tui/src/client/api.ts", 'export * from "../app/app";', "tui-client"],+ ["tui/src/client/api.ts", 'import type { TextRenderable } from "@opentui/core";', "tui-client"],+ ["webui/src/channel-plugins/types.ts", 'import type { View } from "@/components/View";', "channel-ui-contracts"],+ ["webui/src/lib/model.ts", 'import "../../../tui/src/client/api";', "client-app-isolation"],+ ["tui/src/client/api.ts", 'import "../../../webui/src/lib/model";', "client-app-isolation"],+ ["webui/src/lib/model.ts", 'import "../i18n";', "webui-lib-bootstrap"],+ ["webui/src/lib/model.ts", 'import "../i18n/index.ts";', "webui-lib-bootstrap"],+ ["webui/src/lib/format.ts", 'import i18n from "i18next";', "pure-format-utils"],+])("rejects the owning boundary in %s", (relative, source, rule) => {+ expect(inspect(relative, source)).toHaveLength(1);+ expect(inspect(relative, source)[0]).toContain(`[${rule}] must not import`);+});++test.each([+ ["packages/client-events/notifications.ts", 'import "./delivery";'],+ ["tui/src/client/api.ts", 'import "../../../packages/client-events/notifications";'],+ ["webui/src/lib/model.ts", 'import "../../../packages/client-events/notifications";'],+ ["webui/src/channel-plugins/types.ts", 'import type { ComponentType } from "react";'],+])("permits the shared contract or contribution interface in %s", (relative, source) => {+ expect(inspect(relative, source)).toEqual([]);+});++test("checks Vite glob dependencies using configured aliases and extension alternatives", () => {+ expect(inspect("webui/src/lib/model.ts", 'import.meta.glob("@/components/*.{ts,tsx}", { eager: true });')).toEqual([+ "webui/src/lib/model.ts:1: [webui-lib] must not import webui/src/components/View.tsx",+ ]);+});++test("respects Vite glob exclusions", () => {+ expect(inspect("webui/src/lib/model.ts", 'import.meta.glob(["../components/*.{ts,tsx}", "!../components/**"]);')).toEqual([]);+});++test("permits channel registry composition through a Vite glob", () => {+ expect(inspect("webui/src/channel-plugins/registry.ts", 'import.meta.glob("../../../nanobot/channels/*/webui/index.{ts,tsx}", { eager: true });')).toEqual([]);+});++test("includes nested dynamic import locations in diagnostics", () => {+ expect(inspect("webui/src/lib/model.ts", 'export async function load() {\n return import("@/components/View");\n}')).toEqual([+ "webui/src/lib/model.ts:2: [webui-lib] must not import webui/src/components/View",+ ]);+});++function run() {+ return Bun.spawnSync([process.execPath, script, "--project", project, "--root", root], {+ cwd: process.cwd(), stdout: "pipe", stderr: "pipe",+ });+}++test("CLI accepts a repository with valid client and shared dependencies", () => {+ const result = run();+ expect(result.exitCode).toBe(0);+ expect(new TextDecoder().decode(result.stdout)).toContain(`Client import boundaries passed (${project},`);+});++test("CLI rejects a client violation with its source location", () => {+ const relative = project === "webui" ? "webui/src/lib/model.ts" : "tui/src/client/api.ts";+ const target = project === "webui" ? "@/components/View" : "../app/app";+ write(relative, `export async function load() {\n return import("${target}");\n}\n`);+ const result = run();+ expect(result.exitCode).toBe(1);+ expect(new TextDecoder().decode(result.stderr)).toContain(`${relative}:2:`);+});++test("CLI rejects a shared contract that acquires a UI dependency", () => {+ write("packages/client-events/notifications.ts", 'import type { ReactNode } from "react";\n');+ const result = run();+ expect(result.exitCode).toBe(1);+ expect(new TextDecoder().decode(result.stderr)).toContain("packages/client-events/notifications.ts:1: [shared-client-contracts] must not import react");+});++test("ignores test modules in production source scans", () => {+ const relative = project === "webui" ? "webui/src/lib/model.test.ts" : "tui/src/client/api.test.ts";+ write(relative, 'import "../../../webui/src/components/View";\n');+ const result = run();+ expect(result.exitCode).toBe(0);+});++test("checks the actual shared source directory rather than a fixture inventory", () => {+ write("packages/client-events/new-event.ts", 'export * from "../../tui/src/app/app";\n');+ const result = run();+ expect(result.exitCode).toBe(1);+ expect(new TextDecoder().decode(result.stderr)).toContain("new-event.ts:1: [shared-client-contracts]");+});++test("CLI detects a runtime cycle through a barrel re-export", () => {+ const directory = `${project}/src/${project === "webui" ? "components" : "app"}`;+ write(`${directory}/a.ts`, 'import { value } from "./barrel"; export const first = () => value;\n');+ write(`${directory}/barrel.ts`, 'export { value } from "./b";\n');+ write(`${directory}/b.ts`, 'import { first } from "./a"; export const value = () => first;\n');+ const result = run();+ expect(result.exitCode).toBe(1);+ const diagnostic = new TextDecoder().decode(result.stderr);+ expect(diagnostic).toContain("[client-runtime-cycle]");+ for (const file of ["a.ts", "barrel.ts", "b.ts"]) expect(diagnostic).toContain(`${directory}/${file}`);+});++test("CLI permits erased type imports and deferred dynamic imports", () => {+ const directory = `${project}/src/${project === "webui" ? "components" : "app"}`;+ write(`${directory}/a.ts`, 'import { Item } from "./b"; export const first = (item: Item) => item;\n');+ write(`${directory}/b.ts`, 'import { first } from "./a"; export type Item = string; export const second = first;\n');+ write(`${directory}/lazy.ts`, 'export const load = () => import("./owner");\n');+ write(`${directory}/owner.ts`, 'import { load } from "./lazy"; export const owner = load;\n');+ write(`${project}/src/vite-env.d.ts`, 'declare module "virtual:example" { export const value: string; }\n');+ expect(run().exitCode).toBe(0);+});++test("CLI detects eager literal require cycles and permits function-local require", () => {+ const directory = `${project}/src/${project === "webui" ? "components" : "app"}`;+ write(`${directory}/a.ts`, 'export const first = require("./b");\n');+ write(`${directory}/b.ts`, 'export const second = require("./a");\n');+ const result = run();+ expect(result.exitCode).toBe(1);+ expect(new TextDecoder().decode(result.stderr)).toContain("[client-runtime-cycle]");+ write(`${directory}/a.ts`, 'export const first = () => require("./b");\n');+ expect(run().exitCode).toBe(0);+});++test.skipIf(project !== "webui")("CLI detects an eager Vite registry cycle and permits its lazy form", () => {+ write("webui/src/channel-plugins/registry.ts", 'export const plugins = import.meta.glob("../../../nanobot/channels/*/webui/index.ts", { "eager": true });\n');+ write("nanobot/channels/example/webui/index.ts", 'import { plugins } from "../../../../webui/src/channel-plugins/registry"; export default plugins;\n');+ const result = run();+ expect(result.exitCode).toBe(1);+ expect(new TextDecoder().decode(result.stderr)).toContain("[client-runtime-cycle]");+ write("webui/src/channel-plugins/registry.ts", 'export const plugins = import.meta.glob("../../../nanobot/channels/*/webui/index.ts");\n');+ expect(run().exitCode).toBe(0);+});diff --git a/scripts/check_import_boundaries.py b/scripts/check_import_boundaries.pynew file mode 100644index 000000000..ae50a4b32--- /dev/null+++ b/scripts/check_import_boundaries.py@@ -0,0 +1,291 @@+"""Check direct Python imports against the gateway's ownership boundaries."""++from __future__ import annotations++import argparse+import ast+import sys+from dataclasses import dataclass+from importlib.util import resolve_name+from pathlib import Path+++@dataclass(frozen=True)+class ImportEdge:+ target: str+ line: int+ type_only: bool = False+++@dataclass(frozen=True)+class ImportRule:+ name: str+ sources: tuple[str, ...]+ forbidden: tuple[str, ...]+ type_only_allowed: tuple[str, ...] = ()+ allowed_targets: tuple[str, ...] = ()+++@dataclass(frozen=True)+class Violation:+ rule: str+ target: str+ line: int+++_ADAPTERS = (+ "nanobot.api",+ "nanobot.channels",+ "nanobot.cli",+ "nanobot.gateway",+ "nanobot.webui",+)++_TOOL_CONFIG_MODULES = (+ "nanobot.agent.tools.cli_apps_config",+ "nanobot.agent.tools.filesystem_config",+ "nanobot.agent.tools.image_generation_config",+ "nanobot.agent.tools.self_config",+ "nanobot.agent.tools.shell_config",+ "nanobot.agent.tools.web_config",+)++IMPORT_RULES = (+ ImportRule(+ "core-execution",+ ("nanobot.agent.loop", "nanobot.agent.runner", "nanobot.agent.turn_delivery"),+ _ADAPTERS,+ allowed_targets=("nanobot.channels.notification_routes",),+ ),+ ImportRule(+ "channel-routing-contracts",+ ("nanobot.channels.notification_routes",),+ ("nanobot",),+ ),+ ImportRule(+ "session-storage",+ ("nanobot.session.manager", "nanobot.session.history", "nanobot.session.summary",+ "nanobot.session.recovery"),+ (*_ADAPTERS, "nanobot.agent"),+ ),+ ImportRule(+ "security-primitives",+ ("nanobot.security",),+ (*_ADAPTERS, "nanobot.agent", "nanobot.session"),+ ),+ ImportRule(+ "websocket-transport",+ ("nanobot.channels.websocket.runtime",),+ (+ "nanobot.bus.outbound_events",+ "nanobot.command",+ "nanobot.runtime_context",+ "nanobot.security.workspace_access",+ "nanobot.session.goal_state",+ "nanobot.webui.cli_apps_api",+ "nanobot.webui.forking",+ "nanobot.webui.mcp_presets_api",+ "nanobot.webui.sidebar_state",+ "nanobot.webui.transcription_ws",+ ),+ type_only_allowed=("nanobot.bus.outbound_events.ProgressEvent",),+ ),+ ImportRule(+ "tool-config-base",+ ("nanobot.agent.tools", "nanobot.channels"),+ ("nanobot.config.schema.Base",),+ ),+ ImportRule(+ "configuration-contracts",+ ("nanobot.config", "nanobot.config_base"),+ (*_ADAPTERS, "nanobot.agent", "nanobot.apps", "nanobot.session"),+ allowed_targets=_TOOL_CONFIG_MODULES,+ ),+ ImportRule(+ "tool-configuration-contracts",+ _TOOL_CONFIG_MODULES,+ (*_ADAPTERS, "nanobot.agent", "nanobot.apps", "nanobot.session", "nanobot.config"),+ allowed_targets=_TOOL_CONFIG_MODULES,+ ),+ ImportRule(+ "shared-primitives",+ ("nanobot.utils.file_io", "nanobot.agent.skill_metadata", "nanobot.providers.generation",+ "nanobot.llm_usage.types", "nanobot.session.automation_spec"),+ (*_ADAPTERS, "nanobot.agent", "nanobot.apps", "nanobot.session", "nanobot.config"),+ ),+ ImportRule(+ "oauth-catalog-cache",+ ("nanobot.providers.oauth_catalog_cache",),+ ("nanobot.providers.oauth_model_catalog", "nanobot.providers.openai_codex_provider",+ "nanobot.providers.github_copilot_provider", "nanobot.providers.xai_grok_provider"),+ ),+)+++def _within(name: str, prefix: str) -> bool:+ return name == prefix or name.startswith(prefix + ".")+++def _qualified_name(node: ast.expr) -> str:+ if isinstance(node, ast.Name):+ return node.id+ if isinstance(node, ast.Attribute):+ return f"{_qualified_name(node.value)}.{node.attr}"+ return ""+++def _argument(call: ast.Call, position: int, name: str) -> ast.expr | None:+ if len(call.args) > position:+ return call.args[position]+ return next((keyword.value for keyword in call.keywords if keyword.arg == name), None)+++def _literal_string(node: ast.expr | None) -> str | None:+ if isinstance(node, ast.Constant) and isinstance(node.value, str):+ return node.value+ return None+++class ImportCollector(ast.NodeVisitor):+ """Resolve static imports and literal dynamic imports without loading modules."""++ def __init__(self, tree: ast.Module, module: str, *, is_package: bool = False) -> None:+ self.package = module if is_package else module.rpartition(".")[0]+ self.edges: list[ImportEdge] = []+ self.type_only = False+ self.type_guards: set[str] = set()+ self.import_module_calls: set[str] = set()+ self.builtin_import_calls = {"__import__"}+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ for alias in node.names:+ binding = alias.asname or alias.name+ if alias.name == "importlib":+ self.import_module_calls.add(f"{binding}.import_module")+ elif alias.name == "typing":+ self.type_guards.add(f"{binding}.TYPE_CHECKING")+ elif alias.name == "builtins":+ self.builtin_import_calls.add(f"{binding}.__import__")+ elif isinstance(node, ast.ImportFrom) and not node.level:+ for alias in node.names:+ binding = alias.asname or alias.name+ if node.module == "importlib" and alias.name == "import_module":+ self.import_module_calls.add(binding)+ elif node.module == "typing" and alias.name == "TYPE_CHECKING":+ self.type_guards.add(binding)+ elif node.module == "builtins" and alias.name == "__import__":+ self.builtin_import_calls.add(binding)++ def _add(self, target: str, line: int) -> None:+ if _within(target, "nanobot"):+ self.edges.append(ImportEdge(target, line, self.type_only))++ def visit_Import(self, node: ast.Import) -> None:+ for alias in node.names:+ self._add(alias.name, node.lineno)++ def visit_ImportFrom(self, node: ast.ImportFrom) -> None:+ module = node.module or ""+ if node.level:+ module = resolve_name("." * node.level + module, self.package)+ for alias in node.names:+ target = module if alias.name == "*" else f"{module}.{alias.name}"+ self._add(target, node.lineno)++ def visit_If(self, node: ast.If) -> None:+ self.visit(node.test)+ previous = self.type_only+ self.type_only = previous or _qualified_name(node.test) in self.type_guards+ for statement in node.body:+ self.visit(statement)+ self.type_only = previous+ for statement in node.orelse:+ self.visit(statement)++ def visit_Call(self, node: ast.Call) -> None:+ name = _qualified_name(node.func)+ target = _literal_string(_argument(node, 0, "name"))+ if target is not None and name in self.import_module_calls:+ if target.startswith("."):+ package_arg = _argument(node, 1, "package")+ package = _literal_string(package_arg)+ if isinstance(package_arg, ast.Name) and package_arg.id == "__package__":+ package = self.package+ if package is not None:+ self._add(resolve_name(target, package), node.lineno)+ else:+ self._add(target, node.lineno)+ elif target is not None and name in self.builtin_import_calls:+ level = _argument(node, 4, "level")+ if level is None or (isinstance(level, ast.Constant) and level.value == 0):+ self._add(target, node.lineno)+ self.generic_visit(node)+++def find_violations(+ source: str, module: str, *, is_package: bool = False,+) -> list[Violation]:+ tree = ast.parse(source, filename=module)+ collector = ImportCollector(tree, module, is_package=is_package)+ collector.visit(tree)+ violations: list[Violation] = []+ for rule in IMPORT_RULES:+ if not any(_within(module, prefix) for prefix in rule.sources):+ continue+ for edge in collector.edges:+ if edge.type_only and edge.target in rule.type_only_allowed:+ continue+ if any(_within(edge.target, prefix) for prefix in rule.allowed_targets):+ continue+ if any(_within(edge.target, prefix) for prefix in rule.forbidden):+ violations.append(Violation(rule.name, edge.target, edge.line))+ return violations+++def check_repository(root: Path) -> tuple[int, list[str]]:+ checked = 0+ violations: list[str] = []+ for path in sorted((root / "nanobot").rglob("*.py")):+ relative = path.relative_to(root)+ if "tests" in relative.parts:+ continue+ parts = relative.with_suffix("").parts+ is_package = parts[-1] == "__init__"+ module = ".".join(parts[:-1] if is_package else parts)+ if not any(+ _within(module, prefix) for rule in IMPORT_RULES for prefix in rule.sources+ ):+ continue+ checked += 1+ for violation in find_violations(+ path.read_text(encoding="utf-8"), module, is_package=is_package,+ ):+ violations.append(+ f"{relative.as_posix()}:{violation.line}: [{violation.rule}] "+ f"must not import {violation.target}"+ )+ return checked, violations+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "--root", type=Path, default=Path(__file__).resolve().parents[1],+ help="repository root containing nanobot/",+ )+ args = parser.parse_args()+ if not (args.root / "nanobot").is_dir():+ parser.error(f"{args.root} does not contain nanobot/")+ checked, violations = check_repository(args.root)+ if checked == 0:+ parser.error(f"{args.root} contains no protected Python modules")+ if violations:+ for violation in violations:+ print(violation, file=sys.stderr)+ return 1+ print(f"Import boundaries passed ({len(IMPORT_RULES)} rules, {checked} files).")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/agent/test_loop_recovery.py b/tests/agent/test_loop_recovery.pyindex 79dd000fb..3f59b1b03 100644--- a/tests/agent/test_loop_recovery.py+++ b/tests/agent/test_loop_recovery.py@@ -11,8 +11,11 @@ from nanobot.agent.turn_delivery import TurnDeliveryFactoryfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.queue import MessageBusfrom nanobot.session.manager import SessionManager-from nanobot.session.recovery import RECOVERY_METADATA_KEY, RecoveryCoordinator+from nanobot.session.recovery import (+ RECOVERY_METADATA_KEY,+)from nanobot.session.turn_continuation import INTERNAL_CONTINUATION_META+from nanobot.webui.recovery import RecoveryCoordinator@pytest.mark.asynciodiff --git a/tests/agent/test_loop_save_turn.py b/tests/agent/test_loop_save_turn.pyindex b85e85173..42f11dc74 100644--- a/tests/agent/test_loop_save_turn.py+++ b/tests/agent/test_loop_save_turn.py@@ -124,7 +124,10 @@ def _make_full_loop(tmp_path: Path) -> AgentLoop:provider.get_default_model.return_value = "test-model"provider.generation = SimpleNamespace(max_tokens=4096)provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="Test title"))- loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")+ bus = MessageBus()+ loop = AgentLoop(+ bus=bus, provider=provider, workspace=tmp_path, model="test-model",+ )WebuiTurnCoordinator(bus=loop.bus,sessions=loop.sessions,diff --git a/tests/agent/test_session_inbox_controls.py b/tests/agent/test_session_inbox_controls.pyindex 16a5e4680..128a8ac27 100644--- a/tests/agent/test_session_inbox_controls.py+++ b/tests/agent/test_session_inbox_controls.py@@ -21,11 +21,11 @@ from nanobot.session.goal_state import GOAL_STATE_KEYfrom nanobot.session.manager import SessionManagerfrom nanobot.session.recovery import (PENDING_FOLLOWUPS_KEY,- RecoveryCoordinator,pending_followups,record_pending_followup,)from nanobot.triggers.local_session_turns import LOCAL_TRIGGER_META+from nanobot.webui.recovery import RecoveryCoordinator@pytest.fixturediff --git a/tests/agent/test_subagent_control.py b/tests/agent/test_subagent_control.pyindex 0a2b4ad26..e103fe281 100644--- a/tests/agent/test_subagent_control.py+++ b/tests/agent/test_subagent_control.py@@ -13,6 +13,7 @@ from unittest.mock import AsyncMock, MagicMockimport pytestfrom loguru import logger+from nanobot.agent.loop import AgentLoopfrom nanobot.agent.memory import Consolidatorfrom nanobot.agent.runner import AgentRunResultfrom nanobot.agent.subagent import SubagentManager@@ -23,8 +24,11 @@ from nanobot.agent.tools.shell import ExecToolfrom nanobot.agent.tools.subagent import SubagentToolfrom nanobot.bus.events import InboundMessagefrom nanobot.bus.queue import MessageBus+from nanobot.bus.runtime_events import TurnRunStatusChanged+from nanobot.config import Configfrom nanobot.nanobot import Nanobotfrom nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest+from nanobot.session.manager import SessionManagerfrom nanobot.session.webui_turns import WebuiTurnRoutePolicyfrom nanobot.utils.llm_runtime import LLMRuntime@@ -176,6 +180,86 @@ async def test_child_origin_uses_the_channel_turn_identity(loop_factory):await loop.subagents.close()+async def test_default_loop_keeps_slack_thread_for_late_subagent_result(tmp_path, monkeypatch):+ monkeypatch.setattr("nanobot.agent.loop._SUBAGENT_TERMINAL_WAIT_SECONDS", 0.01)+ child_started, release_child, parent_idle = (asyncio.Event() for _ in range(3))++ class Provider(LLMProvider):+ def __init__(self):+ super().__init__(provider_name="test")+ self.parent_calls = 0++ async def chat(self, messages, tools=None, **kwargs):+ if not any(tool.get("function", {}).get("name") == "subagent" for tool in tools or []):+ child_started.set()+ await release_child.wait()+ return LLMResponse(content="Child findings")+ self.parent_calls += 1+ if self.parent_calls == 1:+ return LLMResponse(content=None, tool_calls=[ToolCallRequest(+ id="delegate", name="subagent",+ arguments={"action": "create", "task": "Inspect config", "wait": False},+ )])+ return LLMResponse(content="Parent reply" if self.parent_calls == 2 else "Late follow-up")++ def get_default_model(self):+ return "test-model"++ workspace = tmp_path / "workspace"+ sessions_root = tmp_path / "sessions"+ sessions = SessionManager(workspace, sessions_root=sessions_root)+ config = Config.model_validate({"agents": {"defaults": {+ "workspace": str(workspace), "model": "test-model", "sessionTtlMinutes": 0,+ }}})+ bus = MessageBus()+ loop = AgentLoop.from_config(+ config, bus, provider=Provider(), session_manager=sessions, tool_registry=ToolRegistry(),+ )+ session_key = "slack:C1:1234.5678"+ slack_route = {"thread_ts": "1234.5678", "channel_type": "channel"}+ thread_metadata = {"slack": {"thread_ts": "1234.5678"}}++ def observe_idle(event):+ if event.context.session_key == session_key and event.status == "idle":+ parent_idle.set()++ unsubscribe = bus.subscribe(observe_idle, TurnRunStatusChanged)++ async def next_reply(content):+ async with asyncio.timeout(5):+ while True:+ message = await bus.consume_outbound()+ if message.content == content and message.event is None:+ return message++ consumer = asyncio.create_task(loop.run())+ try:+ await bus.publish_inbound(InboundMessage(+ channel="slack", sender_id="U1", chat_id="C1", content="Delegate this inspection",+ metadata={"slack": slack_route}, session_key_override=session_key,+ ))+ initial_reply = await next_reply("Parent reply")+ await asyncio.wait_for(child_started.wait(), timeout=5)+ await asyncio.wait_for(parent_idle.wait(), timeout=5)+ saved = SessionManager(workspace, sessions_root=sessions_root).get_existing(session_key)+ assert saved is not None+ saved_route = saved.metadata["_compaction_route"]+ release_child.set()+ late_reply = await next_reply("Late follow-up")++ assert (initial_reply.channel, initial_reply.chat_id) == ("slack", "C1")+ assert initial_reply.metadata["slack"] == slack_route+ assert saved_route == {"channel": "slack", "chat_id": "C1", "metadata": thread_metadata}+ assert (late_reply.channel, late_reply.chat_id) == ("slack", "C1")+ assert late_reply.metadata == thread_metadata+ finally:+ release_child.set()+ loop.stop()+ await asyncio.wait_for(consumer, timeout=2)+ unsubscribe()++@pytest.mark.asyncioasync def test_owner_canonical_fallback_and_absent_context(tmp_path):manager, _, ctx = setup(tmp_path)diff --git a/tests/architecture/test_import_boundaries.py b/tests/architecture/test_import_boundaries.pynew file mode 100644index 000000000..b9dbff07d--- /dev/null+++ b/tests/architecture/test_import_boundaries.py@@ -0,0 +1,271 @@+"""Regression coverage for the executable Python import boundaries."""++from __future__ import annotations++import subprocess+import sys+from pathlib import Path++import pytest++from scripts.check_import_boundaries import Violation, find_violations+++def test_repository_respects_import_boundaries() -> None:+ result = subprocess.run(+ [sys.executable, "-m", "scripts.check_import_boundaries"],+ cwd=Path(__file__).resolve().parents[2],+ capture_output=True,+ text=True,+ check=False,+ )++ assert result.returncode == 0, result.stderr+++ ("source", "target", "line"),+ [+ ("import nanobot.webui.metadata", "nanobot.webui.metadata", 1),+ ("from nanobot import webui", "nanobot.webui", 1),+ ("from nanobot.webui import metadata", "nanobot.webui.metadata", 1),+ ("from .. import webui", "nanobot.webui", 1),+ ("from ..webui import metadata", "nanobot.webui.metadata", 1),+ (+ "def load():\n from nanobot.cli import gateway",+ "nanobot.cli.gateway", 2,+ ),+ (+ "import importlib\nimportlib.import_module('nanobot.webui.metadata')",+ "nanobot.webui.metadata", 2,+ ),+ (+ "import importlib as modules\n"+ "modules.import_module(name='nanobot.webui.metadata')",+ "nanobot.webui.metadata", 2,+ ),+ (+ "from importlib import import_module as load\n"+ "load('..webui.metadata', __package__)",+ "nanobot.webui.metadata", 2,+ ),+ (+ "from importlib import import_module\n"+ "import_module('..webui.metadata', package='nanobot.agent')",+ "nanobot.webui.metadata", 2,+ ),+ ("__import__('nanobot.webui.metadata')", "nanobot.webui.metadata", 1),+ (+ "import builtins as imports\nimports.__import__('nanobot.webui.metadata')",+ "nanobot.webui.metadata", 2,+ ),+ ],+)+def test_core_rejects_adapter_imports_in_supported_spellings(+ source: str, target: str, line: int,+) -> None:+ assert find_violations(source, "nanobot.agent.loop") == [+ Violation("core-execution", target, line),+ ]+++ "source",+ [+ "from typing import TYPE_CHECKING as TC\n"+ "if TC:\n from nanobot.webui import metadata",+ "import typing as t\n"+ "if t.TYPE_CHECKING:\n from nanobot.webui import metadata",+ ],+)+def test_core_boundary_includes_type_dependencies(source: str) -> None:+ assert find_violations(source, "nanobot.agent.runner") == [+ Violation("core-execution", "nanobot.webui.metadata", 3),+ ]+++ ("module", "rule"),+ [+ ("nanobot.session.manager", "session-storage"),+ ("nanobot.session.recovery", "session-storage"),+ ("nanobot.security.workspace_policy", "security-primitives"),+ ("nanobot.agent.turn_delivery", "core-execution"),+ ("nanobot.channels.notification_routes", "channel-routing-contracts"),+ ("nanobot.config.schema", "configuration-contracts"),+ ("nanobot.agent.tools.cli_apps_config", "tool-configuration-contracts"),+ ("nanobot.utils.file_io", "shared-primitives"),+ ],+)+def test_storage_and_security_do_not_depend_on_adapters(module: str, rule: str) -> None:+ assert find_violations("from nanobot.cli import gateway", module) == [+ Violation(rule, "nanobot.cli.gateway", 1),+ ]+++def test_websocket_only_permits_progress_event_as_a_type_dependency() -> None:+ source = (+ "from typing import TYPE_CHECKING\n"+ "if TYPE_CHECKING:\n"+ " from nanobot.bus.outbound_events import ProgressEvent\n"+ " from nanobot.command import router\n"+ "else:\n"+ " from nanobot.bus.outbound_events import ProgressEvent\n"+ )+ assert find_violations(source, "nanobot.channels.websocket.runtime") == [+ Violation("websocket-transport", "nanobot.command.router", 4),+ Violation("websocket-transport", "nanobot.bus.outbound_events.ProgressEvent", 6),+ ]+++ "source",+ [+ "from nanobot.config.schema import Base",+ "from ...config.schema import Base as ConfigBase",+ ],+)+def test_tool_configs_import_the_shared_base_directly(source: str) -> None:+ assert find_violations(source, "nanobot.agent.tools.shell") == [+ Violation("tool-config-base", "nanobot.config.schema.Base", 1),+ ]+ assert find_violations(+ "from nanobot.config_base import Base", "nanobot.agent.tools.shell",+ ) == []+++def test_configuration_imports_the_six_tool_owned_config_contracts() -> None:+ source = (+ "from nanobot.agent.tools.cli_apps_config import CliAppsToolConfig\n"+ "from nanobot.agent.tools.filesystem_config import FileToolsConfig\n"+ "from nanobot.agent.tools.image_generation_config import ImageGenerationToolConfig\n"+ "from nanobot.agent.tools.self_config import MyToolConfig\n"+ "from nanobot.agent.tools.shell_config import ExecToolConfig\n"+ "from nanobot.agent.tools.web_config import WebToolsConfig\n"+ )+ assert find_violations(source, "nanobot.config.schema") == []+++ ("module", "source"),+ [+ ("nanobot.agent.loop", "from nanobot.session.recovery import RecoveryAdmission"),+ ("nanobot.session.manager", "from nanobot.providers.base import ProviderConversationState"),+ ("nanobot.session.webui_turns", "from nanobot.webui import transcript"),+ ("nanobot.cli.gateway_runtime", "from nanobot.agent.loop import AgentLoop"),+ ("nanobot.channels.websocket.runtime", "from nanobot.webui import inbound_commands"),+ ("nanobot.agent.tools.cli_apps_config", "from nanobot.config_base import Base"),+ (+ "nanobot.agent.turn_delivery",+ "from nanobot.channels.notification_routes import notification_metadata",+ ),+ ],+)+def test_existing_runtime_and_composition_dependencies_remain_allowed(+ module: str, source: str,+) -> None:+ assert find_violations(source, module) == []+++ ("relative", "source", "rule", "target", "line"),+ [+ (+ "nanobot/agent/runner.py", "import nanobot.webui.metadata",+ "core-execution", "nanobot.webui.metadata", 1,+ ),+ (+ "nanobot/agent/loop.py",+ "import importlib\nif importlib.import_module('nanobot.webui.metadata'):\n pass",+ "core-execution", "nanobot.webui.metadata", 2,+ ),+ (+ "nanobot/agent/loop.py", "if __import__('nanobot.webui.metadata'):\n pass",+ "core-execution", "nanobot.webui.metadata", 1,+ ),+ (+ "nanobot/session/manager.py", "from nanobot.cli import gateway",+ "session-storage", "nanobot.cli.gateway", 1,+ ),+ (+ "nanobot/channels/notification_routes.py",+ "from nanobot.channels.slack.runtime import SlackChannel",+ "channel-routing-contracts", "nanobot.channels.slack.runtime.SlackChannel", 1,+ ),+ (+ "nanobot/channels/notification_routes.py",+ "from nanobot.agent.turn_delivery import TurnRoute",+ "channel-routing-contracts", "nanobot.agent.turn_delivery.TurnRoute", 1,+ ),+ (+ "nanobot/security/__init__.py", "from ..cli import gateway",+ "security-primitives", "nanobot.cli.gateway", 1,+ ),+ (+ "nanobot/channels/websocket/runtime.py",+ "import importlib as modules\nmodules.import_module('nanobot.command.router')",+ "websocket-transport", "nanobot.command.router", 2,+ ),+ (+ "nanobot/agent/tools/shell.py", "from ...config.schema import Base as ConfigBase",+ "tool-config-base", "nanobot.config.schema.Base", 1,+ ),+ (+ "nanobot/channels/telegram/runtime.py", "from nanobot.config.schema import Base",+ "tool-config-base", "nanobot.config.schema.Base", 1,+ ),+ (+ "nanobot/config/schema.py", "from nanobot.agent.tools.shell import ExecTool",+ "configuration-contracts", "nanobot.agent.tools.shell.ExecTool", 1,+ ),+ (+ "nanobot/agent/tools/cli_apps_config.py", "from .cli_apps import CliAppsTool",+ "tool-configuration-contracts", "nanobot.agent.tools.cli_apps.CliAppsTool", 1,+ ),+ (+ "nanobot/agent/tools/web_config.py", "from nanobot.config.schema import Config",+ "tool-configuration-contracts", "nanobot.config.schema.Config", 1,+ ),+ (+ "nanobot/providers/oauth_catalog_cache.py",+ "from nanobot.providers import openai_codex_provider",+ "oauth-catalog-cache", "nanobot.providers.openai_codex_provider", 1,+ ),+ ],+)+def test_cli_rejects_a_violation_and_reports_its_source_location(+ tmp_path: Path, relative: str, source: str, rule: str, target: str, line: int,+) -> None:+ path = tmp_path / relative+ path.parent.mkdir(parents=True)+ path.write_text(source + "\n", encoding="utf-8")++ result = subprocess.run(+ [sys.executable, "-m", "scripts.check_import_boundaries", "--root", str(tmp_path)],+ cwd=Path(__file__).resolve().parents[2],+ capture_output=True,+ text=True,+ check=False,+ )++ assert result.returncode == 1+ assert result.stderr.strip() == f"{relative}:{line}: [{rule}] must not import {target}"+++def test_cli_accepts_a_tool_owned_config_import(tmp_path: Path) -> None:+ path = tmp_path / "nanobot/config/schema.py"+ path.parent.mkdir(parents=True)+ path.write_text(+ "from nanobot.agent.tools.cli_apps_config import CliAppsToolConfig\n",+ encoding="utf-8",+ )++ result = subprocess.run(+ [sys.executable, "-m", "scripts.check_import_boundaries", "--root", str(tmp_path)],+ cwd=Path(__file__).resolve().parents[2],+ capture_output=True,+ text=True,+ check=False,+ )++ assert result.returncode == 0, result.stderrdiff --git a/tests/channels/test_channel_plugins.py b/tests/channels/test_channel_plugins.pyindex a89350f4d..6f27dd4f5 100644--- a/tests/channels/test_channel_plugins.py+++ b/tests/channels/test_channel_plugins.py@@ -2637,7 +2637,7 @@ def test_optional_dependency_metadata_for_enable():required = data["project"]["dependencies"]assert "boto3>=1.43.0" not in data["project"]["dependencies"]- assert deps["bedrock"] == ["boto3>=1.43.0"]+ assert deps["bedrock"] == ["boto3>=1.43.0", "botocore>=1.43.0,<2.0.0"]# The built-in remote WebUI proxy now needs aiohttp even without channels.# Keep the historical API extra installable for existing deployment commands.assert "aiohttp>=3.14.3,<4.0.0" in required@@ -2729,6 +2729,8 @@ def test_optional_dependency_metadata_for_enable():"weixin": ("qrcode[pil]>=8.0", "pycryptodome>=3.20.0"),"whatsapp": ("neonize>=0.4.3.post0,<0.5.0",+ "python-magic>=0.4.27; sys_platform != 'win32'",+ "python-magic-bin>=0.4.14; sys_platform == 'win32'","segno>=1.6.1,<2.0.0",),}diff --git a/tests/channels/test_websocket_application_boundary.py b/tests/channels/test_websocket_application_boundary.pyindex 014cd09cd..90453554d 100644--- a/tests/channels/test_websocket_application_boundary.py+++ b/tests/channels/test_websocket_application_boundary.py@@ -10,18 +10,6 @@ from nanobot.channels.websocket import runtime_REPOSITORY_ROOT = Path(__file__).resolve().parents[2]_RUNTIME_PATH = _REPOSITORY_ROOT / "nanobot" / "channels" / "websocket" / "runtime.py"_SESSION_IDENTITY_PATH = _REPOSITORY_ROOT / "nanobot" / "webui" / "session_identity.py"-_FORBIDDEN_RUNTIME_IMPORTS = (- "nanobot.bus.outbound_events",- "nanobot.command",- "nanobot.runtime_context",- "nanobot.security.workspace_access",- "nanobot.session.goal_state",- "nanobot.webui.cli_apps_api",- "nanobot.webui.forking",- "nanobot.webui.mcp_presets_api",- "nanobot.webui.sidebar_state",- "nanobot.webui.transcription_ws",-)def _channel_method(name: str) -> ast.AsyncFunctionDef:@@ -50,21 +38,6 @@ def _statements_without_docstring(node: ast.AsyncFunctionDef) -> list[ast.stmt]:return body-def test_websocket_runtime_does_not_import_application_command_trees() -> None:- tree = ast.parse(_RUNTIME_PATH.read_text(encoding="utf-8"))- imported = {- node.module- for node in tree.body- if isinstance(node, ast.ImportFrom) and node.module is not None- }- violations = sorted(- module- for module in imported- if module.startswith(_FORBIDDEN_RUNTIME_IMPORTS)- )- assert violations == []--def test_business_entrypoints_are_thin_transport_delegations() -> None:for method_name in ("_dispatch_envelope", "_hydrate_after_subscribe", "send"):statements = _statements_without_docstring(_channel_method(method_name))diff --git a/tests/cli/test_commands.py b/tests/cli/test_commands.pyindex d8edba004..6008c13dc 100644--- a/tests/cli/test_commands.py+++ b/tests/cli/test_commands.py@@ -35,7 +35,6 @@ from nanobot.providers.factory import ProviderSnapshot, make_provider, provider_from nanobot.providers.openai_codex_provider import _strip_model_prefixfrom nanobot.providers.registry import find_by_namefrom nanobot.providers.unconfigured_provider import UnconfiguredProvider-from nanobot.session.webui_turns import WebuiTurnRoutePolicyfrom nanobot.webui.dev import WebUIDevErrorfrom nanobot.webui.metadata import (WEBUI_MESSAGE_SOURCE_METADATA_KEY,@@ -287,6 +286,9 @@ def test_commit_dream_changes_commits_real_edits(tmp_path) -> None:@pytest.fixturedef mock_paths():"""Mock config/workspace paths for test isolation."""+ from importlib import import_module++ import_module("nanobot.channels.validation")with patch("nanobot.config.loader.get_config_path") as mock_cp, \patch("nanobot.config.loader.save_config") as mock_sc, \patch("nanobot.config.loader.load_config") as mock_lc, \@@ -2041,6 +2043,12 @@ def _patch_cli_command_runtime(cron_service=None,get_cron_dir=None,) -> None:+ from importlib import import_module++ # Load adapter contracts before replacing runtime factories for this invocation.+ import_module("nanobot.session.webui_turns")+ import_module("nanobot.channels.validation")+ import_module("nanobot.channels.websocket.runtime")provider_factory = make_provider or (lambda _config: _fake_provider())monkeypatch.setattr(@@ -3591,8 +3599,27 @@ def test_gateway_local_trigger_queue_submits_agent_turns(assert isinstance(turn_delivery_factory, TurnDeliveryFactory)assert turn_delivery_factory.bus is busassert seen["cron_reconciliation"] == ["remove:dream", "remove:heartbeat", "status"]- assert isinstance(turn_delivery_factory.route_policy, WebuiTurnRoutePolicy)- assert turn_delivery_factory.route_policy.sessions is agent.sessions+ websocket_delivery = turn_delivery_factory.create(+ InboundMessage(+ channel="websocket", sender_id="user", chat_id="chat", content="Hello",+ metadata={"webui": True, "webui_turn_id": "turn-1"},+ ),+ "websocket:chat",+ )+ assert websocket_delivery.route.turn_id == "turn-1"+ assert websocket_delivery.route.metadata["_websocket_turn_owner"]+ slack_delivery = turn_delivery_factory.create(+ InboundMessage(+ channel="system", sender_id="subagent", chat_id="slack:C1", content="Done",+ ),+ "slack:C1:1234.5678",+ )+ assert slack_delivery.route.metadata["slack"] == {"thread_ts": "1234.5678"}+ session_metadata = {}+ slack_delivery.remember_session_route(session_metadata)+ assert session_metadata["_compaction_route"] == {+ "channel": "slack", "chat_id": "C1", "metadata": {"slack": {"thread_ts": "1234.5678"}},+ }def test_gateway_workspace_override_does_not_migrate_legacy_cron(diff --git a/tests/config/test_tool_config_boundaries.py b/tests/config/test_tool_config_boundaries.pyindex 7de583f3b..d2ba8d6f2 100644--- a/tests/config/test_tool_config_boundaries.py+++ b/tests/config/test_tool_config_boundaries.py@@ -1,7 +1,8 @@-import astimport subprocessimport sys-from pathlib import Path+from importlib import import_module++import pytestdef test_config_base_import_does_not_load_config_schema():@@ -20,19 +21,90 @@ print("nanobot.config.schema" in sys.modules)assert result.stdout.strip() == "False"-def test_builtin_tool_configs_do_not_depend_on_config_schema_base():- repo = Path(__file__).resolve().parents[2]- tool_paths = sorted((repo / "nanobot/agent/tools").glob("*.py"))+def test_config_validation_and_schema_generation_do_not_import_runtime_implementations():+ code = """+import importlib.abc+import sys++class RuntimeImportBlocker(importlib.abc.MetaPathFinder):+ def find_spec(self, fullname, path, target=None):+ config_modules = {+ 'nanobot.agent', 'nanobot.agent.tools',+ 'nanobot.agent.tools.cli_apps_config',+ 'nanobot.agent.tools.filesystem_config',+ 'nanobot.agent.tools.image_generation_config',+ 'nanobot.agent.tools.self_config',+ 'nanobot.agent.tools.shell_config',+ 'nanobot.agent.tools.web_config',+ }+ if fullname in config_modules:+ return None+ forbidden = (+ 'nanobot.agent', 'nanobot.api', 'nanobot.apps', 'nanobot.channels',+ 'nanobot.cli', 'nanobot.session', 'nanobot.webui', 'nanobot.providers.base',+ )+ if any(fullname == name or fullname.startswith(name + '.') for name in forbidden):+ raise AssertionError('configuration imported runtime implementation: ' + fullname)++sys.meta_path.insert(0, RuntimeImportBlocker())+from nanobot.config import Config+from nanobot.config.schema import ModelPresetConfig++config = Config.model_validate({'tools': {+ 'exec': {'timeout': 37},+ 'imageGeneration': {+ 'enabled': True,+ 'extraHeaders': {'X-Image-Mode': 'test'},+ 'extraBody': {'quality': 'high', 'provider': {'order': ['example']}},+ },+}})+assert config.tools.exec.timeout == 37+restored = Config.model_validate_json(config.model_dump_json(by_alias=True))+assert restored.tools.exec.timeout == 37+assert restored.tools.image_generation.enabled is True+assert restored.tools.image_generation.extra_headers == {'X-Image-Mode': 'test'}+assert restored.tools.image_generation.extra_body == {+ 'quality': 'high', 'provider': {'order': ['example']},+}+assert Config.model_json_schema()['properties']['tools']+assert ModelPresetConfig(model='example').to_generation_settings().max_tokens == 8192+"""+ result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)+ assert result.returncode == 0, result.stderr+++def test_public_tool_contracts_can_be_imported_without_agent_execution():+ code = """+import sys+from nanobot.agent.tools import Tool, ToolResult, tool_parameters+from nanobot.agent.tools.base import Tool as BaseTool++assert Tool is BaseTool+assert callable(tool_parameters)+assert ToolResult+assert 'nanobot.agent.loop' not in sys.modules+assert 'nanobot.agent.runner' not in sys.modules+assert 'nanobot.agent.tools.shell' not in sys.modules+"""+ result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)+ assert result.returncode == 0, result.stderr- violations = []- for path in tool_paths:- tree = ast.parse(path.read_text(encoding="utf-8"))- for node in ast.walk(tree):- if not isinstance(node, ast.ImportFrom):- continue- if node.module != "nanobot.config.schema":- continue- if any(alias.name == "Base" for alias in node.names):- violations.append(str(path.relative_to(repo)))- assert violations == []+ ("module", "names"),+ [+ ("cli_apps", ("CliAppsToolConfig",)),+ ("filesystem", ("FileToolsConfig",)),+ ("image_generation", ("ImageGenerationToolConfig",)),+ ("self", ("MyToolConfig",)),+ ("shell", ("ExecToolConfig",)),+ ("web", ("WebSearchConfig", "WebFetchConfig", "WebToolsConfig")),+ ],+)+def test_tool_config_imports_keep_the_same_public_class(module, names):+ contracts = import_module(f"nanobot.agent.tools.{module}_config")+ aggregate = import_module("nanobot.config.schema")+ implementation = import_module(f"nanobot.agent.tools.{module}")+ for name in names:+ assert getattr(implementation, name) is getattr(contracts, name)+ assert getattr(aggregate, name) is getattr(contracts, name)diff --git a/tests/session/test_recovery.py b/tests/session/test_recovery.pyindex 99829bd8e..8f343f3ea 100644--- a/tests/session/test_recovery.py+++ b/tests/session/test_recovery.py@@ -14,13 +14,12 @@ from nanobot.session.recovery import (PENDING_USER_TURN_KEY,RECOVERY_METADATA_KEY,RUNTIME_CHECKPOINT_KEY,- RecoveryActionError,- RecoveryCoordinator,acknowledge_pending_followups,pending_followups,record_pending_followup,)from nanobot.webui import session_list_index, transcript+from nanobot.webui.recovery import RecoveryActionError, RecoveryCoordinatordef _persist(manager: SessionManager, session: Session) -> None:diff --git a/tests/webui/test_notification_contract.py b/tests/webui/test_notification_contract.pyindex 589df0674..b432f9e71 100644--- a/tests/webui/test_notification_contract.py+++ b/tests/webui/test_notification_contract.py@@ -1,6 +1,8 @@import importlib.utilimport ioimport json+import posixpath+import shleximport tarfilefrom pathlib import Path@@ -37,3 +39,10 @@ def test_tui_source_archive_preserves_shared_module_import_path():assert "nanobot-tui-source/packages/client-events/notifications.ts" in namesassert "nanobot-tui-source/tui/bun.lock" in namesassert "nanobot-tui-source/LICENSE" in names+ package = archive.extractfile("nanobot-tui-source/tui/package.json")+ assert package is not None+ scripts = json.load(package)["scripts"]+ for command in ("check:imports", "test:imports"):+ entrypoint = next(arg for arg in shlex.split(scripts[command]) if arg.endswith(".mjs"))+ archived_path = posixpath.normpath(f"nanobot-tui-source/tui/{entrypoint}")+ assert archived_path in namesdiff --git a/tui/package.json b/tui/package.jsonindex bb3dda0cc..00709264e 100644--- a/tui/package.json+++ b/tui/package.json@@ -7,6 +7,8 @@"start": "bun src/index.ts","build": "bun scripts/build.ts","check": "tsc --noEmit",+ "check:imports": "bun ../scripts/check_client_import_boundaries.mjs --project tui",+ "test:imports": "bun test ../scripts/check_client_import_boundaries.test.mjs","test": "bun test"},"dependencies": {diff --git a/tui/scripts/package-release.py b/tui/scripts/package-release.pyindex 5d35bc095..eb95f0dc7 100644--- a/tui/scripts/package-release.py+++ b/tui/scripts/package-release.py@@ -62,6 +62,8 @@ def _source_archive(root: Path) -> bytes:archive.add(path, arcname=Path("nanobot-tui-source/tui") / relative)archive.add(root.parent / "packages/client-events",arcname="nanobot-tui-source/packages/client-events")+ for name in ("check_client_import_boundaries.mjs", "check_client_import_boundaries.test.mjs"):+ archive.add(root.parent / "scripts" / name, arcname=f"nanobot-tui-source/scripts/{name}")archive.add(root.parent / "LICENSE", arcname="nanobot-tui-source/LICENSE")return output.getvalue()diff --git a/webui/bun.lock b/webui/bun.lockindex 7d6064d49..81a57d874 100644--- a/webui/bun.lock+++ b/webui/bun.lock@@ -41,6 +41,7 @@"@testing-library/jest-dom": "^6.6.3","@testing-library/react": "^16.1.0","@testing-library/user-event": "^14.5.2",+ "@types/mdast": "^4.0.4","@types/node": "^24.0.0","@types/qrcode": "^1.5.6","@types/react": "^18.3.18",@@ -54,6 +55,9 @@"globals": "^17.6.0","happy-dom": "^16.3.0","katex": "^0.16.21",+ "micromark-extension-gfm-autolink-literal": "^2.1.0",+ "micromark-extension-math": "^3.1.0",+ "micromark-util-types": "^2.0.2","postcss": "^8.5.0","tailwindcss": "^3.4.17","tailwindcss-animate": "^1.0.7",diff --git a/webui/eslint.config.js b/webui/eslint.config.jsindex f422efad8..31221d5f2 100644--- a/webui/eslint.config.js+++ b/webui/eslint.config.js@@ -12,6 +12,12 @@ export default tseslint.config(},js.configs.recommended,...tseslint.configs.recommended,+ {+ files: ["scripts/check_client_import_boundaries*.mjs"],+ languageOptions: {+ globals: { ...globals.node, Bun: "readonly" },+ },+ },{files: ["webui/src/**/*.{ts,tsx}",diff --git a/webui/package-lock.json b/webui/package-lock.jsonindex 5c06ef2c7..dfc7fe783 100644--- a/webui/package-lock.json+++ b/webui/package-lock.json@@ -11,6 +11,7 @@"@radix-ui/react-alert-dialog": "^1.1.4","@radix-ui/react-dialog": "^1.1.4","@radix-ui/react-dropdown-menu": "^2.1.4",+ "@radix-ui/react-menu": "2.1.16","@radix-ui/react-popover": "1.1.15","@radix-ui/react-select": "2.2.6","@radix-ui/react-slot": "^1.1.1",@@ -21,6 +22,7 @@"i18next": "^26.0.6","lucide-react": "^0.469.0","micromark-factory-space": "^2.0.1",+ "micromark-util-decode-string": "^2.0.1","qrcode": "^1.5.4","react": "^18.3.1","react-dom": "^18.3.1",@@ -42,6 +44,7 @@"@testing-library/jest-dom": "^6.6.3","@testing-library/react": "^16.1.0","@testing-library/user-event": "^14.5.2",+ "@types/mdast": "^4.0.4","@types/node": "^24.0.0","@types/qrcode": "^1.5.6","@types/react": "^18.3.18",@@ -55,6 +58,9 @@"globals": "^17.6.0","happy-dom": "^16.3.0","katex": "^0.16.21",+ "micromark-extension-gfm-autolink-literal": "^2.1.0",+ "micromark-extension-math": "^3.1.0",+ "micromark-util-types": "^2.0.2","postcss": "^8.5.0","tailwindcss": "^3.4.17","tailwindcss-animate": "^1.0.7",diff --git a/webui/package.json b/webui/package.jsonindex 2820525bc..66f89439d 100644--- a/webui/package.json+++ b/webui/package.json@@ -10,7 +10,9 @@"test": "vitest run","test:coverage": "vitest run --coverage","test:watch": "vitest",- "lint": "cd .. && eslint --config webui/eslint.config.js webui/src \"nanobot/channels/*/webui/**/*.{ts,tsx}\" \"nanobot/channels/*/tests/webui/**/*.{ts,tsx}\" --max-warnings 0"+ "check:imports": "bun ../scripts/check_client_import_boundaries.mjs --project webui",+ "test:imports": "bun test ../scripts/check_client_import_boundaries.test.mjs",+ "lint": "cd .. && eslint --config webui/eslint.config.js webui/src \"nanobot/channels/*/webui/**/*.{ts,tsx}\" \"nanobot/channels/*/tests/webui/**/*.{ts,tsx}\" \"scripts/check_client_import_boundaries*.mjs\" --max-warnings 0"},"dependencies": {"@radix-ui/react-alert-dialog": "^1.1.4",@@ -50,6 +52,7 @@"@testing-library/react": "^16.1.0","@testing-library/user-event": "^14.5.2","@types/node": "^24.0.0",+ "@types/mdast": "^4.0.4","@types/qrcode": "^1.5.6","@types/react": "^18.3.18","@types/react-dom": "^18.3.5",@@ -62,6 +65,9 @@"globals": "^17.6.0","happy-dom": "^16.3.0","katex": "^0.16.21",+ "micromark-util-types": "^2.0.2",+ "micromark-extension-math": "^3.1.0",+ "micromark-extension-gfm-autolink-literal": "^2.1.0","postcss": "^8.5.0","tailwindcss": "^3.4.17","tailwindcss-animate": "^1.0.7",diff --git a/webui/src/App.tsx b/webui/src/App.tsxindex d5613338d..c15a0e41c 100644--- a/webui/src/App.tsx+++ b/webui/src/App.tsx@@ -13,7 +13,8 @@ import { Trans, useTranslation } from "react-i18next";import { channelUiPresentation } from "@/channel-plugins/registry";import { StarPrompt } from "@/components/StarPrompt";import { Sidebar } from "@/components/Sidebar";-import { RemoteInstances, useRemoteConnections } from "@/components/remote/RemoteInstances";+import { RemoteInstances } from "@/components/remote/RemoteInstances";+import { useRemoteConnections } from "@/components/remote/remote-context";import { RemoteConnectionsPage } from "@/components/remote/RemoteConnectionsPage";import { LanguageSwitcher } from "@/components/LanguageSwitcher";import { SidebarResizeHandle, SIDEBAR_MIN_WIDTH, SIDEBAR_MAX_WIDTH } from "@/components/SidebarResizeHandle";diff --git a/webui/src/components/settings/channels/catalog.ts b/webui/src/channel-plugins/catalog.tssimilarity index 100%rename from webui/src/components/settings/channels/catalog.tsrename to webui/src/channel-plugins/catalog.tsdiff --git a/webui/src/channel-plugins/types.ts b/webui/src/channel-plugins/types.tsindex cebfdf609..e8462b296 100644--- a/webui/src/channel-plugins/types.ts+++ b/webui/src/channel-plugins/types.ts@@ -1,6 +1,6 @@import type { ComponentType } from "react";-import type { ChannelPresentation } from "@/components/settings/channels/catalog";+import type { ChannelPresentation } from "@/channel-plugins/catalog";import type {NanobotFeatureInfo,NanobotFeaturesPayload,diff --git a/webui/src/components/ChatList.tsx b/webui/src/components/ChatList.tsxindex 241280037..2aa499b51 100644--- a/webui/src/components/ChatList.tsx+++ b/webui/src/components/ChatList.tsx@@ -51,7 +51,8 @@ import {SIDEBAR_SELECTION_ITEM_CLASS,SidebarSelectionHighlight,} from "@/components/SidebarSelectionHighlight";-import { relativeTime, visibleSessionPreview } from "@/lib/format";+import { visibleSessionPreview } from "@/lib/format";+import { relativeTime } from "@/lib/format-time";import {COLLAPSED_CHATS_VISIBLE_COUNT,displayTitle,diff --git a/webui/src/components/CliAppMentionText.tsx b/webui/src/components/CliAppMentionText.tsxindex dec5db890..b0f6ea747 100644--- a/webui/src/components/CliAppMentionText.tsx+++ b/webui/src/components/CliAppMentionText.tsx@@ -10,16 +10,7 @@ import { logoFallbackUrls } from "@/lib/provider-brand";import { sessionHandleColor } from "@/lib/session-handle";import type { CliAppInfo, McpPresetInfo, SessionMention } from "@/lib/types";import { cn } from "@/lib/utils";-import { composerMentionLabel } from "@/lib/composer-mention-text";--type CliAppMentionSegment =- | { kind: "text"; text: string }- | { kind: "cli"; text: string; app: CliAppInfo };--export type CapabilityMentionSegment =- | CliAppMentionSegment- | { kind: "mcp"; text: string; preset: McpPresetInfo }- | { kind: "session"; text: string; mention: SessionMention };+import { composerMentionLabel, type CapabilityMentionSegment } from "@/lib/composer-mention-text";// Paint-only weight keeps the native textarea's regular-width caret and wrapping in sync.const COMPOSER_BRAND_NAME_CLASS = "[-webkit-text-stroke:0.4px_currentColor]";diff --git a/webui/src/components/DeleteConfirm.tsx b/webui/src/components/DeleteConfirm.tsxindex 44a68c50c..ce1eac2ae 100644--- a/webui/src/components/DeleteConfirm.tsx+++ b/webui/src/components/DeleteConfirm.tsx@@ -12,7 +12,7 @@ import type { TFunction } from "i18next";import { Trash2 } from "lucide-react";import { useTranslation } from "react-i18next";import { currentLocale } from "@/i18n";-import { fmtDateTime } from "@/lib/format";+import { fmtDateTime } from "@/lib/format-time";import type { SessionAutomationJob } from "@/lib/types";interface DeleteConfirmProps {diff --git a/webui/src/components/MessageBubble.tsx b/webui/src/components/MessageBubble.tsxindex 7c41b23b7..cefcf6ed7 100644--- a/webui/src/components/MessageBubble.tsx+++ b/webui/src/components/MessageBubble.tsx@@ -19,12 +19,13 @@ import { InlineImageProvider, useInlineImages } from "@/components/InlineImageCoimport { MarkdownText } from "@/components/MarkdownText";import { SlashCommandText } from "@/components/SlashCommandText";import { ReasoningRow } from "@/components/thread/activity/ReasoningRow";+import { StreamingLabelSheen } from "@/components/ui/streaming-label-sheen";import { ContextCompactionNotice } from "@/components/thread/ContextCompactionNotice";import { UserMessageText } from "@/components/UserMessageText";import { HoverHint } from "@/components/ui/tooltip";import { cn } from "@/lib/utils";import { copyTextToClipboard } from "@/lib/clipboard";-import { formatMessageEndTime } from "@/lib/format";+import { formatMessageEndTime } from "@/lib/format-time";import { toMediaAttachment } from "@/lib/media";import { matchingSlashCommand } from "@/lib/slash-command";import { sessionHandleColor } from "@/lib/session-handle";@@ -704,35 +705,6 @@ function ThinkingState() {);}-/** L→R sheen on the glyphs themselves; inactive labels stay solid muted text. */-export function StreamingLabelSheen({- children,- active,- className,-}: {- children: ReactNode;- active: boolean;- className?: string;-}) {- const sheenText =- typeof children === "string" || typeof children === "number"- ? String(children)- : undefined;- return (- <span className={cn("block min-w-0 overflow-hidden py-px", className)}>- <span- data-sheen-text={active ? sheenText : undefined}- className={cn(- "block w-fit max-w-full truncate pr-0.5 font-medium leading-normal",- active ? "streaming-text-sheen after:pr-0.5" : "text-muted-foreground",- )}- >- {children}- </span>- </span>- );-}-interface ReasoningBubbleProps {text: string;streaming: boolean;diff --git a/webui/src/components/UserMessageText.tsx b/webui/src/components/UserMessageText.tsxindex 0129988c0..5f8f9db74 100644--- a/webui/src/components/UserMessageText.tsx+++ b/webui/src/components/UserMessageText.tsx@@ -4,13 +4,13 @@ import { useTranslation } from "react-i18next";import {CapabilityMentionToken,splitCapabilityMentionSegments,- type CapabilityMentionSegment,} from "@/components/CliAppMentionText";import {INLINE_TOKEN_HIGHLIGHT_COLOR,InlineTokenHighlight,} from "@/components/InlineTokenHighlight";import type { CliAppInfo, McpPresetInfo, SessionMention } from "@/lib/types";+import type { CapabilityMentionSegment } from "@/lib/composer-mention-text";type SkillReferenceSegment =| { kind: "text"; text: string }diff --git a/webui/src/components/remote/HostConnectionStatus.tsx b/webui/src/components/remote/HostConnectionStatus.tsxindex b089cf9d9..24d7cb868 100644--- a/webui/src/components/remote/HostConnectionStatus.tsx+++ b/webui/src/components/remote/HostConnectionStatus.tsx@@ -2,7 +2,7 @@ import { CircleAlert, Loader2 } from "lucide-react";import { useTranslation } from "react-i18next";import { cn } from "@/lib/utils";-export type HostConnectionState = "open" | "closed" | "connecting" | "error";+import type { HostConnectionState } from "./remote-context";/** Connectivity is independent of which host the user is currently viewing. */export function HostConnectionStatus({ state, compact = false }: {diff --git a/webui/src/components/remote/HostSwitcher.tsx b/webui/src/components/remote/HostSwitcher.tsxindex 940526549..eb8efda94 100644--- a/webui/src/components/remote/HostSwitcher.tsx+++ b/webui/src/components/remote/HostSwitcher.tsx@@ -9,7 +9,8 @@ import { useClient } from "@/providers/ClientProvider";import { cn } from "@/lib/utils";import type { ConnectionStatus } from "@/lib/types";import type { HostAnchor, EmbeddedHost } from "./host-bridge";-import { HostConnectionStatus, type HostConnectionState } from "./HostConnectionStatus";+import { HostConnectionStatus } from "./HostConnectionStatus";+import type { HostConnectionState } from "./remote-context";export interface HostPicker {kind: "shell";diff --git a/webui/src/components/remote/PairRouteSettings.tsx b/webui/src/components/remote/PairRouteSettings.tsxindex 9c8fea706..3dc67e3ae 100644--- a/webui/src/components/remote/PairRouteSettings.tsx+++ b/webui/src/components/remote/PairRouteSettings.tsx@@ -5,7 +5,7 @@ import { Button } from "@/components/ui/button";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { useClient } from "@/providers/ClientProvider";import { remoteAction } from "@/lib/remote-instances";-import { useRemoteConnections } from "./RemoteInstances";+import { useRemoteConnections } from "./remote-context";/** An explicit escape hatch for a VPN/bound-interface route, not a new SSH form. */export function PairRouteSettings({ id, onSaved, showHint = true }: { id: string; onSaved?: () => void; showHint?: boolean }) {diff --git a/webui/src/components/remote/QuickPairSetup.tsx b/webui/src/components/remote/QuickPairSetup.tsxindex 33424a225..a012e88bc 100644--- a/webui/src/components/remote/QuickPairSetup.tsx+++ b/webui/src/components/remote/QuickPairSetup.tsx@@ -12,7 +12,7 @@ import { CodeBlock } from "@/components/CodeBlock";import { remoteAction } from "@/lib/remote-instances";import { pairingReturnOrigin, type PairReturn } from "@/lib/remote-pair-return";import type { ConnectionStatus } from "@/lib/types";-import { useRemoteConnections } from "./RemoteInstances";+import { useRemoteConnections } from "./remote-context";import { PairRouteSettings } from "./PairRouteSettings";import "./remote-layout.css";diff --git a/webui/src/components/remote/RemoteConnectionsPage.tsx b/webui/src/components/remote/RemoteConnectionsPage.tsxindex 71eba1dd3..932c40a1a 100644--- a/webui/src/components/remote/RemoteConnectionsPage.tsx+++ b/webui/src/components/remote/RemoteConnectionsPage.tsx@@ -13,7 +13,7 @@ import { groupRemoteProfiles, isCompatibilityError, remoteAction, type RemoteInsimport { cn } from "@/lib/utils";import { parseSSHAddress } from "@/lib/ssh-address";import { clearPairReturn, readPairReturn, subscribePairReturn } from "@/lib/remote-pair-return";-import { useRemoteConnections } from "./RemoteInstances";+import { useRemoteConnections } from "./remote-context";import { SSHHostPicker } from "./SSHHostPicker";import { QuickPairSetup } from "./QuickPairSetup";import { PairRouteSettings } from "./PairRouteSettings";diff --git a/webui/src/components/remote/RemoteInstances.tsx b/webui/src/components/remote/RemoteInstances.tsxindex 74e64625b..bb12a0147 100644--- a/webui/src/components/remote/RemoteInstances.tsx+++ b/webui/src/components/remote/RemoteInstances.tsx@@ -1,39 +1,16 @@-import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type ReactNode } from "react";+import { useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type ReactNode } from "react";import { Loader2, PlugZap } from "lucide-react";import { useTranslation } from "react-i18next";import { Button } from "@/components/ui/button";-import { groupRemoteProfiles, isCompatibilityError, needsRemoteSetup, type RemoteDirectory } from "@/lib/remote-instances";+import { groupRemoteProfiles, isCompatibilityError, needsRemoteSetup } from "@/lib/remote-instances";import { HostCompatibilityDialog } from "./HostCompatibilityDialog";import { RemoteConnectionsPage } from "./RemoteConnectionsPage";-import type { HostAnchor } from "./host-bridge";import { ThemeProvider } from "@/hooks/useTheme";import { useHostSessions } from "./useHostSessions";import { HostNavigationContext, HostSwitcher, RemoteHostMenu, type HostPicker } from "./HostSwitcher";import { useSidebarHostBridge } from "./useSidebarHostBridge";import { readPairReturn, subscribePairReturn } from "@/lib/remote-pair-return";-import type { HostConnectionState } from "./HostConnectionStatus";--const RemoteContext = createContext<{- available: boolean;- localActive: boolean;- activeHostId: string | null;- hostStates: Record<string, HostConnectionState>;- managing: boolean;- embeddedManagement?: boolean;- reportManagementSurface?: (rect: HostAnchor, theme: "light" | "dark") => void;- closeManagement: () => void;- selectLocal: () => void;- openHostIds: string[];- directory: RemoteDirectory | null;- directoryError: boolean;- refresh: () => Promise<RemoteDirectory>;- rename: (id: string, name: string) => Promise<void>;- connect: (id: string, stillWanted?: () => boolean) => Promise<void>;- disconnect: (id: string) => Promise<void>;- remove: (id: string) => Promise<void>;- cancel: () => void;-} | null>(null);-export function useRemoteConnections() { return useContext(RemoteContext); }+import { RemoteContext, type HostConnectionState } from "./remote-context";/** Keep host views alive; navigation belongs in each view's sidebar, not a second header. */export function RemoteInstances({ children }: { children: ReactNode }) {diff --git a/webui/src/components/remote/remote-context.ts b/webui/src/components/remote/remote-context.tsnew file mode 100644index 000000000..93ed511cf--- /dev/null+++ b/webui/src/components/remote/remote-context.ts@@ -0,0 +1,28 @@+import { createContext, useContext } from "react";++import type { RemoteDirectory } from "@/lib/remote-instances";+import type { HostAnchor } from "./host-bridge";++export type HostConnectionState = "open" | "closed" | "connecting" | "error";++export const RemoteContext = createContext<{+ available: boolean;+ localActive: boolean;+ activeHostId: string | null;+ hostStates: Record<string, HostConnectionState>;+ managing: boolean;+ embeddedManagement?: boolean;+ reportManagementSurface?: (rect: HostAnchor, theme: "light" | "dark") => void;+ closeManagement: () => void;+ selectLocal: () => void;+ openHostIds: string[];+ directory: RemoteDirectory | null;+ directoryError: boolean;+ refresh: () => Promise<RemoteDirectory>;+ rename: (id: string, name: string) => Promise<void>;+ connect: (id: string, stillWanted?: () => boolean) => Promise<void>;+ disconnect: (id: string) => Promise<void>;+ remove: (id: string) => Promise<void>;+ cancel: () => void;+} | null>(null);+export function useRemoteConnections() { return useContext(RemoteContext); }diff --git a/webui/src/components/settings/channels/ChannelCredentialFields.tsx b/webui/src/components/settings/channels/ChannelCredentialFields.tsxindex 89e5e2b28..7c540e4b3 100644--- a/webui/src/components/settings/channels/ChannelCredentialFields.tsx+++ b/webui/src/components/settings/channels/ChannelCredentialFields.tsx@@ -4,7 +4,7 @@ import type {ChannelConfigField,ChannelFieldSection,ChannelSetupRequirement,-} from "@/components/settings/channels/catalog";+} from "@/channel-plugins/catalog";import {CredentialForm,channelFieldInputId,diff --git a/webui/src/components/settings/channels/ChannelHelpMenu.tsx b/webui/src/components/settings/channels/ChannelHelpMenu.tsxindex a08f567c9..8f0eb57b4 100644--- a/webui/src/components/settings/channels/ChannelHelpMenu.tsx+++ b/webui/src/components/settings/channels/ChannelHelpMenu.tsx@@ -2,7 +2,7 @@ import { channelUiContribution } from "@/channel-plugins/registry";import { CircleHelp, ExternalLink } from "lucide-react";import { useTranslation } from "react-i18next";import { channelSetup } from "@/components/settings/channels/ChannelIdentity";-import { docsUrlWithBase } from "@/components/settings/channels/catalog";+import { docsUrlWithBase } from "@/channel-plugins/catalog";import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu";import { Tooltip, TooltipProvider, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";import type { NanobotFeatureInfo } from "@/lib/types";diff --git a/webui/src/components/settings/channels/ChannelIdentity.tsx b/webui/src/components/settings/channels/ChannelIdentity.tsxindex f578b228c..71686412e 100644--- a/webui/src/components/settings/channels/ChannelIdentity.tsx+++ b/webui/src/components/settings/channels/ChannelIdentity.tsx@@ -15,7 +15,7 @@ import type {ChannelConfigField,ChannelFieldPresentation,ChannelSetupPresentation,-} from "@/components/settings/channels/catalog";+} from "@/channel-plugins/catalog";import { channelValidationMessage } from "@/components/settings/channels/validationMessages";import { useLogoFallback } from "@/hooks/useLogoFallback";import { normalizeLocale } from "@/i18n/config";diff --git a/webui/src/components/settings/channels/ChannelInstancesPanel.tsx b/webui/src/components/settings/channels/ChannelInstancesPanel.tsxindex 186eda421..23d4d3e31 100644--- a/webui/src/components/settings/channels/ChannelInstancesPanel.tsx+++ b/webui/src/components/settings/channels/ChannelInstancesPanel.tsx@@ -4,7 +4,7 @@ import { useTranslation } from "react-i18next";import { channelUiPresentation } from "@/channel-plugins/registry";import { ToggleButton } from "@/components/settings/ToggleButton";-import type { ChannelConfigField } from "@/components/settings/channels/catalog";+import type { ChannelConfigField } from "@/channel-plugins/catalog";import {CredentialForm,channelValuesForSave,diff --git a/webui/src/components/settings/channels/ChannelSetupPanel.tsx b/webui/src/components/settings/channels/ChannelSetupPanel.tsxindex 7577b04b9..2e119855f 100644--- a/webui/src/components/settings/channels/ChannelSetupPanel.tsx+++ b/webui/src/components/settings/channels/ChannelSetupPanel.tsx@@ -29,7 +29,7 @@ import { useAutoSave } from "@/components/settings/shared/useAutoSave";import {type ChannelProviderPreset,type ChannelSetupPresentation,-} from "@/components/settings/channels/catalog";+} from "@/channel-plugins/catalog";import {ChannelFieldGroups,channelRequirementErrors,diff --git a/webui/src/components/settings/channels/ChannelSetupParts.tsx b/webui/src/components/settings/channels/ChannelSetupParts.tsxindex 09123f46b..d6bfb6e5b 100644--- a/webui/src/components/settings/channels/ChannelSetupParts.tsx+++ b/webui/src/components/settings/channels/ChannelSetupParts.tsx@@ -6,7 +6,7 @@ import { Button } from "@/components/ui/button";import {type ChannelProviderPreset,type ChannelSetupPresentation,-} from "@/components/settings/channels/catalog";+} from "@/channel-plugins/catalog";import { copyTextToClipboard } from "@/lib/clipboard";import type { NanobotFeatureInfo } from "@/lib/types";diff --git a/webui/src/components/settings/channels/CredentialForm.tsx b/webui/src/components/settings/channels/CredentialForm.tsxindex 7ccdbd8e4..d771705e8 100644--- a/webui/src/components/settings/channels/CredentialForm.tsx+++ b/webui/src/components/settings/channels/CredentialForm.tsx@@ -3,7 +3,7 @@ import { useTranslation } from "react-i18next";import { Input } from "@/components/ui/input";import { Textarea } from "@/components/ui/textarea";-import type { ChannelConfigField } from "@/components/settings/channels/catalog";+import type { ChannelConfigField } from "@/channel-plugins/catalog";import { cn } from "@/lib/utils";function channelFieldValue(field: ChannelConfigField, values: Record<string, string>): string {diff --git a/webui/src/components/settings/system/AutomationsSettings.tsx b/webui/src/components/settings/system/AutomationsSettings.tsxindex daf94c9f1..c2c313270 100644--- a/webui/src/components/settings/system/AutomationsSettings.tsx+++ b/webui/src/components/settings/system/AutomationsSettings.tsx@@ -41,7 +41,7 @@ import { SegmentedControl } from "@/components/ui/segmented-control";import { Textarea } from "@/components/ui/textarea";import { displayTitle } from "@/lib/chat-groups";import { copyTextToClipboard } from "@/lib/clipboard";-import { fmtDateTime, relativeTime } from "@/lib/format";+import { fmtDateTime, relativeTime } from "@/lib/format-time";import type { SendAttachment, SendOptions } from "@/hooks/useNanobotStream";import type {AutomationsPayload,diff --git a/webui/src/components/thread/ComposerUsagePopover.tsx b/webui/src/components/thread/ComposerUsagePopover.tsxindex d5a34229e..6b65b8510 100644--- a/webui/src/components/thread/ComposerUsagePopover.tsx+++ b/webui/src/components/thread/ComposerUsagePopover.tsx@@ -14,7 +14,8 @@ import {TooltipProvider,TooltipTrigger,} from "@/components/ui/tooltip";-import { formatCompactTokenCount, formatTurnLatency } from "@/lib/format";+import { formatCompactTokenCount } from "@/lib/format";+import { formatTurnLatency } from "@/lib/format-time";import { cn } from "@/lib/utils";export interface ComposerContextUsage {diff --git a/webui/src/components/thread/PromptNavigator.tsx b/webui/src/components/thread/PromptNavigator.tsxindex 653cc1f6b..7209ed777 100644--- a/webui/src/components/thread/PromptNavigator.tsx+++ b/webui/src/components/thread/PromptNavigator.tsx@@ -16,7 +16,7 @@ import {type PromptAnchor,userPromptAnchors,} from "@/components/thread/promptNavigation";-import { fmtDateTime } from "@/lib/format";+import { fmtDateTime } from "@/lib/format-time";import type { UIMessage } from "@/lib/types";import { cn } from "@/lib/utils";diff --git a/webui/src/components/thread/SessionInfoPopover.tsx b/webui/src/components/thread/SessionInfoPopover.tsxindex aa3f969dd..bd57df81c 100644--- a/webui/src/components/thread/SessionInfoPopover.tsx+++ b/webui/src/components/thread/SessionInfoPopover.tsx@@ -25,7 +25,7 @@ import { useSessionAutomationJobs } from "@/hooks/useSessionAutomationJobs";import { currentLocale } from "@/i18n";import { runAutomationAction, updateAutomation } from "@/lib/api";import type { WebUIMutationTransport } from "@/lib/api";-import { fmtDateTime } from "@/lib/format";+import { fmtDateTime } from "@/lib/format-time";import type {AutomationUpdatePayload,SessionAutomationJob,diff --git a/webui/src/components/thread/ThreadComposer.tsx b/webui/src/components/thread/ThreadComposer.tsxindex 34a9b8e73..5b8c881c5 100644--- a/webui/src/components/thread/ThreadComposer.tsx+++ b/webui/src/components/thread/ThreadComposer.tsx@@ -43,8 +43,8 @@ import {cliAppInitials,mcpPresetInitials,splitCapabilityMentionSegments,- type CapabilityMentionSegment,} from "@/components/CliAppMentionText";+import type { CapabilityMentionSegment } from "@/lib/composer-mention-text";import { INLINE_TOKEN_HIGHLIGHT_COLOR } from "@/components/InlineTokenHighlight";import {ArrowUp,diff --git a/webui/src/components/thread/ThreadMessages.tsx b/webui/src/components/thread/ThreadMessages.tsxindex 42a0c9493..106cd6195 100644--- a/webui/src/components/thread/ThreadMessages.tsx+++ b/webui/src/components/thread/ThreadMessages.tsx@@ -15,7 +15,7 @@ import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";import { useMediaQuery } from "@/hooks/useMediaQuery";import { useLocalPreferences } from "@/hooks/useLocalPreferences";-import { fmtDateTime, formatMessageHoverTime } from "@/lib/format";+import { fmtDateTime, formatMessageHoverTime } from "@/lib/format-time";import { projectActivityTimeline, type TurnUnit } from "@/lib/activity-timeline";import { cn } from "@/lib/utils";import type { CliAppInfo, McpPresetInfo, RetryStatus, SlashCommand, UIMessage } from "@/lib/types";diff --git a/webui/src/components/thread/activity/ActivityStep.tsx b/webui/src/components/thread/activity/ActivityStep.tsxindex 4c0e3ad67..6db1d23a2 100644--- a/webui/src/components/thread/activity/ActivityStep.tsx+++ b/webui/src/components/thread/activity/ActivityStep.tsx@@ -1,7 +1,7 @@import { useRef, useState, type CSSProperties, type ReactNode } from "react";import type { LucideIcon } from "lucide-react";-import { StreamingLabelSheen } from "@/components/MessageBubble";+import { StreamingLabelSheen } from "@/components/ui/streaming-label-sheen";import { formControlFocusClassName } from "@/components/ui/form-control";import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";import { cn } from "@/lib/utils";diff --git a/webui/src/components/ui/streaming-label-sheen.tsx b/webui/src/components/ui/streaming-label-sheen.tsxnew file mode 100644index 000000000..cc08e561a--- /dev/null+++ b/webui/src/components/ui/streaming-label-sheen.tsx@@ -0,0 +1,32 @@+import type { ReactNode } from "react";++import { cn } from "@/lib/utils";++/** L→R sheen on the glyphs themselves; inactive labels stay solid muted text. */+export function StreamingLabelSheen({+ children,+ active,+ className,+}: {+ children: ReactNode;+ active: boolean;+ className?: string;+}) {+ const sheenText =+ typeof children === "string" || typeof children === "number"+ ? String(children)+ : undefined;+ return (+ <span className={cn("block min-w-0 overflow-hidden py-px", className)}>+ <span+ data-sheen-text={active ? sheenText : undefined}+ className={cn(+ "block w-fit max-w-full truncate pr-0.5 font-medium leading-normal",+ active ? "streaming-text-sheen after:pr-0.5" : "text-muted-foreground",+ )}+ >+ {children}+ </span>+ </span>+ );+}diff --git a/webui/src/hooks/useComposerMentionInput.ts b/webui/src/hooks/useComposerMentionInput.tsindex 0f09c496c..26b52cacd 100644--- a/webui/src/hooks/useComposerMentionInput.ts+++ b/webui/src/hooks/useComposerMentionInput.ts@@ -1,8 +1,7 @@import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import type { ChangeEvent, ClipboardEvent, KeyboardEvent, RefObject } from "react";-import type { CapabilityMentionSegment } from "@/components/CliAppMentionText";-import { composerCompositionSegments, composerMentionText, editComposerMentionText, mentionTextOffset } from "@/lib/composer-mention-text";+import { composerCompositionSegments, composerMentionText, editComposerMentionText, mentionTextOffset, type CapabilityMentionSegment } from "@/lib/composer-mention-text";type Snapshot = { value: string; start: number; end: number };const HISTORY_LIMIT = 100;diff --git a/webui/src/lib/composer-mention-text.ts b/webui/src/lib/composer-mention-text.tsindex d298e2f64..7802ef190 100644--- a/webui/src/lib/composer-mention-text.ts+++ b/webui/src/lib/composer-mention-text.ts@@ -1,4 +1,10 @@-import type { CapabilityMentionSegment } from "@/components/CliAppMentionText";+import type { CliAppInfo, McpPresetInfo, SessionMention } from "@/lib/types";++export type CapabilityMentionSegment =+ | { kind: "text"; text: string }+ | { kind: "cli"; text: string; app: CliAppInfo }+ | { kind: "mcp"; text: string; preset: McpPresetInfo }+ | { kind: "session"; text: string; mention: SessionMention };export function composerMentionLabel(segment: CapabilityMentionSegment): string {const app = segment.kind === "cli" ? segment.app : segment.kind === "mcp" ? segment.preset : null;diff --git a/webui/src/lib/format-time.ts b/webui/src/lib/format-time.tsnew file mode 100644index 000000000..bd1fd4e9c--- /dev/null+++ b/webui/src/lib/format-time.ts@@ -0,0 +1,159 @@+import i18n from "i18next";++import { normalizeLocale } from "@/i18n/config";++/** Loose ISO-or-epoch parser; returns ``null`` for missing/invalid input. */+function parseDate(value: string | number | null | undefined): Date | null {+ if (value === null || value === undefined || value === "") return null;+ const d = new Date(value);+ return Number.isNaN(d.getTime()) ? null : d;+}++const RELATIVE_THRESHOLDS: [number, Intl.RelativeTimeFormatUnit][] = [+ [60, "second"],+ [60, "minute"],+ [24, "hour"],+ [7, "day"],+ [4.345, "week"],+ [12, "month"],+ [Number.POSITIVE_INFINITY, "year"],+];++const relativeTimeFormatters = new Map<string, Intl.RelativeTimeFormat>();+const dateTimeFormatters = new Map<string, Intl.DateTimeFormat>();+const clockTimeFormatters = new Map<string, Intl.DateTimeFormat>();+const hoverTimeFormatters = new Map<string, Intl.DateTimeFormat>();++function activeLocale(locale?: string): string {+ return locale || i18n.resolvedLanguage || i18n.language || normalizeLocale(i18n.resolvedLanguage ?? i18n.language);+}++function relativeTimeFormatter(locale: string): Intl.RelativeTimeFormat {+ const existing = relativeTimeFormatters.get(locale);+ if (existing) return existing;+ const formatter = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });+ relativeTimeFormatters.set(locale, formatter);+ return formatter;+}++function dateTimeFormatter(locale: string): Intl.DateTimeFormat {+ const existing = dateTimeFormatters.get(locale);+ if (existing) return existing;+ const formatter = new Intl.DateTimeFormat(locale, {+ dateStyle: "medium",+ timeStyle: "short",+ });+ dateTimeFormatters.set(locale, formatter);+ return formatter;+}++function clockTimeFormatter(locale: string): Intl.DateTimeFormat {+ const existing = clockTimeFormatters.get(locale);+ if (existing) return existing;+ const formatter = new Intl.DateTimeFormat(locale, {+ hour: "2-digit",+ minute: "2-digit",+ });+ clockTimeFormatters.set(locale, formatter);+ return formatter;+}++function isSameLocalCalendarDay(left: Date, right: Date): boolean {+ return (+ left.getFullYear() === right.getFullYear()+ && left.getMonth() === right.getMonth()+ && left.getDate() === right.getDate()+ );+}++export function relativeTime(+ value: string | number | null | undefined,+ locale?: string,+): string {+ const date = parseDate(value);+ if (!date) return "";+ let delta = (date.getTime() - Date.now()) / 1000;+ const formatter = relativeTimeFormatter(activeLocale(locale));+ for (const [step, unit] of RELATIVE_THRESHOLDS) {+ if (Math.abs(delta) < step) {+ return formatter.format(Math.round(delta), unit);+ }+ delta /= step;+ }+ return formatter.format(Math.round(delta), "year");+}++export function fmtDateTime(+ value: string | number | null | undefined,+ locale?: string,+): string {+ const date = parseDate(value);+ return date ? dateTimeFormatter(activeLocale(locale)).format(date) : "";+}++/**+ * Format a completion timestamp in the browser's local timezone.+ * Today's messages stay compact; older messages include their date for orientation.+ */+export function formatMessageEndTime(+ value: number | null | undefined,+ locale?: string,+): string {+ const date = parseDate(value);+ if (!date) return "";+ const loc = activeLocale(locale);+ return isSameLocalCalendarDay(date, new Date())+ ? clockTimeFormatter(loc).format(date)+ : dateTimeFormatter(loc).format(date);+}++/** One-line gutter label; the full local date/time belongs in its tooltip. */+export function formatMessageHoverTime(+ value: number | null | undefined,+ locale?: string,+ now = new Date(),+): string {+ const date = parseDate(value);+ if (!date) return "";+ const loc = activeLocale(locale);+ const today = isSameLocalCalendarDay(date, now);+ const key = `${loc}:${today ? "clock" : "date"}`;+ let formatter = hoverTimeFormatters.get(key);+ if (!formatter) {+ formatter = new Intl.DateTimeFormat(loc, today+ ? { hour: "2-digit", minute: "2-digit", hourCycle: "h23" }+ : { month: "numeric", day: "numeric" });+ hoverTimeFormatters.set(key, formatter);+ }+ return formatter.format(date);+}++/** Human-readable turn duration (wall-clock), locale-aware via ``Intl`` (seconds/minutes). */+export function formatTurnLatency(ms: number, locale?: string): string {+ const loc = activeLocale(locale);+ const msClamped = Math.max(0, ms);+ const secTotal = msClamped / 1000;+ if (secTotal < 60) {+ return new Intl.NumberFormat(loc, {+ style: "unit",+ unit: "second",+ unitDisplay: "narrow",+ maximumFractionDigits: secTotal < 10 ? 1 : 0,+ minimumFractionDigits: 0,+ }).format(secTotal);+ }+ const wholeMin = Math.floor(secTotal / 60);+ const remSec = Math.max(0, Math.round(secTotal - wholeMin * 60));+ const minStr = new Intl.NumberFormat(loc, {+ style: "unit",+ unit: "minute",+ unitDisplay: "narrow",+ }).format(wholeMin);+ const secStr = new Intl.NumberFormat(loc, {+ style: "unit",+ unit: "second",+ unitDisplay: "narrow",+ maximumFractionDigits: 0,+ }).format(remSec);+ return `${minStr}\u00a0${secStr}`;+}diff --git a/webui/src/lib/format.ts b/webui/src/lib/format.tsindex 29f8e19d0..82d5f83af 100644--- a/webui/src/lib/format.ts+++ b/webui/src/lib/format.ts@@ -1,5 +1,3 @@-import i18n, { currentLocale } from "@/i18n";-/** Compact token counts for dense runtime metadata (for example, 74.9K). */export function formatCompactTokenCount(value: number): string {if (value < 1_000) return Math.round(value).toLocaleString();@@ -62,159 +60,3 @@ export function deriveTitle(preview: string | undefined, fallback: string): striif (isLowInformationTitlePreview(oneLine)) return fallback;return oneLine.length > 60 ? `${oneLine.slice(0, 57)}…` : oneLine;}--/** Loose ISO-or-epoch parser; returns ``null`` for missing/invalid input. */-function parseDate(value: string | number | null | undefined): Date | null {- if (value === null || value === undefined || value === "") return null;- const d = new Date(value);- return Number.isNaN(d.getTime()) ? null : d;-}--const RELATIVE_THRESHOLDS: [number, Intl.RelativeTimeFormatUnit][] = [- [60, "second"],- [60, "minute"],- [24, "hour"],- [7, "day"],- [4.345, "week"],- [12, "month"],- [Number.POSITIVE_INFINITY, "year"],-];--const relativeTimeFormatters = new Map<string, Intl.RelativeTimeFormat>();-const dateTimeFormatters = new Map<string, Intl.DateTimeFormat>();-const clockTimeFormatters = new Map<string, Intl.DateTimeFormat>();-const hoverTimeFormatters = new Map<string, Intl.DateTimeFormat>();--function activeLocale(locale?: string): string {- return locale || i18n.resolvedLanguage || i18n.language || currentLocale();-}--function relativeTimeFormatter(locale: string): Intl.RelativeTimeFormat {- const existing = relativeTimeFormatters.get(locale);- if (existing) return existing;- const formatter = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });- relativeTimeFormatters.set(locale, formatter);- return formatter;-}--function dateTimeFormatter(locale: string): Intl.DateTimeFormat {- const existing = dateTimeFormatters.get(locale);- if (existing) return existing;- const formatter = new Intl.DateTimeFormat(locale, {- dateStyle: "medium",- timeStyle: "short",- });- dateTimeFormatters.set(locale, formatter);- return formatter;-}--function clockTimeFormatter(locale: string): Intl.DateTimeFormat {- const existing = clockTimeFormatters.get(locale);- if (existing) return existing;- const formatter = new Intl.DateTimeFormat(locale, {- hour: "2-digit",- minute: "2-digit",- });- clockTimeFormatters.set(locale, formatter);- return formatter;-}--function isSameLocalCalendarDay(left: Date, right: Date): boolean {- return (- left.getFullYear() === right.getFullYear()- && left.getMonth() === right.getMonth()- && left.getDate() === right.getDate()- );-}--export function relativeTime(- value: string | number | null | undefined,- locale?: string,-): string {- const date = parseDate(value);- if (!date) return "";- let delta = (date.getTime() - Date.now()) / 1000;- const formatter = relativeTimeFormatter(activeLocale(locale));- for (const [step, unit] of RELATIVE_THRESHOLDS) {- if (Math.abs(delta) < step) {- return formatter.format(Math.round(delta), unit);- }- delta /= step;- }- return formatter.format(Math.round(delta), "year");-}--export function fmtDateTime(- value: string | number | null | undefined,- locale?: string,-): string {- const date = parseDate(value);- return date ? dateTimeFormatter(activeLocale(locale)).format(date) : "";-}--/**- * Format a completion timestamp in the browser's local timezone.- * Today's messages stay compact; older messages include their date for orientation.- */-export function formatMessageEndTime(- value: number | null | undefined,- locale?: string,-): string {- const date = parseDate(value);- if (!date) return "";- const loc = activeLocale(locale);- return isSameLocalCalendarDay(date, new Date())- ? clockTimeFormatter(loc).format(date)- : dateTimeFormatter(loc).format(date);-}--/** One-line gutter label; the full local date/time belongs in its tooltip. */-export function formatMessageHoverTime(- value: number | null | undefined,- locale?: string,- now = new Date(),-): string {- const date = parseDate(value);- if (!date) return "";- const loc = activeLocale(locale);- const today = isSameLocalCalendarDay(date, now);- const key = `${loc}:${today ? "clock" : "date"}`;- let formatter = hoverTimeFormatters.get(key);- if (!formatter) {- formatter = new Intl.DateTimeFormat(loc, today- ? { hour: "2-digit", minute: "2-digit", hourCycle: "h23" }- : { month: "numeric", day: "numeric" });- hoverTimeFormatters.set(key, formatter);- }- return formatter.format(date);-}--/** Human-readable turn duration (wall-clock), locale-aware via ``Intl`` (seconds/minutes). */-export function formatTurnLatency(ms: number, locale?: string): string {- const loc = activeLocale(locale);- const msClamped = Math.max(0, ms);- const secTotal = msClamped / 1000;- if (secTotal < 60) {- return new Intl.NumberFormat(loc, {- style: "unit",- unit: "second",- unitDisplay: "narrow",- maximumFractionDigits: secTotal < 10 ? 1 : 0,- minimumFractionDigits: 0,- }).format(secTotal);- }- const wholeMin = Math.floor(secTotal / 60);- const remSec = Math.max(0, Math.round(secTotal - wholeMin * 60));- const minStr = new Intl.NumberFormat(loc, {- style: "unit",- unit: "minute",- unitDisplay: "narrow",- }).format(wholeMin);- const secStr = new Intl.NumberFormat(loc, {- style: "unit",- unit: "second",- unitDisplay: "narrow",- maximumFractionDigits: 0,- }).format(remSec);- return `${minStr}\u00a0${secStr}`;-}diff --git a/webui/src/tests/channel-credential-form.test.tsx b/webui/src/tests/channel-credential-form.test.tsxindex 0cd330001..b6b54132d 100644--- a/webui/src/tests/channel-credential-form.test.tsx+++ b/webui/src/tests/channel-credential-form.test.tsx@@ -7,7 +7,7 @@ import {defaultChannelFieldValues,} from "@/components/settings/channels/CredentialForm";import { channelSetup } from "@/components/settings/channels/ChannelIdentity";-import type { ChannelConfigField } from "@/components/settings/channels/catalog";+import type { ChannelConfigField } from "@/channel-plugins/catalog";const fields: ChannelConfigField[] = [{diff --git a/webui/src/tests/format.i18n.test.ts b/webui/src/tests/format.i18n.test.tsindex 9b09078ba..6ae532146 100644--- a/webui/src/tests/format.i18n.test.ts+++ b/webui/src/tests/format.i18n.test.ts@@ -7,7 +7,7 @@ import {formatMessageHoverTime,formatTurnLatency,relativeTime,-} from "@/lib/format";+} from "@/lib/format-time";describe("localized format helpers", () => {beforeEach(() => {diff --git a/webui/src/tests/linear-reset-connection.test.tsx b/webui/src/tests/linear-reset-connection.test.tsxindex 3c0d1558d..a2eeb6b48 100644--- a/webui/src/tests/linear-reset-connection.test.tsx+++ b/webui/src/tests/linear-reset-connection.test.tsx@@ -2,7 +2,7 @@ import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-liimport { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { LinearResetConnection } from "../../../nanobot/channels/linear/webui/LinearResetConnection";-import type { ChannelConfigField } from "@/components/settings/channels/catalog";+import type { ChannelConfigField } from "@/channel-plugins/catalog";const { requestMutation } = vi.hoisted(() => ({ requestMutation: vi.fn() }));vi.mock("@/providers/ClientProvider", () => ({diff --git a/webui/src/tests/message-bubble.test.tsx b/webui/src/tests/message-bubble.test.tsxindex b1790b22a..97071b9d3 100644--- a/webui/src/tests/message-bubble.test.tsx+++ b/webui/src/tests/message-bubble.test.tsx@@ -5,7 +5,7 @@ import { MessageBlockMenuActions, MessageBubble } from "@/components/MessageBubbimport { ThreadMessages } from "@/components/thread/ThreadMessages";import { setAppLanguage } from "@/i18n";import * as clipboard from "@/lib/clipboard";-import { formatMessageEndTime } from "@/lib/format";+import { formatMessageEndTime } from "@/lib/format-time";import type {CliAppInfo,McpPresetInfo,diff --git a/webui/src/tests/message-hover-time.test.tsx b/webui/src/tests/message-hover-time.test.tsxindex 8d4db53b3..8ac242103 100644--- a/webui/src/tests/message-hover-time.test.tsx+++ b/webui/src/tests/message-hover-time.test.tsx@@ -1,7 +1,7 @@import { cleanup, fireEvent, render, screen } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";import { ThreadMessages } from "@/components/thread/ThreadMessages";-import { fmtDateTime } from "@/lib/format";+import { fmtDateTime } from "@/lib/format-time";vi.mock("@/components/MarkdownText", () => ({ MarkdownText: ({ content }: { content: string }) => <p>{content}</p> }));afterEach(() => { cleanup(); vi.useRealTimers(); });diff --git a/webui/src/tests/pair-route.test.tsx b/webui/src/tests/pair-route.test.tsxindex 40147a499..5c9921c5d 100644--- a/webui/src/tests/pair-route.test.tsx+++ b/webui/src/tests/pair-route.test.tsx@@ -6,7 +6,7 @@ import i18n from "@/i18n";const mocks = vi.hoisted(() => ({ action: vi.fn(), refresh: vi.fn(), config: "" }));vi.mock("@/providers/ClientProvider", () => ({ useClient: () => ({ client: { requestMutation: mocks.action } }) }));-vi.mock("@/components/remote/RemoteInstances", () => ({ useRemoteConnections: () => ({ refresh: mocks.refresh, directory: { profiles: [{ id: "paired", paired: true, ssh_config: mocks.config }, { id: "ssh", name: "Team SSH", paired: false }] } }) }));+vi.mock("@/components/remote/remote-context", () => ({ useRemoteConnections: () => ({ refresh: mocks.refresh, directory: { profiles: [{ id: "paired", paired: true, ssh_config: mocks.config }, { id: "ssh", name: "Team SSH", paired: false }] } }) }));beforeEach(async () => { await i18n.changeLanguage("en"); mocks.action.mockReset().mockResolvedValue({}); mocks.refresh.mockReset().mockResolvedValue(undefined); mocks.config = ""; });afterEach(cleanup);diff --git a/webui/src/tests/quick-pair.test.tsx b/webui/src/tests/quick-pair.test.tsxindex 6d99ee117..6755bd885 100644--- a/webui/src/tests/quick-pair.test.tsx+++ b/webui/src/tests/quick-pair.test.tsx@@ -21,7 +21,7 @@ const mocks = vi.hoisted(() => {return { action, client, listeners, transportClient: null as NanobotClient | null, connect: vi.fn(), refresh: vi.fn(), cancel: vi.fn(), copy: vi.fn() };});vi.mock("@/providers/ClientProvider", () => ({ useClient: () => ({ client: mocks.transportClient ?? mocks.client }) }));-vi.mock("@/components/remote/RemoteInstances", () => ({ useRemoteConnections: () => ({ connect: mocks.connect, refresh: mocks.refresh, cancel: mocks.cancel, directory: { profiles: [] } }) }));+vi.mock("@/components/remote/remote-context", () => ({ useRemoteConnections: () => ({ connect: mocks.connect, refresh: mocks.refresh, cancel: mocks.cancel, directory: { profiles: [] } }) }));vi.mock("@/lib/clipboard", () => ({ copyTextToClipboard: mocks.copy }));const request = () => ({ id: "request-1", command: "nanobot remote pair nbpr1.public", expires: Date.now() / 1000 + 600 });const preview = { id: "request-1", host: "ubuntu@server", hostname: "team", fingerprint: "SHA256:trusted-server", authorized_until: Date.now() / 1000 + 86400, revoke_command: "nanobot remote revoke request-1" };diff --git a/webui/src/tests/remote-instances.test.tsx b/webui/src/tests/remote-instances.test.tsxindex f25fa1c39..03c76ead4 100644--- a/webui/src/tests/remote-instances.test.tsx+++ b/webui/src/tests/remote-instances.test.tsx@@ -1,7 +1,8 @@import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";import { useEffect, useState } from "react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { RemoteInstances, useRemoteConnections } from "@/components/remote/RemoteInstances";+import { RemoteInstances } from "@/components/remote/RemoteInstances";+import { useRemoteConnections } from "@/components/remote/remote-context";import { RemoteConnectionsPage } from "@/components/remote/RemoteConnectionsPage";import { Sidebar } from "@/components/Sidebar";import { HOST_BRIDGE } from "@/components/remote/host-bridge";