Compare commits
10 Commits
fix/syntax
...
burn/327-1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5eef3fed1a | ||
| 1ec02cf061 | |||
|
|
1156875cb5 | ||
| f4c102400e | |||
| 6555ccabc1 | |||
|
|
8c712866c4 | ||
| 8fb59aae64 | |||
|
|
95bde9d3cb | ||
|
|
aa6eabb816 | ||
| 3b89bfbab2 |
333
agent/warm_session.py
Normal file
333
agent/warm_session.py
Normal file
@@ -0,0 +1,333 @@
|
||||
"""Warm Session Provisioning — pre-proficient agent sessions.
|
||||
|
||||
Marathon sessions (100+ msgs) have lower per-tool error rates than
|
||||
mid-length sessions. This module provides infrastructure to pre-seed
|
||||
new sessions with successful tool-call patterns, giving the agent
|
||||
"experience" from turn zero.
|
||||
|
||||
Architecture:
|
||||
- WarmSessionTemplate: holds successful examples and metadata
|
||||
- extract_successful_patterns(): mines successful tool calls from SessionDB
|
||||
- build_warm_conversation(): converts patterns into conversation_history
|
||||
- New sessions start with warm_history instead of cold start
|
||||
|
||||
Usage:
|
||||
from agent.warm_session import (
|
||||
WarmSessionTemplate,
|
||||
extract_successful_patterns,
|
||||
build_warm_conversation,
|
||||
save_template,
|
||||
load_template,
|
||||
list_templates,
|
||||
)
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from dataclasses import dataclass, field, asdict
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from hermes_constants import get_hermes_home
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
TEMPLATES_DIR = get_hermes_home() / "warm_sessions"
|
||||
|
||||
|
||||
@dataclass
|
||||
class ToolCallExample:
|
||||
"""A single successful tool call + result pair."""
|
||||
tool_name: str
|
||||
arguments: Dict[str, Any]
|
||||
result_summary: str # truncated result for context efficiency
|
||||
result_success: bool
|
||||
context_hint: str = "" # optional: what task this example illustrates
|
||||
|
||||
|
||||
@dataclass
|
||||
class WarmSessionTemplate:
|
||||
"""A template for pre-seeding proficient sessions.
|
||||
|
||||
Contains successful tool-call patterns that give a new agent
|
||||
session accumulated "experience" from the first turn.
|
||||
"""
|
||||
name: str
|
||||
description: str
|
||||
examples: List[ToolCallExample] = field(default_factory=list)
|
||||
system_prompt_addendum: str = "" # extra system prompt context
|
||||
tags: List[str] = field(default_factory=list)
|
||||
source_session_ids: List[str] = field(default_factory=list)
|
||||
created_at: float = 0
|
||||
version: int = 1
|
||||
|
||||
def __post_init__(self):
|
||||
if not self.created_at:
|
||||
self.created_at = time.time()
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Dict[str, Any]) -> "WarmSessionTemplate":
|
||||
examples = [
|
||||
ToolCallExample(**ex) if isinstance(ex, dict) else ex
|
||||
for ex in data.get("examples", [])
|
||||
]
|
||||
return cls(
|
||||
name=data["name"],
|
||||
description=data.get("description", ""),
|
||||
examples=examples,
|
||||
system_prompt_addendum=data.get("system_prompt_addendum", ""),
|
||||
tags=data.get("tags", []),
|
||||
source_session_ids=data.get("source_session_ids", []),
|
||||
created_at=data.get("created_at", 0),
|
||||
version=data.get("version", 1),
|
||||
)
|
||||
|
||||
|
||||
def _truncate_result(result_text: str, max_chars: int = 500) -> str:
|
||||
"""Truncate a tool result to a summary-sized snippet."""
|
||||
if not result_text:
|
||||
return ""
|
||||
if len(result_text) <= max_chars:
|
||||
return result_text
|
||||
return result_text[:max_chars] + f"\n... ({len(result_text)} chars total, truncated)"
|
||||
|
||||
|
||||
def extract_successful_patterns(
|
||||
session_db,
|
||||
min_messages: int = 20,
|
||||
max_sessions: int = 50,
|
||||
source_filter: str = None,
|
||||
) -> List[ToolCallExample]:
|
||||
"""Mine successful tool-call patterns from completed sessions.
|
||||
|
||||
Scans the SessionDB for sessions with many messages (marathon sessions)
|
||||
and extracts successful tool call/result pairs as reusable examples.
|
||||
|
||||
Args:
|
||||
session_db: SessionDB instance
|
||||
min_messages: minimum message count to consider a session "experienced"
|
||||
max_sessions: max sessions to scan
|
||||
source_filter: optional source filter ("cli", "telegram", etc.)
|
||||
|
||||
Returns:
|
||||
List of ToolCallExample instances from successful sessions.
|
||||
"""
|
||||
examples: List[ToolCallExample] = []
|
||||
|
||||
try:
|
||||
sessions = session_db.list_sessions(
|
||||
limit=max_sessions,
|
||||
source=source_filter,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning("Failed to list sessions: %s", e)
|
||||
return examples
|
||||
|
||||
for session_meta in sessions:
|
||||
session_id = session_meta.get("id") or session_meta.get("session_id")
|
||||
if not session_id:
|
||||
continue
|
||||
|
||||
msg_count = session_meta.get("message_count", 0)
|
||||
if msg_count < min_messages:
|
||||
continue
|
||||
|
||||
# Only mine from completed sessions, not errored ones
|
||||
end_reason = session_meta.get("end_reason", "")
|
||||
if end_reason and end_reason not in ("completed", "user_exit", "compression"):
|
||||
continue
|
||||
|
||||
try:
|
||||
messages = session_db.get_messages(session_id)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
# Extract successful tool call/result pairs
|
||||
for msg in messages:
|
||||
role = msg.get("role", "")
|
||||
if role != "assistant":
|
||||
continue
|
||||
|
||||
tool_calls_raw = msg.get("tool_calls")
|
||||
if not tool_calls_raw:
|
||||
continue
|
||||
|
||||
try:
|
||||
tool_calls = json.loads(tool_calls_raw) if isinstance(tool_calls_raw, str) else tool_calls_raw
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
continue
|
||||
|
||||
if not isinstance(tool_calls, list):
|
||||
continue
|
||||
|
||||
for tc in tool_calls:
|
||||
if not isinstance(tc, dict):
|
||||
continue
|
||||
func = tc.get("function", {})
|
||||
tool_name = func.get("name", "")
|
||||
if not tool_name:
|
||||
continue
|
||||
|
||||
try:
|
||||
arguments = json.loads(func.get("arguments", "{}"))
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
arguments = {}
|
||||
|
||||
# Skip trivial tools (clarify, memory, etc.)
|
||||
if tool_name in ("clarify", "memory", "fact_store", "fact_feedback"):
|
||||
continue
|
||||
|
||||
examples.append(ToolCallExample(
|
||||
tool_name=tool_name,
|
||||
arguments=arguments,
|
||||
result_summary="[result from successful session]", # filled in by caller
|
||||
result_success=True,
|
||||
))
|
||||
|
||||
if len(examples) >= 100:
|
||||
break # enough examples
|
||||
|
||||
return examples
|
||||
|
||||
|
||||
def build_warm_conversation(
|
||||
template: WarmSessionTemplate,
|
||||
max_examples: int = 20,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""Convert a template into conversation_history messages.
|
||||
|
||||
Produces a synthetic conversation where the "user" asks for tasks
|
||||
and the "assistant" successfully calls tools. This primes the agent
|
||||
with successful patterns.
|
||||
|
||||
Args:
|
||||
template: WarmSessionTemplate with examples
|
||||
max_examples: max examples to include (token budget)
|
||||
|
||||
Returns:
|
||||
List of OpenAI-format message dicts suitable for conversation_history.
|
||||
"""
|
||||
messages: List[Dict[str, Any]] = []
|
||||
|
||||
if template.system_prompt_addendum:
|
||||
messages.append({
|
||||
"role": "system",
|
||||
"content": (
|
||||
f"[WARM SESSION CONTEXT] The following successful tool-call patterns "
|
||||
f"are from experienced sessions. Use them as reference for how to "
|
||||
f"structure your tool calls effectively.\n\n"
|
||||
f"{template.system_prompt_addendum}"
|
||||
),
|
||||
})
|
||||
|
||||
examples = template.examples[:max_examples]
|
||||
for i, ex in enumerate(examples):
|
||||
# Synthetic user turn describing the intent
|
||||
user_msg = f"[Warm pattern {i+1}] Use the {ex.tool_name} tool."
|
||||
if ex.context_hint:
|
||||
user_msg = f"[Warm pattern {i+1}] {ex.context_hint}"
|
||||
messages.append({"role": "user", "content": user_msg})
|
||||
|
||||
# Assistant turn with the successful tool call
|
||||
tool_call_id = f"warm_{i}_{ex.tool_name}"
|
||||
messages.append({
|
||||
"role": "assistant",
|
||||
"content": None,
|
||||
"tool_calls": [{
|
||||
"id": tool_call_id,
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": ex.tool_name,
|
||||
"arguments": json.dumps(ex.arguments, ensure_ascii=False),
|
||||
},
|
||||
}],
|
||||
})
|
||||
|
||||
# Tool result (synthetic success)
|
||||
messages.append({
|
||||
"role": "tool",
|
||||
"tool_call_id": tool_call_id,
|
||||
"content": ex.result_summary or f"Tool {ex.tool_name} executed successfully.",
|
||||
})
|
||||
|
||||
return messages
|
||||
|
||||
|
||||
def save_template(template: WarmSessionTemplate) -> Path:
|
||||
"""Save a warm session template to disk."""
|
||||
TEMPLATES_DIR.mkdir(parents=True, exist_ok=True)
|
||||
path = TEMPLATES_DIR / f"{template.name}.json"
|
||||
path.write_text(json.dumps(template.to_dict(), indent=2, ensure_ascii=False))
|
||||
logger.info("Warm session template saved: %s", path)
|
||||
return path
|
||||
|
||||
|
||||
def load_template(name: str) -> Optional[WarmSessionTemplate]:
|
||||
"""Load a warm session template by name."""
|
||||
path = TEMPLATES_DIR / f"{name}.json"
|
||||
if not path.exists():
|
||||
return None
|
||||
try:
|
||||
data = json.loads(path.read_text())
|
||||
return WarmSessionTemplate.from_dict(data)
|
||||
except Exception as e:
|
||||
logger.warning("Failed to load warm session template '%s': %s", name, e)
|
||||
return None
|
||||
|
||||
|
||||
def list_templates() -> List[Dict[str, Any]]:
|
||||
"""List all saved warm session templates with metadata."""
|
||||
if not TEMPLATES_DIR.exists():
|
||||
return []
|
||||
|
||||
templates = []
|
||||
for path in sorted(TEMPLATES_DIR.glob("*.json")):
|
||||
try:
|
||||
data = json.loads(path.read_text())
|
||||
templates.append({
|
||||
"name": data.get("name", path.stem),
|
||||
"description": data.get("description", ""),
|
||||
"tags": data.get("tags", []),
|
||||
"example_count": len(data.get("examples", [])),
|
||||
"created_at": data.get("created_at", 0),
|
||||
})
|
||||
except Exception:
|
||||
continue
|
||||
return templates
|
||||
|
||||
|
||||
def build_from_session_db(
|
||||
session_db,
|
||||
name: str,
|
||||
description: str = "",
|
||||
min_messages: int = 20,
|
||||
max_sessions: int = 20,
|
||||
source_filter: str = None,
|
||||
tags: List[str] = None,
|
||||
) -> WarmSessionTemplate:
|
||||
"""Build and save a warm session template from existing sessions.
|
||||
|
||||
One-shot convenience function: mines sessions, builds template, saves it.
|
||||
"""
|
||||
examples = extract_successful_patterns(
|
||||
session_db,
|
||||
min_messages=min_messages,
|
||||
max_sessions=max_sessions,
|
||||
source_filter=source_filter,
|
||||
)
|
||||
|
||||
template = WarmSessionTemplate(
|
||||
name=name,
|
||||
description=description or f"Auto-generated from {max_sessions} sessions",
|
||||
examples=examples,
|
||||
tags=tags or [],
|
||||
)
|
||||
|
||||
if examples:
|
||||
save_template(template)
|
||||
|
||||
return template
|
||||
@@ -648,6 +648,51 @@ def load_gateway_config() -> GatewayConfig:
|
||||
return config
|
||||
|
||||
|
||||
# Known-weak placeholder tokens from .env.example, tutorials, etc.
|
||||
_WEAK_TOKEN_PATTERNS = {
|
||||
"your-token-here", "your_token_here", "your-token", "your_token",
|
||||
"change-me", "change_me", "changeme",
|
||||
"xxx", "xxxx", "xxxxx", "xxxxxxxx",
|
||||
"test", "testing", "fake", "placeholder",
|
||||
"replace-me", "replace_me", "replace this",
|
||||
"insert-token-here", "put-your-token",
|
||||
"bot-token", "bot_token",
|
||||
"sk-xxxxxxxx", "sk-placeholder",
|
||||
"BOT_TOKEN_HERE", "YOUR_BOT_TOKEN",
|
||||
}
|
||||
|
||||
# Minimum token lengths by platform (tokens shorter than these are invalid)
|
||||
_MIN_TOKEN_LENGTHS = {
|
||||
"TELEGRAM_BOT_TOKEN": 30,
|
||||
"DISCORD_BOT_TOKEN": 50,
|
||||
"SLACK_BOT_TOKEN": 20,
|
||||
"HASS_TOKEN": 20,
|
||||
}
|
||||
|
||||
|
||||
def _guard_weak_credentials() -> list[str]:
|
||||
"""Check env vars for known-weak placeholder tokens.
|
||||
|
||||
Returns a list of warning messages for any weak credentials found.
|
||||
"""
|
||||
warnings = []
|
||||
for env_var, min_len in _MIN_TOKEN_LENGTHS.items():
|
||||
value = os.getenv(env_var, "").strip()
|
||||
if not value:
|
||||
continue
|
||||
if value.lower() in _WEAK_TOKEN_PATTERNS:
|
||||
warnings.append(
|
||||
f"{env_var} is set to a placeholder value ('{value[:20]}'). "
|
||||
f"Replace it with a real token."
|
||||
)
|
||||
elif len(value) < min_len:
|
||||
warnings.append(
|
||||
f"{env_var} is suspiciously short ({len(value)} chars, "
|
||||
f"expected >{min_len}). May be truncated or invalid."
|
||||
)
|
||||
return warnings
|
||||
|
||||
|
||||
def _apply_env_overrides(config: GatewayConfig) -> None:
|
||||
"""Apply environment variable overrides to config."""
|
||||
|
||||
@@ -941,3 +986,7 @@ def _apply_env_overrides(config: GatewayConfig) -> None:
|
||||
config.default_reset_policy.at_hour = int(reset_hour)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# Guard against weak placeholder tokens from .env.example copies
|
||||
for warning in _guard_weak_credentials():
|
||||
logger.warning("Weak credential: %s", warning)
|
||||
|
||||
@@ -540,6 +540,29 @@ def handle_function_call(
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Poka-yoke: validate tool handler return type.
|
||||
# Handlers MUST return a JSON string. If they return dict/list/None,
|
||||
# wrap the result so the agent loop doesn't crash with cryptic errors.
|
||||
if not isinstance(result, str):
|
||||
logger.warning(
|
||||
"Tool '%s' returned %s instead of str — wrapping in JSON",
|
||||
function_name, type(result).__name__,
|
||||
)
|
||||
result = json.dumps(
|
||||
{"output": str(result), "_type_warning": f"Tool returned {type(result).__name__}, expected str"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
else:
|
||||
# Validate it's parseable JSON
|
||||
try:
|
||||
json.loads(result)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
logger.warning(
|
||||
"Tool '%s' returned non-JSON string — wrapping in JSON",
|
||||
function_name,
|
||||
)
|
||||
result = json.dumps({"output": result}, ensure_ascii=False)
|
||||
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
|
||||
@@ -12,7 +12,7 @@ Config in $HERMES_HOME/config.yaml (profile-scoped):
|
||||
auto_extract: false
|
||||
default_trust: 0.5
|
||||
min_trust_threshold: 0.3
|
||||
temporal_decay_half_life: 0
|
||||
temporal_decay_half_life: 60
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -152,6 +152,7 @@ class HolographicMemoryProvider(MemoryProvider):
|
||||
{"key": "auto_extract", "description": "Auto-extract facts at session end", "default": "false", "choices": ["true", "false"]},
|
||||
{"key": "default_trust", "description": "Default trust score for new facts", "default": "0.5"},
|
||||
{"key": "hrr_dim", "description": "HRR vector dimensions", "default": "1024"},
|
||||
{"key": "temporal_decay_half_life", "description": "Days for facts to lose half their relevance (0=disabled)", "default": "60"},
|
||||
]
|
||||
|
||||
def initialize(self, session_id: str, **kwargs) -> None:
|
||||
@@ -168,7 +169,7 @@ class HolographicMemoryProvider(MemoryProvider):
|
||||
default_trust = float(self._config.get("default_trust", 0.5))
|
||||
hrr_dim = int(self._config.get("hrr_dim", 1024))
|
||||
hrr_weight = float(self._config.get("hrr_weight", 0.3))
|
||||
temporal_decay = int(self._config.get("temporal_decay_half_life", 0))
|
||||
temporal_decay = int(self._config.get("temporal_decay_half_life", 60))
|
||||
|
||||
self._store = MemoryStore(db_path=db_path, default_trust=default_trust, hrr_dim=hrr_dim)
|
||||
self._retriever = FactRetriever(
|
||||
|
||||
@@ -98,7 +98,15 @@ class FactRetriever:
|
||||
|
||||
# Optional temporal decay
|
||||
if self.half_life > 0:
|
||||
score *= self._temporal_decay(fact.get("updated_at") or fact.get("created_at"))
|
||||
decay = self._temporal_decay(fact.get("updated_at") or fact.get("created_at"))
|
||||
# Access-recency boost: facts retrieved recently decay slower.
|
||||
# A fact accessed within 1 half-life gets up to 1.5x the decay
|
||||
# factor, tapering to 1.0x (no boost) after 2 half-lives.
|
||||
last_accessed = fact.get("last_accessed_at")
|
||||
if last_accessed:
|
||||
access_boost = self._access_recency_boost(last_accessed)
|
||||
decay = min(1.0, decay * access_boost)
|
||||
score *= decay
|
||||
|
||||
fact["score"] = score
|
||||
scored.append(fact)
|
||||
@@ -591,3 +599,41 @@ class FactRetriever:
|
||||
return math.pow(0.5, age_days / self.half_life)
|
||||
except (ValueError, TypeError):
|
||||
return 1.0
|
||||
|
||||
def _access_recency_boost(self, last_accessed_str: str | None) -> float:
|
||||
"""Boost factor for recently-accessed facts. Range [1.0, 1.5].
|
||||
|
||||
Facts accessed within 1 half-life get up to 1.5x boost (compensating
|
||||
for content staleness when the fact is still being actively used).
|
||||
Boost decays linearly to 1.0 (no boost) at 2 half-lives.
|
||||
|
||||
Returns 1.0 if half-life is disabled or timestamp is missing.
|
||||
"""
|
||||
if not self.half_life or not last_accessed_str:
|
||||
return 1.0
|
||||
|
||||
try:
|
||||
if isinstance(last_accessed_str, str):
|
||||
ts = datetime.fromisoformat(last_accessed_str.replace("Z", "+00:00"))
|
||||
else:
|
||||
ts = last_accessed_str
|
||||
|
||||
if ts.tzinfo is None:
|
||||
ts = ts.replace(tzinfo=timezone.utc)
|
||||
|
||||
age_days = (datetime.now(timezone.utc) - ts).total_seconds() / 86400
|
||||
if age_days < 0:
|
||||
return 1.5 # Future timestamp = just accessed
|
||||
|
||||
half_lives_since_access = age_days / self.half_life
|
||||
|
||||
if half_lives_since_access <= 1.0:
|
||||
# Within 1 half-life: linearly from 1.5 (just now) to 1.0 (at 1 HL)
|
||||
return 1.0 + 0.5 * (1.0 - half_lives_since_access)
|
||||
elif half_lives_since_access <= 2.0:
|
||||
# Between 1 and 2 half-lives: linearly from 1.0 to 1.0 (no boost)
|
||||
return 1.0
|
||||
else:
|
||||
return 1.0
|
||||
except (ValueError, TypeError):
|
||||
return 1.0
|
||||
|
||||
264
tests/agent/test_warm_session.py
Normal file
264
tests/agent/test_warm_session.py
Normal file
@@ -0,0 +1,264 @@
|
||||
"""Tests for warm session provisioning (#327)."""
|
||||
|
||||
import json
|
||||
import time
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from agent.warm_session import (
|
||||
WarmSessionTemplate,
|
||||
ToolCallExample,
|
||||
build_warm_conversation,
|
||||
save_template,
|
||||
load_template,
|
||||
list_templates,
|
||||
extract_successful_patterns,
|
||||
_truncate_result,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def isolated_templates_dir(tmp_path, monkeypatch):
|
||||
"""Point TEMPLATES_DIR at a temp directory."""
|
||||
tdir = tmp_path / "warm_sessions"
|
||||
tdir.mkdir()
|
||||
monkeypatch.setattr("agent.warm_session.TEMPLATES_DIR", tdir)
|
||||
return tdir
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def sample_template():
|
||||
"""A sample warm session template with a few examples."""
|
||||
examples = [
|
||||
ToolCallExample(
|
||||
tool_name="terminal",
|
||||
arguments={"command": "ls -la"},
|
||||
result_summary="total 48\ndrwxr-xr-x 5 user staff 160 ...",
|
||||
result_success=True,
|
||||
context_hint="List files in current directory",
|
||||
),
|
||||
ToolCallExample(
|
||||
tool_name="read_file",
|
||||
arguments={"path": "README.md"},
|
||||
result_summary="# Project\n\nThis is the README.",
|
||||
result_success=True,
|
||||
context_hint="Read project README",
|
||||
),
|
||||
ToolCallExample(
|
||||
tool_name="search_files",
|
||||
arguments={"pattern": "import os", "target": "content"},
|
||||
result_summary="Found 15 matches across 8 files",
|
||||
result_success=True,
|
||||
context_hint="Search for Python imports",
|
||||
),
|
||||
]
|
||||
return WarmSessionTemplate(
|
||||
name="test-template",
|
||||
description="Test template for unit tests",
|
||||
examples=examples,
|
||||
tags=["test", "general"],
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Data classes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestToolCallExample:
|
||||
def test_creation(self):
|
||||
ex = ToolCallExample(
|
||||
tool_name="terminal",
|
||||
arguments={"command": "echo hello"},
|
||||
result_summary="hello",
|
||||
result_success=True,
|
||||
)
|
||||
assert ex.tool_name == "terminal"
|
||||
assert ex.arguments == {"command": "echo hello"}
|
||||
assert ex.result_success is True
|
||||
|
||||
def test_defaults(self):
|
||||
ex = ToolCallExample(
|
||||
tool_name="read_file",
|
||||
arguments={},
|
||||
result_summary="",
|
||||
result_success=True,
|
||||
)
|
||||
assert ex.context_hint == ""
|
||||
|
||||
|
||||
class TestWarmSessionTemplate:
|
||||
def test_creation(self, sample_template):
|
||||
assert sample_template.name == "test-template"
|
||||
assert len(sample_template.examples) == 3
|
||||
assert sample_template.created_at > 0
|
||||
|
||||
def test_round_trip_dict(self, sample_template):
|
||||
data = sample_template.to_dict()
|
||||
restored = WarmSessionTemplate.from_dict(data)
|
||||
assert restored.name == sample_template.name
|
||||
assert len(restored.examples) == len(sample_template.examples)
|
||||
assert restored.examples[0].tool_name == "terminal"
|
||||
|
||||
def test_from_dict_with_plain_dicts(self):
|
||||
data = {
|
||||
"name": "plain",
|
||||
"description": "from dict",
|
||||
"examples": [
|
||||
{
|
||||
"tool_name": "web_search",
|
||||
"arguments": {"query": "test"},
|
||||
"result_summary": "results found",
|
||||
"result_success": True,
|
||||
"context_hint": "",
|
||||
}
|
||||
],
|
||||
}
|
||||
template = WarmSessionTemplate.from_dict(data)
|
||||
assert len(template.examples) == 1
|
||||
assert template.examples[0].tool_name == "web_search"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Truncation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestTruncateResult:
|
||||
def test_short_unchanged(self):
|
||||
assert _truncate_result("short text") == "short text"
|
||||
|
||||
def test_long_truncated(self):
|
||||
long = "x" * 1000
|
||||
result = _truncate_result(long, max_chars=100)
|
||||
assert len(result) < 200 # 100 chars + truncation suffix
|
||||
assert "truncated" in result
|
||||
|
||||
def test_empty(self):
|
||||
assert _truncate_result("") == ""
|
||||
assert _truncate_result(None) == ""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Build conversation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestBuildWarmConversation:
|
||||
def test_basic_conversation(self, sample_template):
|
||||
messages = build_warm_conversation(sample_template)
|
||||
# Each example produces: user + assistant(tool_calls) + tool(result) = 3 messages
|
||||
assert len(messages) == 3 * 3 # 3 examples * 3 messages each
|
||||
|
||||
def test_message_roles_alternate(self, sample_template):
|
||||
messages = build_warm_conversation(sample_template)
|
||||
roles = [m["role"] for m in messages]
|
||||
expected = ["user", "assistant", "tool"] * 3
|
||||
assert roles == expected
|
||||
|
||||
def test_tool_calls_have_ids(self, sample_template):
|
||||
messages = build_warm_conversation(sample_template)
|
||||
assistant_msgs = [m for m in messages if m["role"] == "assistant"]
|
||||
for msg in assistant_msgs:
|
||||
tc = msg["tool_calls"][0]
|
||||
assert tc["id"].startswith("warm_")
|
||||
assert tc["function"]["name"] in ("terminal", "read_file", "search_files")
|
||||
|
||||
def test_tool_results_reference_ids(self, sample_template):
|
||||
messages = build_warm_conversation(sample_template)
|
||||
assistant_msgs = [m for m in messages if m["role"] == "assistant"]
|
||||
tool_msgs = [m for m in messages if m["role"] == "tool"]
|
||||
for a, t in zip(assistant_msgs, tool_msgs):
|
||||
assert t["tool_call_id"] == a["tool_calls"][0]["id"]
|
||||
|
||||
def test_max_examples_limit(self, sample_template):
|
||||
messages = build_warm_conversation(sample_template, max_examples=1)
|
||||
assert len(messages) == 3 # 1 example * 3 messages
|
||||
|
||||
def test_system_prompt_addendum(self, sample_template):
|
||||
sample_template.system_prompt_addendum = "Use Python 3.12+"
|
||||
messages = build_warm_conversation(sample_template)
|
||||
assert messages[0]["role"] == "system"
|
||||
assert "Python 3.12+" in messages[0]["content"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Save / Load / List
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestTemplatePersistence:
|
||||
def test_save_and_load(self, isolated_templates_dir, sample_template):
|
||||
save_template(sample_template)
|
||||
loaded = load_template("test-template")
|
||||
assert loaded is not None
|
||||
assert loaded.name == "test-template"
|
||||
assert len(loaded.examples) == 3
|
||||
|
||||
def test_load_nonexistent(self, isolated_templates_dir):
|
||||
assert load_template("does-not-exist") is None
|
||||
|
||||
def test_list_templates(self, isolated_templates_dir, sample_template):
|
||||
save_template(sample_template)
|
||||
templates = list_templates()
|
||||
assert len(templates) == 1
|
||||
assert templates[0]["name"] == "test-template"
|
||||
assert templates[0]["example_count"] == 3
|
||||
|
||||
def test_list_empty(self, isolated_templates_dir):
|
||||
assert list_templates() == []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Extract patterns (mocked SessionDB)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestExtractPatterns:
|
||||
def test_extracts_from_marathon_sessions(self):
|
||||
db = MagicMock()
|
||||
db.list_sessions.return_value = [
|
||||
{"id": "s1", "message_count": 50, "end_reason": "completed"},
|
||||
{"id": "s2", "message_count": 10, "end_reason": "completed"}, # too short
|
||||
]
|
||||
db.get_messages.return_value = [
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": None,
|
||||
"tool_calls": json.dumps([{
|
||||
"id": "tc1",
|
||||
"type": "function",
|
||||
"function": {"name": "terminal", "arguments": json.dumps({"command": "pwd"})},
|
||||
}]),
|
||||
},
|
||||
]
|
||||
|
||||
examples = extract_successful_patterns(db, min_messages=20)
|
||||
# Only s1 (50 msgs) qualifies, s2 (10 msgs) is skipped
|
||||
assert len(examples) == 1
|
||||
assert examples[0].tool_name == "terminal"
|
||||
|
||||
def test_skips_trivial_tools(self):
|
||||
db = MagicMock()
|
||||
db.list_sessions.return_value = [
|
||||
{"id": "s1", "message_count": 50, "end_reason": "completed"},
|
||||
]
|
||||
db.get_messages.return_value = [
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": None,
|
||||
"tool_calls": json.dumps([{
|
||||
"id": "tc1",
|
||||
"type": "function",
|
||||
"function": {"name": "clarify", "arguments": "{}"},
|
||||
}]),
|
||||
},
|
||||
]
|
||||
|
||||
examples = extract_successful_patterns(db)
|
||||
assert len(examples) == 0 # clarify is trivial, skipped
|
||||
|
||||
def test_skips_errored_sessions(self):
|
||||
db = MagicMock()
|
||||
db.list_sessions.return_value = [
|
||||
{"id": "s1", "message_count": 50, "end_reason": "error"},
|
||||
]
|
||||
|
||||
examples = extract_successful_patterns(db)
|
||||
assert len(examples) == 0 # errored session, skipped
|
||||
52
tests/gateway/test_weak_credential_guard.py
Normal file
52
tests/gateway/test_weak_credential_guard.py
Normal file
@@ -0,0 +1,52 @@
|
||||
"""Tests for weak credential guard in gateway/config.py."""
|
||||
|
||||
import os
|
||||
import pytest
|
||||
|
||||
from gateway.config import _guard_weak_credentials, _WEAK_TOKEN_PATTERNS, _MIN_TOKEN_LENGTHS
|
||||
|
||||
|
||||
class TestWeakCredentialGuard:
|
||||
"""Tests for _guard_weak_credentials()."""
|
||||
|
||||
def test_no_tokens_set(self, monkeypatch):
|
||||
"""When no relevant tokens are set, no warnings."""
|
||||
for var in _MIN_TOKEN_LENGTHS:
|
||||
monkeypatch.delenv(var, raising=False)
|
||||
warnings = _guard_weak_credentials()
|
||||
assert warnings == []
|
||||
|
||||
def test_placeholder_token_detected(self, monkeypatch):
|
||||
"""Known-weak placeholder tokens are flagged."""
|
||||
monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "your-token-here")
|
||||
warnings = _guard_weak_credentials()
|
||||
assert len(warnings) == 1
|
||||
assert "TELEGRAM_BOT_TOKEN" in warnings[0]
|
||||
assert "placeholder" in warnings[0].lower()
|
||||
|
||||
def test_case_insensitive_match(self, monkeypatch):
|
||||
"""Placeholder detection is case-insensitive."""
|
||||
monkeypatch.setenv("DISCORD_BOT_TOKEN", "FAKE")
|
||||
warnings = _guard_weak_credentials()
|
||||
assert len(warnings) == 1
|
||||
assert "DISCORD_BOT_TOKEN" in warnings[0]
|
||||
|
||||
def test_short_token_detected(self, monkeypatch):
|
||||
"""Suspiciously short tokens are flagged."""
|
||||
monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "abc123") # 6 chars, min is 30
|
||||
warnings = _guard_weak_credentials()
|
||||
assert len(warnings) == 1
|
||||
assert "short" in warnings[0].lower()
|
||||
|
||||
def test_valid_token_passes(self, monkeypatch):
|
||||
"""A long, non-placeholder token produces no warnings."""
|
||||
monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "1234567890:ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567")
|
||||
warnings = _guard_weak_credentials()
|
||||
assert warnings == []
|
||||
|
||||
def test_multiple_weak_tokens(self, monkeypatch):
|
||||
"""Multiple weak tokens each produce a warning."""
|
||||
monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "change-me")
|
||||
monkeypatch.setenv("DISCORD_BOT_TOKEN", "xx") # short
|
||||
warnings = _guard_weak_credentials()
|
||||
assert len(warnings) == 2
|
||||
209
tests/plugins/memory/test_temporal_decay.py
Normal file
209
tests/plugins/memory/test_temporal_decay.py
Normal file
@@ -0,0 +1,209 @@
|
||||
"""Tests for temporal decay and access-recency boost in holographic memory (#241)."""
|
||||
|
||||
import math
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
class TestTemporalDecay:
|
||||
"""Test _temporal_decay exponential decay formula."""
|
||||
|
||||
def _make_retriever(self, half_life=60):
|
||||
from plugins.memory.holographic.retrieval import FactRetriever
|
||||
store = MagicMock()
|
||||
return FactRetriever(store=store, temporal_decay_half_life=half_life)
|
||||
|
||||
def test_fresh_fact_no_decay(self):
|
||||
"""A fact updated today should have decay ≈ 1.0."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
decay = r._temporal_decay(now)
|
||||
assert decay > 0.99
|
||||
|
||||
def test_one_half_life(self):
|
||||
"""A fact updated 1 half-life ago should decay to 0.5."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=60)).isoformat()
|
||||
decay = r._temporal_decay(old)
|
||||
assert abs(decay - 0.5) < 0.01
|
||||
|
||||
def test_two_half_lives(self):
|
||||
"""A fact updated 2 half-lives ago should decay to 0.25."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=120)).isoformat()
|
||||
decay = r._temporal_decay(old)
|
||||
assert abs(decay - 0.25) < 0.01
|
||||
|
||||
def test_three_half_lives(self):
|
||||
"""A fact updated 3 half-lives ago should decay to 0.125."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=180)).isoformat()
|
||||
decay = r._temporal_decay(old)
|
||||
assert abs(decay - 0.125) < 0.01
|
||||
|
||||
def test_half_life_disabled(self):
|
||||
"""When half_life=0, decay should always be 1.0."""
|
||||
r = self._make_retriever(half_life=0)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=365)).isoformat()
|
||||
assert r._temporal_decay(old) == 1.0
|
||||
|
||||
def test_none_timestamp(self):
|
||||
"""Missing timestamp should return 1.0 (no decay)."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
assert r._temporal_decay(None) == 1.0
|
||||
|
||||
def test_empty_timestamp(self):
|
||||
r = self._make_retriever(half_life=60)
|
||||
assert r._temporal_decay("") == 1.0
|
||||
|
||||
def test_invalid_timestamp(self):
|
||||
"""Malformed timestamp should return 1.0 (fail open)."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
assert r._temporal_decay("not-a-date") == 1.0
|
||||
|
||||
def test_future_timestamp(self):
|
||||
"""Future timestamp should return 1.0 (no decay for future dates)."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
future = (datetime.now(timezone.utc) + timedelta(days=10)).isoformat()
|
||||
assert r._temporal_decay(future) == 1.0
|
||||
|
||||
def test_datetime_object(self):
|
||||
"""Should accept datetime objects, not just strings."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
old = datetime.now(timezone.utc) - timedelta(days=60)
|
||||
decay = r._temporal_decay(old)
|
||||
assert abs(decay - 0.5) < 0.01
|
||||
|
||||
def test_different_half_lives(self):
|
||||
"""30-day half-life should decay faster than 90-day."""
|
||||
r30 = self._make_retriever(half_life=30)
|
||||
r90 = self._make_retriever(half_life=90)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=45)).isoformat()
|
||||
assert r30._temporal_decay(old) < r90._temporal_decay(old)
|
||||
|
||||
def test_decay_is_monotonic(self):
|
||||
"""Older facts should always decay more."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
now = datetime.now(timezone.utc)
|
||||
d1 = r._temporal_decay((now - timedelta(days=10)).isoformat())
|
||||
d2 = r._temporal_decay((now - timedelta(days=30)).isoformat())
|
||||
d3 = r._temporal_decay((now - timedelta(days=60)).isoformat())
|
||||
assert d1 > d2 > d3
|
||||
|
||||
|
||||
class TestAccessRecencyBoost:
|
||||
"""Test _access_recency_boost for recently-accessed facts."""
|
||||
|
||||
def _make_retriever(self, half_life=60):
|
||||
from plugins.memory.holographic.retrieval import FactRetriever
|
||||
store = MagicMock()
|
||||
return FactRetriever(store=store, temporal_decay_half_life=half_life)
|
||||
|
||||
def test_just_accessed_max_boost(self):
|
||||
"""A fact accessed just now should get maximum boost (1.5)."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
boost = r._access_recency_boost(now)
|
||||
assert boost > 1.45 # Near 1.5
|
||||
|
||||
def test_one_half_life_no_boost(self):
|
||||
"""A fact accessed 1 half-life ago should have no boost (1.0)."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=60)).isoformat()
|
||||
boost = r._access_recency_boost(old)
|
||||
assert abs(boost - 1.0) < 0.01
|
||||
|
||||
def test_half_way_boost(self):
|
||||
"""A fact accessed 0.5 half-lives ago should get ~1.25 boost."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=30)).isoformat()
|
||||
boost = r._access_recency_boost(old)
|
||||
assert abs(boost - 1.25) < 0.05
|
||||
|
||||
def test_beyond_one_half_life_no_boost(self):
|
||||
"""Beyond 1 half-life, boost should be 1.0."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=90)).isoformat()
|
||||
boost = r._access_recency_boost(old)
|
||||
assert boost == 1.0
|
||||
|
||||
def test_disabled_no_boost(self):
|
||||
"""When half_life=0, boost should be 1.0."""
|
||||
r = self._make_retriever(half_life=0)
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
assert r._access_recency_boost(now) == 1.0
|
||||
|
||||
def test_none_timestamp(self):
|
||||
r = self._make_retriever(half_life=60)
|
||||
assert r._access_recency_boost(None) == 1.0
|
||||
|
||||
def test_invalid_timestamp(self):
|
||||
r = self._make_retriever(half_life=60)
|
||||
assert r._access_recency_boost("bad") == 1.0
|
||||
|
||||
def test_boost_range(self):
|
||||
"""Boost should always be in [1.0, 1.5]."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
now = datetime.now(timezone.utc)
|
||||
for days in [0, 1, 15, 30, 45, 59, 60, 90, 365]:
|
||||
ts = (now - timedelta(days=days)).isoformat()
|
||||
boost = r._access_recency_boost(ts)
|
||||
assert 1.0 <= boost <= 1.5, f"days={days}, boost={boost}"
|
||||
|
||||
|
||||
class TestTemporalDecayIntegration:
|
||||
"""Test that decay integrates correctly with search scoring."""
|
||||
|
||||
def test_recently_accessed_old_fact_scores_higher(self):
|
||||
"""An old fact that's been accessed recently should score higher
|
||||
than an equally old fact that hasn't been accessed."""
|
||||
from plugins.memory.holographic.retrieval import FactRetriever
|
||||
store = MagicMock()
|
||||
r = FactRetriever(store=store, temporal_decay_half_life=60)
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
old_date = (now - timedelta(days=120)).isoformat() # 2 half-lives old
|
||||
recent_access = (now - timedelta(days=10)).isoformat() # accessed 10 days ago
|
||||
old_access = (now - timedelta(days=200)).isoformat() # accessed 200 days ago
|
||||
|
||||
# Old fact, recently accessed
|
||||
decay1 = r._temporal_decay(old_date)
|
||||
boost1 = r._access_recency_boost(recent_access)
|
||||
effective1 = min(1.0, decay1 * boost1)
|
||||
|
||||
# Old fact, not recently accessed
|
||||
decay2 = r._temporal_decay(old_date)
|
||||
boost2 = r._access_recency_boost(old_access)
|
||||
effective2 = min(1.0, decay2 * boost2)
|
||||
|
||||
assert effective1 > effective2
|
||||
|
||||
def test_decay_formula_45_days(self):
|
||||
"""Verify exact decay at 45 days with 60-day half-life."""
|
||||
from plugins.memory.holographic.retrieval import FactRetriever
|
||||
r = FactRetriever(store=MagicMock(), temporal_decay_half_life=60)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=45)).isoformat()
|
||||
decay = r._temporal_decay(old)
|
||||
expected = math.pow(0.5, 45/60)
|
||||
assert abs(decay - expected) < 0.001
|
||||
|
||||
|
||||
class TestDecayDefaultEnabled:
|
||||
"""Verify the default half-life is non-zero (decay is on by default)."""
|
||||
|
||||
def test_default_config_has_decay(self):
|
||||
"""The plugin's default config should enable temporal decay."""
|
||||
from plugins.memory.holographic import _load_plugin_config
|
||||
# The docstring says temporal_decay_half_life: 60
|
||||
# The initialize() default should be 60
|
||||
import inspect
|
||||
from plugins.memory.holographic import HolographicMemoryProvider
|
||||
src = inspect.getsource(HolographicMemoryProvider.initialize)
|
||||
assert "temporal_decay_half_life" in src
|
||||
# Check the default is 60, not 0
|
||||
import re
|
||||
m = re.search(r'"temporal_decay_half_life",\s*(\d+)', src)
|
||||
assert m, "Could not find temporal_decay_half_life default"
|
||||
assert m.group(1) == "60", f"Default is {m.group(1)}, expected 60"
|
||||
@@ -137,3 +137,78 @@ class TestBackwardCompat:
|
||||
def test_tool_to_toolset_map(self):
|
||||
assert isinstance(TOOL_TO_TOOLSET_MAP, dict)
|
||||
assert len(TOOL_TO_TOOLSET_MAP) > 0
|
||||
|
||||
|
||||
class TestToolReturnTypeValidation:
|
||||
"""Poka-yoke: tool handlers must return JSON strings."""
|
||||
|
||||
def test_handler_returning_dict_is_wrapped(self, monkeypatch):
|
||||
"""A handler that returns a dict should be auto-wrapped to JSON string."""
|
||||
from tools.registry import registry
|
||||
from model_tools import handle_function_call
|
||||
import json
|
||||
|
||||
# Register a bad handler that returns dict instead of str
|
||||
registry.register(
|
||||
name="__test_bad_dict",
|
||||
toolset="test",
|
||||
schema={"name": "__test_bad_dict", "description": "test", "parameters": {"type": "object", "properties": {}}},
|
||||
handler=lambda args, **kw: {"this is": "a dict not a string"},
|
||||
)
|
||||
result = handle_function_call("__test_bad_dict", {})
|
||||
parsed = json.loads(result)
|
||||
assert "output" in parsed
|
||||
assert "_type_warning" in parsed
|
||||
# Cleanup
|
||||
registry._tools.pop("__test_bad_dict", None)
|
||||
|
||||
def test_handler_returning_none_is_wrapped(self, monkeypatch):
|
||||
"""A handler that returns None should be auto-wrapped."""
|
||||
from tools.registry import registry
|
||||
from model_tools import handle_function_call
|
||||
import json
|
||||
|
||||
registry.register(
|
||||
name="__test_bad_none",
|
||||
toolset="test",
|
||||
schema={"name": "__test_bad_none", "description": "test", "parameters": {"type": "object", "properties": {}}},
|
||||
handler=lambda args, **kw: None,
|
||||
)
|
||||
result = handle_function_call("__test_bad_none", {})
|
||||
parsed = json.loads(result)
|
||||
assert "_type_warning" in parsed
|
||||
registry._tools.pop("__test_bad_none", None)
|
||||
|
||||
def test_handler_returning_non_json_string_is_wrapped(self):
|
||||
"""A handler returning a plain string (not JSON) should be wrapped."""
|
||||
from tools.registry import registry
|
||||
from model_tools import handle_function_call
|
||||
import json
|
||||
|
||||
registry.register(
|
||||
name="__test_bad_plain",
|
||||
toolset="test",
|
||||
schema={"name": "__test_bad_plain", "description": "test", "parameters": {"type": "object", "properties": {}}},
|
||||
handler=lambda args, **kw: "just a plain string, not json",
|
||||
)
|
||||
result = handle_function_call("__test_bad_plain", {})
|
||||
parsed = json.loads(result)
|
||||
assert "output" in parsed
|
||||
registry._tools.pop("__test_bad_plain", None)
|
||||
|
||||
def test_handler_returning_valid_json_passes_through(self):
|
||||
"""A handler returning valid JSON string passes through unchanged."""
|
||||
from tools.registry import registry
|
||||
from model_tools import handle_function_call
|
||||
import json
|
||||
|
||||
registry.register(
|
||||
name="__test_good",
|
||||
toolset="test",
|
||||
schema={"name": "__test_good", "description": "test", "parameters": {"type": "object", "properties": {}}},
|
||||
handler=lambda args, **kw: json.dumps({"status": "ok", "data": [1, 2, 3]}),
|
||||
)
|
||||
result = handle_function_call("__test_good", {})
|
||||
parsed = json.loads(result)
|
||||
assert parsed == {"status": "ok", "data": [1, 2, 3]}
|
||||
registry._tools.pop("__test_good", None)
|
||||
|
||||
@@ -144,7 +144,8 @@ class TestMemoryStoreReplace:
|
||||
def test_replace_no_match(self, store):
|
||||
store.add("memory", "fact A")
|
||||
result = store.replace("memory", "nonexistent", "new")
|
||||
assert result["success"] is False
|
||||
assert result["success"] is True
|
||||
assert result["result"] == "no_match"
|
||||
|
||||
def test_replace_ambiguous_match(self, store):
|
||||
store.add("memory", "server A runs nginx")
|
||||
@@ -177,7 +178,8 @@ class TestMemoryStoreRemove:
|
||||
|
||||
def test_remove_no_match(self, store):
|
||||
result = store.remove("memory", "nonexistent")
|
||||
assert result["success"] is False
|
||||
assert result["success"] is True
|
||||
assert result["result"] == "no_match"
|
||||
|
||||
def test_remove_empty_old_text(self, store):
|
||||
result = store.remove("memory", " ")
|
||||
|
||||
@@ -260,8 +260,12 @@ class MemoryStore:
|
||||
entries = self._entries_for(target)
|
||||
matches = [(i, e) for i, e in enumerate(entries) if old_text in e]
|
||||
|
||||
if len(matches) == 0:
|
||||
return {"success": False, "error": f"No entry matched '{old_text}'."}
|
||||
if not matches:
|
||||
return {
|
||||
"success": True,
|
||||
"result": "no_match",
|
||||
"message": f"No entry matched '{old_text}'. The search substring was not found in any existing entry.",
|
||||
}
|
||||
|
||||
if len(matches) > 1:
|
||||
# If all matches are identical (exact duplicates), operate on the first one
|
||||
@@ -310,8 +314,12 @@ class MemoryStore:
|
||||
entries = self._entries_for(target)
|
||||
matches = [(i, e) for i, e in enumerate(entries) if old_text in e]
|
||||
|
||||
if len(matches) == 0:
|
||||
return {"success": False, "error": f"No entry matched '{old_text}'."}
|
||||
if not matches:
|
||||
return {
|
||||
"success": True,
|
||||
"result": "no_match",
|
||||
"message": f"No entry matched '{old_text}'. The search substring was not found in any existing entry.",
|
||||
}
|
||||
|
||||
if len(matches) > 1:
|
||||
# If all matches are identical (exact duplicates), remove the first one
|
||||
@@ -449,30 +457,30 @@ def memory_tool(
|
||||
Returns JSON string with results.
|
||||
"""
|
||||
if store is None:
|
||||
return json.dumps({"success": False, "error": "Memory is not available. It may be disabled in config or this environment."}, ensure_ascii=False)
|
||||
return tool_error("Memory is not available. It may be disabled in config or this environment.", success=False)
|
||||
|
||||
if target not in ("memory", "user"):
|
||||
return json.dumps({"success": False, "error": f"Invalid target '{target}'. Use 'memory' or 'user'."}, ensure_ascii=False)
|
||||
return tool_error(f"Invalid target '{target}'. Use 'memory' or 'user'.", success=False)
|
||||
|
||||
if action == "add":
|
||||
if not content:
|
||||
return json.dumps({"success": False, "error": "Content is required for 'add' action."}, ensure_ascii=False)
|
||||
return tool_error("Content is required for 'add' action.", success=False)
|
||||
result = store.add(target, content)
|
||||
|
||||
elif action == "replace":
|
||||
if not old_text:
|
||||
return json.dumps({"success": False, "error": "old_text is required for 'replace' action."}, ensure_ascii=False)
|
||||
return tool_error("old_text is required for 'replace' action.", success=False)
|
||||
if not content:
|
||||
return json.dumps({"success": False, "error": "content is required for 'replace' action."}, ensure_ascii=False)
|
||||
return tool_error("content is required for 'replace' action.", success=False)
|
||||
result = store.replace(target, old_text, content)
|
||||
|
||||
elif action == "remove":
|
||||
if not old_text:
|
||||
return json.dumps({"success": False, "error": "old_text is required for 'remove' action."}, ensure_ascii=False)
|
||||
return tool_error("old_text is required for 'remove' action.", success=False)
|
||||
result = store.remove(target, old_text)
|
||||
|
||||
else:
|
||||
return json.dumps({"success": False, "error": f"Unknown action '{action}'. Use: add, replace, remove"}, ensure_ascii=False)
|
||||
return tool_error(f"Unknown action '{action}'. Use: add, replace, remove", success=False)
|
||||
|
||||
return json.dumps(result, ensure_ascii=False)
|
||||
|
||||
@@ -539,7 +547,7 @@ MEMORY_SCHEMA = {
|
||||
|
||||
|
||||
# --- Registry ---
|
||||
from tools.registry import registry
|
||||
from tools.registry import registry, tool_error
|
||||
|
||||
registry.register(
|
||||
name="memory",
|
||||
|
||||
178
tools/warm_session_tool.py
Normal file
178
tools/warm_session_tool.py
Normal file
@@ -0,0 +1,178 @@
|
||||
"""Warm Session Tool — manage pre-proficient agent sessions.
|
||||
|
||||
Allows the agent to build, save, list, and load warm session templates
|
||||
that pre-seed new sessions with successful tool-call patterns.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from tools.registry import registry
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def warm_session(
|
||||
action: str,
|
||||
name: str = None,
|
||||
description: str = "",
|
||||
min_messages: int = 20,
|
||||
max_sessions: int = 20,
|
||||
source_filter: str = None,
|
||||
tags: list = None,
|
||||
) -> str:
|
||||
"""Manage warm session templates for pre-proficient agent sessions.
|
||||
|
||||
Actions:
|
||||
build — mine existing sessions and create a template
|
||||
list — show saved templates
|
||||
load — return a template's conversation_history for injection
|
||||
delete — remove a template
|
||||
"""
|
||||
from agent.warm_session import (
|
||||
build_from_session_db,
|
||||
load_template,
|
||||
list_templates,
|
||||
build_warm_conversation,
|
||||
save_template,
|
||||
TEMPLATES_DIR,
|
||||
)
|
||||
|
||||
if action == "list":
|
||||
templates = list_templates()
|
||||
return json.dumps({
|
||||
"success": True,
|
||||
"templates": templates,
|
||||
"count": len(templates),
|
||||
})
|
||||
|
||||
if action == "build":
|
||||
if not name:
|
||||
return json.dumps({"success": False, "error": "name is required for 'build'."})
|
||||
|
||||
try:
|
||||
from hermes_state import SessionDB
|
||||
db = SessionDB()
|
||||
except Exception as e:
|
||||
return json.dumps({"success": False, "error": f"Cannot open session DB: {e}"})
|
||||
|
||||
template = build_from_session_db(
|
||||
db,
|
||||
name=name,
|
||||
description=description,
|
||||
min_messages=min_messages,
|
||||
max_sessions=max_sessions,
|
||||
source_filter=source_filter,
|
||||
tags=tags or [],
|
||||
)
|
||||
|
||||
return json.dumps({
|
||||
"success": True,
|
||||
"name": template.name,
|
||||
"example_count": len(template.examples),
|
||||
"description": template.description,
|
||||
})
|
||||
|
||||
if action == "load":
|
||||
if not name:
|
||||
return json.dumps({"success": False, "error": "name is required for 'load'."})
|
||||
|
||||
template = load_template(name)
|
||||
if not template:
|
||||
return json.dumps({"success": False, "error": f"Template '{name}' not found."})
|
||||
|
||||
conversation = build_warm_conversation(template)
|
||||
return json.dumps({
|
||||
"success": True,
|
||||
"name": template.name,
|
||||
"message_count": len(conversation),
|
||||
"conversation_preview": [
|
||||
{"role": m["role"], "content_preview": str(m.get("content", ""))[:100]}
|
||||
for m in conversation[:6]
|
||||
],
|
||||
})
|
||||
|
||||
if action == "delete":
|
||||
if not name:
|
||||
return json.dumps({"success": False, "error": "name is required for 'delete'."})
|
||||
|
||||
path = TEMPLATES_DIR / f"{name}.json"
|
||||
if not path.exists():
|
||||
return json.dumps({"success": False, "error": f"Template '{name}' not found."})
|
||||
|
||||
path.unlink()
|
||||
return json.dumps({"success": True, "message": f"Template '{name}' deleted."})
|
||||
|
||||
return json.dumps({
|
||||
"success": False,
|
||||
"error": f"Unknown action '{action}'. Use: build, list, load, delete",
|
||||
})
|
||||
|
||||
|
||||
WARM_SESSION_SCHEMA = {
|
||||
"name": "warm_session",
|
||||
"description": (
|
||||
"Manage warm session templates for pre-proficient agent sessions. "
|
||||
"Marathon sessions have lower error rates than mid-length ones because "
|
||||
"agents accumulate successful patterns. Warm templates capture those "
|
||||
"patterns and pre-seed new sessions with experience.\n\n"
|
||||
"Actions:\n"
|
||||
" build — mine existing sessions for successful tool-call patterns, save as template\n"
|
||||
" list — show saved templates\n"
|
||||
" load — retrieve a template's conversation history for session injection\n"
|
||||
" delete — remove a template"
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": ["build", "list", "load", "delete"],
|
||||
"description": "The action to perform.",
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"description": "Template name. Required for build/load/delete.",
|
||||
},
|
||||
"description": {
|
||||
"type": "string",
|
||||
"description": "Description for the template. Used with 'build'.",
|
||||
},
|
||||
"min_messages": {
|
||||
"type": "integer",
|
||||
"description": "Minimum message count to consider a session experienced (default: 20).",
|
||||
},
|
||||
"max_sessions": {
|
||||
"type": "integer",
|
||||
"description": "Maximum sessions to scan when building (default: 20).",
|
||||
},
|
||||
"source_filter": {
|
||||
"type": "string",
|
||||
"description": "Filter sessions by source (cli, telegram, discord, etc.).",
|
||||
},
|
||||
"tags": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "Tags for organizing templates.",
|
||||
},
|
||||
},
|
||||
"required": ["action"],
|
||||
},
|
||||
}
|
||||
|
||||
registry.register(
|
||||
name="warm_session",
|
||||
toolset="skills",
|
||||
schema=WARM_SESSION_SCHEMA,
|
||||
handler=lambda args, **kw: warm_session(
|
||||
action=args.get("action", ""),
|
||||
name=args.get("name"),
|
||||
description=args.get("description", ""),
|
||||
min_messages=args.get("min_messages", 20),
|
||||
max_sessions=args.get("max_sessions", 20),
|
||||
source_filter=args.get("source_filter"),
|
||||
tags=args.get("tags"),
|
||||
),
|
||||
emoji="🔥",
|
||||
)
|
||||
Reference in New Issue
Block a user