session_recap.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. """Session recap — summarize the current session from in-memory history. Pure local computation: no
  2. LLM call, no auxiliary model, no prompt-cache invalidation. A recap should be instant and free."""
  3. from __future__ import annotations
  4. import json
  5. import os
  6. from collections import Counter
  7. from typing import Any, Iterable, List, Mapping, Optional, Sequence, Tuple
  8. from tools.ansi_strip import sanitize_display_text
  9. _RECENT_TURN_WINDOW = 20 # user/assistant turns considered "recent activity"
  10. _PROMPT_PREVIEW_CHARS = 140
  11. _ASSISTANT_PREVIEW_CHARS = 200
  12. _MAX_FILES_LISTED = 5
  13. # File-touching tool name -> argument key holding the path.
  14. _FILE_EDIT_TOOLS: Mapping[str, str] = {
  15. "write_file": "path", "patch": "path", "read_file": "path",
  16. "skill_manage": "file_path", "skill_view": "file_path",
  17. }
  18. def _coerce_text(value: Any) -> str:
  19. """Flatten ``content`` (string, or list of blocks whose text-like parts are joined) into a string."""
  20. if value is None:
  21. return ""
  22. if isinstance(value, str):
  23. return value
  24. if not isinstance(value, list):
  25. return str(value)
  26. parts: list[str] = []
  27. for block in value:
  28. text = block if isinstance(block, str) else block.get("text") if isinstance(block, Mapping) else None
  29. if isinstance(text, str) and (text or isinstance(block, str)):
  30. parts.append(text)
  31. return "\n".join(parts)
  32. def _tool_call_name_and_args(tool_call: Any) -> tuple[str, Mapping[str, Any]]:
  33. """``(name, arguments_dict)`` from a tool_call; ``arguments`` may be a JSON string or dict ({} if unparsable)."""
  34. fn = tool_call.get("function") if isinstance(tool_call, Mapping) else None
  35. if not isinstance(fn, Mapping):
  36. return "", {}
  37. name = str(fn.get("name") or "")
  38. raw_args = fn.get("arguments")
  39. if isinstance(raw_args, str) and raw_args:
  40. try:
  41. raw_args = json.loads(raw_args)
  42. except Exception:
  43. return name, {}
  44. return name, raw_args if isinstance(raw_args, Mapping) else {}
  45. def _iter_assistant_tool_calls(messages: Sequence[Mapping[str, Any]]) -> Iterable[tuple[str, Mapping[str, Any]]]:
  46. for msg in messages:
  47. if not isinstance(msg, Mapping) or msg.get("role") != "assistant":
  48. continue
  49. tool_calls = msg.get("tool_calls") or []
  50. for tc in tool_calls if isinstance(tool_calls, list) else ():
  51. name, args = _tool_call_name_and_args(tc)
  52. if name:
  53. yield name, args
  54. def _count_visible_turns(messages: Sequence[Mapping[str, Any]]) -> tuple[int, int, int]:
  55. """Return ``(user_turn_count, assistant_turn_count, tool_message_count)``."""
  56. roles = Counter(msg.get("role") for msg in messages if isinstance(msg, Mapping))
  57. return roles["user"], roles["assistant"], roles["tool"]
  58. def _latest_text(messages: Sequence[Mapping[str, Any]], role: str) -> Optional[str]:
  59. """Most recent non-empty ``content`` text for *role*, or None."""
  60. for msg in reversed(messages):
  61. if isinstance(msg, Mapping) and msg.get("role") == role:
  62. text = _coerce_text(msg.get("content")).strip()
  63. if text:
  64. return text
  65. return None
  66. def _recent_window(
  67. messages: Sequence[Mapping[str, Any]], window: int = _RECENT_TURN_WINDOW
  68. ) -> list[Mapping[str, Any]]:
  69. """Tail slice covering at most ``window`` user+assistant turns (tool messages ride along)."""
  70. count = 0
  71. for i in range(len(messages) - 1, -1, -1):
  72. if isinstance(messages[i], Mapping) and messages[i].get("role") in {"user", "assistant"}:
  73. count += 1
  74. if count >= window:
  75. return list(messages[i:])
  76. return list(messages)
  77. def _shortened_path(path: str) -> str:
  78. """Show a path relative to cwd when possible, otherwise with ~ expansion."""
  79. if not path:
  80. return path
  81. try:
  82. abs_path = os.path.abspath(os.path.expanduser(path))
  83. cwd, home = os.getcwd(), os.path.expanduser("~")
  84. if abs_path == cwd:
  85. return "."
  86. if abs_path.startswith(cwd + os.sep):
  87. return abs_path[len(cwd) + 1 :]
  88. if abs_path.startswith(home + os.sep):
  89. return "~/" + abs_path[len(home) + 1 :]
  90. return abs_path
  91. except Exception:
  92. return path
  93. def _summarise_tool_activity(
  94. tool_calls: Sequence[tuple[str, Mapping[str, Any]]],
  95. ) -> tuple[list[tuple[str, int]], list[str]]:
  96. """``(tool_counts_sorted_desc, recently_edited_files)`` — files are distinct paths, newest first."""
  97. counter: Counter[str] = Counter()
  98. files_seen: dict[str, str] = {} # raw path -> shortened, insertion ordered
  99. for name, args in reversed(list(tool_calls)): # reversed so files_seen comes out newest -> oldest
  100. counter[name] += 1
  101. path = args.get(_FILE_EDIT_TOOLS[name]) if name in _FILE_EDIT_TOOLS else None
  102. if isinstance(path, str) and path and path not in files_seen:
  103. files_seen[path] = _shortened_path(path)
  104. return sorted(counter.items(), key=lambda kv: (-kv[1], kv[0])), list(files_seen.values())
  105. def _join_capped(items: list[str], limit: int) -> str:
  106. """``a, b, c (+N more)`` — comma-join the first *limit* items and count the rest."""
  107. text = ", ".join(items[:limit])
  108. extra = len(items) - limit
  109. return f"{text} (+{extra} more)" if extra > 0 else text
  110. def _truncate(text: str, limit: int) -> str:
  111. # Stored history is untrusted for display: strip escapes/control chars so a recap line can't clear
  112. # the screen or retitle the window when echoed to a terminal.
  113. text = " ".join(sanitize_display_text(text).split()) # collapse newlines for a compact one-liner
  114. return text if len(text) <= limit else text[: limit - 1].rstrip() + "…"
  115. def build_recap(
  116. messages: Sequence[Mapping[str, Any]], *, session_title: Optional[str] = None, session_id: Optional[str] = None,
  117. platform: Optional[str] = None,
  118. ) -> str:
  119. """Multi-line plain-text recap of recent activity (80-col terminal / gateway bubble friendly).
  120. ``platform`` is accepted for forward compat and does not change behavior."""
  121. lines: list[str] = ["Session recap"]
  122. if session_title or session_id:
  123. lines[0] += f" — {session_title or session_id[:8]}"
  124. if not messages:
  125. lines.append(" (nothing to recap — no messages yet)")
  126. return "\n".join(lines)
  127. users, assistants, tool_msgs = _count_visible_turns(messages)
  128. window = _recent_window(messages)
  129. win_users, win_assistants, _ = _count_visible_turns(window)
  130. scope = (
  131. f"{win_users} user turn{'s' if win_users != 1 else ''} / "
  132. f"{win_assistants} assistant repl{'ies' if win_assistants != 1 else 'y'}"
  133. )
  134. if (users, assistants) != (win_users, win_assistants):
  135. scope += f" (of {users}/{assistants} total)"
  136. lines.append(f" Recent: {scope}, {tool_msgs} tool result{'s' if tool_msgs != 1 else ''}")
  137. tool_calls = list(_iter_assistant_tool_calls(window))
  138. tool_counts, files = _summarise_tool_activity(tool_calls)
  139. if tool_counts:
  140. top = _join_capped([f"{name}×{count}" for name, count in tool_counts], 5)
  141. lines.append(f" Tools used: {top}")
  142. if files:
  143. lines.append(f" Files touched: {_join_capped(files, _MAX_FILES_LISTED)}")
  144. previews = (("user", "Last ask", _PROMPT_PREVIEW_CHARS), ("assistant", "Last reply", _ASSISTANT_PREVIEW_CHARS))
  145. for role, label, limit in previews:
  146. latest = _latest_text(window, role)
  147. if latest:
  148. lines.append(f" {label}: {_truncate(latest, limit)}")
  149. if len(lines) == 2: # only header + scope line: nothing substantive to show
  150. lines.append(" (no assistant activity yet in this window)")
  151. return "\n".join(lines)
  152. __all__ = ["build_recap"]