refactor: isolate runtime contracts and enforce import boundaries (#6166)
* test: enforce Python import ownership boundaries * test: protect client import boundaries and rehome shared UI contracts * refactor: remove gateway and client dependency inversions * fix: detect dynamic imports in conditional expressions * refactor(tools): keep configuration contracts with their owners * docs: keep design guidance focused on ownership and checks * fix: preserve default threaded turn delivery
This commit is contained in:
1 parent
cd2a863710
commit
328e933d36
162 files changed
+3449
-1888
No files matched your search
+13
-1
@@ -8,6 +8,18 @@ New capabilities should be added via `channels/`, `tools/`, skills, or MCP serve
|
||||
|
||||
Runtime 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 abstraction
|
||||
|
||||
Channels 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.
|
||||
@@ -104,6 +104,10 @@ jobs:
|
||||
python_required=true
|
||||
docker_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 uv
|
||||
uses: astral-sh/setup-uv@v4
|
||||
with:
|
||||
@@ -195,7 +203,7 @@ jobs:
|
||||
# later uv run sync pruning the packages installed by the previous step.
|
||||
- name: Lint with ruff
|
||||
if: 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: webui
|
||||
run: 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 WebUI
|
||||
working-directory: webui
|
||||
run: bun run lint
|
||||
@@ -331,6 +347,14 @@ jobs:
|
||||
working-directory: tui
|
||||
run: 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 TUI
|
||||
working-directory: tui
|
||||
run: bun run check
|
||||
|
||||
+1
-1
@@ -63,7 +63,7 @@ def _isolate_sessions_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> I
|
||||
def _isolate_llm_usage_stores(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
|
||||
) -> Iterator[None]:
|
||||
from nanobot import llm_usage
|
||||
import nanobot.llm_usage.service as llm_usage
|
||||
|
||||
stores: dict[Path, llm_usage.LLMUsageStore] = {}
|
||||
monkeypatch.setattr(llm_usage, "_STORES", stores)
|
||||
|
||||
+1
-1
@@ -57,7 +57,7 @@ __logo__ = "🐈"
|
||||
|
||||
_LAZY_EXPORTS = {
|
||||
"Nanobot": ".nanobot",
|
||||
"LLMUsage": ".nanobot",
|
||||
"LLMUsage": ".llm_usage.types",
|
||||
"RunStream": ".nanobot",
|
||||
"RunResult": ".nanobot",
|
||||
"RequestContext": ".agent.tools.context",
|
||||
|
||||
+48
-13
@@ -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",
|
||||
|
||||
@@ -500,7 +500,7 @@ class MemoryStore:
|
||||
|
||||
@staticmethod
|
||||
def default_dream_prompt() -> str:
|
||||
from nanobot.agent.skills import BUILTIN_SKILLS_DIR
|
||||
from nanobot.agent.skill_metadata import BUILTIN_SKILLS_DIR
|
||||
|
||||
return 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_DIR
|
||||
from nanobot.agent.tools.apply_patch import ApplyPatchTool
|
||||
from nanobot.agent.tools.file_state import FileStates
|
||||
from nanobot.agent.tools.filesystem import EditFileTool, ReadFileTool, WriteFileTool
|
||||
|
||||
@@ -13,7 +13,7 @@ from typing import cast
|
||||
from loguru import logger
|
||||
from 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_metadata
|
||||
from nanobot.config.loader import get_config_path
|
||||
from nanobot.config.schema import MCPServerConfig
|
||||
|
||||
|
||||
@@ -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
|
||||
)
|
||||
+12
-36
@@ -7,47 +7,23 @@ import shutil
|
||||
from pathlib import Path
|
||||
from 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.
|
||||
|
||||
@@ -1,18 +1,56 @@
|
||||
"""Agent tools module."""
|
||||
"""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))
|
||||
|
||||
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,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"Schema",
|
||||
|
||||
@@ -6,9 +6,8 @@ from __future__ import annotations
|
||||
|
||||
from 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 CliAppsToolConfig
|
||||
from nanobot.agent.tools.context import RequestContext, ToolContext
|
||||
from nanobot.agent.tools.schema import (
|
||||
ArraySchema,
|
||||
@@ -19,20 +18,10 @@ from nanobot.agent.tools.schema import (
|
||||
)
|
||||
from nanobot.apps.cli import CliAppError, CliAppManager, CliAppsRuntimeConfig
|
||||
from nanobot.apps.cli.utils import runtime_lines_for_request
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.runtime_context import RuntimeContextBlock, wrap_runtime_context_lines
|
||||
from 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"],
|
||||
|
||||
@@ -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)
|
||||
@@ -26,6 +26,7 @@ from nanobot.agent.tools.schema import (
|
||||
StringSchema,
|
||||
tool_parameters_schema,
|
||||
)
|
||||
from nanobot.agent.tools.shell_config import ExecToolConfig
|
||||
|
||||
DEFAULT_YIELD_MS = 1000
|
||||
MAX_YIELD_MS = 30_000
|
||||
@@ -583,8 +584,6 @@ class ExecSessionTool(Tool):
|
||||
|
||||
@classmethod
|
||||
def config_cls(cls):
|
||||
from nanobot.agent.tools.shell import ExecToolConfig
|
||||
|
||||
return ExecToolConfig
|
||||
|
||||
@classmethod
|
||||
@@ -744,8 +743,6 @@ class ListExecSessionsTool(Tool):
|
||||
|
||||
@classmethod
|
||||
def config_cls(cls):
|
||||
from nanobot.agent.tools.shell import ExecToolConfig
|
||||
|
||||
return ExecToolConfig
|
||||
|
||||
@classmethod
|
||||
|
||||
@@ -12,6 +12,7 @@ from typing import Any
|
||||
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
|
||||
from nanobot.agent.tools.context import ToolContext
|
||||
from nanobot.agent.tools.file_state import FileStates, current_file_states
|
||||
from nanobot.agent.tools.filesystem_config import FileToolsConfig
|
||||
from nanobot.agent.tools.path_utils import resolve_workspace_path
|
||||
from 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 Base
|
||||
from nanobot.security.workspace_access import current_tool_workspace
|
||||
from nanobot.utils.file_edit_events import FileDiff, FileEditResult, display_file_edit_path
|
||||
from 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):
|
||||
|
||||
@classmethod
|
||||
def create(cls, ctx: ToolContext) -> Tool:
|
||||
from nanobot.agent.skills import BUILTIN_SKILLS_DIR
|
||||
from nanobot.agent.skill_metadata import BUILTIN_SKILLS_DIR
|
||||
|
||||
agent_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_DIR
|
||||
|
||||
requested = Path(path)
|
||||
if requested.is_absolute():
|
||||
|
||||
@@ -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 = True
|
||||
@@ -7,9 +7,9 @@ from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from loguru import logger
|
||||
from pydantic import Field
|
||||
|
||||
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
|
||||
from nanobot.agent.tools.image_generation_config import ImageGenerationToolConfig
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from 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 Base
|
||||
from 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(
|
||||
|
||||
@@ -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)
|
||||
@@ -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 MyToolConfig
|
||||
|
||||
if 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 False
|
||||
|
||||
@@ -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 = False
|
||||
@@ -17,7 +17,6 @@ from typing import Any, Protocol, cast
|
||||
from urllib.parse import unquote
|
||||
|
||||
from loguru import logger
|
||||
from pydantic import Field
|
||||
|
||||
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
|
||||
from 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 ExecToolConfig
|
||||
from nanobot.config.paths import get_media_dir
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.security.workspace_access import current_scope_allows_loopback, current_tool_workspace
|
||||
from 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]
|
||||
|
||||
@@ -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)
|
||||
@@ -15,7 +15,6 @@ from urllib.parse import parse_qsl, quote, urljoin, urlparse
|
||||
|
||||
import httpx
|
||||
from loguru import logger
|
||||
from pydantic import Field
|
||||
|
||||
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
|
||||
from 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, WebToolsConfig
|
||||
from 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)
|
||||
|
||||
@@ -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)
|
||||
@@ -19,7 +19,7 @@ from nanobot.bus.outbound_events import (
|
||||
)
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.bus.runtime_events import RuntimeEventPublisher
|
||||
from nanobot.channels.notification_routes import notification_metadata
|
||||
from nanobot.channels.notification_routes import notification_metadata, system_reply_metadata
|
||||
from 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_id
|
||||
return TurnRoute(channel=channel, chat_id=chat_id, metadata=metadata)
|
||||
|
||||
@@ -20,7 +20,7 @@ from urllib.parse import urlparse
|
||||
import httpx
|
||||
from 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_metadata
|
||||
from nanobot.apps.protocol import app_manifest, compact_dict
|
||||
from nanobot.config.paths import get_runtime_subdir
|
||||
from nanobot.security.workspace_policy import is_path_within
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
@dataclass
|
||||
class InboundMessage:
|
||||
|
||||
@@ -20,7 +20,7 @@ from pydantic import Field
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.config.schema import Base
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.events import ContextCompactionEvent
|
||||
from nanobot.security.network import validate_resolved_url, validate_url_target
|
||||
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -19,7 +19,7 @@ from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.command.builtin import build_help_text
|
||||
from nanobot.config.paths import get_media_dir
|
||||
from nanobot.config.schema import Base
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.utils.helpers import safe_filename, split_message
|
||||
|
||||
DISCORD_AVAILABLE = importlib.util.find_spec("discord") is not None
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -28,7 +28,7 @@ from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.config.paths import get_media_dir
|
||||
from nanobot.config.schema import Base
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.events import ContextCompactionEvent
|
||||
from nanobot.utils.helpers import safe_filename
|
||||
|
||||
|
||||
@@ -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[] = [
|
||||
{
|
||||
|
||||
@@ -4,7 +4,7 @@ from typing import Literal
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from nanobot.config.schema import Base
|
||||
from nanobot.config_base import Base
|
||||
|
||||
|
||||
class FeishuConfig(Base):
|
||||
|
||||
@@ -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 }) => ({
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
|
||||
@@ -63,7 +63,7 @@ from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.config.paths import get_data_dir, get_media_dir
|
||||
from nanobot.config.schema import Base
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.events import ContextCompactionEvent
|
||||
from nanobot.utils.helpers import safe_filename
|
||||
from nanobot.utils.logging_bridge import redirect_lib_logging
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -19,7 +19,7 @@ from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.config.paths import get_runtime_subdir
|
||||
from nanobot.config.schema import Base
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.events import ContextCompactionEvent
|
||||
|
||||
try:
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -39,7 +39,7 @@ from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.config.paths import get_workspace_path
|
||||
from nanobot.config.schema import Base
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.events import ContextCompactionEvent
|
||||
|
||||
MSTEAMS_AVAILABLE = (
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -23,7 +23,7 @@ from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.config.paths import get_media_dir
|
||||
from nanobot.config.schema import Base
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.events import ContextCompactionEvent
|
||||
from nanobot.security.network import validate_url_target
|
||||
from nanobot.utils.helpers import safe_filename
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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 {}
|
||||
@@ -41,7 +41,7 @@ from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ContextCompactionEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.config.schema import Base
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.security.network import validate_url_target
|
||||
from nanobot.utils.logging_bridge import redirect_lib_logging
|
||||
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -22,7 +22,7 @@ from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.config.paths import get_media_dir
|
||||
from nanobot.config.schema import Base
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.events import ContextCompactionEvent
|
||||
from nanobot.pairing import is_approved
|
||||
from nanobot.utils.helpers import safe_filename, split_message
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -19,7 +19,7 @@ from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.config.paths import get_media_dir
|
||||
from nanobot.config.schema import Base
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.events import ContextCompactionEvent
|
||||
from nanobot.pairing import is_approved
|
||||
from nanobot.security.network import (
|
||||
|
||||
@@ -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: nanobot
|
||||
|
||||
@@ -35,7 +35,7 @@ from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.command.builtin import build_help_text
|
||||
from nanobot.config.paths import get_media_dir
|
||||
from nanobot.config.schema import Base
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.events import ContextCompactionEvent
|
||||
from nanobot.security.network import validate_url_target
|
||||
from nanobot.utils.helpers import split_message
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -28,7 +28,7 @@ from nanobot.bus.events import (
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.channels.websocket.binary_http import BinaryHTTPBridge
|
||||
from nanobot.config.schema import Base
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.session.webui_turns import (
|
||||
clear_websocket_turn_if_current,
|
||||
mark_websocket_turn_transcript_persistence_failed,
|
||||
|
||||
@@ -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";
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.config.paths import get_media_dir
|
||||
from nanobot.config.schema import Base
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.events import ContextCompactionEvent
|
||||
|
||||
WECOM_AVAILABLE = importlib.util.find_spec("wecom_aibot_sdk") is not None
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -36,7 +36,7 @@ from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.config.paths import get_media_dir, get_runtime_subdir
|
||||
from nanobot.config.schema import Base
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.events import ContextCompactionEvent
|
||||
from nanobot.utils.logging_bridge import redirect_lib_logging
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -22,7 +22,7 @@ from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.config.paths import get_media_dir, get_runtime_subdir
|
||||
from nanobot.config.schema import Base
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.events import ContextCompactionEvent
|
||||
from nanobot.security.network import PinnedDNSAsyncTransport
|
||||
|
||||
|
||||
@@ -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";
|
||||
|
||||
|
||||
@@ -382,7 +382,6 @@ def _run_gateway(
|
||||
)
|
||||
from nanobot.providers.fallback_provider import FallbackProvider
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.recovery import RecoveryCoordinator
|
||||
from nanobot.session.webui_turns import (
|
||||
WebuiTurnCoordinator,
|
||||
WebuiTurnRoutePolicy,
|
||||
@@ -390,6 +389,7 @@ def _run_gateway(
|
||||
)
|
||||
from nanobot.triggers.local_runner import run_local_trigger_queue
|
||||
from nanobot.triggers.local_store import LocalTriggerStore
|
||||
from nanobot.webui.recovery import RecoveryCoordinator
|
||||
|
||||
port = port if port is not None else config.gateway.port
|
||||
webui_url = _webui_browser_url(config)
|
||||
|
||||
+54
-15
@@ -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",
|
||||
|
||||
@@ -11,15 +11,11 @@ from pydantic_settings import SettingsError
|
||||
|
||||
from nanobot.config.errors import ConfigIssue, ConfigLoadError, validation_issues
|
||||
from 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 = False
|
||||
|
||||
|
||||
def _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:
|
||||
|
||||
@@ -5,7 +5,7 @@ from __future__ import annotations
|
||||
from pathlib import Path
|
||||
|
||||
from nanobot.config.home import get_home_path
|
||||
from nanobot.utils.helpers import ensure_dir
|
||||
from nanobot.utils.file_io import ensure_dir
|
||||
|
||||
|
||||
def get_config_path() -> Path:
|
||||
|
||||
+22
-75
@@ -2,26 +2,31 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, ClassVar, Literal, cast
|
||||
from typing import Any, ClassVar, Literal, cast
|
||||
|
||||
from pydantic import AliasChoices, ConfigDict, Field, PrivateAttr, field_validator, model_validator
|
||||
from 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 WebToolsConfig
|
||||
from nanobot.config.home import get_default_workspace
|
||||
from nanobot.config.provider_api_migration import migrate_legacy_provider_api
|
||||
from nanobot.config.timezone import detect_system_timezone
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.cron.types import CronSchedule
|
||||
from nanobot.providers.generation import GenerationSettings
|
||||
from 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 = None
|
||||
api: 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.
|
||||
"""Root settings assembled from tool-owned configuration models."""
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
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:
|
||||
pass
|
||||
@@ -5,7 +5,7 @@ from __future__ import annotations
|
||||
from typing import Any, Mapping
|
||||
|
||||
from nanobot.cron.types import CronJob
|
||||
from nanobot.session.automation_turns import (
|
||||
from nanobot.session.automation_spec import (
|
||||
AutomationTurnSpec,
|
||||
automation_trigger,
|
||||
)
|
||||
|
||||
@@ -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 importlib import import_module
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from loguru import logger
|
||||
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
|
||||
|
||||
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] = {}
|
||||
_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 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 __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 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()
|
||||
def __dir__() -> list[str]:
|
||||
return sorted(set(globals()) | set(_EXPORTS))
|
||||
|
||||
|
||||
__all__ = [
|
||||
|
||||
@@ -5,7 +5,7 @@ from __future__ import annotations
|
||||
from dataclasses import dataclass
|
||||
|
||||
from nanobot.llm_usage.context import LLMUsageSource
|
||||
from nanobot.providers.base import LLMUsage
|
||||
from nanobot.llm_usage.types import LLMUsage
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
|
||||
@@ -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()
|
||||
@@ -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 usage
|
||||
@@ -5,8 +5,6 @@ from __future__ import annotations
|
||||
from importlib import import_module
|
||||
from 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 AnthropicProvider
|
||||
from nanobot.providers.azure_openai_provider import AzureOpenAIProvider
|
||||
from nanobot.providers.base import LLMProvider, LLMResponse, LLMUsage
|
||||
from nanobot.providers.bedrock_provider import BedrockProvider
|
||||
from nanobot.providers.github_copilot_provider import GitHubCopilotProvider
|
||||
from nanobot.providers.openai_codex_provider import OpenAICodexProvider
|
||||
|
||||
+2
-294
@@ -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 GenerationSettings
|
||||
from nanobot.utils.helpers import sanitize_surrogates_deep
|
||||
|
||||
if 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
|
||||
|
||||
|
||||
@dataclass
|
||||
class 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)"
|
||||
|
||||
|
||||
|
||||
@@ -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_rejected
|
||||
from nanobot.providers.registry import find_by_name
|
||||
|
||||
# Circuit breaker tuned to match OpenAICompatProvider's Responses API breaker.
|
||||
|
||||
@@ -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 = None
|
||||
@@ -20,7 +20,7 @@ from oauth_cli_kit.storage import FileTokenStorage
|
||||
|
||||
from nanobot.providers.base import LLMResponse, ProviderCallContext
|
||||
from nanobot.providers.model_api import ModelAPICapabilities, RequestAPI
|
||||
from nanobot.providers.oauth_model_catalog import (
|
||||
from nanobot.providers.oauth_catalog_cache import (
|
||||
OAuthCatalogAuthRequiredError,
|
||||
OAuthModelCatalog,
|
||||
OAuthModelCatalogSnapshot,
|
||||
|
||||
@@ -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)
|
||||
@@ -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(
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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, extra
|
||||
@@ -2,59 +2,26 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from collections.abc import Mapping
|
||||
from functools import lru_cache
|
||||
from typing import Any, cast
|
||||
from typing import Any
|
||||
|
||||
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 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_SPEC
|
||||
from nanobot.triggers.local_session_turns import LOCAL_TRIGGER_AUTOMATION_SPEC
|
||||
|
||||
|
||||
+6
-522
@@ -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 annotations
|
||||
|
||||
import asyncio
|
||||
import dataclasses
|
||||
import json
|
||||
from collections.abc import Iterable, Mapping
|
||||
from datetime import datetime
|
||||
@@ -18,17 +12,7 @@ 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.webui.metadata import WEBUI_TURN_METADATA_KEY
|
||||
from nanobot.webui.session_identity import webui_chat_id, webui_session_key
|
||||
from nanobot.session.manager import Session
|
||||
|
||||
RUNTIME_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[str
|
||||
if isinstance(can_continue, bool):
|
||||
payload["can_continue"] = can_continue
|
||||
return payload
|
||||
|
||||
|
||||
@dataclasses.dataclass(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 None
|
||||
@@ -44,7 +44,6 @@ from nanobot.runtime_context import public_history_message
|
||||
from nanobot.session.goal_state import goal_state_ws_blob
|
||||
from nanobot.session.history_visibility import is_hidden_history_message
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
from nanobot.session.recovery import RecoveryCoordinator
|
||||
from nanobot.session.session_handles import session_handle_for_name
|
||||
from 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 RecoveryCoordinator
|
||||
from nanobot.webui.session_identity import is_webui_session_key, webui_session_key
|
||||
from nanobot.webui.star_prompt import update_star_prompt
|
||||
from nanobot.webui.transcript import append_session_message_input
|
||||
|
||||
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any, Mapping
|
||||
|
||||
from nanobot.session.automation_turns import (
|
||||
from nanobot.session.automation_spec import (
|
||||
AutomationTurnSpec,
|
||||
automation_trigger,
|
||||
)
|
||||
|
||||
@@ -6,7 +6,7 @@ import sys
|
||||
from importlib import import_module
|
||||
from types import ModuleType
|
||||
|
||||
from nanobot.utils.helpers import ensure_dir
|
||||
from nanobot.utils.file_io import ensure_dir
|
||||
from nanobot.utils.path import abbreviate_path
|
||||
|
||||
__all__ = ["ensure_dir", "abbreviate_path"]
|
||||
|
||||
@@ -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)
|
||||
@@ -8,7 +8,6 @@ import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import stat
|
||||
import time
|
||||
import uuid
|
||||
from collections.abc import Iterable
|
||||
@@ -19,6 +18,8 @@ from typing import TYPE_CHECKING, Any, TypeVar, cast, overload
|
||||
|
||||
from 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_atomic
|
||||
from nanobot.utils.token_encoding import get_token_encoding as _get_token_encoding
|
||||
|
||||
if 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,
|
||||
|
||||
@@ -9,7 +9,7 @@ from contextlib import suppress
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, cast
|
||||
|
||||
from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY
|
||||
from nanobot.bus.events import INBOUND_META_TURN_ID
|
||||
|
||||
RESTART_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_id
|
||||
os.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(
|
||||
|
||||
@@ -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_ID
|
||||
WEBUI_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"
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@dataclasses.dataclass(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 None
|
||||
@@ -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_error
|
||||
|
||||
async 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_process
|
||||
|
||||
if self._process is not None:
|
||||
await stop_process(self._process)
|
||||
|
||||
@@ -21,14 +21,13 @@ from typing import Any, cast
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
from 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) -> li
|
||||
return 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]:
|
||||
|
||||
@@ -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()
|
||||
@@ -34,7 +34,6 @@ from nanobot.cron.session_turns import is_bound_cron_job
|
||||
from nanobot.cron.types import CronJob, CronSchedule
|
||||
from nanobot.security.workspace_access import WorkspaceScope, WorkspaceScopeError
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.recovery import RecoveryActionError
|
||||
from nanobot.session.session_handles import (
|
||||
SessionHandleResolver,
|
||||
)
|
||||
@@ -95,6 +94,7 @@ from nanobot.webui.http_utils import (
|
||||
)
|
||||
from nanobot.webui.ingress_policy import WebUIIngressPolicy
|
||||
from nanobot.webui.media_gateway import WebUIMediaGateway
|
||||
from nanobot.webui.recovery import RecoveryActionError
|
||||
from nanobot.webui.session_automations import (
|
||||
all_automations_payload,
|
||||
serialize_automation_jobs,
|
||||
|
||||
@@ -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.
|
||||
|
||||
Loaded 100 of 162 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user