Skip to content

The agent that grows with you

refactor(agent/coding_context,context_breakdown,context_engine): compact prose, unify helpers, table dispatch (1423->1059 LOC)

Teknium7a9e36f226b5
diff --git a/agent/coding_context.py b/agent/coding_context.py
index ce8f6c8cd34..43fb33d4b75 100644
--- a/agent/coding_context.py
+++ b/agent/coding_context.py
@@ -1,29 +1,11 @@
-"""Coding-context awareness — base Hermes, every interactive surface.
-
-When Hermes runs inside a code workspace (CLI, TUI, desktop, ACP editor) it
-shifts into a **coding posture**. This module is the single place that decides
-whether we're in that posture and what it implies, so nothing else re-derives
-"are we coding?". The posture is a frozen :class:`RuntimeMode` selected from a
-small :class:`ContextProfile` registry (``coding`` / ``general``); a profile is
-*data* (toolset, operating brief, skill-index hints) that every domain reads:
-
- * System prompt — ``RuntimeMode.system_prompt_parts()`` → operating brief +
- live git/workspace snapshot (``agent/system_prompt.py``).
- * Toolset — ``RuntimeMode.toolset_selection()`` → ``coding`` toolset + enabled
- MCP servers, ONLY under the opt-in ``focus`` mode. The default posture is
- prompt-only and never strips a toolset the user explicitly enabled.
- * Delegation — subagents inherit the toolset and prompt builder, so the
- posture propagates for free.
-
-Cache safety: the mode is resolved once and immutable; the workspace snapshot
-is built once at prompt-build time and never re-probed per turn (the brief
-tells the model to re-check with ``git``). A ``/coding`` flip takes effect next
-session.
-
-Activation (config ``agent.coding_context``): ``auto`` (default) — posture on an
-interactive surface in a code workspace, prompt-only; ``focus`` — also collapse
-the toolset and demote non-coding skill categories to names-only (never
-hidden); ``on`` — force the posture anywhere; ``off`` — disable.
+"""Coding-context awareness: the single place that decides "are we coding?".
+
+In a code workspace on an interactive surface Hermes adopts a **coding posture**: a
+frozen :class:`RuntimeMode` built from a :class:`ContextProfile` (pure data). The
+system prompt reads ``system_prompt_parts()``; the toolset collapses ONLY under opt-in
+``focus`` (never strips a user-enabled toolset). ``agent.coding_context``: ``auto``
+(default, prompt-only) / ``focus`` / ``on`` / ``off``. Resolved once, immutable; the
+workspace snapshot is never re-probed per turn (cache safety).
"""
from __future__ import annotations
@@ -43,89 +25,41 @@ logger = logging.getLogger("hermes.coding_context")
CODING_TOOLSET = "coding"
-# Surfaces where a coding posture makes sense under ``auto``. Messaging
-# platforms are intentionally absent — a chat bot in a group is not pairing.
+# Surfaces where ``auto`` may adopt the posture; messaging platforms are deliberately absent.
INTERACTIVE_CODING_PLATFORMS = {"cli", "tui", "acp", "desktop", ""}
-
-# Project-root signals that mark a directory as a code workspace even when it
-# isn't (yet) a git repo. Cheap filename checks — no parsing.
+# Project-root signals (cheap filename checks) marking a code workspace even without git.
_PROJECT_MARKERS = (
- "pyproject.toml", "setup.py", "setup.cfg", "requirements.txt",
- "package.json", "tsconfig.json", "deno.json",
- "Cargo.toml", "go.mod", "pom.xml", "build.gradle", "build.gradle.kts",
- "Gemfile", "composer.json", "mix.exs", "pubspec.yaml",
- "CMakeLists.txt", "Makefile", "Dockerfile",
- "AGENTS.md", "CLAUDE.md", ".cursorrules",
+ "pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "package.json", "tsconfig.json", "deno.json",
+ "Cargo.toml", "go.mod", "pom.xml", "build.gradle", "build.gradle.kts", "Gemfile", "composer.json", "mix.exs",
+ "pubspec.yaml", "CMakeLists.txt", "Makefile", "Dockerfile", "AGENTS.md", "CLAUDE.md", ".cursorrules",
)
-
# Agent-instruction files surfaced separately from manifests in the snapshot.
_CONTEXT_FILES = ("AGENTS.md", "CLAUDE.md", ".cursorrules")
-# Source extensions that make a manifest-less git repo a *code* workspace, so
-# `git init` on a notes/writing folder does not flip the session into coding.
+# Extensions that make a manifest-less git repo a *code* workspace (a `git init` notes folder is not).
_CODE_EXTENSIONS = frozenset({
- ".py", ".pyi", ".ipynb", ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs",
- ".go", ".rs", ".java", ".kt", ".kts", ".scala", ".rb", ".php", ".c", ".h",
- ".cc", ".cpp", ".hpp", ".cs", ".swift", ".m", ".mm", ".dart", ".ex", ".exs",
- ".lua", ".sh", ".bash", ".zsh", ".sql", ".vue", ".svelte", ".r", ".jl",
- ".hs", ".clj", ".erl", ".pl",
+ ".py", ".pyi", ".ipynb", ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".go", ".rs", ".java", ".kt", ".kts",
+ ".scala", ".rb", ".php", ".c", ".h", ".cc", ".cpp", ".hpp", ".cs", ".swift", ".m", ".mm", ".dart", ".ex", ".exs",
+ ".lua", ".sh", ".bash", ".zsh", ".sql", ".vue", ".svelte", ".r", ".jl", ".hs", ".clj", ".erl", ".pl",
})
-
_CODE_SCAN_SKIP_DIRS = frozenset({
- ".git", "node_modules", "venv", ".venv", "__pycache__", "dist", "build",
- "target", ".next", ".turbo", "vendor",
+ ".git", "node_modules", "venv", ".venv", "__pycache__", "dist", "build", "target", ".next", ".turbo", "vendor",
})
# Bounded sweep: a code workspace reveals itself in the first handful of entries.
_CODE_SCAN_MAX_ENTRIES = 500
-
-
-def _has_code_files(root: Path) -> bool:
- """Bounded check for source files in the root and its immediate subdirs."""
- seen = 0
- stack = [(root, True)]
- while stack:
- directory, is_root = stack.pop()
- try:
- with os.scandir(directory) as entries:
- for entry in entries:
- seen += 1
- if seen > _CODE_SCAN_MAX_ENTRIES:
- return False
- name = entry.name
- try:
- if entry.is_file():
- if os.path.splitext(name)[1].lower() in _CODE_EXTENSIONS:
- return True
- elif is_root and entry.is_dir() and name not in _CODE_SCAN_SKIP_DIRS and not name.startswith("."):
- stack.append((Path(entry.path), False))
- except OSError:
- continue
- except OSError:
- continue
- return False
-
-
# Lockfile → package manager, checked in priority order.
_PY_LOCKFILES = (("uv.lock", "uv"), ("poetry.lock", "poetry"), ("Pipfile.lock", "pipenv"))
_JS_LOCKFILES = (
- ("pnpm-lock.yaml", "pnpm"), ("bun.lockb", "bun"), ("bun.lock", "bun"),
- ("yarn.lock", "yarn"), ("package-lock.json", "npm"),
+ ("pnpm-lock.yaml", "pnpm"), ("bun.lockb", "bun"), ("bun.lock", "bun"), ("yarn.lock", "yarn"), ("package-lock.json", "npm"),
)
-
# package.json scripts / Makefile targets worth surfacing as verify commands.
_VERIFY_TARGETS = ("test", "tests", "lint", "typecheck", "check", "build", "fmt", "format")
_MAX_VERIFY_COMMANDS = 8
_MAX_FACT_FILE_BYTES = 256 * 1024
-
_GIT_TIMEOUT = 2.5
-
-
-# Per-model edit-format steering: nudge each family toward the `patch` mode it
-# was trained on (unknown families get nothing). GPT/Codex get V4A for ALL
-# edits incl. single-file — codex-rs ships apply_patch as its ONLY editor and
-# its prompts say to use it even for single files, so a replace-mode nudge
-# would steer them toward a format their first-party harness never taught.
-# Anthropic and most open-weight coding models were RL'd on str_replace-style
+# Per-model edit-format steering toward the `patch` mode each family was trained on (unknown
+# families get nothing). GPT/Codex get V4A for ALL edits incl. single-file: codex-rs ships
+# apply_patch as its ONLY editor. Anthropic and most open-weight coders were RL'd on str_replace
# editors. Substrings match the model id; aligned with TOOL_USE_ENFORCEMENT_MODELS.
_EDIT_FORMAT_GUIDANCE: dict[str, tuple[tuple[str, ...], str]] = {
"patch": (
@@ -145,26 +79,7 @@ _EDIT_FORMAT_GUIDANCE: dict[str, tuple[tuple[str, ...], str]] = {
),
}
-
-def _model_family(model: Optional[str]) -> Optional[str]:
- """Edit-format family key for a model id, or ``None`` (neutral wording applies)."""
- if not model:
- return None
- lowered = model.lower()
- for family, (needles, _line) in _EDIT_FORMAT_GUIDANCE.items():
- if any(n in lowered for n in needles):
- return family
- return None
-
-
-def _edit_format_line(model: Optional[str]) -> str:
- """The edit-format guidance line for this model's family (``""`` if none)."""
- family = _model_family(model)
- return "" if family is None else _EDIT_FORMAT_GUIDANCE[family][1]
-
-
-# Operating brief for the coding posture. Tool names referenced here are in the
-# coding toolset and in _HERMES_CORE_TOOLS, so they exist on every surface this fires on.
+# Operating brief. Tool names referenced here are in the coding toolset and _HERMES_CORE_TOOLS.
CODING_AGENT_GUIDANCE = (
"You are a coding agent pairing with the user inside their codebase. "
"Operate like a careful senior engineer.\n"
@@ -214,27 +129,28 @@ CODING_AGENT_GUIDANCE = (
"`git branch` before relying on it. Be concise: lead with the change or "
"answer, not a preamble."
)
-
_TODO_SENTENCE = (
"- Track multi-step work with `todo_list`. Reference code as "
"`path:line` instead of pasting whole files."
)
_NO_TODO_SENTENCE = "- Reference code as `path:line` instead of pasting whole files."
-
-
-# ── Context profiles (declarative posture definitions) ──────────────────────
+# Clearly non-coding skill categories (deny-list; coding-adjacent and custom ones keep full entries).
+_NON_CODING_SKILL_CATEGORIES = (
+ "apple", "communication", "cooking", "creative", "email", "finance", "gaming", "gifs", "health", "media",
+ "music", "note-taking", "productivity", "shopping", "smart-home", "social-media", "travel", "yuanbao",
+)
+_MODE_ALIASES = {
+ **dict.fromkeys(("focus", "strict", "lean"), "focus"),
+ **dict.fromkeys(("on", "true", "yes", "1", "always"), "on"),
+ **dict.fromkeys(("off", "false", "no", "0", "never"), "off"),
+}
@dataclass(frozen=True)
class ContextProfile:
- """A named operating posture. Pure data — consumers read these fields.
-
- ``toolset``: collapse to this toolset (+ enabled MCP) under ``focus``;
- ``None`` keeps the platform default. ``guidance``: operating brief for the
- stable system prompt. ``model_hint``: routing preference (extension seam).
- ``compact_skill_categories``: categories DEMOTED to names-only in the skill
- index under ``focus`` — deny-list, never hidden, so recall keeps working.
- """
+ """A named operating posture (pure data). ``toolset``: collapse target under ``focus``
+ (``None`` keeps the platform default). ``compact_skill_categories``: DEMOTED to
+ names-only under ``focus`` — deny-list, never hidden, so recall keeps working."""
name: str
toolset: Optional[str] = None
@@ -243,43 +159,22 @@ class ContextProfile:
compact_skill_categories: tuple[str, ...] = ()
-# Clearly non-coding skill categories (deny-list: custom categories keep full
-# entries). Coding-adjacent ones (devops, github, mcp, research, …) are absent.
-_NON_CODING_SKILL_CATEGORIES = (
- "apple", "communication", "cooking", "creative", "email", "finance",
- "gaming", "gifs", "health", "media", "music", "note-taking",
- "productivity", "shopping", "smart-home", "social-media", "travel",
- "yuanbao",
-)
-
-
GENERAL_PROFILE = ContextProfile(name="general")
CODING_PROFILE = ContextProfile(
- name="coding",
- toolset=CODING_TOOLSET,
- guidance=CODING_AGENT_GUIDANCE,
- model_hint="coding",
+ name="coding", toolset=CODING_TOOLSET, guidance=CODING_AGENT_GUIDANCE, model_hint="coding",
compact_skill_categories=_NON_CODING_SKILL_CATEGORIES,
)
-_PROFILES: dict[str, ContextProfile] = {
- GENERAL_PROFILE.name: GENERAL_PROFILE,
- CODING_PROFILE.name: CODING_PROFILE,
-}
-
-
-def get_profile(name: str) -> ContextProfile:
- """Return a registered profile, falling back to ``general``."""
- return _PROFILES.get(name, GENERAL_PROFILE)
+# ── Detection helpers ───────────────────────────────────────────────────────
-# ── Helpers ─────────────────────────────────────────────────────────────────
-
-_MODE_ALIASES = {
- **dict.fromkeys(("focus", "strict", "lean"), "focus"),
- **dict.fromkeys(("on", "true", "yes", "1", "always"), "on"),
- **dict.fromkeys(("off", "false", "no", "0", "never"), "off"),
-}
+def _model_family(model: Optional[str]) -> Optional[str]:
+ """Edit-format family key for a model id, or ``None`` (neutral wording applies)."""
+ lowered = (model or "").lower()
+ for family, (needles, _line) in _EDIT_FORMAT_GUIDANCE.items():
+ if lowered and any(n in lowered for n in needles):
+ return family
+ return None
def _agent_config_value(config: Optional[dict[str, Any]], key: str, default: Any, *, readonly: bool) -> Any:
@@ -287,7 +182,6 @@ def _agent_config_value(config: Optional[dict[str, Any]], key: str, default: Any
if config is None:
try:
from hermes_cli.config import load_config, load_config_readonly
-
config = load_config_readonly() if readonly else load_config()
except Exception:
config = {}
@@ -300,24 +194,11 @@ def _coding_mode(config: Optional[dict[str, Any]]) -> str:
return _MODE_ALIASES.get(str(raw).strip().lower(), "auto")
-def _coding_instructions(config: Optional[dict[str, Any]]) -> str:
- """Standing operator instructions (``agent.coding_instructions``: str or list).
-
- Appended to the brief as an extra stable block so a user can pin
- project-wide workflow rules without editing the shipped brief.
- """
- raw = _agent_config_value(config, "coding_instructions", "", readonly=False)
- if isinstance(raw, (list, tuple)):
- return "\n".join(str(item).strip() for item in raw if str(item).strip())
- return str(raw or "").strip()
-
-
def _resolve_cwd(cwd: Optional[str | Path]) -> Path:
if cwd:
return Path(cwd).expanduser()
try:
from agent.runtime_cwd import resolve_agent_cwd
-
return resolve_agent_cwd()
except Exception:
return Path(os.getcwd())
@@ -325,10 +206,7 @@ def _resolve_cwd(cwd: Optional[str | Path]) -> Path:
def _git_root(cwd: Path) -> Optional[Path]:
current = cwd.resolve()
- for parent in [current, *current.parents]:
- if (parent / ".git").exists():
- return parent
- return None
+ return next((p for p in (current, *current.parents) if (p / ".git").exists()), None)
def _home() -> Optional[Path]:
@@ -339,72 +217,94 @@ def _home() -> Optional[Path]:
def _marker_root(cwd: Path) -> Optional[Path]:
- """Nearest ancestor (≤6 levels) that looks like a project root, or ``None``.
-
- ``$HOME`` and the shared temp root are skipped: a Makefile/AGENTS.md in the
- home dir is global user config, and a stray manifest in /tmp must not flip
- every session whose cwd lives under it into the coding posture.
- """
+ """Nearest ancestor (≤6 levels) that looks like a project root, or ``None``. ``$HOME``
+ and the shared temp root are skipped: a Makefile/AGENTS.md in the home dir is global
+ config, and a stray manifest in /tmp must not flip every session under it."""
current = cwd.resolve()
- home = _home()
try:
temp_root = Path(tempfile.gettempdir()).resolve()
except Exception:
temp_root = None
- for depth, parent in enumerate([current, *current.parents]):
- if depth > 6:
- break
- if parent == home or (temp_root is not None and parent == temp_root):
- continue
- for marker in _PROJECT_MARKERS:
- if (parent / marker).exists():
- return parent
+ skip = (_home(), temp_root)
+ for parent in (current, *current.parents)[:7]:
+ if parent not in skip and any((parent / marker).exists() for marker in _PROJECT_MARKERS):
+ return parent
return None
-def _detect_profile_name(mode: str, platform: str, cwd_str: str) -> str:
- """Resolve which profile applies.
+def _has_code_files(root: Path) -> bool:
+ """Bounded check for source files in the root and its immediate subdirs."""
+ seen = 0
+ stack = [(root, True)]
+ while stack:
+ directory, is_root = stack.pop()
+ try:
+ entries = os.scandir(directory)
+ except OSError:
+ continue
+ with entries:
+ for entry in entries:
+ seen += 1
+ if seen > _CODE_SCAN_MAX_ENTRIES:
+ return False
+ try:
+ if entry.is_file():
+ if os.path.splitext(entry.name)[1].lower() in _CODE_EXTENSIONS:
+ return True
+ elif is_root and entry.is_dir() and entry.name not in _CODE_SCAN_SKIP_DIRS and not entry.name.startswith("."):
+ stack.append((Path(entry.path), False))
+ except OSError:
+ continue
+ return False
+
- ``auto``/``focus``: coding when the surface is interactive AND the cwd is a
- code workspace (project root, or a git repo that actually holds code).
- ``on``: always coding. ``off``: always general. A git repo rooted at
- ``$HOME`` (dotfiles) is NOT a workspace signal. Deliberately not memoized:
- a long-lived gateway/TUI process serves sessions from different cwds.
- """
+def _detect_profile(mode: str, platform: str, cwd: Path) -> ContextProfile:
+ """``auto``/``focus``: coding when the surface is interactive AND the cwd is a code
+ workspace (project root, or a git repo that actually holds code; a repo rooted at
+ ``$HOME`` is NOT a signal). ``on``/``off`` force. Not memoized: one gateway serves many cwds."""
if mode == "off":
- return GENERAL_PROFILE.name
+ return GENERAL_PROFILE
if mode == "on":
- return CODING_PROFILE.name
+ return CODING_PROFILE
if platform and platform.strip().lower() not in INTERACTIVE_CODING_PLATFORMS:
- return GENERAL_PROFILE.name
- cwd = Path(cwd_str)
+ return GENERAL_PROFILE
if _marker_root(cwd) is not None:
- return CODING_PROFILE.name
+ return CODING_PROFILE
git_root = _git_root(cwd)
if git_root is not None and git_root != _home() and _has_code_files(git_root):
- return CODING_PROFILE.name
- return GENERAL_PROFILE.name
+ return CODING_PROFILE
+ return GENERAL_PROFILE
-# ── RuntimeMode (the seam) ──────────────────────────────────────────────────
+def _enabled_mcp_servers(config: Optional[dict[str, Any]]) -> list[str]:
+ """Names of MCP servers the user has enabled — kept in the coding posture."""
+ try:
+ from hermes_cli.config import read_raw_config
+ from hermes_cli.tools_config import _parse_enabled_flag
+ servers = read_raw_config().get("mcp_servers") or {}
+ return [
+ str(name) for name, cfg in servers.items()
+ if isinstance(cfg, dict) and _parse_enabled_flag(cfg.get("enabled", True), default=True)
+ ]
+ except Exception:
+ return []
+# ── RuntimeMode (the seam) ──────────────────────────────────────────────────
+
@dataclass(frozen=True)
class RuntimeMode:
- """The resolved operating posture for a session. Immutable by construction.
-
- Built once via :func:`resolve_runtime_mode`; never re-resolved mid-session
- (that would break the prompt cache).
- """
+ """The resolved operating posture for a session; immutable, built once via
+ :func:`resolve_runtime_mode` and never re-resolved mid-session (prompt cache).
+ ``config_mode``: normalized ``agent.coding_context`` (toolset collapse gated on
+ ``focus``); ``model``: steers edit-format guidance only; ``instructions``:
+ ``agent.coding_instructions``."""
profile: ContextProfile
surface: str
cwd: Path
- # Normalized ``agent.coding_context`` mode; toolset collapse is gated on ``focus``.
config_mode: str = "auto"
- # Model id, used only to steer edit-format guidance (fixed per session).
model: Optional[str] = None
- # ``agent.coding_instructions``, appended as an extra stable block.
instructions: str = ""
@property
@@ -416,27 +316,19 @@ class RuntimeMode:
return self.profile.name == CODING_PROFILE.name
def toolset_selection(self, config: Optional[dict[str, Any]] = None) -> Optional[list[str]]:
- """Toolset list for this posture, or ``None`` to keep the platform default.
-
- Non-``None`` only under ``focus``. Callers apply it only when the user
- hasn't pinned an explicit selection (``--toolsets``, ``HERMES_TUI_TOOLSETS``).
- """
+ """Toolset list (only under ``focus``), or ``None`` to keep the platform default. Callers
+ apply it only when the user hasn't pinned a selection (``--toolsets``, ``HERMES_TUI_TOOLSETS``)."""
if self.config_mode != "focus" or self.profile.toolset is None:
return None
return [self.profile.toolset, *_enabled_mcp_servers(config)]
- def system_prompt_parts(
- self, valid_tool_names=None
- ) -> tuple[list[str], list[str], list[str]]:
- """Return (prefix, workspace, trailing) posture blocks.
-
- The brief carries the model-family edit-format nudge appended to it
- (one cached string). ``valid_tool_names`` drops the ``todo_list``
- sentence when that tool isn't loaded (e.g. Blank Slate). The three
- lists preserve the historical flat order — brief, workspace snapshot,
- operator instructions — so prompt assembly can put a cache boundary
- before the snapshot without changing the persisted bytes.
- """
+ def system_prompt_parts(self, valid_tool_names=None) -> tuple[list[str], list[str], list[str]]:
+ """Return (prefix, workspace, trailing) posture blocks in the historical flat order —
+ brief, snapshot, operator instructions — so prompt assembly can put a cache boundary
+ before the snapshot without changing persisted bytes. The brief carries the model-family
+ edit-format nudge (one cached string); ``valid_tool_names`` drops the ``todo_list``
+ sentence when that tool isn't loaded; operator instructions ride their own block so
+ the brief stays byte-stable."""
if not self.is_coding:
return [], [], []
prefix: list[str] = []
@@ -444,19 +336,13 @@ class RuntimeMode:
brief = self.profile.guidance
if valid_tool_names is not None and "todo_list" not in valid_tool_names:
brief = brief.replace(_TODO_SENTENCE, _NO_TODO_SENTENCE)
- edit_line = _edit_format_line(self.model)
- if edit_line:
- brief = f"{brief}\n{edit_line}"
+ family = _model_family(self.model)
+ if family is not None:
+ brief = f"{brief}\n{_EDIT_FORMAT_GUIDANCE[family][1]}"
prefix.append(brief)
workspace = build_coding_workspace_block(self.cwd)
- workspace_parts = [workspace] if workspace else []
- # Operator instructions ride their own block so the brief stays
- # byte-stable independently of user config.
- trailing = (
- [f"Operator instructions (from config):\n{self.instructions}"]
- if self.instructions else []
- )
- return prefix, workspace_parts, trailing
+ trailing = [f"Operator instructions (from config):\n{self.instructions}"] if self.instructions else []
+ return prefix, [workspace] if workspace else [], trailing
def system_blocks(self) -> list[str]:
"""Posture blocks as one flat list in historical order (compat helper)."""
@@ -464,123 +350,69 @@ class RuntimeMode:
return [*prefix, *workspace, *trailing]
def compact_skill_categories(self) -> frozenset[str]:
- """Skill categories to demote to names-only in the skill index.
-
- Gated on ``focus`` like the toolset collapse — index changes under
- ``auto`` proved too surprising. Demoted, never hidden: fully pruning
- them caused silent capability loss (agent-created skills are the
- model's project memory and models don't reliably re-run ``skills_list``).
- """
+ """Skill categories to demote to names-only in the skill index. Gated on ``focus``
+ like the toolset collapse (index changes under ``auto`` proved too surprising).
+ Demoted, never hidden: pruning caused silent capability loss."""
if not self.is_coding or self.config_mode != "focus":
return frozenset()
return frozenset(self.profile.compact_skill_categories)
def resolve_runtime_mode(
- *,
- platform: Optional[str] = None,
- cwd: Optional[str | Path] = None,
- config: Optional[dict[str, Any]] = None,
+ *, platform: Optional[str] = None, cwd: Optional[str | Path] = None, config: Optional[dict[str, Any]] = None,
model: Optional[str] = None,
) -> RuntimeMode:
- """Resolve the operating posture once (a handful of ``stat`` calls).
-
- The single entry point every domain should call; the result is immutable
- and safe to hold for the session. ``model`` only steers edit-format guidance.
- """
+ """Resolve the operating posture once (a handful of ``stat`` calls) — the single entry
+ point every domain should call; the result is safe to hold for the session. ``model``
+ only steers edit-format guidance; ``agent.coding_instructions`` (str or list) becomes
+ the trailing block so a user can pin workflow rules without editing the shipped brief."""
resolved_cwd = _resolve_cwd(cwd)
mode = _coding_mode(config)
- name = _detect_profile_name(
- mode, (platform or "").strip().lower(), str(resolved_cwd)
- )
+ raw = _agent_config_value(config, "coding_instructions", "", readonly=False)
+ items = raw if isinstance(raw, (list, tuple)) else [raw or ""]
+ instructions = "\n".join(str(item).strip() for item in items if str(item).strip())
return RuntimeMode(
- profile=get_profile(name),
+ profile=_detect_profile(mode, (platform or "").strip().lower(), resolved_cwd),
surface=platform or "",
cwd=resolved_cwd,
config_mode=mode,
model=model,
- instructions=_coding_instructions(config),
+ instructions=instructions,
)
# ── Back-compat surface (thin wrappers over RuntimeMode) ────────────────────
-
-def is_coding_context(
- *,
- platform: Optional[str] = None,
- cwd: Optional[str | Path] = None,
- config: Optional[dict[str, Any]] = None,
-) -> bool:
+def is_coding_context(*, platform: Optional[str] = None, cwd: Optional[str | Path] = None, config: Optional[dict[str, Any]] = None) -> bool:
"""Whether Hermes should operate in its coding posture right now."""
return resolve_runtime_mode(platform=platform, cwd=cwd, config=config).is_coding
-def coding_selection(
- *,
- platform: Optional[str] = None,
- cwd: Optional[str | Path] = None,
- config: Optional[dict[str, Any]] = None,
-) -> Optional[list[str]]:
+def coding_selection(*, platform: Optional[str] = None, cwd: Optional[str | Path] = None, config: Optional[dict[str, Any]] = None) -> Optional[list[str]]:
"""Toolset selection for the coding posture (``None`` unless ``focus`` and active)."""
- return resolve_runtime_mode(
- platform=platform, cwd=cwd, config=config
- ).toolset_selection(config)
+ return resolve_runtime_mode(platform=platform, cwd=cwd, config=config).toolset_selection(config)
def coding_system_prompt_parts(
- *,
- platform: Optional[str] = None,
- cwd: Optional[str | Path] = None,
- config: Optional[dict[str, Any]] = None,
- model: Optional[str] = None,
- valid_tool_names=None,
+ *, platform: Optional[str] = None, cwd: Optional[str | Path] = None, config: Optional[dict[str, Any]] = None,
+ model: Optional[str] = None, valid_tool_names=None,
) -> tuple[list[str], list[str], list[str]]:
"""Return coding prefix, workspace snapshot, and trailing guidance."""
- return resolve_runtime_mode(
- platform=platform, cwd=cwd, config=config, model=model
- ).system_prompt_parts(valid_tool_names=valid_tool_names)
+ mode = resolve_runtime_mode(platform=platform, cwd=cwd, config=config, model=model)
+ return mode.system_prompt_parts(valid_tool_names=valid_tool_names)
-def coding_compact_skill_categories(
- *,
- platform: Optional[str] = None,
- cwd: Optional[str | Path] = None,
- config: Optional[dict[str, Any]] = None,
-) -> frozenset[str]:
+def coding_compact_skill_categories(*, platform: Optional[str] = None, cwd: Optional[str | Path] = None, config: Optional[dict[str, Any]] = None) -> frozenset[str]:
"""Skill categories the active posture demotes to names-only (empty outside ``focus``)."""
- return resolve_runtime_mode(
- platform=platform, cwd=cwd, config=config
- ).compact_skill_categories()
-
-
-def _enabled_mcp_servers(config: Optional[dict[str, Any]]) -> list[str]:
- """Names of MCP servers the user has enabled — kept in the coding posture."""
- try:
- from hermes_cli.config import read_raw_config
- from hermes_cli.tools_config import _parse_enabled_flag
-
- servers = read_raw_config().get("mcp_servers") or {}
- return [
- str(name)
- for name, cfg in servers.items()
- if isinstance(cfg, dict)
- and _parse_enabled_flag(cfg.get("enabled", True), default=True)
- ]
- except Exception:
- return []
+ return resolve_runtime_mode(platform=platform, cwd=cwd, config=config).compact_skill_categories()
# ── git/workspace probe ─────────────────────────────────────────────────────
-
def _git(cwd: Path, *args: str) -> str:
- """``git -C <cwd> <args>`` → stripped stdout, or ``""`` on any failure.
-
- :func:`bounded_git_probe` bounds the post-kill cleanup on Windows — a plain
- ``subprocess.run(timeout=...)`` deadlocked when a killed git left a
- suspended descendant holding the pipe handles.
- """
+ """``git -C <cwd> <args>`` → stripped stdout, or ``""`` on any failure. bounded_git_probe
+ bounds post-kill cleanup on Windows — plain ``subprocess.run(timeout=...)`` deadlocked
+ when a killed git left a suspended descendant holding the pipe handles."""
return bounded_git_probe(["git", "-C", str(cwd), *args], timeout=_GIT_TIMEOUT)
@@ -589,23 +421,18 @@ def _parse_status(porcelain: str) -> tuple[dict[str, str], dict[str, int]]:
branch: dict[str, str] = {}
counts = {"staged": 0, "modified": 0, "untracked": 0, "conflicts": 0}
for line in porcelain.splitlines():
- if line.startswith("# branch.head"):
- branch["head"] = line.split(maxsplit=2)[-1]
- elif line.startswith("# branch.upstream"):
- branch["upstream"] = line.split(maxsplit=2)[-1]
+ if line.startswith(("# branch.head", "# branch.upstream")):
+ parts = line.split(maxsplit=2)
+ branch[parts[1].removeprefix("branch.")] = parts[-1]
elif line.startswith("# branch.ab"):
parts = line.split()
branch["ahead"], branch["behind"] = parts[2].lstrip("+"), parts[3].lstrip("-")
elif line.startswith(("1 ", "2 ")):
xy = line.split(maxsplit=2)[1]
- if xy[0] != ".":
- counts["staged"] += 1
- if xy[1] != ".":
- counts["modified"] += 1
- elif line.startswith("u "):
- counts["conflicts"] += 1
- elif line.startswith("? "):
- counts["untracked"] += 1
+ counts["staged"] += xy[0] != "."
+ counts["modified"] += xy[1] != "."
+ elif line.startswith(("u ", "? ")):
+ counts["conflicts" if line[0] == "u" else "untracked"] += 1
return branch, counts
@@ -630,16 +457,7 @@ class ProjectFacts:
def detect_project_facts(root: Path) -> ProjectFacts:
- """Detect manifests, package manager(s), verify commands, and context files.
-
- Single source of truth for the prompt snapshot and the gateway's
- ``project.facts``. Cheap: stat calls plus a couple of small file reads.
- """
- manifests = [m for m in _PROJECT_MARKERS if m not in _CONTEXT_FILES and (root / m).is_file()]
- package_managers = list(
- dict.fromkeys(pm for lock, pm in (*_PY_LOCKFILES, *_JS_LOCKFILES) if (root / lock).is_file())
- )
-
+ """Detect manifests, package manager(s), verify commands, context files (single source of truth)."""
verify: list[str] = []
if (root / "scripts" / "run_tests.sh").is_file():
verify.append("scripts/run_tests.sh")
@@ -653,36 +471,20 @@ def detect_project_facts(root: Path) -> ProjectFacts:
if (root / "pytest.ini").is_file() or "[tool.pytest" in _read_small(root / "pyproject.toml"):
verify.append("pytest")
makefile = _read_small(root / "Makefile")
- if makefile:
- verify.extend(
- f"make {name}" for name in _VERIFY_TARGETS
- if re.search(rf"^{re.escape(name)}\s*:", makefile, re.MULTILINE)
- )
-
+ verify.extend(
+ f"make {name}" for name in _VERIFY_TARGETS
+ if makefile and re.search(rf"^{re.escape(name)}\s*:", makefile, re.MULTILINE)
+ )
return ProjectFacts(
- manifests=manifests,
- package_managers=package_managers,
+ manifests=[m for m in _PROJECT_MARKERS if m not in _CONTEXT_FILES and (root / m).is_file()],
+ package_managers=list(dict.fromkeys(
+ pm for lock, pm in (*_PY_LOCKFILES, *_JS_LOCKFILES) if (root / lock).is_file()
+ )),
verify_commands=list(dict.fromkeys(verify))[:_MAX_VERIFY_COMMANDS],
context_files=[c for c in _CONTEXT_FILES if (root / c).is_file()],
)
-def _project_facts(root: Path) -> list[str]:
- """Render :func:`detect_project_facts` as workspace-snapshot lines (byte-stable)."""
- f = detect_project_facts(root)
- facts: list[str] = []
- if f.manifests:
- line = f"- Project: {', '.join(f.manifests[:6])}"
- if f.package_managers:
- line += f" ({'/'.join(f.package_managers)})"
- facts.append(line)
- if f.verify_commands:
- facts.append(f"- Verify: {'; '.join(f.verify_commands)}")
- if f.context_files:
- facts.append(f"- Context files: {', '.join(f.context_files)}")
- return facts
-
-
def _workspace_roots(cwd: Optional[str | Path]) -> tuple[Optional[Path], Optional[Path]]:
"""(git_root, workspace_root) for *cwd*; workspace root is git root else marker root."""
resolved = _resolve_cwd(cwd)
@@ -691,11 +493,7 @@ def _workspace_roots(cwd: Optional[str | Path]) -> tuple[Optional[Path], Optiona
def project_facts_for(cwd: Optional[str | Path] = None) -> Optional[dict[str, Any]]:
- """Structured project facts for ``cwd`` — ``None`` outside a workspace.
-
- Same detection the system-prompt snapshot uses, exposed for non-prompt
- consumers (the desktop verify UI).
- """
+ """Structured project facts for ``cwd`` (desktop verify UI) — ``None`` outside a workspace."""
_, root = _workspace_roots(cwd)
if root is None:
return None
@@ -710,49 +508,46 @@ def project_facts_for(cwd: Optional[str | Path] = None) -> Optional[dict[str, An
def build_coding_workspace_block(cwd: Optional[str | Path] = None) -> str:
- """Workspace snapshot for the system prompt (empty outside a workspace).
-
- Git state when the cwd is in a repo, plus detected project facts — so
- marker-only (non-git) projects still get a snapshot.
- """
+ """Workspace snapshot for the system prompt (empty outside a workspace): git state when
+ in a repo, plus project facts — so marker-only (non-git) projects still get one."""
git_root, root = _workspace_roots(cwd)
if root is None:
return ""
-
- lines = ["Workspace (snapshot at session start — re-check with `git` before acting on it):"]
- lines.append(f"- Root: {root}")
-
+ lines = [
+ "Workspace (snapshot at session start — re-check with `git` before acting on it):",
+ f"- Root: {root}",
+ ]
if git_root is not None:
branch, counts = _parse_status(_git(root, "status", "--porcelain=2", "--branch"))
head = branch.get("head", "")
- if head and head != "(detached)":
- line = f"- Branch: {head}"
- if branch.get("upstream"):
- line += f" \u2192 {branch['upstream']}"
- ahead, behind = branch.get("ahead", "0"), branch.get("behind", "0")
- if ahead != "0" or behind != "0":
- line += f" (ahead {ahead}, behind {behind})"
- lines.append(line)
- elif head == "(detached)":
+ if head == "(detached)":
lines.append("- Branch: (detached HEAD)")
-
- # Linked worktree: say so (branches/stashes are shared state) but do
- # NOT expose the primary tree path — a second absolute path makes the
- # model run commands in the wrong directory.
+ elif head:
+ ahead, behind = branch.get("ahead", "0"), branch.get("behind", "0")
+ upstream = f" \u2192 {branch['upstream']}" if branch.get("upstream") else ""
+ ab = f" (ahead {ahead}, behind {behind})" if upstream and (ahead, behind) != ("0", "0") else ""
+ lines.append(f"- Branch: {head}{upstream}{ab}")
+
+ # Linked worktree: say so (branches/stashes are shared state) but do NOT expose
+ # the primary tree path — a second absolute path makes the model run commands
+ # in the wrong directory.
git_dir, common_dir = _git(root, "rev-parse", "--git-dir"), _git(root, "rev-parse", "--git-common-dir")
if git_dir and common_dir and Path(git_dir).resolve() != Path(common_dir).resolve():
lines.append("- Worktree: linked (git state shared with primary tree)")
- dirty = [f"{n} {label}" for label, n in (
- ("staged", counts["staged"]), ("modified", counts["modified"]),
- ("untracked", counts["untracked"]), ("conflicts", counts["conflicts"]),
- ) if n]
+ dirty = [f"{n} {label}" for label, n in counts.items() if n]
lines.append(f"- Status: {', '.join(dirty) if dirty else 'clean'}")
recent = _git(root, "log", "-3", "--pretty=%h %s")
if recent:
- lines.append("- Recent commits:")
- lines.extend(f" {c}" for c in recent.splitlines())
+ lines.extend(["- Recent commits:", *(f" {c}" for c in recent.splitlines())])
- lines.extend(_project_facts(root))
+ f = detect_project_facts(root)
+ if f.manifests:
+ managers = f" ({'/'.join(f.package_managers)})" if f.package_managers else ""
+ lines.append(f"- Project: {', '.join(f.manifests[:6])}{managers}")
+ if f.verify_commands:
+ lines.append(f"- Verify: {'; '.join(f.verify_commands)}")
+ if f.context_files:
+ lines.append(f"- Context files: {', '.join(f.context_files)}")
return "\n".join(lines)
diff --git a/agent/context_breakdown.py b/agent/context_breakdown.py
index 238a10b7d2c..597bfc8218b 100644
--- a/agent/context_breakdown.py
+++ b/agent/context_breakdown.py
@@ -13,23 +13,27 @@ import re
from typing import Any, Dict, List, Optional, Sequence, Tuple
_SKILLS_BLOCK_RE = re.compile(r"<available_skills>.*?</available_skills>", re.DOTALL)
-
_SUBAGENT_TOOL_NAMES = frozenset({"delegate_task"})
-_CATEGORY_COLORS = {
- "system_prompt": "var(--context-usage-system)",
- "tool_definitions": "var(--context-usage-tools)",
- "rules": "var(--context-usage-rules)",
- "skills": "var(--context-usage-skills)",
- "mcp": "var(--context-usage-mcp)",
- "subagent_definitions": "var(--context-usage-subagents)",
- "memory": "var(--context-usage-memory)",
- "conversation": "var(--context-usage-conversation)",
+# id -> (label, dashboard color, /context glyph); declaration order is display order.
+_CATEGORIES = {
+ "system_prompt": ("System prompt", "var(--context-usage-system)", "■"),
+ "tool_definitions": ("Tool definitions", "var(--context-usage-tools)", "▣"),
+ "rules": ("Rules", "var(--context-usage-rules)", "▩"),
+ "skills": ("Skills", "var(--context-usage-skills)", "▤"),
+ "mcp": ("MCP", "var(--context-usage-mcp)", "▥"),
+ "subagent_definitions": ("Subagent definitions", "var(--context-usage-subagents)", "▦"),
+ "memory": ("Memory", "var(--context-usage-memory)", "▧"),
+ "conversation": ("Conversation", "var(--context-usage-conversation)", "▨"),
}
+_FREE_GLYPH = "·"
+_GRID_COLUMNS = 20
+_GRID_ROWS = 5 # 100 cells → 1 cell per percent of the context window
+_DETAILS_TABLE_LIMIT = 15 # display cap only; the underlying data keeps everything
def _chars_to_tokens(text: str) -> int:
- return (len(text) + 3) // 4 if text else 0
+ return (len(text) + 3) // 4
def _json_tokens(value: Any) -> int:
@@ -40,13 +44,6 @@ def _bytes_to_tokens(size: Optional[int]) -> Optional[int]:
return None if size is None else (int(size) + 3) // 4
-def _tool_name(tool: dict) -> str:
- fn = tool.get("function") if isinstance(tool, dict) else None
- if isinstance(fn, dict):
- return str(fn.get("name") or "")
- return str(tool.get("name") or "")
-
-
def _skills_block(stable: str) -> str:
"""The live ``<available_skills>`` block inside the stable tier, or ''."""
m = _SKILLS_BLOCK_RE.search(stable)
@@ -58,25 +55,20 @@ def _split_tools(tools: Sequence[dict]) -> Tuple[List[dict], List[dict], List[di
mcp: List[dict] = []
subagent: List[dict] = []
for tool in tools:
- name = _tool_name(tool)
- if name.startswith("mcp_"):
- mcp.append(tool)
- elif name in _SUBAGENT_TOOL_NAMES:
- subagent.append(tool)
- else:
- builtin.append(tool)
+ fn = tool.get("function") if isinstance(tool, dict) else None
+ name = str((fn if isinstance(fn, dict) else tool).get("name") or "")
+ bucket = mcp if name.startswith("mcp_") else subagent if name in _SUBAGENT_TOOL_NAMES else builtin
+ bucket.append(tool)
return builtin, mcp, subagent
def _memory_blocks(agent: Any) -> Tuple[str, str]:
memory_block = user_block = ""
store = getattr(agent, "_memory_store", None)
- if store is None:
- return memory_block, user_block
try:
- if getattr(agent, "_memory_enabled", True):
+ if store is not None and getattr(agent, "_memory_enabled", True):
memory_block = store.format_for_system_prompt("memory") or ""
- if getattr(agent, "_user_profile_enabled", True):
+ if store is not None and getattr(agent, "_user_profile_enabled", True):
user_block = store.format_for_system_prompt("user") or ""
except Exception:
pass
@@ -84,164 +76,128 @@ def _memory_blocks(agent: Any) -> Tuple[str, str]:
def _strip_blocks(text: str, *blocks: str) -> str:
- out = text
for block in blocks:
if block:
- out = out.replace(block, "")
- return out.strip()
+ text = text.replace(block, "")
+ return text.strip()
+
+def _join(*parts: str) -> str:
+ return "\n\n".join(part for part in parts if part).strip()
-def compute_session_context_breakdown(
- agent: Any,
- messages: Optional[List[dict]] = None,
-) -> Dict[str, Any]:
+
+def _glyph(cat: Dict[str, Any]) -> str:
+ return _CATEGORIES.get(str(cat.get("id") or ""), (None, None, "▪"))[2]
+
+
+def compute_session_context_breakdown(agent: Any, messages: Optional[List[dict]] = None) -> Dict[str, Any]:
"""Return a Cursor-style context usage breakdown for one live agent."""
- from agent.model_metadata import estimate_messages_tokens_rough
+ from agent.model_metadata import anchored_context_tokens, estimate_messages_tokens_rough
from agent.system_prompt import build_system_prompt_parts
+ messages = messages or []
parts = build_system_prompt_parts(agent)
stable = parts.get("stable", "") or ""
- context = parts.get("context", "") or ""
- volatile = parts.get("volatile", "") or ""
skills_index = _skills_block(stable)
-
memory_block, user_block = _memory_blocks(agent)
- memory_text = "\n\n".join(part for part in (memory_block, user_block) if part).strip()
-
- system_core = _strip_blocks(stable, skills_index)
- system_tail = _strip_blocks(volatile, memory_block, user_block)
- system_prompt_text = "\n\n".join(part for part in (system_core, system_tail) if part).strip()
-
+ system_prompt_text = _join(
+ _strip_blocks(stable, skills_index), _strip_blocks(parts.get("volatile", "") or "", memory_block, user_block)
+ )
builtin_tools, mcp_tools, subagent_tools = _split_tools(list(getattr(agent, "tools", None) or []))
- categories = [
- ("system_prompt", "System prompt", _chars_to_tokens(system_prompt_text)),
- ("tool_definitions", "Tool definitions", _json_tokens(builtin_tools)),
- ("rules", "Rules", _chars_to_tokens(context)),
- ("skills", "Skills", _chars_to_tokens(skills_index)),
- ("mcp", "MCP", _json_tokens(mcp_tools)),
- ("subagent_definitions", "Subagent definitions", _json_tokens(subagent_tools)),
- ("memory", "Memory", _chars_to_tokens(memory_text)),
- ("conversation", "Conversation", estimate_messages_tokens_rough(messages or [])),
- ]
- estimated_total = sum(tokens for _, _, tokens in categories)
+ tokens_by_id = {
+ "system_prompt": _chars_to_tokens(system_prompt_text),
+ "tool_definitions": _json_tokens(builtin_tools),
+ "rules": _chars_to_tokens(parts.get("context", "") or ""),
+ "skills": _chars_to_tokens(skills_index),
+ "mcp": _json_tokens(mcp_tools),
+ "subagent_definitions": _json_tokens(subagent_tools),
+ "memory": _chars_to_tokens(_join(memory_block, user_block)),
+ "conversation": estimate_messages_tokens_rough(messages),
+ }
+ estimated_total = sum(tokens_by_id.values())
comp = getattr(agent, "context_compressor", None)
context_max = int(getattr(comp, "context_length", 0) or 0) if comp else 0
- # Usage-anchored figure (provider-exact tokens of a response + delta of what
- # was appended since) beats last_prompt_tokens (lags) and the heuristic.
- # Prefer the turn-base anchor: on reasoning models later same-turn
- # responses inflate prompt_tokens with replayed thinking that evaporates at
- # the turn boundary, so anchoring on the LAST response makes the meter
- # sawtooth. Fall back to last-response anchor, then measured/estimated.
- from agent.model_metadata import anchored_context_tokens
-
- anchored_used = anchored_context_tokens(
- messages or [],
- getattr(agent, "_turn_base_usage_anchor", None),
- charge_stale_thinking=False,
+ # Usage-anchored figure (provider-exact tokens of a response + delta of what was
+ # appended since) beats last_prompt_tokens (lags) and the heuristic. Prefer the
+ # turn-base anchor: on reasoning models later same-turn responses inflate
+ # prompt_tokens with replayed thinking that evaporates at the turn boundary, so
+ # anchoring on the LAST response makes the meter sawtooth. Fall back to the
+ # last-response anchor, then measured, then estimated.
+ context_used = anchored_context_tokens(
+ messages, getattr(agent, "_turn_base_usage_anchor", None), charge_stale_thinking=False
)
- if anchored_used is None:
- anchored_used = anchored_context_tokens(messages or [], getattr(agent, "_usage_anchor", None))
- measured_used = int(getattr(comp, "last_prompt_tokens", 0) or 0) if comp else 0
- if anchored_used is not None:
- context_used = anchored_used
- else:
+ if context_used is None:
+ context_used = anchored_context_tokens(messages, getattr(agent, "_usage_anchor", None))
+ if context_used is None:
+ measured_used = int(getattr(comp, "last_prompt_tokens", 0) or 0) if comp else 0
context_used = measured_used if measured_used > 0 else estimated_total
- context_percent = max(0, min(100, round(context_used / context_max * 100))) if context_max else 0
return {
"categories": [
- {
- "color": _CATEGORY_COLORS.get(category_id, "var(--ui-text-tertiary)"),
- "id": category_id,
- "label": label,
- "tokens": tokens,
- }
- for category_id, label, tokens in categories
- if tokens > 0
+ {"color": color, "id": category_id, "label": label, "tokens": tokens_by_id[category_id]}
+ for category_id, (label, color, _glyph_) in _CATEGORIES.items()
+ if tokens_by_id[category_id] > 0
],
"context_max": context_max,
- "context_percent": context_percent,
+ "context_percent": max(0, min(100, round(context_used / context_max * 100))) if context_max else 0,
"context_used": context_used,
"estimated_total": estimated_total,
"model": getattr(agent, "model", "") or "",
}
-# ── /context rendering (CLI + gateway) ──────────────────────────────────────
-# Pure text renderers over the payload above. The gateway skips the glyph grid
-# (monospace is not guaranteed on messaging platforms).
-
-_CATEGORY_GLYPHS = {
- "system_prompt": "■",
- "tool_definitions": "▣",
- "rules": "▩",
- "skills": "▤",
- "mcp": "▥",
- "subagent_definitions": "▦",
- "memory": "▧",
- "conversation": "▨",
-}
-_FREE_GLYPH = "·"
-_GRID_COLUMNS = 20
-_GRID_ROWS = 5 # 100 cells → 1 cell per percent of the context window
-_DETAILS_TABLE_LIMIT = 15 # display cap only; the underlying data keeps everything
-
-
def compute_context_details(agent: Any) -> Dict[str, Any]:
- """Expanded per-skill / per-toolset cost listing for ``/context all``,
- reusing the ``hermes prompt-size`` attribution (index-line bytes from the
- live skills block; schema bytes via the registry's tool→toolset map)."""
- from hermes_cli.prompt_size import (
- _compute_skills_breakdown,
- _compute_toolsets_breakdown,
- )
+ """Expanded per-skill / per-toolset cost listing for ``/context all``.
+
+ Reuses the ``hermes prompt-size`` attribution (index-line bytes from the
+ live skills block; schema bytes via the registry's tool→toolset map).
+ """
+ from hermes_cli.prompt_size import _compute_skills_breakdown, _compute_toolsets_breakdown
from agent.system_prompt import build_system_prompt_parts
skills_block = _skills_block(build_system_prompt_parts(agent).get("stable", "") or "")
- skills = [
- {
- "name": entry.get("name", ""),
- "index_tokens": _bytes_to_tokens(entry.get("index_line_bytes")) or 0,
- "skill_md_tokens": _bytes_to_tokens(entry.get("skill_md_bytes")),
- }
- for entry in (_compute_skills_breakdown(skills_block) if skills_block else [])
- ]
tools = list(getattr(agent, "tools", None) or [])
- toolsets = [
- {
- "toolset": group.get("toolset", ""),
- "tool_count": int(group.get("tool_count", 0) or 0),
- "schema_tokens": _bytes_to_tokens(group.get("json_bytes")) or 0,
- }
- for group in (_compute_toolsets_breakdown(tools) if tools else [])
- ]
- return {"skills": skills, "toolsets": toolsets}
+ return {
+ "skills": [
+ {
+ "name": entry.get("name", ""),
+ "index_tokens": _bytes_to_tokens(entry.get("index_line_bytes")) or 0,
+ "skill_md_tokens": _bytes_to_tokens(entry.get("skill_md_bytes")),
+ }
+ for entry in (_compute_skills_breakdown(skills_block) if skills_block else [])
+ ],
+ "toolsets": [
+ {
+ "toolset": group.get("toolset", ""),
+ "tool_count": int(group.get("tool_count", 0) or 0),
+ "schema_tokens": _bytes_to_tokens(group.get("json_bytes")) or 0,
+ }
+ for group in (_compute_toolsets_breakdown(tools) if tools else [])
+ ],
+ }
+
+
+# ── /context rendering (CLI + gateway) ──────────────────────────────────────
+# Pure text renderers over the payload above. The gateway skips the glyph grid
+# (monospace is not guaranteed on messaging platforms).
def render_context_grid(payload: Dict[str, Any]) -> List[str]:
- """Glyph block grid: 100 cells, one per percent of the context window;
- categories fill in declaration order, the remainder is free space."""
+ """Glyph grid: 100 cells, one per percent of the context window; categories
+ fill in declaration order, the remainder is free space."""
context_max = int(payload.get("context_max") or 0)
- categories = payload.get("categories") or []
total_cells = _GRID_COLUMNS * _GRID_ROWS
-
cells: List[str] = []
if context_max > 0:
- for cat in categories:
+ for cat in payload.get("categories") or []:
tokens = int(cat.get("tokens") or 0)
- n = round(tokens / context_max * total_cells)
- if tokens > 0 and n == 0:
- n = 1 # never render a nonzero category as invisible
- glyph = _CATEGORY_GLYPHS.get(str(cat.get("id") or ""), "▪")
- cells.extend([glyph] * n)
+ # never render a nonzero category as invisible
+ n = round(tokens / context_max * total_cells) or (1 if tokens > 0 else 0)
+ cells.extend([_glyph(cat)] * n)
cells = cells[:total_cells]
cells.extend([_FREE_GLYPH] * (total_cells - len(cells)))
-
- return [
- " ".join(cells[row * _GRID_COLUMNS:(row + 1) * _GRID_COLUMNS])
- for row in range(_GRID_ROWS)
- ]
+ return [" ".join(cells[row * _GRID_COLUMNS:(row + 1) * _GRID_COLUMNS]) for row in range(_GRID_ROWS)]
def render_context_category_lines(payload: Dict[str, Any]) -> List[str]:
@@ -253,61 +209,47 @@ def render_context_category_lines(payload: Dict[str, Any]) -> List[str]:
lines = ["Estimated usage by category"]
if not categories:
- lines.append(" (no data yet — send a message first)")
- return lines
-
- width = max(len(str(cat.get("label") or "")) for cat in categories)
- width = max(width, len("Free space"))
+ return [*lines, " (no data yet — send a message first)"]
+ width = max(len("Free space"), *(len(str(cat.get("label") or "")) for cat in categories))
for cat in categories:
- tokens = int(cat.get("tokens") or 0)
- glyph = _CATEGORY_GLYPHS.get(str(cat.get("id") or ""), "▪")
- pct = tokens / denom * 100 if denom else 0.0
- label = str(cat.get("label") or cat.get("id") or "")
- lines.append(f"{glyph} {label:<{width}} {tokens:>9,} tokens {pct:>5.1f}%")
+ tokens, label = int(cat.get("tokens") or 0), str(cat.get("label") or cat.get("id") or "")
+ lines.append(f"{_glyph(cat)} {label:<{width}} {tokens:>9,} tokens {tokens / denom * 100 if denom else 0.0:>5.1f}%")
if context_max > 0:
free = max(0, context_max - estimated_total)
- pct = free / context_max * 100
- lines.append(f"{_FREE_GLYPH} {'Free space':<{width}} {free:>9,} tokens {pct:>5.1f}%")
+ lines.append(f"{_FREE_GLYPH} {'Free space':<{width}} {free:>9,} tokens {free / context_max * 100:>5.1f}%")
return lines
-def _append_overflow(lines: List[str], count: int) -> None:
- remaining = count - _DETAILS_TABLE_LIMIT
- if remaining > 0:
- lines.append(f" … and {remaining} more")
+def _toolset_row(group: Dict[str, Any]) -> str:
+ return f" {group['toolset']:<24} {group['tool_count']:>3} tools {group['schema_tokens']:>8,} tokens"
+
+
+def _skill_row(entry: Dict[str, Any]) -> str:
+ name = str(entry.get("name") or "")
+ if len(name) > 28:
+ name = name[:27] + "…"
+ md = entry.get("skill_md_tokens")
+ md_str = f"{md:>8,}" if md is not None else f"{'n/a':>8}"
+ return f" {name:<28} index {entry['index_tokens']:>6,} SKILL.md {md_str} tokens"
+
+
+def _table(lines: List[str], title: str, rows: List[Dict[str, Any]], fmt) -> None:
+ """Append a titled, display-capped table (blank-separated from a preceding one)."""
+ if not rows:
+ return
+ if lines:
+ lines.append("")
+ lines.append(title)
+ lines.extend(fmt(row) for row in rows[:_DETAILS_TABLE_LIMIT])
+ if len(rows) > _DETAILS_TABLE_LIMIT:
+ lines.append(f" … and {len(rows) - _DETAILS_TABLE_LIMIT} more")
def render_context_details_lines(details: Dict[str, Any]) -> List[str]:
"""Render the expanded ``/context all`` per-skill / per-toolset tables."""
lines: List[str] = []
-
- toolsets = details.get("toolsets") or []
- if toolsets:
- lines.append("Toolsets by schema cost (largest first)")
- for group in toolsets[:_DETAILS_TABLE_LIMIT]:
- lines.append(
- f" {group['toolset']:<24} {group['tool_count']:>3} tools"
- f" {group['schema_tokens']:>8,} tokens"
- )
- _append_overflow(lines, len(toolsets))
-
- skills = details.get("skills") or []
- if skills:
- if lines:
- lines.append("")
- lines.append("Skills by cost (index = always-on; SKILL.md = cost when loaded)")
- for entry in skills[:_DETAILS_TABLE_LIMIT]:
- name = str(entry.get("name") or "")
- if len(name) > 28:
- name = name[:27] + "…"
- md = entry.get("skill_md_tokens")
- md_str = f"{md:>8,}" if md is not None else f"{'n/a':>8}"
- lines.append(
- f" {name:<28} index {entry['index_tokens']:>6,}"
- f" SKILL.md {md_str} tokens"
- )
- _append_overflow(lines, len(skills))
-
+ _table(lines, "Toolsets by schema cost (largest first)", details.get("toolsets") or [], _toolset_row)
+ _table(lines, "Skills by cost (index = always-on; SKILL.md = cost when loaded)", details.get("skills") or [], _skill_row)
return lines
@@ -317,27 +259,18 @@ def render_context_breakdown_lines(
details: Optional[Dict[str, Any]] = None,
grid: bool = True,
) -> List[str]:
- """Full /context view. ``grid`` prepends the glyph grid (CLI; the gateway
+ """Full /context view. ``grid`` prepends the glyph grid (CLI; the gateway
keeps its own gauge); ``details`` appends the expanded listings."""
- lines: List[str] = []
- if grid:
- lines.extend(render_context_grid(payload))
- lines.append("")
+ lines: List[str] = [*render_context_grid(payload), ""] if grid else []
lines.extend(render_context_category_lines(payload))
context_max = int(payload.get("context_max") or 0)
- context_used = int(payload.get("context_used") or 0)
if context_max > 0:
- pct = int(payload.get("context_percent") or 0)
- lines.append("")
- lines.append(f"Context window: {context_used:,} / {context_max:,} tokens ({pct}%)")
-
- if details is not None:
- detail_lines = render_context_details_lines(details)
- if detail_lines:
- lines.append("")
- lines.extend(detail_lines)
- else:
- lines.append("")
- lines.append("Use /context all for per-skill and per-toolset costs.")
+ used, pct = int(payload.get("context_used") or 0), int(payload.get("context_percent") or 0)
+ lines.extend(["", f"Context window: {used:,} / {context_max:,} tokens ({pct}%)"])
+
+ if details is None:
+ lines.extend(["", "Use /context all for per-skill and per-toolset costs."])
+ elif detail_lines := render_context_details_lines(details):
+ lines.extend(["", *detail_lines])
return lines
diff --git a/agent/context_engine.py b/agent/context_engine.py
index ff153fa2f90..ef9c6f4c932 100644
--- a/agent/context_engine.py
+++ b/agent/context_engine.py
@@ -1,16 +1,14 @@
"""Abstract base class for pluggable context engines.
-A context engine decides when and how conversation context is compacted near
-the model's token limit, tracks token usage, and may expose tools. The
-built-in ContextCompressor is the default; ``context.engine`` in config.yaml
-selects a plugin engine (``plugins/context_engine/<name>/``). One engine is
-active at a time.
-
-Lifecycle: on_session_start() -> per API response update_from_response() ->
-per turn should_compress() / compress() -> on_session_end() at real session
-boundaries only (CLI exit, /reset, gateway expiry), never per-turn.
+A context engine decides when/how conversation context is compacted near the token
+limit, tracks usage, and may expose tools. ContextCompressor is the default;
+``context.engine`` selects a plugin (``plugins/context_engine/<name>/``); one is active.
+Lifecycle: on_session_start() -> per API response update_from_response() -> per turn
+should_compress() / compress() -> on_session_end() at real session boundaries only
+(CLI exit, /reset, gateway expiry), never per-turn.
"""
+import json
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional
@@ -25,27 +23,13 @@ _MEMORY_CONTEXT_TRUNCATION_MARKER = "\n...[memory provider context truncated]...
def sanitize_memory_context(memory_context: str) -> str:
"""Prepare provider context for a context-engine/LLM egress boundary."""
- sanitized = redact_sensitive_text(
- memory_context.strip(),
- force=True,
- redact_url_credentials=True,
- )
+ sanitized = redact_sensitive_text(memory_context.strip(), force=True, redact_url_credentials=True)
if len(sanitized) <= MEMORY_CONTEXT_MAX_CHARS:
return sanitized
- return (
- sanitized[:_MEMORY_CONTEXT_HEAD_CHARS]
- + _MEMORY_CONTEXT_TRUNCATION_MARKER
- + sanitized[-_MEMORY_CONTEXT_TAIL_CHARS:]
- )
-
-
-def automatic_compaction_status_message(
- engine: Any,
- *,
- phase: str,
- default_message: str,
- **context: Any,
-) -> str | None:
+ return sanitized[:_MEMORY_CONTEXT_HEAD_CHARS] + _MEMORY_CONTEXT_TRUNCATION_MARKER + sanitized[-_MEMORY_CONTEXT_TAIL_CHARS:]
+
+
+def automatic_compaction_status_message(engine: Any, *, phase: str, default_message: str, **context: Any) -> str | None:
"""Host-visible status for an automatic compaction event; ``None`` = emit nothing.
Engines suppress via ``emit_automatic_compaction_status = False`` or
@@ -53,64 +37,45 @@ def automatic_compaction_status_message(
"""
if not getattr(engine, "emit_automatic_compaction_status", True):
return None
-
formatter = getattr(engine, "get_automatic_compaction_status_message", None)
- if callable(formatter):
- message = formatter(
- phase=phase,
- default_message=default_message,
- **context,
- )
- else:
- message = default_message
-
+ message = formatter(phase=phase, default_message=default_message, **context) if callable(formatter) else default_message
if message is None:
return None
- message = str(message).strip()
- return message or None
+ return str(message).strip() or None
class ContextEngine(ABC):
"""Base class all context engines must implement."""
- # -- Identity ----------------------------------------------------------
-
@property
@abstractmethod
def name(self) -> str:
"""Short identifier (e.g. 'compressor', 'lcm')."""
- # -- Token state: engines MUST maintain these; run_agent.py reads them directly.
-
+ # Token state: engines MUST maintain these; run_agent.py reads them directly.
last_prompt_tokens: int = 0
last_completion_tokens: int = 0
last_total_tokens: int = 0
threshold_tokens: int = 0
context_length: int = 0
compression_count: int = 0
-
- # -- Compaction parameters (read by run_agent.py for preflight). protect_first_n
- # counts non-system head messages kept verbatim IN ADDITION to the always-
- # protected system prompt (3 keeps the historical head shape).
-
+ # Compaction parameters (read by run_agent.py for preflight). protect_first_n counts
+ # non-system head messages kept verbatim IN ADDITION to the always-protected system
+ # prompt (3 keeps the historical head shape).
threshold_percent: float = 0.75
protect_first_n: int = 3
protect_last_n: int = 6
-
- # False keeps successful automatic compaction passes silent (routine
- # background maintenance); warnings, errors and manual /compress still surface.
+ # False keeps successful automatic compaction passes silent (routine background
+ # maintenance); warnings, errors and manual /compress still surface.
emit_automatic_compaction_status: bool = True
- # -- Core interface ----------------------------------------------------
-
@abstractmethod
def update_from_response(self, usage: Dict[str, Any]) -> None:
"""Update tracked token usage after every LLM call.
- ``prompt_tokens``/``completion_tokens``/``total_tokens`` are always
- present; the canonical buckets (``input_tokens``, ``output_tokens``,
- ``cache_read_tokens``, ``cache_write_tokens``, ``reasoning_tokens``)
- are optional on older hosts.
+ ``prompt_tokens``/``completion_tokens``/``total_tokens`` are always present; the
+ canonical buckets (``input_tokens``, ``output_tokens``, ``cache_read_tokens``,
+ ``cache_write_tokens``, ``reasoning_tokens``) are optional on older hosts.
"""
@abstractmethod
@@ -120,103 +85,71 @@ class ContextEngine(ABC):
def should_compress_info(self, prompt_tokens: int = None) -> "tuple[bool, str | None]":
"""Return ``(should_compress, reason)``.
- Engines with block reasons (summary-LLM cooldown, anti-thrashing guard)
- override this so callers can warn the user instead of silently skipping
- compression. The default keeps plugin engines from raising AttributeError.
+ Engines with block reasons (summary-LLM cooldown, anti-thrashing guard) override
+ this so callers can warn instead of silently skipping; the default keeps plugin
+ engines from raising AttributeError.
"""
return self.should_compress(prompt_tokens), None
@abstractmethod
def compress(
- self,
- messages: List[Dict[str, Any]],
- current_tokens: Optional[int] = None,
- focus_topic: Optional[str] = None,
- force: bool = False,
- memory_context: str = "",
+ self, messages: List[Dict[str, Any]], current_tokens: Optional[int] = None,
+ focus_topic: Optional[str] = None, force: bool = False, memory_context: str = "",
) -> List[Dict[str, Any]]:
- """Compact ``messages`` and return a valid OpenAI-format message list
- that fits the context budget (summarize, build a DAG, anything).
-
- ``focus_topic`` comes from manual ``/compress <focus>`` (prioritise that
- topic); ``force`` asks to bypass an engine-owned cooldown;
- ``memory_context`` is provider text to include in the handoff prompt.
- Older engines may omit optional parameters — the host filters them by
- signature.
- """
+ """Compact ``messages`` into a valid OpenAI-format list that fits the budget.
- # -- Optional: proactive tool-result prune -----------------------------
+ ``focus_topic`` comes from manual ``/compress <focus>`` (prioritise that topic);
+ ``force`` asks to bypass an engine-owned cooldown; ``memory_context`` is provider
+ text for the handoff prompt. Older engines may omit optional parameters — the
+ host filters them by signature.
+ """
def prune_tool_results_only(
- self,
- messages: List[Dict[str, Any]],
- current_tokens: int | None = None,
+ self, messages: List[Dict[str, Any]], current_tokens: int | None = None,
) -> tuple[List[Dict[str, Any]], int]:
"""Deterministically trim old tool-result payloads without an LLM call.
- Runs on a low, cost-oriented trigger independent of ``should_compress``
- so large-window engines reclaim re-sent tool output long before full
- compaction. Returns ``(messages, n_pruned)``; default is a no-op so
- engines predating this hook never raise in the post-tool-call prune path.
+ Runs on a low, cost-oriented trigger independent of ``should_compress`` so
+ large-window engines reclaim re-sent tool output long before full compaction.
+ Returns ``(messages, n_pruned)``; the default no-op keeps older engines safe.
"""
return messages, 0
- # -- Optional: per-turn context selection (distinct from compression) --
-
def select_context(
- self,
- request_messages: List[Dict[str, Any]],
- *,
- conversation_messages: List[Dict[str, Any]] = None,
- incoming_message: Dict[str, Any] = None,
- budget_tokens: int = 0,
+ self, request_messages: List[Dict[str, Any]], *, conversation_messages: List[Dict[str, Any]] = None,
+ incoming_message: Dict[str, Any] = None, budget_tokens: int = 0,
) -> List[Dict[str, Any]]:
"""Optionally *select* (replace) the context for THIS request, pre-generation.
- Runs every provider request (so also on retries), independent of
- ``should_compress()``: ``compress()`` shrinks context that is too long,
- ``select_context()`` swaps in a different context (retrieval, topic
- routing, branch switching) without abusing ``compress()`` as a per-turn
- callback. Return ``None`` to leave the request unchanged.
-
- The returned list is request-only — it MUST NOT be treated as persisted
- transcript state; the session DB history is untouched. Unlike the
- ``pre_llm_call`` hook it may replace the list. The host runs it before
- prompt cache-control and before every request sanitizer, so a malformed
- replacement never reaches the provider and the default no-op keeps the
- request byte-identical (prompt-cache stability preserved). An engine that
- replaces the list changes its own cache prefix; breakpoints are
- re-derived on the selected list.
-
- ``request_messages`` is the assembled request (system prompt + history +
- ephemeral prefill); ``conversation_messages`` is the persisted history
- for reference only (do not mutate); ``budget_tokens`` is the model's
- context length or 0 if unknown.
+ Runs on every provider request (also retries), independent of
+ ``should_compress()``: ``compress()`` shrinks over-long context, this swaps in a
+ different one (retrieval, topic routing, branch switching). Return ``None`` to
+ leave the request unchanged. The returned list is request-only — it MUST NOT be
+ treated as persisted transcript state (session DB history is untouched); unlike
+ ``pre_llm_call`` it may replace the list. The host runs it before prompt
+ cache-control and every request sanitizer, so a malformed replacement never
+ reaches the provider and the default no-op keeps the request byte-identical;
+ an engine that replaces the list changes its own cache prefix (breakpoints are
+ re-derived on the selected list). ``request_messages`` is the assembled request
+ (system prompt + history + ephemeral prefill); ``conversation_messages`` is the
+ persisted history for reference only (do not mutate); ``budget_tokens`` is the
+ model's context length or 0 if unknown.
"""
return None
- def on_turn_complete(
- self,
- messages: List[Dict[str, Any]],
- usage: Dict[str, Any] = None,
- **kwargs: Any,
- ) -> None:
- """Observe a finished turn (complement of ``select_context()``) so the
- engine can ingest/index/update routing state for the next request.
-
- Fires from the normal finalization seam only; some abnormal early
- returns (content-policy block, provider terminal failure) do not emit
- it — treat it as best-effort, not guaranteed. ``messages`` is a
- read-only shallow copy (return value ignored; never rely on transcript
- mutation). ``usage`` has the ``update_from_response`` dict shape and is
- ``None`` when the turn never reached a provider response (interrupt).
- ``kwargs`` may include ``turn_id``, ``task_id``, ``api_call_count``,
- ``interrupted``, ``failed``, ``turn_exit_reason``.
+ def on_turn_complete(self, messages: List[Dict[str, Any]], usage: Dict[str, Any] = None, **kwargs: Any) -> None:
+ """Observe a finished turn (complement of ``select_context()``) to index/update
+ routing state for the next request.
+
+ Best-effort, not guaranteed: fires from the normal finalization seam only; some
+ abnormal early returns (content-policy block, provider terminal failure) skip it.
+ ``messages`` is a read-only shallow copy (return value ignored; never rely on
+ transcript mutation). ``usage`` has the ``update_from_response`` shape and is
+ ``None`` when no provider response was reached (interrupt). ``kwargs`` may include
+ ``turn_id``, ``task_id``, ``api_call_count``, ``interrupted``, ``failed``, ``turn_exit_reason``.
"""
return None
- # -- Optional: pre-flight check ----------------------------------------
-
def should_compress_preflight(self, messages: List[Dict[str, Any]]) -> bool:
"""Cheap rough check before the API call (no real token count yet); default skips."""
return False
@@ -227,31 +160,21 @@ class ContextEngine(ABC):
return False
def get_automatic_compaction_status_message(
- self,
- *,
- phase: str,
- default_message: str,
- **context: Any,
+ self, *, phase: str, default_message: str, **context: Any,
) -> str | None:
"""User-visible status for automatic compaction, or ``None`` to suppress it.
- ``phase`` is the host call site (``"preflight"`` / ``"compress"``);
- ``context`` carries best-effort ``approx_tokens`` / ``threshold_tokens``.
- Warnings, errors and manual ``/compress`` are not governed by this hook.
+ ``phase`` is the host call site (``"preflight"`` / ``"compress"``); ``context``
+ carries best-effort ``approx_tokens`` / ``threshold_tokens``. Warnings, errors
+ and manual ``/compress`` are not governed by this hook.
"""
- if not self.emit_automatic_compaction_status:
- return None
- return default_message
-
- # -- Optional: manual /compress preflight ------------------------------
+ return default_message if self.emit_automatic_compaction_status else None
def has_content_to_compress(self, messages: List[Dict[str, Any]]) -> bool:
"""Preflight guard for gateway ``/compress``: False reports "nothing to
compress yet" without an LLM call (e.g. transcript entirely protected)."""
return True
- # -- Optional: session lifecycle ---------------------------------------
-
def on_session_start(self, session_id: str, **kwargs) -> None:
"""Session begins: load persisted state. kwargs may include hermes_home, platform, model."""
@@ -265,8 +188,6 @@ class ContextEngine(ABC):
self.last_total_tokens = 0
self.compression_count = 0
- # -- Optional: tools ---------------------------------------------------
-
def get_tool_schemas(self) -> List[Dict[str, Any]]:
"""Tool schemas this engine exposes to the agent (default: none)."""
return []
@@ -274,49 +195,36 @@ class ContextEngine(ABC):
def handle_tool_call(self, name: str, args: Dict[str, Any], **kwargs) -> str:
"""Handle a call to one of this engine's tools; must return a JSON string.
kwargs may include ``messages`` (live in-memory list)."""
- import json
return json.dumps({"error": f"Unknown context engine tool: {name}"})
- # -- Optional: status / display ----------------------------------------
-
def get_status(self) -> Dict[str, Any]:
"""Status dict with the standard fields run_agent.py expects."""
- # Clamp the -1 "compression just ran, awaiting real usage" sentinel to 0
- # so no reader sees a negative usage_percent on the transitional turn.
- last_prompt = self.last_prompt_tokens if self.last_prompt_tokens > 0 else 0
+ # Clamp the -1 "compression just ran, awaiting real usage" sentinel to 0 so no
+ # reader sees a negative usage_percent on the transitional turn.
+ last_prompt = max(self.last_prompt_tokens, 0)
return {
"last_prompt_tokens": last_prompt,
"threshold_tokens": self.threshold_tokens,
"context_length": self.context_length,
- "usage_percent": (
- min(100, last_prompt / self.context_length * 100)
- if self.context_length else 0
- ),
+ "usage_percent": min(100, last_prompt / self.context_length * 100) if self.context_length else 0,
"compression_count": self.compression_count,
}
- # -- Optional: model switch support ------------------------------------
-
def update_model(
- self,
- model: str,
- context_length: int,
- base_url: str = "",
- api_key: str = "",
- provider: str = "",
- api_mode: str = "",
+ self, model: str, context_length: int, base_url: str = "", api_key: str = "",
+ provider: str = "", api_mode: str = "",
) -> None:
- """Model switch / fallback: recompute threshold_tokens (override for more)."""
+ """Model switch / fallback: recompute threshold_tokens (override for more).
+
+ Per-model threshold override (longest substring match), else the raw config
+ percent — snapshotted ONCE so repeated switches fall back to the configured
+ value, not the previous model's override.
+ """
self.context_length = context_length
- # Per-model threshold override (longest substring match), else the raw
- # config percent. Snapshot that percent ONCE so repeated switches fall
- # back to the configured value, not the previous model's override.
from agent.context_compressor import resolve_model_threshold
if not hasattr(self, "_config_threshold_percent"):
self._config_threshold_percent = self.threshold_percent
self._base_threshold_percent = resolve_model_threshold(
- model, getattr(self, "model_thresholds", {}),
- self._config_threshold_percent,
- )
+ model, getattr(self, "model_thresholds", {}), self._config_threshold_percent)
self.threshold_percent = self._base_threshold_percent
self.threshold_tokens = int(context_length * self.threshold_percent)