|
| 1 | +""" |
| 2 | +context-saver plugin for Hermes Agent. |
| 3 | +
|
| 4 | +Enforces context-mode routing rules and provides context window optimization. |
| 5 | +
|
| 6 | +Two layers: |
| 7 | + - pre_tool_call: blocks high-output terminal commands, redirects to sandbox |
| 8 | + - transform_tool_result: sandboxes large outputs to files with compact summaries |
| 9 | + - pre_llm_call: injects routing rules on first turn |
| 10 | +
|
| 11 | +Inspired by context-mode (github.com/mksglu/context-mode). |
| 12 | +""" |
| 13 | + |
| 14 | +from __future__ import annotations |
| 15 | + |
| 16 | +import json |
| 17 | +import logging |
| 18 | +import re |
| 19 | +import sqlite3 |
| 20 | +from collections import Counter |
| 21 | +from datetime import datetime |
| 22 | +from pathlib import Path |
| 23 | +from typing import Optional |
| 24 | + |
| 25 | +logger = logging.getLogger("context-saver") |
| 26 | + |
| 27 | +SANDBOX_THRESHOLD = 3000 |
| 28 | +SESSION_GUIDANCE_SHOWN: dict[str, bool] = {} |
| 29 | + |
| 30 | +# Blocked patterns |
| 31 | +BLOCKED_CURL_WGET = re.compile(r"\b(curl|wget)\b") |
| 32 | +BLOCKED_INLINE_HTTP = re.compile( |
| 33 | + r"\b(fetch\s*\(\s*['"]http|" |
| 34 | + r"requests\.(get|post|put|delete|patch)\s*\(|" |
| 35 | + r"http\.(get|post|request)\s*\(|" |
| 36 | + r"urllib\.request\.urlopen\s*\()" |
| 37 | +) |
| 38 | +BLOCKED_BUILD = re.compile(r"\b(gradle|mvn|cargo\s+(build|test|run|check))\b") |
| 39 | + |
| 40 | +ALLOWED_COMMANDS = [ |
| 41 | + "git ", "mkdir", "rm ", "mv ", "cp ", "touch", "chmod", |
| 42 | + "ls ", "pwd", "cd ", "echo ", "cat ", "head ", "tail ", |
| 43 | + "npm install ", "pip install ", "pip3 install ", |
| 44 | + "which ", "whoami", "hostname", "uname", "date", "env", |
| 45 | + "hermes ", "brew ", |
| 46 | +] |
| 47 | + |
| 48 | +SANDBOX_TOOLS = frozenset({ |
| 49 | + "browser_snapshot", "browser_vision", "web_search", "web_extract", |
| 50 | + "terminal", "read_file", "search_files", "browser_console", |
| 51 | + "execute_code", "delegate_task", "browser_get_images", |
| 52 | +}) |
| 53 | +NEVER_SANDBOX = frozenset({ |
| 54 | + "todo", "memory", "send_message", "clarify", "cronjob", |
| 55 | + "browser_click", "browser_type", "browser_navigate", |
| 56 | + "browser_press", "browser_scroll", "browser_back", |
| 57 | + "skill_view", "skills_list", "skill_manage", |
| 58 | + "text_to_speech", "patch", "write_file", |
| 59 | +}) |
| 60 | + |
| 61 | +ROUTING_BLOCK = """<context_window_protection> |
| 62 | + Think in code - write scripts instead of reading raw data into context. |
| 63 | + - Use execute_code with Python to process files, fetch URLs, analyze data. |
| 64 | + - Use ctx_execute(language, code) for sandboxed execution. |
| 65 | + - Tool outputs >3KB are sandboxed to files. |
| 66 | + - curl/wget/build tools are BLOCKED - use execute_code or ctx_execute instead. |
| 67 | +</context_window_protection>""" |
| 68 | + |
| 69 | +_session_stats: dict[str, dict] = {} |
| 70 | + |
| 71 | +def _check_short_command(stripped: str) -> bool: |
| 72 | + for allowed in ALLOWED_COMMANDS: |
| 73 | + if stripped.startswith(allowed): |
| 74 | + return True |
| 75 | + return False |
| 76 | + |
| 77 | +def pre_tool_call(*, tool_name: str, args: dict, task_id: str, |
| 78 | + session_id: str = "", **_kwargs) -> Optional[dict]: |
| 79 | + if tool_name != "terminal": |
| 80 | + return None |
| 81 | + command = args.get("command", "") |
| 82 | + if not isinstance(command, str) or not command.strip(): |
| 83 | + return None |
| 84 | + stripped = command.strip() |
| 85 | + if _check_short_command(stripped): |
| 86 | + return None |
| 87 | + if BLOCKED_CURL_WGET.search(stripped): |
| 88 | + return {"action": "block", "message": "context-saver: curl/wget blocked. Use execute_code or ctx_execute."} |
| 89 | + if BLOCKED_INLINE_HTTP.search(stripped): |
| 90 | + return {"action": "block", "message": "context-saver: Inline HTTP blocked. Use execute_code instead."} |
| 91 | + if BLOCKED_BUILD.search(stripped): |
| 92 | + return {"action": "block", "message": "context-saver: Build tool redirected. Use ctx_execute with shell."} |
| 93 | + return None |
| 94 | + |
| 95 | +def pre_llm_call(session_id: str, user_message: str, is_first_turn: bool, |
| 96 | + **kwargs) -> Optional[dict]: |
| 97 | + if not is_first_turn or session_id in SESSION_GUIDANCE_SHOWN: |
| 98 | + return None |
| 99 | + SESSION_GUIDANCE_SHOWN[session_id] = True |
| 100 | + return {"context": ROUTING_BLOCK} |
| 101 | + |
| 102 | +def register(ctx) -> None: |
| 103 | + ctx.register_hook("pre_tool_call", pre_tool_call) |
| 104 | + ctx.register_hook("pre_llm_call", pre_llm_call) |
| 105 | + logger.info("context-saver registered: pre_tool_call + pre_llm_call") |
0 commit comments