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

+10 -11
View File
@@ -4,6 +4,7 @@ import mimetypes
from collections.abc import Iterator
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from zipfile import BadZipFile, ZipFile
from loguru import logger
@@ -102,7 +103,7 @@ class PdfExtraction:
end_page: int
def extract_text(path: Path) -> str | None:
def extract_text(path: str | Path) -> str | None:
"""Extract text from a file.
Args:
@@ -112,9 +113,7 @@ def extract_text(path: Path) -> str | None:
Extracted text as string, None for unsupported types,
or error string for failures.
"""
if not isinstance(path, Path):
path = Path(path)
path = Path(path)
if not path.exists():
return f"[error: file not found: {path}]"
try:
@@ -217,14 +216,14 @@ def _extract_docx(path: Path) -> str:
"""Extract text from DOCX using python-docx."""
try:
from docx import Document as DocxDocument
from docx.table import Table, _Cell
from docx.table import Table, _Cell # pyright: ignore[reportPrivateUsage]
from docx.text.paragraph import Paragraph
except ImportError:
return "[error: python-docx not installed]"
try:
if error := _office_archive_error(path):
return error
doc = DocxDocument(path)
doc = DocxDocument(str(path))
collector = _TextCollector(_MAX_TEXT_LENGTH)
table_cell_count = 0
@@ -235,7 +234,7 @@ def _extract_docx(path: Path) -> str:
text = " ".join(block.text.split())
if text:
parts.append(text)
elif isinstance(block, Table):
elif isinstance(block, Table): # pyright: ignore[reportUnnecessaryIsInstance]
parts.extend(row.replace("\t", " | ") for row in table_rows(block, depth + 1))
return " ".join(parts)
@@ -249,7 +248,7 @@ def _extract_docx(path: Path) -> str:
cells: list[str] = []
# row.cells expands w:gridSpan before callers can apply a bound.
# Physical w:tc elements keep malformed documents proportional to XML size.
for tc in row._tr.tc_lst:
for tc in row._tr.tc_lst: # pyright: ignore[reportPrivateUsage]
table_cell_count += 1
if table_cell_count > _MAX_DOCX_TABLE_CELLS:
raise DocxSafetyError(
@@ -265,7 +264,7 @@ def _extract_docx(path: Path) -> str:
if text and not collector.add(text, separator="\n\n"):
break
continue
if not isinstance(block, Table):
if not isinstance(block, Table): # pyright: ignore[reportUnnecessaryIsInstance]
continue
first_row = True
for row_text in table_rows(block, 1):
@@ -325,7 +324,7 @@ def _extract_pptx(path: Path) -> str:
try:
if error := _office_archive_error(path):
return error
prs = PptxPresentation(path)
prs = PptxPresentation(str(path))
collector = _TextCollector(_MAX_TEXT_LENGTH)
for i, slide in enumerate(prs.slides, 1):
slide_text: list[str] = []
@@ -343,7 +342,7 @@ def _extract_pptx(path: Path) -> str:
return f"[error: failed to extract PPTX: {e!s}]"
def _collect_pptx_shape_text(shape, out: list[str]) -> None:
def _collect_pptx_shape_text(shape: Any, out: list[str]) -> None:
"""Collect text from a PPTX shape, recursing into groups and tables.
Groups have ``has_text_frame=False`` and must be walked via ``.shapes``;
+7 -6
View File
@@ -6,7 +6,7 @@ import difflib
import re
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from typing import Any, cast
TRACKED_FILE_EDIT_TOOLS = frozenset({"write_file", "edit_file", "apply_patch"})
_MAX_SNAPSHOT_BYTES = 2 * 1024 * 1024
@@ -351,12 +351,13 @@ def _resolve_apply_patch_paths(
edits = params.get("edits")
if not isinstance(edits, list):
return []
patch_edits = cast(list[Any], edits)
paths: list[Path] = []
seen: set[Path] = set()
for edit in edits:
for edit in patch_edits:
if not isinstance(edit, dict):
continue
raw_path = edit.get("path")
raw_path = cast(dict[str, Any], edit).get("path")
if not isinstance(raw_path, str):
continue
raw_path = raw_path.strip()
@@ -379,7 +380,7 @@ def _resolve_single_path(tool: Any, workspace: Path | None, raw_path: Any) -> Pa
if isinstance(resolved, Path):
return resolved
if resolved:
return Path(resolved)
return Path(cast(str, resolved))
except Exception:
return None
resolver = getattr(tool, "_resolve", None)
@@ -389,7 +390,7 @@ def _resolve_single_path(tool: Any, workspace: Path | None, raw_path: Any) -> Pa
if isinstance(resolved, Path):
return resolved
if resolved:
return Path(resolved)
return Path(cast(str, resolved))
except Exception:
return None
if workspace is None:
@@ -407,7 +408,7 @@ def _display_workspace(tool: Any, fallback: Path | None) -> Path | None:
if isinstance(value, Path):
return value
if value:
return Path(value)
return Path(cast(str, value))
return fallback
+51 -24
View File
@@ -7,9 +7,15 @@ import time
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import TYPE_CHECKING, Iterable, cast
from loguru import logger
if TYPE_CHECKING:
from dulwich.objects import Blob, Commit, ObjectID, Tree, TreeEntry
from dulwich.refs import Ref
from dulwich.repo import Repo
# Cap on the unified-diff block embedded in Dream commit messages. Memory files
# are tiny in practice, but a pathological rewrite must not blow up the audit
# record. The structured per-file summary is always emitted in full regardless.
@@ -46,7 +52,9 @@ class LineAge:
age_days: int # days since last modification
def _compute_line_ages(annotated) -> list[LineAge]:
def _compute_line_ages(
annotated: Iterable[tuple[tuple["Commit", "TreeEntry"], bytes]],
) -> list[LineAge]:
"""Convert annotate results to per-line ages."""
now = datetime.now(tz=timezone.utc).date()
ages: list[LineAge] = []
@@ -148,10 +156,17 @@ class GitStore:
# .gitignore excludes everything except tracked files,
# so any staged/unstaged change must be in our files.
st = porcelain.status(str(self._workspace))
if not st.unstaged and not any(st.staged.values()):
unstaged = cast(list[object], st.unstaged)
staged = cast(dict[object, list[object]], st.staged)
if not unstaged and not any(staged.values()):
return None
msg_bytes = message.encode("utf-8") if isinstance(message, str) else message
message_value = cast(object, message)
msg_bytes = (
message_value.encode("utf-8")
if isinstance(message_value, str)
else cast(bytes, message_value)
)
porcelain.add(str(self._workspace), paths=self._staging_paths(*self._tracked_files))
sha_bytes = porcelain.commit(
str(self._workspace),
@@ -159,7 +174,7 @@ class GitStore:
author=b"nanobot <nanobot@dream>",
committer=b"nanobot <nanobot@dream>",
)
if sha_bytes is None:
if cast(object, sha_bytes) is None:
return None
sha = sha_bytes.hex()[:8]
logger.debug("Git auto-commit: {} ({})", sha, message)
@@ -180,16 +195,17 @@ class GitStore:
with Repo(str(self._workspace)) as repo:
try:
sha = repo.refs[b"HEAD"]
sha: ObjectID | None = repo.refs[cast("Ref", b"HEAD")]
except KeyError:
return None
while sha:
if sha.hex().startswith(short_sha):
return sha
commit = repo[sha]
if commit.type_name != b"commit":
commit_obj = repo[sha]
if commit_obj.type_name != b"commit":
break
commit = cast("Commit", commit_obj)
sha = commit.parents[0] if commit.parents else None
return None
except Exception as exc:
@@ -247,15 +263,16 @@ class GitStore:
entries: list[CommitInfo] = []
with Repo(str(self._workspace)) as repo:
try:
head = repo.refs[b"HEAD"]
head = repo.refs[cast("Ref", b"HEAD")]
except KeyError:
return []
sha = head
sha: ObjectID | None = head
while sha and len(entries) < max_entries:
commit = repo[sha]
if commit.type_name != b"commit":
commit_obj = repo[sha]
if commit_obj.type_name != b"commit":
break
commit = cast("Commit", commit_obj)
ts = time.strftime(
"%Y-%m-%d %H:%M",
time.localtime(commit.commit_time),
@@ -429,16 +446,17 @@ class GitStore:
return body
@staticmethod
def _head_tree(repo) -> object | None:
def _head_tree(repo: "Repo") -> "Tree | None":
"""Return the tree object at HEAD, or None if there are no commits."""
try:
head = repo.refs[b"HEAD"]
head = repo.refs[cast("Ref", b"HEAD")]
except KeyError:
return None
commit = repo[head]
if commit.type_name != b"commit":
commit_obj = repo[head]
if commit_obj.type_name != b"commit":
return None
return repo[commit.tree]
commit = cast("Commit", commit_obj)
return cast("Tree", repo[commit.tree])
def find_commit(self, short_sha: str, max_entries: int = 20) -> CommitInfo | None:
"""Find a commit by short SHA prefix match."""
@@ -464,7 +482,7 @@ class GitStore:
if not full_sha:
return None
with Repo(str(self._workspace)) as repo:
commit = repo[full_sha]
commit = cast("Commit", repo[full_sha])
parent = commit.parents[0] if commit.parents else None
diff = self.diff_commits(parent.hex()[:8], c.sha) if parent else ""
return c, diff
@@ -500,8 +518,12 @@ class GitStore:
commit_obj = repo[full_sha]
if commit_obj.type_name != b"commit":
return None
typed_commit = cast("Commit", commit_obj)
commit_message = commit_obj.message.decode("utf-8", errors="replace").strip()
commit_message = typed_commit.message.decode(
"utf-8",
errors="replace",
).strip()
if message_prefix is not None and not commit_message.startswith(message_prefix):
logger.warning(
"Git revert: commit {} does not match message prefix {!r}",
@@ -510,13 +532,13 @@ class GitStore:
)
return None
if not commit_obj.parents:
if not typed_commit.parents:
logger.warning("Git revert: cannot revert root commit {}", commit)
return None
# Use the parent's tree — this undoes the commit's changes
parent_obj = repo[commit_obj.parents[0]]
tree = repo[parent_obj.tree]
parent_obj = cast("Commit", repo[typed_commit.parents[0]])
tree = cast("Tree", repo[parent_obj.tree])
restored: list[str] = []
for filepath in self._tracked_files:
@@ -536,7 +558,11 @@ class GitStore:
raise GitStoreError(f"Git revert failed for {commit}") from exc
@staticmethod
def _read_blob_from_tree(repo, tree, filepath: str) -> str | None:
def _read_blob_from_tree(
repo: "Repo",
tree: "Tree",
filepath: str,
) -> str | None:
"""Read a blob's content from a tree object by walking path parts."""
parts = Path(filepath).parts
current = tree
@@ -547,9 +573,10 @@ class GitStore:
return None
obj = repo[entry[1]]
if obj.type_name == b"blob":
return obj.data.decode("utf-8", errors="replace")
blob = cast("Blob", obj)
return blob.data.decode("utf-8", errors="replace")
if obj.type_name == b"tree":
current = obj
current = cast("Tree", obj)
else:
return None
return None
+50 -32
View File
@@ -12,16 +12,25 @@ from contextlib import suppress
from datetime import datetime
from functools import lru_cache
from pathlib import Path
from typing import Any
from typing import Any, TypeVar, cast, overload
import tiktoken
from loguru import logger
_TOOLS_TOKEN_CACHE_MAX_ENTRIES = 64
_TOOLS_TOKEN_CACHE: dict[int, tuple[tuple[int, ...], dict[bool, int]]] = {}
_T = TypeVar("_T")
def sanitize_surrogates(text: str) -> str:
@overload
def sanitize_surrogates(text: str) -> str: ...
@overload
def sanitize_surrogates(text: _T) -> _T: ...
def sanitize_surrogates(text: Any) -> Any:
"""Reconstruct surrogate pairs and replace unpaired surrogates.
Lone UTF-16 surrogate code points (``U+D800``..``U+DFFF``) cannot be
@@ -62,24 +71,29 @@ def sanitize_surrogates_deep(value: Any) -> Any:
if isinstance(value, list):
result_list: list[Any] = []
mutated = False
for item in value:
for item in cast(list[Any], value):
new_item = sanitize_surrogates_deep(item)
if new_item is not item:
mutated = True
result_list.append(new_item)
return result_list if mutated else value
return result_list if mutated else cast(Any, value)
if isinstance(value, dict):
result_dict: dict[Any, Any] = {}
mutated = False
for key, item in value.items():
for key, item in cast(dict[Any, Any], value).items():
new_item = sanitize_surrogates_deep(item)
if new_item is not item:
mutated = True
result_dict[key] = new_item
return result_dict if mutated else value
return result_dict if mutated else cast(Any, value)
if isinstance(value, tuple):
result_tuple = tuple(sanitize_surrogates_deep(item) for item in value)
return result_tuple if any(a is not b for a, b in zip(result_tuple, value)) else value
tuple_value = cast(tuple[Any, ...], value)
result_tuple = tuple(sanitize_surrogates_deep(item) for item in tuple_value)
return (
result_tuple
if any(a is not b for a, b in zip(result_tuple, tuple_value))
else cast(Any, value)
)
return value
@@ -289,7 +303,7 @@ def extract_reasoning(
parts = [
strip_reasoning_tags(tb.get("thinking", ""))
for tb in thinking_blocks
if isinstance(tb, dict) and tb.get("type") == "thinking"
if tb.get("type") == "thinking"
]
joined = "\n\n".join(p for p in parts if p)
return (joined or None), strip_think(content) if content else content
@@ -377,7 +391,7 @@ def content_with_media_breadcrumbs(
return content
breadcrumbs = "\n".join(
image_placeholder_text(path)
for path in media
for path in cast(list[object], media)
if isinstance(path, str) and path
)
if not breadcrumbs:
@@ -468,9 +482,10 @@ def find_legal_message_start(messages: list[dict[str, Any]]) -> int:
for i, msg in enumerate(messages):
role = msg.get("role")
if role == "assistant":
for tc in msg.get("tool_calls") or []:
if isinstance(tc, dict) and tc.get("id"):
declared.add(str(tc["id"]))
for raw_call in cast(list[object], msg.get("tool_calls") or []):
tool_call = cast(dict[str, Any], raw_call) if isinstance(raw_call, dict) else None
if tool_call is not None and tool_call.get("id"):
declared.add(str(tool_call["id"]))
elif role == "tool":
tid = msg.get("tool_call_id")
if tid and str(tid) not in declared:
@@ -479,11 +494,12 @@ def find_legal_message_start(messages: list[dict[str, Any]]) -> int:
return start
def stringify_text_blocks(content: list[dict[str, Any]]) -> str | None:
def stringify_text_blocks(content: list[object]) -> str | None:
parts: list[str] = []
for block in content:
if not isinstance(block, dict):
for raw_block in content:
if not isinstance(raw_block, dict):
return None
block = cast(dict[str, Any], raw_block)
if block.get("type") != "text":
return None
text = block.get("text")
@@ -574,15 +590,15 @@ def maybe_persist_tool_result(
if isinstance(content, str):
text_payload = content
elif isinstance(content, list):
text_payload = stringify_text_blocks(content)
text_payload = stringify_text_blocks(cast(list[object], content))
if text_payload is None:
return content
return cast(Any, content)
suffix = "json"
else:
return content
if len(text_payload) <= max_chars:
return content
return cast(Any, content)
root = ensure_dir(workspace / _TOOL_RESULTS_DIR)
bucket = ensure_dir(root / safe_filename(session_key or "default"))
@@ -645,7 +661,7 @@ def build_assistant_message(
content: str | None,
tool_calls: list[dict[str, Any]] | None = None,
reasoning_content: str | None = None,
thinking_blocks: list[dict] | None = None,
thinking_blocks: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""Build a provider-safe assistant message with optional reasoning fields."""
msg: dict[str, Any] = {"role": "assistant", "content": content or ""}
@@ -677,11 +693,12 @@ def _estimate_prompt_tokens_with_source(
if isinstance(content, str):
parts.append(content)
elif isinstance(content, list):
for part in content:
if isinstance(part, dict) and part.get("type") == "text":
txt = part.get("text", "")
if txt:
parts.append(txt)
for raw_part in cast(list[object], content):
part = cast(dict[str, Any], raw_part) if isinstance(raw_part, dict) else None
if part is not None and part.get("type") == "text":
text = part.get("text", "")
if isinstance(text, str) and text:
parts.append(text)
tc = msg.get("tool_calls")
if tc:
@@ -732,13 +749,14 @@ def estimate_message_tokens(message: dict[str, Any]) -> int:
if isinstance(content, str):
parts.append(content)
elif isinstance(content, list):
for part in content:
if isinstance(part, dict) and part.get("type") == "text":
for raw_part in cast(list[object], content):
part = cast(dict[str, Any], raw_part) if isinstance(raw_part, dict) else None
if part is not None and part.get("type") == "text":
text = part.get("text", "")
if text:
if isinstance(text, str) and text:
parts.append(text)
else:
parts.append(json.dumps(part, ensure_ascii=False))
parts.append(json.dumps(raw_part, ensure_ascii=False))
elif content is not None:
parts.append(json.dumps(content, ensure_ascii=False))
@@ -764,7 +782,7 @@ def estimate_message_tokens(message: dict[str, Any]) -> int:
def estimate_prompt_tokens_chain(
provider: Any,
provider: object,
model: str | None,
messages: list[dict[str, Any]],
tools: list[dict[str, Any]] | None = None,
@@ -773,7 +791,7 @@ def estimate_prompt_tokens_chain(
provider_counter = getattr(provider, "estimate_prompt_tokens", None)
if callable(provider_counter):
with suppress(Exception):
tokens, source = provider_counter(messages, tools, model)
tokens, source = cast(tuple[object, object], provider_counter(messages, tools, model))
if isinstance(tokens, (int, float)) and tokens > 0:
return int(tokens), str(source or "provider_counter")
estimated, source = _estimate_prompt_tokens_with_source(messages, tools)
@@ -851,7 +869,7 @@ def sync_workspace_templates(workspace: Path, silent: bool = False) -> list[str]
added: list[str] = []
def _write(src, dest: Path):
def _write(src: Any, dest: Path) -> None:
content = src.read_text(encoding="utf-8") if src else ""
if dest.exists():
return
+8 -5
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
import inspect
from collections.abc import Awaitable, Callable
from typing import Any
from typing import Any, cast
from nanobot.agent.hook import AgentHookContext
@@ -51,7 +51,7 @@ async def invoke_file_edit_progress(
def _tool_event_arguments(tool_call: Any) -> dict[str, Any]:
arguments = getattr(tool_call, "arguments", {}) or {}
return arguments if isinstance(arguments, dict) else {}
return cast(dict[str, Any], arguments) if isinstance(arguments, dict) else {}
def build_tool_event_start_payload(tool_call: Any) -> dict[str, Any]:
@@ -71,8 +71,11 @@ def build_tool_event_start_payload(tool_call: Any) -> dict[str, Any]:
def tool_event_result_extras(result: Any) -> tuple[list[Any], list[Any]]:
if not isinstance(result, dict):
return [], []
files = result.get("files") if isinstance(result.get("files"), list) else []
embeds = result.get("embeds") if isinstance(result.get("embeds"), list) else []
result_data = cast(dict[str, Any], result)
raw_files = result_data.get("files")
raw_embeds = result_data.get("embeds")
files: list[Any] = cast(list[Any], raw_files) if isinstance(raw_files, list) else []
embeds: list[Any] = cast(list[Any], raw_embeds) if isinstance(raw_embeds, list) else []
return files, embeds
@@ -82,7 +85,7 @@ def build_tool_event_finish_payloads(context: AgentHookContext) -> list[dict[str
for idx in range(count):
tool_call = context.tool_calls[idx]
result = context.tool_results[idx]
event = context.tool_events[idx] if isinstance(context.tool_events[idx], dict) else {}
event = context.tool_events[idx]
status = event.get("status")
phase = "end" if status == "ok" else "error"
files, embeds = tool_event_result_extras(result)
+2 -2
View File
@@ -7,7 +7,7 @@ import os
import time
from contextlib import suppress
from dataclasses import dataclass, field
from typing import Any
from typing import Any, cast
from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY
@@ -71,7 +71,7 @@ def consume_restart_notice_from_env() -> RestartNotice | None:
except (TypeError, ValueError):
parsed = None
if isinstance(parsed, dict):
metadata = parsed
metadata = cast(dict[str, Any], parsed)
return RestartNotice(
channel=channel,
chat_id=chat_id,
+5 -3
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
import re
from pathlib import Path
from typing import Any
from typing import Any, cast
from loguru import logger
@@ -61,10 +61,10 @@ def ensure_nonempty_tool_result(tool_name: str, content: Any) -> Any:
if isinstance(content, list):
if not content:
return empty_tool_result_message(tool_name)
text_payload = stringify_text_blocks(content)
text_payload = stringify_text_blocks(cast(list[Any], content))
if text_payload is not None and not text_payload.strip():
return empty_tool_result_message(tool_name)
return content
return cast(Any, content)
def is_blank_text(content: str | None) -> bool:
@@ -106,6 +106,7 @@ def external_lookup_signature(tool_name: str, arguments: Any) -> str | None:
"""Stable signature for repeated external lookups we want to throttle."""
if not isinstance(arguments, dict):
return None
arguments = cast(dict[str, Any], arguments)
if tool_name == "web_fetch":
url = str(arguments.get("url") or "").strip()
if url:
@@ -153,6 +154,7 @@ def workspace_violation_signature(
"""Return a stable cross-tool signature for the outside-workspace target."""
if not isinstance(arguments, dict):
return None
arguments = cast(dict[str, Any], arguments)
for key in ("path", "file_path", "target", "source", "destination"):
val = arguments.get(key)
if isinstance(val, str) and val.strip():
+6 -5
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
import os
from dataclasses import dataclass
from typing import Any
from typing import Any, cast
@dataclass
@@ -28,7 +28,7 @@ class SearchUsageInfo:
def format(self) -> str:
"""Return a human-readable multi-line string for /status output."""
lines = [f"🔍 Web Search: {self.provider}"]
lines: list[str] = [f"🔍 Web Search: {self.provider}"]
if not self.supported:
lines.append(" Usage tracking: not available for this provider")
@@ -44,7 +44,7 @@ class SearchUsageInfo:
lines.append(f" Usage: {self.used} requests")
# Tavily breakdown
breakdown_parts = []
breakdown_parts: list[str] = []
if self.search_used is not None:
breakdown_parts.append(f"Search: {self.search_used}")
if self.extract_used is not None:
@@ -109,7 +109,7 @@ async def _fetch_tavily_usage(api_key: str | None) -> SearchUsageInfo:
headers={"Authorization": f"Bearer {key}"},
)
r.raise_for_status()
data: dict[str, Any] = r.json()
data = cast(dict[str, Any], r.json())
return _parse_tavily_usage(data)
except httpx.HTTPStatusError as e:
return SearchUsageInfo(
@@ -145,7 +145,8 @@ def _parse_tavily_usage(data: dict[str, Any]) -> SearchUsageInfo:
}
}
"""
account = data.get("account") or {}
raw_account = data.get("account")
account = cast(dict[str, Any], raw_account) if isinstance(raw_account, dict) else {}
used = _optional_int(account.get("plan_usage"))
limit = _optional_int(account.get("plan_limit"))
+2 -2
View File
@@ -7,7 +7,7 @@ should show only the header plus a truncated result body."""
from __future__ import annotations
from typing import Any
from typing import Any, cast
# Cap Result section length so WebSocket session replay stays readable; full text
# remains on disk for LLM replay (we only mutate outgoing API copies in websocket).
@@ -49,7 +49,7 @@ def scrub_subagent_announce_body(content: str) -> str:
def scrub_subagent_messages_for_channel(messages: list[dict[str, Any]]) -> None:
"""Mutate message dicts in place when they carry ``subagent_result`` inject."""
for msg in messages:
if not isinstance(msg, dict):
if not isinstance(cast(object, msg), dict):
continue
if msg.get("injected_event") != "subagent_result":
continue
+21 -15
View File
@@ -3,7 +3,9 @@
from __future__ import annotations
import re
from typing import cast
from nanobot.providers.base import ToolCallRequest
from nanobot.utils.path import abbreviate_path
# Registry: tool_name -> (key_args, template, is_path, is_command)
@@ -29,12 +31,15 @@ _PATH_IN_CMD_RE = re.compile(
)
def format_tool_hints(tool_calls: list, max_length: int = 40) -> str:
ToolFormat = tuple[list[str], str, bool, bool]
def format_tool_hints(tool_calls: list[ToolCallRequest], max_length: int = 40) -> str:
"""Format tool calls as concise hints with smart abbreviation."""
if not tool_calls:
return ""
formatted = []
formatted: list[str] = []
for tc in tool_calls:
name = getattr(tc, "name", None)
if not isinstance(name, str) or not name:
@@ -49,7 +54,7 @@ def format_tool_hints(tool_calls: list, max_length: int = 40) -> str:
else:
formatted.append(_fmt_fallback(tc, max_length))
hints = []
hints: list[tuple[str, int]] = []
for hint in formatted:
if hints and hints[-1][0] == hint:
hints[-1] = (hint, hints[-1][1] + 1)
@@ -61,22 +66,23 @@ def format_tool_hints(tool_calls: list, max_length: int = 40) -> str:
)
def _get_args(tc) -> dict:
def _get_args(tc: ToolCallRequest) -> dict[str, object]:
"""Extract args dict from tc.arguments, handling list/dict/None/empty."""
if tc.arguments is None:
return {}
if isinstance(tc.arguments, list):
return tc.arguments[0] if tc.arguments else {}
if isinstance(tc.arguments, dict):
return tc.arguments
arguments = tc.arguments
if isinstance(arguments, list):
argument_list = cast(list[object], arguments)
first_argument = argument_list[0] if argument_list else None
return cast(dict[str, object], first_argument) if isinstance(first_argument, dict) else {}
if isinstance(arguments, dict):
return cast(dict[str, object], arguments)
return {}
def _extract_arg(tc, key_args: list[str]) -> str | None:
def _extract_arg(tc: ToolCallRequest, key_args: list[str]) -> str | None:
"""Extract the first available value from preferred key names."""
args = _get_args(tc)
if not isinstance(args, dict):
return None
for key in key_args:
val = args.get(key)
if isinstance(val, str) and val:
@@ -87,7 +93,7 @@ def _extract_arg(tc, key_args: list[str]) -> str | None:
return None
def _fmt_known(tc, fmt: tuple, max_length: int = 40) -> str:
def _fmt_known(tc: ToolCallRequest, fmt: ToolFormat, max_length: int = 40) -> str:
"""Format a registered tool using its template."""
if not fmt[0] and "{}" not in fmt[1]:
return fmt[1]
@@ -118,7 +124,7 @@ def _abbreviate_command(cmd: str, max_len: int = 40) -> str:
return abbreviated[:max_len - 1] + "\u2026"
def _fmt_mcp(tc, max_length: int = 40) -> str:
def _fmt_mcp(tc: ToolCallRequest, max_length: int = 40) -> str:
"""Format MCP tool as server::tool."""
name = tc.name
if "__" in name:
@@ -139,10 +145,10 @@ def _fmt_mcp(tc, max_length: int = 40) -> str:
return f'{server}::{tool}("{abbreviate_path(val, max_length)}")'
def _fmt_fallback(tc, max_length: int = 40) -> str:
def _fmt_fallback(tc: ToolCallRequest, max_length: int = 40) -> str:
"""Original formatting logic for unregistered tools."""
args = _get_args(tc)
val = next(iter(args.values()), None) if isinstance(args, dict) else None
val = next(iter(args.values()), None)
if not isinstance(val, str):
return tc.name
return f'{tc.name}("{abbreviate_path(val, max_length)}")' if len(val) > max_length else f'{tc.name}("{val}")'