The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tools): graph client/auth, session_search, memory — collapse defensive layers, fold iterate_pages, hug brackets
Teknium2e0ba8931747
diff --git a/tools/memory_tool.py b/tools/memory_tool.pyindex f3d5ecc037f..f7ff4e72235 100644--- a/tools/memory_tool.py+++ b/tools/memory_tool.py@@ -35,8 +35,7 @@ logger = logging.getLogger(__name__)# builds isolated while letting the check_fn result flow to the immediately# following dynamic_schema_overrides call in ToolRegistry.get_definitions()._memory_surface_flags: ContextVar[Optional[Tuple[bool, bool]]] = ContextVar(- "memory_surface_flags", default=None-)+ "memory_surface_flags", default=None)def get_memory_dir() -> Path:@@ -47,15 +46,13 @@ def get_memory_dir() -> Path:from tools.memory_tool_store import ( # noqa: E402,F401 (re-exports)ENTRY_DELIMITER, MEMORY_BLOCK_HEADERS, MemoryStore,- _drift_error, _read_failed_error, _scan_memory_content,-)+ _drift_error, _read_failed_error, _scan_memory_content)def load_on_disk_store() -> "MemoryStore":"""Fresh on-disk MemoryStore with configured limits/flags, for contexts withno live agent (gateway, Desktop, bare CLI ``/memory``) so approvals enforcethe SAME caps as ``agent_init``. Defaults if config can't load; never raises."""- kwargs: Dict[str, Any] = {}try:from hermes_cli.config import load_config@@ -66,10 +63,9 @@ def load_on_disk_store() -> "MemoryStore":"memory_char_limit": int(mem_cfg.get("memory_char_limit", 2200)),"user_char_limit": int(mem_cfg.get("user_char_limit", 1375)),"memory_enabled": memory_enabled,- "user_profile_enabled": user_profile_enabled,- }+ "user_profile_enabled": user_profile_enabled}except Exception:- kwargs = {} # config optional — fall back to defaults rather than break /memory+ kwargs: Dict[str, Any] = {} # config optional — fall back to defaults rather than break /memorystore = MemoryStore(**kwargs)store.load_from_disk()return store@@ -99,8 +95,7 @@ def _gate_or_stage(summary: str, detail: str, payload: Dict[str, Any]) -> Option_GATE_TEXT = {"add": lambda label, content, old_text: (f"add to {label}", content or ""),"replace": lambda label, content, old_text: (f"replace in {label}", f"old: {old_text}\nnew: {content}"),- "remove": lambda label, content, old_text: (f"remove from {label}", old_text or ""),-}+ "remove": lambda label, content, old_text: (f"remove from {label}", old_text or "")}def _apply_write_gate(action: str, target: str, content: Optional[str], old_text: Optional[str]) -> Optional[str]:@@ -158,8 +153,7 @@ def _validate_single_op(store, action, target, content, old_text) -> Optional[st_STORE_ACTIONS = {"add": lambda store, target, content, old_text: store.add(target, content),"replace": lambda store, target, content, old_text: store.replace(target, old_text, content),- "remove": lambda store, target, content, old_text: store.remove(target, old_text),-}+ "remove": lambda store, target, content, old_text: store.remove(target, old_text)}def memory_tool(@@ -169,8 +163,7 @@ def memory_tool(old_text: str = None,new_text: str = None,operations: Optional[List[Dict[str, Any]]] = None,- store: Optional[MemoryStore] = None,-) -> str:+ store: Optional[MemoryStore] = None) -> str:"""Tool entry point; returns a JSON string. Single op (action + content /old_text) or batch (``operations`` applied atomically against the finalbudget). ``new_text`` aliases ``content`` — callers mirror ``old_text``@@ -230,8 +223,7 @@ def get_builtin_memory_store_flags(config: Optional[Dict[str, Any]] = None) -> Tsection = get_builtin_memory_config(config)return (is_truthy_value(section.get("memory_enabled"), default=True),- is_truthy_value(section.get("user_profile_enabled"), default=True),- )+ is_truthy_value(section.get("user_profile_enabled"), default=True))@no_cache_check_fn@@ -351,13 +343,10 @@ _SINGLE_TARGET_TEXT = {("memory",): ("The enabled built-in store: 'memory' for personal notes.","TARGET: only 'memory' is enabled for personal notes (environment, conventions, "- "tool quirks, lessons).",- ),+ "tool quirks, lessons)."),("user",): ("The enabled built-in store: 'user' for user profile.",- "TARGET: only 'user' is enabled for user profile facts (name, role, preferences, style).",- ),-}+ "TARGET: only 'user' is enabled for user profile facts (name, role, preferences, style).")}def _build_memory_schema_overrides() -> Dict[str, Any]:@@ -377,8 +366,7 @@ def _build_memory_schema_overrides() -> Dict[str, Any]:description = description.replace("TARGETS: 'user' = who the user is (name, role, preferences, style). 'memory' = your ""notes (environment, conventions, tool quirks, lessons).",- replacement,- )+ replacement)return {"description": description, "parameters": parameters}@@ -390,14 +378,8 @@ registry.register(toolset="memory",schema=MEMORY_SCHEMA,handler=lambda args, **kw: memory_tool(- action=args.get("action", ""),- target=args.get("target", "memory"),- content=args.get("content"),- old_text=args.get("old_text"),- new_text=args.get("new_text"),- operations=args.get("operations"),- store=kw.get("store")),+ action=args.get("action", ""), target=args.get("target", "memory"), store=kw.get("store"),+ **{k: args.get(k) for k in ("content", "old_text", "new_text", "operations")}),check_fn=check_memory_requirements,emoji="🧠",- dynamic_schema_overrides=_build_memory_schema_overrides,-)+ dynamic_schema_overrides=_build_memory_schema_overrides)diff --git a/tools/memory_tool_store.py b/tools/memory_tool_store.pyindex b5cffcdf0a8..242e2058544 100644--- a/tools/memory_tool_store.py+++ b/tools/memory_tool_store.py@@ -18,9 +18,7 @@ logger = logging.getLogger("tools.memory_tool")# agent/conversation_compression.py uses them to detect a leftover block for a# target whose entries have since been emptied — keep in lockstep.MEMORY_BLOCK_HEADERS = {- "memory": "MEMORY (your personal notes)",- "user": "USER PROFILE (who the user is)",-}+ "memory": "MEMORY (your personal notes)", "user": "USER PROFILE (who the user is)"}ENTRY_DELIMITER = "\n§\n"@@ -53,8 +51,7 @@ def _drift_error(path: "Path", bak_path: str) -> Dict[str, Any]:"remediation": ("Open the .bak file, integrate the missing entries into the memory tool one at a time via ""memory(action=add, content=...), then remove or rewrite the original file to a clean state."- ),- }+ )}def _read_failed_error(path: "Path") -> Dict[str, Any]:@@ -64,8 +61,7 @@ def _read_failed_error(path: "Path") -> Dict[str, Any]:f"Refusing to write {path.name}: the file exists on disk but could not be read right now "f"(temporarily locked by another program, a permission change, invalid/corrupt text encoding, "f"or a filesystem error). Treating an unreadable file as empty and saving would wipe existing "- f"memory, so the write is refused. Nothing was changed — retry in a moment."- )}+ f"memory, so the write is refused. Nothing was changed — retry in a moment.")}def _find_unique_match(entries: List[str], old_text: str) -> Tuple[Optional[int], bool]:@@ -122,8 +118,7 @@ class MemoryStore:return {"success": False, "done": True, "error": (f"Memory consolidation failed {self._consolidation_failures} times this turn. Stop retrying ""memory calls — leave memory unchanged for now and continue with your reply to the user. "- "The fact can be saved in a later turn."- )}+ "The fact can be saved in a later turn.")}def load_from_disk(self):"""Load MEMORY.md / USER.md and capture the frozen system-prompt snapshot.@@ -174,20 +169,20 @@ class MemoryStore:yieldreturnfd = open(lock_path, "a+", encoding="utf-8")- try:++ def _flock(unlock: bool):if fcntl:- fcntl.flock(fd, fcntl.LOCK_EX)+ fcntl.flock(fd, fcntl.LOCK_UN if unlock else fcntl.LOCK_EX)else:fd.seek(0)- msvcrt.locking(fd.fileno(), msvcrt.LK_LOCK, 1)+ msvcrt.locking(fd.fileno(), msvcrt.LK_UNLCK if unlock else msvcrt.LK_LOCK, 1)++ try:+ _flock(False)yieldfinally:try:- if fcntl:- fcntl.flock(fd, fcntl.LOCK_UN)- else:- fd.seek(0)- msvcrt.locking(fd.fileno(), msvcrt.LK_UNLCK, 1)+ _flock(True)except OSError:passfd.close()@@ -221,10 +216,7 @@ class MemoryStore:return self.user_entries if target == "user" else self.memory_entriesdef _set_entries(self, target: str, entries: List[str]):- if target == "user":- self.user_entries = entries- else:- self.memory_entries = entries+ setattr(self, "user_entries" if target == "user" else "memory_entries", entries)def _char_count(self, target: str) -> int:return len(ENTRY_DELIMITER.join(self._entries_for(target)))@@ -252,8 +244,7 @@ class MemoryStore:return None, self._consolidation_failure({"success": False,"error": f"No entry matched '{old_text}'. Check current_entries below and retry with the exact text of the entry you want to {verb}.",- "current_entries": entries,- })+ "current_entries": entries})return idx, Nonedef _commit(self, target: str, entries: List[str], message: str) -> Dict[str, Any]:@@ -285,8 +276,7 @@ class MemoryStore:f"Memory at {self._char_count(target):,}/{limit:,} chars. Adding this entry "f"({len(content)} chars) would exceed the limit. Consolidate now: use 'replace' to merge "f"overlapping entries into shorter ones or 'remove' stale or less important entries (see "- f"current_entries below), then retry this add — all in this turn."- ))+ f"current_entries below), then retry this add — all in this turn."))entries.append(content)return self._commit(target, entries, "Entry added.")@@ -315,8 +305,7 @@ class MemoryStore:return self._failure_with_entries(target, (f"Replacement would put memory at {new_total:,}/{limit:,} chars. Shorten the new content, "f"or 'remove' other stale or less important entries to make room (see current_entries "- f"below), then retry — all in this turn."- ))+ f"below), then retry — all in this turn."))entries[idx] = new_contentreturn self._commit(target, entries, "Entry replaced.")@@ -406,8 +395,7 @@ class MemoryStore:return self._failure_with_entries(target, (f"After applying all {len(operations)} operations, memory would be at "f"{new_total:,}/{limit:,} chars -- over the limit. Remove or shorten more "- f"entries in the same batch (see current_entries below), then retry."- ))+ f"entries in the same batch (see current_entries below), then retry."))return self._commit(target, working, f"Applied {len(operations)} operation(s).")def format_for_system_prompt(self, target: str) -> Optional[str]:diff --git a/tools/microsoft_graph_auth.py b/tools/microsoft_graph_auth.pyindex f58eac5f16b..b2fbc73a5fe 100644--- a/tools/microsoft_graph_auth.py+++ b/tools/microsoft_graph_auth.py@@ -41,9 +41,7 @@ def format_graph_error(error: Any) -> str | None:if not isinstance(error, dict):return Nonecode, message = error.get("code"), error.get("message")- if code and message:- return f"{code}: {message}"- return str(message) if message else None+ return f"{code}: {message}" if code and message else (str(message) if message else None)@dataclass(frozen=True)@@ -75,8 +73,7 @@ class GraphCredentials:return cls(*values,scope=(env.get("MSGRAPH_SCOPE") or DEFAULT_GRAPH_SCOPE).strip(),- authority_url=(env.get("MSGRAPH_AUTHORITY_URL") or DEFAULT_GRAPH_AUTHORITY_URL).strip(),- )+ authority_url=(env.get("MSGRAPH_AUTHORITY_URL") or DEFAULT_GRAPH_AUTHORITY_URL).strip())@dataclass@@ -128,8 +125,7 @@ class MicrosoftGraphTokenProvider:"cached": bool(cached),"expires_in_seconds": cached.expires_in_seconds if cached else None,"is_expired": cached.is_expired(skew_seconds=0) if cached else None,- "refresh_skew_seconds": self.skew_seconds,- }+ "refresh_skew_seconds": self.skew_seconds}def _fresh_cached(self) -> CachedAccessToken | None:"""The cached token unless it expires within ``skew_seconds``."""@@ -145,28 +141,24 @@ class MicrosoftGraphTokenProvider:async with self._lock:if not force_refresh and (cached := self._fresh_cached()):return cached.access_token- token = await self._fetch_access_token()- self._cached_token = token- return token.access_token+ self._cached_token = await self._fetch_access_token()+ return self._cached_token.access_tokenasync def _fetch_access_token(self) -> CachedAccessToken:data = {"grant_type": "client_credentials","client_id": self.credentials.client_id,"client_secret": self.credentials.client_secret,- "scope": self.credentials.scope,- }+ "scope": self.credentials.scope}async with httpx.AsyncClient(timeout=httpx.Timeout(self.timeout), transport=self._transport) as client:response = await client.post(self.credentials.token_url, data=data,- headers={"Content-Type": "application/x-www-form-urlencoded"},- )+ headers={"Content-Type": "application/x-www-form-urlencoded"})if response.status_code >= 400:raise MicrosoftGraphTokenError("Microsoft Graph token request failed with HTTP "- f"{response.status_code}: {_extract_error_detail(response)}"- )+ f"{response.status_code}: {_extract_error_detail(response)}")try:payload = response.json()except ValueError as exc:@@ -185,8 +177,7 @@ class MicrosoftGraphTokenProvider:return CachedAccessToken(access_token=access_token,token_type=str(payload.get("token_type") or "Bearer").strip() or "Bearer",- expires_at=time.time() + max(0, expires_in_seconds),- )+ expires_at=time.time() + max(0, expires_in_seconds))def _extract_error_detail(response: httpx.Response) -> str:diff --git a/tools/microsoft_graph_client.py b/tools/microsoft_graph_client.pyindex ab8842dcf43..25a1aa40e55 100644--- a/tools/microsoft_graph_client.py+++ b/tools/microsoft_graph_client.py@@ -5,16 +5,12 @@ from __future__ import annotationsimport asyncioimport osfrom pathlib import Path-from typing import Any, AsyncIterator, Awaitable, Callable+from typing import Any, Awaitable, Callableimport httpxfrom agent.retry_utils import parse_retry_after_seconds-from tools.microsoft_graph_auth import (- GraphCredentials,- MicrosoftGraphTokenProvider,- format_graph_error,-)+from tools.microsoft_graph_auth import GraphCredentials, MicrosoftGraphTokenProvider, format_graph_errorDEFAULT_GRAPH_BASE_URL = "https://graph.microsoft.com/v1.0"@@ -32,8 +28,7 @@ class MicrosoftGraphAPIError(MicrosoftGraphClientError):def __init__(self, status_code: int, method: str, url: str, message: str, *,- retry_after_seconds: float | None = None, payload: Any = None,- ) -> None:+ retry_after_seconds: float | None = None, payload: Any = None) -> None:self.status_code = status_codeself.method = methodself.url = url@@ -55,8 +50,7 @@ class MicrosoftGraphClient:base_url: str = DEFAULT_GRAPH_BASE_URL, timeout: float = 60.0, max_retries: int = 3,transport: httpx.AsyncBaseTransport | None = None,sleep: Callable[[float], Awaitable[None]] | None = None,- user_agent: str = "Hermes-Agent/graph-client",- ) -> None:+ user_agent: str = "Hermes-Agent/graph-client") -> None:self.token_provider = token_providerself.base_url = base_url.rstrip("/")self.timeout = timeout@@ -87,9 +81,10 @@ class MicrosoftGraphClient:return {"deleted": True, "status_code": response.status_code}return self._decode_json(response)- async def iterate_pages(- self, path: str, *, params: Params = None, headers: Headers = None- ) -> AsyncIterator[dict[str, Any]]:+ async def collect_paginated(+ self, path: str, *, params: Params = None, headers: Headers = None) -> list[Any]:+ """Follow ``@odata.nextLink`` and concatenate every page's ``value`` list."""+ items: list[Any] = []# Query params go on the first request only; @odata.nextLink already embeds them.next_url: str | None = self._resolve_url(path)next_params = dict(params or {})@@ -98,20 +93,10 @@ class MicrosoftGraphClient:payload = self._decode_json(response)if not isinstance(payload, dict):raise MicrosoftGraphClientError(- f"Expected paginated Graph response dict, got {type(payload).__name__}."- )- yield payload- next_url = payload.get("@odata.nextLink")- next_params = {}-- async def collect_paginated(- self, path: str, *, params: Params = None, headers: Headers = None- ) -> list[Any]:- items: list[Any] = []- async for page in self.iterate_pages(path, params=params, headers=headers):- value = page.get("value")- if isinstance(value, list):- items.extend(value)+ f"Expected paginated Graph response dict, got {type(payload).__name__}.")+ if isinstance(payload.get("value"), list):+ items.extend(payload["value"])+ next_url, next_params = payload.get("@odata.nextLink"), {}return itemsasync def download_to_file(@@ -147,8 +132,7 @@ class MicrosoftGraphClient:async def _request(self, method: str, path_or_url: str, *,- params: Params = None, json_body: Any | None = None, headers: Headers = None,- ) -> httpx.Response:+ params: Params = None, json_body: Any | None = None, headers: Headers = None) -> httpx.Response:url = self._resolve_url(path_or_url)async def perform(client: httpx.AsyncClient, request_headers: dict[str, str]):@@ -160,8 +144,7 @@ class MicrosoftGraphClient:async def _with_retries(self, method: str, url: str, accept: str, json_body: Any | None, headers: Headers,perform: Callable[[httpx.AsyncClient, dict[str, str]], Awaitable[tuple[httpx.Response, Any]]],- kind: str,- ) -> Any:+ kind: str) -> Any:"""Run ``perform`` (returning ``(response, result)``) under the retry policy.``kind`` ("request"/"download") only labels the transport-failure messages.@@ -175,8 +158,7 @@ class MicrosoftGraphClient:token = await self.token_provider.get_access_token(force_refresh=attempt > 0and isinstance(last_error, MicrosoftGraphAPIError)- and last_error.status_code == 401- )+ and last_error.status_code == 401)request_headers = {"Authorization": f"Bearer {token}", "Accept": accept, "User-Agent": self.user_agent}if json_body is not None:request_headers["Content-Type"] = "application/json"@@ -190,8 +172,7 @@ class MicrosoftGraphClient:last_error = excif attempt >= self.max_retries:raise MicrosoftGraphClientError(- f"Microsoft Graph {kind} failed for {method} {url}: {exc}"- ) from exc+ f"Microsoft Graph {kind} failed for {method} {url}: {exc}") from excawait self._sleep(self._retry_delay(None, attempt))attempt += 1continue@@ -224,29 +205,20 @@ class MicrosoftGraphClient:except ValueError as exc:raise MicrosoftGraphClientError("Microsoft Graph response was not valid JSON for "- f"{response.request.method} {response.request.url}"- ) from exc+ f"{response.request.method} {response.request.url}") from exc@staticmethoddef _retry_delay(response: httpx.Response | None, attempt: int) -> float:- if response is not None:- retry_after = parse_retry_after_seconds(response.headers)- if retry_after is not None:- return retry_after- return min(8.0, 0.5 * (2 ** attempt))+ retry_after = parse_retry_after_seconds(response.headers) if response is not None else None+ return min(8.0, 0.5 * (2 ** attempt)) if retry_after is None else retry_after@staticmethoddef _build_api_error(method: str, url: str, response: httpx.Response) -> MicrosoftGraphAPIError:- message = response.text.strip() or "unknown error"try:payload: Any = response.json()except ValueError:payload = None- if isinstance(payload, dict):- detail = format_graph_error(payload.get("error"))- if detail is not None:- message = detail+ detail = format_graph_error(payload.get("error")) if isinstance(payload, dict) else Nonereturn MicrosoftGraphAPIError(- response.status_code, method, url, message,- retry_after_seconds=parse_retry_after_seconds(response.headers), payload=payload,- )+ response.status_code, method, url, detail if detail is not None else (response.text.strip() or "unknown error"),+ retry_after_seconds=parse_retry_after_seconds(response.headers), payload=payload)diff --git a/tools/session_search_tool.py b/tools/session_search_tool.pyindex 5a8ff6fd4da..d8d25c8c413 100644--- a/tools/session_search_tool.py+++ b/tools/session_search_tool.py@@ -19,11 +19,9 @@ from tools.session_search_tool_common import ( # noqa: F401 (re-exports)_annotate_rebuild_status, _format_timestamp, _get_message_storage_state,_is_compacted_message, _is_compacted_state, _is_compaction_summary,_ok, _order_for_recall, _quiet, _resolve_lineage, _resolve_to_parent, _session_end_reason,- _session_left_live_context, _session_link, _session_meta_block, _shape_message,-)+ _session_left_live_context, _session_link, _session_meta_block, _shape_message)from tools.session_search_tool_discover import ( # noqa: F401 (re-exports)- _discover, _normalize_title_query, _title_match_result,-)+ _discover, _normalize_title_query, _title_match_result)def _resolve_profile_db(profile: str):@@ -110,13 +108,10 @@ def _list_recent_sessions(db, limit: int, current_session_id: str = None, link_psessions = db.list_sessions_rich(limit=limit + 15, # extra so we can skip current / compression rootsexclude_sources=list(_HIDDEN_SESSION_SOURCES),- order_by_last_active=True,- )+ order_by_last_active=True)current_root, has_compression_hop = (- _resolve_to_parent(db, current_session_id)- if current_session_id else (None, False)- )+ _resolve_to_parent(db, current_session_id) if current_session_id else (None, False))results = []for s in sessions:sid = s.get("id", "")@@ -131,8 +126,7 @@ def _list_recent_sessions(db, limit: int, current_session_id: str = None, link_p"session_id": sid, "link": _session_link(sid, link_profile), "title": s.get("title") or None,"source": s.get("source", ""), "started_at": s.get("started_at", ""),"last_active": s.get("last_active", ""), "message_count": s.get("message_count", 0),- "preview": s.get("preview", ""),- })+ "preview": s.get("preview", "")})if len(results) >= limit:breakreturn _ok(mode="browse", results=results, count=len(results), message=(@@ -165,10 +159,7 @@ def _anchor_in_live_context(db, anchor_state, anchor_session_id: str, current_sereturn False# Rewind/undo rows (active=0, compacted!=1) never count as out-of-context history.is_inactive_non_compacted = (- anchor_state is not None- and anchor_state["active"] == 0- and anchor_state["compacted"] != 1- )+ anchor_state is not None and anchor_state["active"] == 0 and anchor_state["compacted"] != 1)return is_inactive_non_compacted or not _session_left_live_context(db, anchor_session_id)@@ -205,8 +196,7 @@ def _scroll(db, session_id: str, around_message_id: int, window: int = 5,owning_session_id = anchor_state.get("session_id") if anchor_state is not None else Noneif current_session_id and _anchor_in_live_context(- db, anchor_state, owning_session_id or session_id, current_session_id- ):+ db, anchor_state, owning_session_id or session_id, current_session_id):return tool_error("scroll rejected: anchor lives in the current session lineage (already in your active context)", success=False)session_meta = _get_session_meta(db, session_id)@@ -223,8 +213,7 @@ def _scroll(db, session_id: str, around_message_id: int, window: int = 5,rebind_warning = Noneif not messages and owning_session_id and owning_session_id != session_id:rebind_view, rebind_warning = _rebind_to_owner(- db, session_id, owning_session_id, around_message_id, window- )+ db, session_id, owning_session_id, around_message_id, window)if rebind_view is not None:view = rebind_viewmessages = view["window"]@@ -243,8 +232,7 @@ def _scroll(db, session_id: str, around_message_id: int, window: int = 5,"id; backward: the FIRST message's id (the boundary message repeats ""as an orientation marker). messages_before/messages_after < window ""means you've hit that end of the session."),- **({"warning": rebind_warning} if rebind_warning else {}),- )+ **({"warning": rebind_warning} if rebind_warning else {}))def _read_with_profile_fallback(db, sid: str, profile: Optional[str]) -> str:@@ -310,8 +298,7 @@ def _dispatch(query, role_filter, limit, db, current_session_id, session_id,detail_norm = "full" if isinstance(detail, str) and detail.strip().lower() == "full" else "adaptive"return _discover(db=db, query=query.strip(), role_filter=role_list, limit=limit, sort=sort_norm,- detail=detail_norm, current_session_id=current_session_id, link_profile=profile,- )+ detail=detail_norm, current_session_id=current_session_id, link_profile=profile)def session_search(query: str = "", role_filter: str = None, limit: int = 3, db=None,@@ -465,18 +452,8 @@ registry.register(toolset="session_search",schema=SESSION_SEARCH_SCHEMA,handler=lambda args, **kw: session_search(- query=args.get("query") or "",- role_filter=args.get("role_filter"),- limit=args.get("limit", 3),- session_id=args.get("session_id"),- around_message_id=args.get("around_message_id"),- window=args.get("window", 5),- sort=args.get("sort"),- detail=args.get("detail", "adaptive"),- profile=args.get("profile"),- db=kw.get("db"),- current_session_id=kw.get("current_session_id"),- ),+ query=args.get("query") or "", limit=args.get("limit", 3), window=args.get("window", 5),+ detail=args.get("detail", "adaptive"), db=kw.get("db"), current_session_id=kw.get("current_session_id"),+ **{k: args.get(k) for k in ("role_filter", "session_id", "around_message_id", "sort", "profile")}),check_fn=check_session_search_requirements,- emoji="🔍",-)+ emoji="🔍")diff --git a/tools/session_search_tool_common.py b/tools/session_search_tool_common.pyindex 0a0d2c44f02..f9613796ea5 100644--- a/tools/session_search_tool_common.py+++ b/tools/session_search_tool_common.py@@ -118,9 +118,9 @@ def _session_end_reason(db, session_id: str) -> Optional[str]:return Nonetry:s = db.get_session(session_id)- return (s.get("end_reason") or None) if s else Noneexcept Exception:return None+ return (s.get("end_reason") or None) if s else Nonedef _session_left_live_context(db, session_id: str) -> bool:@@ -176,8 +176,7 @@ def _annotate_rebuild_status(db, payload: Dict[str, Any]) -> None:payload["index_rebuild"] = {"percent": status["percent"], "note": (f"The search index is rebuilding in the background ({status['percent']}% done, "f"{status['indexed']:,} of {status['total']:,} messages). Results from older messages "- f"may be incomplete until it finishes."- )}+ f"may be incomplete until it finishes.")}def _order_for_recall(raw_results: List[Dict[str, Any]]) -> List[Dict[str, Any]]:diff --git a/tools/session_search_tool_discover.py b/tools/session_search_tool_discover.pyindex 08ba5264210..4867f3d4216 100644--- a/tools/session_search_tool_discover.py+++ b/tools/session_search_tool_discover.py@@ -9,8 +9,7 @@ from tools.registry import tool_errorfrom tools.session_search_tool_common import (_DISCOVER_SCAN_LIMIT, _DISCOVER_SEARCH_FIELDS, _HIDDEN_SESSION_SOURCES, _annotate_rebuild_status,_format_timestamp, _is_compacted_message, _is_compaction_summary, _order_for_recall, _quiet,- _resolve_lineage, _resolve_to_parent, _session_left_live_context, _session_link, _shape_message,-)+ _resolve_lineage, _resolve_to_parent, _session_left_live_context, _session_link, _shape_message)def _normalize_title_query(query: str) -> str:@@ -33,8 +32,7 @@ def _title_match_result(db, query: str, current_lineage_root: Optional[str]) ->if (current_lineage_rootand lineage_root == current_lineage_root- and not _session_left_live_context(db, session_id)- ):+ and not _session_left_live_context(db, session_id)):return Nonesession_meta = _quiet(lambda: db.get_session(lineage_root) or db.get_session(session_id), None,@@ -58,8 +56,7 @@ def _title_match_result(db, query: str, current_lineage_root: Optional[str]) ->"bookend_end": [_shape_message(m) for m in (view.get("bookend_end") or messages[-3:])],"messages_before": view.get("messages_before", 0),"messages_after": view.get("messages_after", max(len(messages) - 5, 0)),- "detail": "full", "_lineage_root": lineage_root,- }+ "detail": "full", "_lineage_root": lineage_root}if lineage_root and lineage_root != session_id:entry["parent_session_id"] = lineage_rootreturn entry@@ -92,8 +89,7 @@ def _dedupe_by_lineage(db, raw_results, limit, seen_sessions, current_session_idif (current_lineage_rootand resolved_sid == current_lineage_root- and not (is_ended_session or is_compacted_hit)- ):+ and not (is_ended_session or is_compacted_hit)):continueif current_session_id and raw_sid == current_session_id and not is_compacted_hit:continue@@ -131,8 +127,7 @@ def _hydrate_hit(db, lineage_root: str, match_info: Dict[str, Any], result_detai"messages": [_shape_message(m, anchor_id=msg_id, max_content_len=4000) for m in window_messages],"bookend_end": _bookend(view, "bookend_end") if full else [],"messages_before": view.get("messages_before", 0), "messages_after": view.get("messages_after", 0),- "detail": result_detail,- }+ "detail": result_detail}if lineage_root and lineage_root != hit_sid:entry["parent_session_id"] = lineage_rootreturn entry@@ -148,8 +143,7 @@ def _discover(db, query: str, role_filter: Optional[List[str]], limit: int, sorttry:raw_results = db.search_messages(query=query, role_filter=role_list, exclude_sources=list(_HIDDEN_SESSION_SOURCES),- limit=_DISCOVER_SCAN_LIMIT, offset=0, sort=sort, fields=_DISCOVER_SEARCH_FIELDS,- )+ limit=_DISCOVER_SCAN_LIMIT, offset=0, sort=sort, fields=_DISCOVER_SEARCH_FIELDS)except Exception as e:logging.error("FTS5 search failed: %s", e, exc_info=True)return tool_error(f"Search failed: {e}", success=False)@@ -162,8 +156,7 @@ def _discover(db, query: str, role_filter: Optional[List[str]], limit: int, sortreturn _discover_payload(db, query, detail, [], message=("No matching sessions found. FTS5 ANDs all terms by default — ""broaden with OR (`alpha OR beta`), exact-match with quoted "- "phrases, exclude with NOT, or prefix-match with `deploy*`."- ))+ "phrases, exclude with NOT, or prefix-match with `deploy*`."))seen_sessions: Dict[str, Dict[str, Any]] = {}results = []@@ -188,5 +181,4 @@ def _discover(db, query: str, role_filter: Optional[List[str]], limit: int, sort"verbatim inline mid-sentence (it renders as a titled link) — never ""as markdown, in backticks, on its own line, or next to the ""title/id/date. To read more around a compact result, scroll: "- "session_search(session_id=..., around_message_id=match_message_id)."- ))+ "session_search(session_id=..., around_message_id=match_message_id)."))