refactor: enforce BasedPyright strict type checking (#5158)

This commit is contained in:
chengyongru authored and GitHub committed 2026-07-29 21:37:11 +08:00
1 parent e703481755
commit 757ad9c764
166 files changed
+4728 -2621

No files matched your search

+40 -24
View File
@@ -1,5 +1,10 @@
"""Memory system: pure file I/O store and lightweight Consolidator."""
# Tool schemas are installed by the ``@tool_parameters`` class decorator at
# runtime; static analyzers cannot observe that it clears ``parameters`` from
# ``__abstractmethods__`` before these classes are instantiated.
# pyright: reportAbstractUsage=false, reportPrivateUsage=false
from __future__ import annotations
import asyncio
@@ -11,7 +16,7 @@ import weakref
from contextlib import suppress
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Iterator
from typing import TYPE_CHECKING, Any, Callable, Iterator, cast
from loguru import logger
@@ -38,6 +43,7 @@ from nanobot.utils.workspace_prompts import (
)
if TYPE_CHECKING:
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.utils.llm_runtime import LLMRuntime
# ---------------------------------------------------------------------------
@@ -58,7 +64,7 @@ class DreamRunProgress:
**_kwargs: Any,
) -> None:
if any(
isinstance(event, dict) and event.get("phase") == "error"
isinstance(cast(object, event), dict) and event.get("phase") == "error"
for event in tool_events or ()
):
self.had_tool_errors = True
@@ -474,11 +480,11 @@ class MemoryStore:
line = line.strip()
if line:
try:
parsed = json.loads(line)
parsed: object = json.loads(line)
except json.JSONDecodeError:
continue
if isinstance(parsed, dict):
entries.append(parsed)
entries.append(cast(dict[str, Any], parsed))
return entries
@@ -496,8 +502,8 @@ class MemoryStore:
lines = [line for line in data.split("\n") if line.strip()]
if not lines:
return None
parsed = json.loads(lines[-1])
return parsed if isinstance(parsed, dict) else None
parsed: object = json.loads(lines[-1])
return cast(dict[str, Any], parsed) if isinstance(parsed, dict) else None
except (FileNotFoundError, json.JSONDecodeError, UnicodeDecodeError):
return None
@@ -612,7 +618,7 @@ class MemoryStore:
("USER.md", self.user_file),
("memory/MEMORY.md", self.memory_file),
]
blocks = []
blocks: list[str] = []
for label, path in files:
try:
content = path.read_text(encoding="utf-8") if path.exists() else ""
@@ -633,7 +639,7 @@ class MemoryStore:
return ""
return self._git.summarize_working_tree(list(self._DREAM_CONTENT_PATHS))
def build_dream_tools(self):
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.tools.apply_patch import ApplyPatchTool
@@ -684,17 +690,15 @@ class MemoryStore:
) -> bool:
"""Return True only when a Dream turn completed without tool failures."""
metadata = getattr(resp, "metadata", None)
return (
not had_tool_errors
and isinstance(metadata, dict)
and metadata.get("_stop_reason") == "completed"
)
if had_tool_errors or not isinstance(metadata, dict):
return False
return cast(dict[str, Any], metadata).get("_stop_reason") == "completed"
# -- message formatting utility ------------------------------------------
@staticmethod
def _format_messages(messages: list[dict]) -> str:
lines = []
def _format_messages(messages: list[dict[str, Any]]) -> str:
lines: list[str] = []
for message in messages:
content = content_with_media_breadcrumbs(
message.get("role"),
@@ -703,16 +707,22 @@ class MemoryStore:
)
if not content:
continue
tools = f" [tools: {', '.join(message['tools_used'])}]" if message.get("tools_used") else ""
tools_used = message.get("tools_used")
tools = (
f" [tools: {', '.join(cast(list[str], tools_used))}]"
if tools_used
else ""
)
timestamp = cast(str, message.get("timestamp", "?"))
role = cast(str, message["role"])
lines.append(
f"[{message.get('timestamp', '?')[:16]}] "
f"{message['role'].upper()}{tools}: {content}"
f"[{timestamp[:16]}] {role.upper()}{tools}: {content}"
)
return "\n".join(lines)
def raw_archive(
self,
messages: list[dict],
messages: list[dict[str, Any]],
*,
max_chars: int | None = None,
session_key: str | None = None,
@@ -766,9 +776,9 @@ class MemoryStore:
Only current base64url-encoded Dream session keys are considered.
Non-dream session files are never touched.
"""
dream_files = []
dream_files: list[Path] = []
for path in sessions_dir.glob("*.jsonl"):
decoded_key = SessionManager._decode_storage_key(path.stem)
decoded_key = SessionManager.decode_storage_key(path.stem)
if decoded_key is not None and decoded_key.startswith("dream:"):
dream_files.append(path)
dream_files.sort(key=lambda p: p.stat().st_mtime)
@@ -943,7 +953,13 @@ class Consolidator:
channel = session.key.split(":", 1)[0] if ":" in session.key else None
# Include archived summary in estimation so the budget accounts for it.
meta = session.metadata.get("_last_summary")
summary = meta.get("text") if isinstance(meta, dict) else (meta if isinstance(meta, str) else None)
summary = (
cast(dict[str, Any], meta).get("text")
if isinstance(meta, dict)
else meta
if isinstance(meta, str)
else None
)
probe_messages = self._build_messages(
history=history,
current_message="[token-probe]",
@@ -976,11 +992,11 @@ class Consolidator:
async def archive(
self,
messages: list[dict],
messages: list[dict[str, Any]],
*,
runtime: LLMRuntime,
session_key: str | None = None,
summary_messages: list[dict] | None = None,
summary_messages: list[dict[str, Any]] | None = None,
) -> str | None:
"""Summarize messages via LLM and append to history.jsonl.