Compare commits
1 Commits
queue/327-
...
q/375-1776
| Author | SHA1 | Date | |
|---|---|---|---|
| 5ae1bf697d |
270
deploy-crons.py
270
deploy-crons.py
@@ -1,154 +1,174 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
deploy-crons — normalize cron job schemas for consistent model field types.
|
||||
deploy-crons -- deploy cron jobs from YAML config and normalize jobs.json.
|
||||
|
||||
This script ensures that the model field in jobs.json is always a dict when
|
||||
either model or provider is specified, preventing schema inconsistency.
|
||||
Two modes:
|
||||
--deploy Sync jobs from cron-jobs.yaml into jobs.json (create / update).
|
||||
--normalize Normalize model field types in existing jobs.json.
|
||||
|
||||
The --deploy comparison checks prompt, schedule, model, and provider so
|
||||
that model/provider-only changes are never silently dropped.
|
||||
|
||||
Usage:
|
||||
python deploy-crons.py [--dry-run] [--jobs-file PATH]
|
||||
python deploy-crons.py --deploy [--config PATH] [--jobs-file PATH] [--dry-run]
|
||||
python deploy-crons.py --normalize [--jobs-file PATH] [--dry-run]
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Optional
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
try:
|
||||
import yaml
|
||||
HAS_YAML = True
|
||||
except ImportError:
|
||||
HAS_YAML = False
|
||||
|
||||
|
||||
def _flat_model(job: Dict[str, Any]) -> Optional[str]:
|
||||
m = job.get("model")
|
||||
if isinstance(m, dict):
|
||||
return m.get("model")
|
||||
return m
|
||||
|
||||
|
||||
def _flat_provider(job: Dict[str, Any]) -> Optional[str]:
|
||||
m = job.get("model")
|
||||
if isinstance(m, dict):
|
||||
return m.get("provider")
|
||||
return job.get("provider")
|
||||
|
||||
|
||||
def normalize_job(job: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
Normalize a job dict to ensure consistent model field types.
|
||||
|
||||
Before normalization:
|
||||
- If model AND provider: model = raw string, provider = raw string (inconsistent)
|
||||
- If only model: model = raw string
|
||||
- If only provider: provider = raw string at top level
|
||||
|
||||
After normalization:
|
||||
- If model exists: model = {"model": "xxx"}
|
||||
- If provider exists: model = {"provider": "yyy"}
|
||||
- If both exist: model = {"model": "xxx", "provider": "yyy"}
|
||||
- If neither: model = None
|
||||
"""
|
||||
job = dict(job) # Create a copy to avoid modifying the original
|
||||
|
||||
model = job.get("model")
|
||||
provider = job.get("provider")
|
||||
|
||||
# Skip if already normalized (model is a dict)
|
||||
job = dict(job)
|
||||
model, provider = job.get("model"), job.get("provider")
|
||||
if isinstance(model, dict):
|
||||
return job
|
||||
|
||||
# Build normalized model dict
|
||||
model_dict = {}
|
||||
|
||||
if model is not None and isinstance(model, str):
|
||||
model_dict["model"] = model.strip()
|
||||
|
||||
if provider is not None and isinstance(provider, str):
|
||||
model_dict["provider"] = provider.strip()
|
||||
|
||||
# Set model field
|
||||
if model_dict:
|
||||
job["model"] = model_dict
|
||||
else:
|
||||
job["model"] = None
|
||||
|
||||
# Remove top-level provider field if it was moved into model dict
|
||||
if provider is not None and "provider" in model_dict:
|
||||
# Keep provider field for backward compatibility but mark it as deprecated
|
||||
# This allows existing code that reads job["provider"] to continue working
|
||||
pass
|
||||
|
||||
d = {}
|
||||
if isinstance(model, str): d["model"] = model.strip()
|
||||
if isinstance(provider, str): d["provider"] = provider.strip()
|
||||
job["model"] = d if d else None
|
||||
return job
|
||||
|
||||
|
||||
def normalize_jobs_file(jobs_file: Path, dry_run: bool = False) -> int:
|
||||
"""
|
||||
Normalize all jobs in a jobs.json file.
|
||||
|
||||
Returns the number of jobs that were modified.
|
||||
"""
|
||||
if not jobs_file.exists():
|
||||
print(f"Error: Jobs file not found: {jobs_file}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
def _jobs_changed(cur: Dict[str, Any], desired: Dict[str, Any]) -> bool:
|
||||
if cur.get("prompt") != desired.get("prompt"): return True
|
||||
if cur.get("schedule") != desired.get("schedule"): return True
|
||||
if _flat_model(cur) != _flat_model(desired): return True
|
||||
if _flat_provider(cur) != _flat_provider(desired): return True
|
||||
return False
|
||||
|
||||
|
||||
def _parse_schedule(schedule: str) -> Dict[str, Any]:
|
||||
try:
|
||||
with open(jobs_file, 'r', encoding='utf-8') as f:
|
||||
from cron.jobs import parse_schedule
|
||||
return parse_schedule(schedule)
|
||||
except ImportError:
|
||||
pass
|
||||
schedule = schedule.strip()
|
||||
if schedule.startswith("every "):
|
||||
dur = schedule[6:].strip()
|
||||
minutes = int(dur[:-1]) * {"m": 1, "h": 60, "d": 1440}.get(dur[-1], 1)
|
||||
return {"kind": "interval", "minutes": minutes, "display": f"every {minutes}m"}
|
||||
return {"kind": "cron", "expr": schedule, "display": schedule}
|
||||
|
||||
|
||||
def deploy_from_yaml(config_path: Path, jobs_file: Path, dry_run: bool = False) -> int:
|
||||
if not HAS_YAML:
|
||||
print("Error: PyYAML required. pip install pyyaml", file=sys.stderr); return 1
|
||||
if not config_path.exists():
|
||||
print(f"Error: {config_path}", file=sys.stderr); return 1
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
yaml_jobs = (yaml.safe_load(f) or {}).get("jobs", [])
|
||||
if jobs_file.exists():
|
||||
with open(jobs_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"Error: Invalid JSON in {jobs_file}: {e}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
jobs = data.get("jobs", [])
|
||||
if not jobs:
|
||||
print("No jobs found in file.")
|
||||
return 0
|
||||
|
||||
modified_count = 0
|
||||
for i, job in enumerate(jobs):
|
||||
original_model = job.get("model")
|
||||
original_provider = job.get("provider")
|
||||
|
||||
normalized_job = normalize_job(job)
|
||||
|
||||
# Check if anything changed
|
||||
if (normalized_job.get("model") != original_model or
|
||||
normalized_job.get("provider") != original_provider):
|
||||
jobs[i] = normalized_job
|
||||
modified_count += 1
|
||||
|
||||
job_id = job.get("id", "?")
|
||||
job_name = job.get("name", "(unnamed)")
|
||||
print(f"Normalized job {job_id} ({job_name}):")
|
||||
print(f" model: {original_model!r} -> {normalized_job.get('model')!r}")
|
||||
print(f" provider: {original_provider!r} -> {normalized_job.get('provider')!r}")
|
||||
|
||||
if modified_count == 0:
|
||||
print("All jobs already have consistent model field types.")
|
||||
return 0
|
||||
|
||||
else:
|
||||
data = {"jobs": [], "updated_at": None}
|
||||
existing = data.get("jobs", [])
|
||||
index = {}
|
||||
for i, j in enumerate(existing):
|
||||
key = f"{j.get('prompt','')}||{json.dumps(j.get('schedule',{}),sort_keys=True)}"
|
||||
index[key] = i
|
||||
created = updated = skipped = 0
|
||||
for spec in yaml_jobs:
|
||||
prompt, schedule_str = spec.get("prompt",""), spec.get("schedule","")
|
||||
name, model, provider = spec.get("name",""), spec.get("model"), spec.get("provider")
|
||||
skills = spec.get("skills", [])
|
||||
parsed = _parse_schedule(schedule_str)
|
||||
key = f"{prompt}||{json.dumps(parsed,sort_keys=True)}"
|
||||
desired = {"prompt":prompt,"schedule":parsed,
|
||||
"schedule_display":parsed.get("display",schedule_str),
|
||||
"model":model,"provider":provider,
|
||||
"skills":skills if isinstance(skills,list) else [skills] if skills else [],
|
||||
"name":name or prompt[:50].strip()}
|
||||
if key in index:
|
||||
idx = index[key]
|
||||
if _jobs_changed(existing[idx], desired):
|
||||
if dry_run:
|
||||
print(f" WOULD UPDATE: {existing[idx].get('id','?')} model: {_flat_model(existing[idx])!r} -> {model!r} provider: {_flat_provider(existing[idx])!r} -> {provider!r}")
|
||||
else:
|
||||
existing[idx].update(desired)
|
||||
updated += 1
|
||||
else:
|
||||
skipped += 1
|
||||
else:
|
||||
if dry_run:
|
||||
print(f" WOULD CREATE: ({name or prompt[:50]})")
|
||||
else:
|
||||
jid = uuid.uuid4().hex[:12]
|
||||
existing.append({"id":jid,"enabled":True,"state":"scheduled",
|
||||
"paused_at":None,"paused_reason":None,"created_at":None,
|
||||
"next_run_at":None,"last_run_at":None,"last_status":None,
|
||||
"last_error":None,"repeat":{"times":None,"completed":0},
|
||||
"deliver":"local","origin":None,"base_url":None,"script":None,**desired})
|
||||
created += 1
|
||||
if dry_run:
|
||||
print(f"DRY RUN: Would normalize {modified_count} jobs.")
|
||||
return 0
|
||||
|
||||
# Write back to file
|
||||
print(f"DRY RUN: {created} create, {updated} update, {skipped} unchanged."); return 0
|
||||
data["jobs"] = existing
|
||||
jobs_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(jobs_file, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, indent=2, ensure_ascii=False)
|
||||
print(f"Deployed: {created} created, {updated} updated, {skipped} unchanged."); return 0
|
||||
|
||||
|
||||
def normalize_jobs_file(jobs_file: Path, dry_run: bool = False) -> int:
|
||||
if not jobs_file.exists():
|
||||
print(f"Error: {jobs_file}", file=sys.stderr); return 1
|
||||
with open(jobs_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
jobs = data.get("jobs", [])
|
||||
if not jobs: print("No jobs."); return 0
|
||||
modified = 0
|
||||
for i, job in enumerate(jobs):
|
||||
om, op = job.get("model"), job.get("provider")
|
||||
n = normalize_job(job)
|
||||
if n.get("model") != om or n.get("provider") != op:
|
||||
jobs[i] = n; modified += 1
|
||||
print(f"Normalized {job.get('id','?')}: model {om!r} -> {n['model']!r} provider {op!r} -> {n['provider']!r}")
|
||||
if modified == 0: print("All consistent."); return 0
|
||||
if dry_run: print(f"DRY RUN: {modified}"); return 0
|
||||
data["jobs"] = jobs
|
||||
try:
|
||||
with open(jobs_file, 'w', encoding='utf-8') as f:
|
||||
json.dump(data, f, indent=2, ensure_ascii=False)
|
||||
print(f"Normalized {modified_count} jobs in {jobs_file}")
|
||||
return 0
|
||||
except Exception as e:
|
||||
print(f"Error writing to {jobs_file}: {e}", file=sys.stderr)
|
||||
return 1
|
||||
with open(jobs_file, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, indent=2, ensure_ascii=False)
|
||||
print(f"Normalized {modified} jobs."); return 0
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Normalize cron job schemas for consistent model field types."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dry-run",
|
||||
action="store_true",
|
||||
help="Show what would be changed without modifying the file."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--jobs-file",
|
||||
type=Path,
|
||||
default=Path.home() / ".hermes" / "cron" / "jobs.json",
|
||||
help="Path to jobs.json file (default: ~/.hermes/cron/jobs.json)"
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.dry_run:
|
||||
print("DRY RUN MODE — no changes will be made.")
|
||||
print()
|
||||
|
||||
return normalize_jobs_file(args.jobs_file, args.dry_run)
|
||||
|
||||
p = argparse.ArgumentParser(description="Deploy and normalize cron jobs.")
|
||||
g = p.add_mutually_exclusive_group(required=True)
|
||||
g.add_argument("--deploy", action="store_true")
|
||||
g.add_argument("--normalize", action="store_true")
|
||||
p.add_argument("--config", type=Path, default=Path.home()/".hermes"/"cron-jobs.yaml")
|
||||
p.add_argument("--jobs-file", type=Path, default=Path.home()/".hermes"/"cron"/"jobs.json")
|
||||
p.add_argument("--dry-run", action="store_true")
|
||||
a = p.parse_args()
|
||||
if a.dry_run: print("DRY RUN."); print()
|
||||
if a.deploy: return deploy_from_yaml(a.config, a.jobs_file, a.dry_run)
|
||||
else: return normalize_jobs_file(a.jobs_file, a.dry_run)
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
||||
@@ -1,139 +0,0 @@
|
||||
# Warm Session Provisioning
|
||||
|
||||
**Issue:** #327
|
||||
|
||||
## Overview
|
||||
|
||||
Warm session provisioning allows creating pre-contextualized agent sessions that start with established patterns and context, reducing initial errors and improving session quality.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
### Session Seed
|
||||
A `SessionSeed` contains:
|
||||
- **System context**: Key instructions and context from previous sessions
|
||||
- **Tool examples**: Successful tool call patterns to establish conventions
|
||||
- **User patterns**: User interaction style preferences
|
||||
- **Context markers**: Important files, URLs, and references
|
||||
|
||||
### Warm Template
|
||||
A `WarmTemplate` wraps a seed with metadata:
|
||||
- Name and description
|
||||
- Source session ID
|
||||
- Usage statistics
|
||||
- Success rate tracking
|
||||
|
||||
## Usage
|
||||
|
||||
### Extract Template from Session
|
||||
|
||||
```bash
|
||||
# Create a template from a successful session
|
||||
hermes warm extract SESSION_ID --name "Code Review Template" --description "For code review tasks"
|
||||
|
||||
# The template captures:
|
||||
# - System context and key instructions
|
||||
# - Successful tool call examples
|
||||
# - User interaction patterns
|
||||
# - Important context markers
|
||||
```
|
||||
|
||||
### List Templates
|
||||
|
||||
```bash
|
||||
hermes warm list
|
||||
```
|
||||
|
||||
Output:
|
||||
```
|
||||
=== Warm Session Templates ===
|
||||
|
||||
ID: warm_20260413_123456
|
||||
Name: Code Review Template
|
||||
Description: For code review tasks
|
||||
Usage: 5 times, 80% success
|
||||
```
|
||||
|
||||
### Test Warm Session
|
||||
|
||||
```bash
|
||||
# Test what messages would be generated
|
||||
hermes warm test warm_20260413_123456 "Review this pull request"
|
||||
```
|
||||
|
||||
Output shows the messages that would be sent to the agent, including:
|
||||
- System context with warm-up information
|
||||
- Tool call examples
|
||||
- The actual user message
|
||||
|
||||
### Delete Template
|
||||
|
||||
```bash
|
||||
hermes warm delete warm_20260413_123456
|
||||
```
|
||||
|
||||
## How It Works
|
||||
|
||||
### 1. Extraction Phase
|
||||
When you extract a template:
|
||||
1. System messages provide base context
|
||||
2. First 10 user messages establish patterns
|
||||
3. Successful tool calls become examples
|
||||
4. File paths and URLs become context markers
|
||||
|
||||
### 2. Bootstrap Phase
|
||||
When creating a warm session:
|
||||
1. System context is injected as initial message
|
||||
2. Tool examples establish successful patterns
|
||||
3. User message follows the warm-up context
|
||||
4. Agent starts with established conventions
|
||||
|
||||
## Example Workflow
|
||||
|
||||
```bash
|
||||
# 1. Have a successful session
|
||||
# ... work with the agent on a complex task ...
|
||||
|
||||
# 2. Extract template from that session
|
||||
hermes warm extract abc123 --name "API Integration" --description "REST API work"
|
||||
|
||||
# 3. Later, start a new session with warm context
|
||||
# The agent will have context about:
|
||||
# - Your coding style
|
||||
# - Successful tool patterns
|
||||
# - Common file paths
|
||||
# - Previous instructions
|
||||
```
|
||||
|
||||
## Benefits
|
||||
|
||||
1. **Reduced Initial Errors**: Agent starts with proven patterns
|
||||
2. **Consistent Behavior**: Established conventions carry over
|
||||
3. **Faster Context**: No need to re-explain preferences
|
||||
4. **Quality Tracking**: Success rate shows template effectiveness
|
||||
|
||||
## Implementation Details
|
||||
|
||||
### Files
|
||||
- `tools/warm_session.py`: Core implementation
|
||||
- `~/.hermes/warm_templates/`: Template storage
|
||||
|
||||
### Data Flow
|
||||
```
|
||||
Session -> SessionExtractor -> SessionSeed -> WarmTemplate
|
||||
↓
|
||||
WarmSessionBootstrapper -> Messages -> Agent
|
||||
```
|
||||
|
||||
## Research Context
|
||||
|
||||
This implementation addresses Finding #4 from the empirical audit:
|
||||
- Marathon sessions show different error patterns
|
||||
- Context establishment affects session quality
|
||||
- Pre-seeding can improve initial session reliability
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
1. **Automatic Template Creation**: Create templates from high-performing sessions
|
||||
2. **Template Sharing**: Export/import templates between installations
|
||||
3. **A/B Testing**: Compare warm vs cold session performance
|
||||
4. **Smart Selection**: Automatically choose best template for task type
|
||||
@@ -5258,36 +5258,6 @@ For more help on a command:
|
||||
|
||||
sessions_parser.set_defaults(func=cmd_sessions)
|
||||
|
||||
|
||||
# Warm session command
|
||||
warm_parser = subparsers.add_parser(
|
||||
"warm",
|
||||
help="Warm session provisioning",
|
||||
description="Create pre-contextualized sessions from templates"
|
||||
)
|
||||
warm_subparsers = warm_parser.add_subparsers(dest="warm_command")
|
||||
|
||||
# Extract command
|
||||
warm_extract = warm_subparsers.add_parser("extract", help="Extract template from session")
|
||||
warm_extract.add_argument("session_id", help="Session ID to extract from")
|
||||
warm_extract.add_argument("--name", "-n", required=True, help="Template name")
|
||||
warm_extract.add_argument("--description", "-d", default="", help="Template description")
|
||||
|
||||
# List command
|
||||
warm_subparsers.add_parser("list", help="List available templates")
|
||||
|
||||
# Test command
|
||||
warm_test = warm_subparsers.add_parser("test", help="Test warm session creation")
|
||||
warm_test.add_argument("template_id", help="Template ID")
|
||||
warm_test.add_argument("message", help="Test message")
|
||||
|
||||
# Delete command
|
||||
warm_delete = warm_subparsers.add_parser("delete", help="Delete a template")
|
||||
warm_delete.add_argument("template_id", help="Template ID to delete")
|
||||
|
||||
warm_parser.set_defaults(func=cmd_warm)
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# insights command
|
||||
# =========================================================================
|
||||
@@ -5628,44 +5598,3 @@ Examples:
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
|
||||
def cmd_warm(args):
|
||||
"""Handle warm session commands."""
|
||||
from hermes_cli.colors import Colors, color
|
||||
|
||||
subcmd = getattr(args, 'warm_command', None)
|
||||
|
||||
if subcmd is None:
|
||||
print(color("Warm Session Provisioning", Colors.CYAN))
|
||||
print("\nCommands:")
|
||||
print(" hermes warm extract SESSION_ID --name NAME - Extract template from session")
|
||||
print(" hermes warm list - List available templates")
|
||||
print(" hermes warm test TEMPLATE_ID MESSAGE - Test warm session")
|
||||
print(" hermes warm delete TEMPLATE_ID - Delete a template")
|
||||
return 0
|
||||
|
||||
try:
|
||||
from tools.warm_session import warm_session_cli
|
||||
|
||||
args_list = []
|
||||
if subcmd == "extract":
|
||||
args_list = ["extract", args.session_id, "--name", args.name]
|
||||
if args.description:
|
||||
args_list.extend(["--description", args.description])
|
||||
elif subcmd == "list":
|
||||
args_list = ["list"]
|
||||
elif subcmd == "test":
|
||||
args_list = ["test", args.template_id, args.message]
|
||||
elif subcmd == "delete":
|
||||
args_list = ["delete", args.template_id]
|
||||
|
||||
return warm_session_cli(args_list)
|
||||
|
||||
except ImportError as e:
|
||||
print(color(f"Error: Cannot import warm_session module: {e}", Colors.RED))
|
||||
return 1
|
||||
except Exception as e:
|
||||
print(color(f"Error: {e}", Colors.RED))
|
||||
return 1
|
||||
|
||||
|
||||
@@ -1,485 +0,0 @@
|
||||
"""
|
||||
Warm Session Provisioning: Practical Implementation
|
||||
|
||||
Provides mechanisms to create pre-contextualized sessions that start
|
||||
with established patterns and context, reducing initial errors.
|
||||
|
||||
Issue: #327
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional
|
||||
from dataclasses import dataclass, asdict, field
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class SessionSeed:
|
||||
"""Seed data for warming up a new session."""
|
||||
system_context: str = ""
|
||||
tool_examples: List[Dict[str, Any]] = field(default_factory=list)
|
||||
user_patterns: Dict[str, Any] = field(default_factory=dict)
|
||||
context_markers: List[str] = field(default_factory=list)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Dict[str, Any]) -> 'SessionSeed':
|
||||
return cls(**data)
|
||||
|
||||
|
||||
@dataclass
|
||||
class WarmTemplate:
|
||||
"""Template for creating warm sessions."""
|
||||
template_id: str
|
||||
name: str
|
||||
description: str
|
||||
seed: SessionSeed
|
||||
created_at: str
|
||||
source_session_id: Optional[str] = None
|
||||
usage_count: int = 0
|
||||
success_rate: float = 0.0
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
"template_id": self.template_id,
|
||||
"name": self.name,
|
||||
"description": self.description,
|
||||
"seed": self.seed.to_dict(),
|
||||
"created_at": self.created_at,
|
||||
"source_session_id": self.source_session_id,
|
||||
"usage_count": self.usage_count,
|
||||
"success_rate": self.success_rate
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Dict[str, Any]) -> 'WarmTemplate':
|
||||
seed = SessionSeed.from_dict(data.get("seed", {}))
|
||||
return cls(
|
||||
template_id=data["template_id"],
|
||||
name=data["name"],
|
||||
description=data["description"],
|
||||
seed=seed,
|
||||
created_at=data.get("created_at", datetime.now().isoformat()),
|
||||
source_session_id=data.get("source_session_id"),
|
||||
usage_count=data.get("usage_count", 0),
|
||||
success_rate=data.get("success_rate", 0.0)
|
||||
)
|
||||
|
||||
|
||||
class SessionExtractor:
|
||||
"""Extract seed data from existing sessions."""
|
||||
|
||||
def __init__(self, session_db=None):
|
||||
self.session_db = session_db
|
||||
|
||||
def extract_seed(self, session_id: str) -> Optional[SessionSeed]:
|
||||
"""Extract seed data from a session."""
|
||||
if not self.session_db:
|
||||
return None
|
||||
|
||||
try:
|
||||
messages = self.session_db.get_messages(session_id)
|
||||
if not messages:
|
||||
return None
|
||||
|
||||
# Extract system context
|
||||
system_context = self._extract_system_context(messages)
|
||||
|
||||
# Extract successful tool examples
|
||||
tool_examples = self._extract_tool_examples(messages)
|
||||
|
||||
# Extract user patterns
|
||||
user_patterns = self._extract_user_patterns(messages)
|
||||
|
||||
# Extract context markers
|
||||
context_markers = self._extract_context_markers(messages)
|
||||
|
||||
return SessionSeed(
|
||||
system_context=system_context,
|
||||
tool_examples=tool_examples,
|
||||
user_patterns=user_patterns,
|
||||
context_markers=context_markers
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to extract seed: {e}")
|
||||
return None
|
||||
|
||||
def _extract_system_context(self, messages: List[Dict]) -> str:
|
||||
"""Extract useful system context from messages."""
|
||||
context_parts = []
|
||||
|
||||
# Look for system messages
|
||||
for msg in messages:
|
||||
if msg.get("role") == "system":
|
||||
content = msg.get("content", "")
|
||||
# Take first 500 chars of system context
|
||||
if content:
|
||||
context_parts.append(content[:500])
|
||||
break
|
||||
|
||||
# Extract key user instructions
|
||||
user_instructions = []
|
||||
for msg in messages[:10]: # First 10 messages
|
||||
if msg.get("role") == "user":
|
||||
content = msg.get("content", "")
|
||||
if len(content) > 50 and "?" not in content[:20]: # Likely instructions
|
||||
user_instructions.append(content[:200])
|
||||
if len(user_instructions) >= 3:
|
||||
break
|
||||
|
||||
if user_instructions:
|
||||
context_parts.append("\nKey instructions from session:\n" + "\n".join(f"- {i}" for i in user_instructions))
|
||||
|
||||
return "\n".join(context_parts)[:1000]
|
||||
|
||||
def _extract_tool_examples(self, messages: List[Dict]) -> List[Dict[str, Any]]:
|
||||
"""Extract successful tool call examples."""
|
||||
examples = []
|
||||
|
||||
for i, msg in enumerate(messages):
|
||||
if msg.get("role") == "assistant" and msg.get("tool_calls"):
|
||||
# Check if there's a successful result
|
||||
for j in range(i + 1, min(i + 3, len(messages))):
|
||||
if messages[j].get("role") == "tool":
|
||||
content = messages[j].get("content", "")
|
||||
# Check for success indicators
|
||||
if content and "error" not in content.lower()[:100]:
|
||||
for tool_call in msg["tool_calls"]:
|
||||
func = tool_call.get("function", {})
|
||||
examples.append({
|
||||
"tool": func.get("name"),
|
||||
"arguments": func.get("arguments", "{}"),
|
||||
"result_preview": content[:200]
|
||||
})
|
||||
if len(examples) >= 5:
|
||||
break
|
||||
break
|
||||
|
||||
if len(examples) >= 5:
|
||||
break
|
||||
|
||||
return examples
|
||||
|
||||
def _extract_user_patterns(self, messages: List[Dict]) -> Dict[str, Any]:
|
||||
"""Extract user interaction patterns."""
|
||||
user_messages = [m for m in messages if m.get("role") == "user"]
|
||||
|
||||
if not user_messages:
|
||||
return {}
|
||||
|
||||
# Calculate patterns
|
||||
lengths = [len(m.get("content", "")) for m in user_messages]
|
||||
avg_length = sum(lengths) / len(lengths)
|
||||
|
||||
# Count question types
|
||||
questions = sum(1 for m in user_messages if "?" in m.get("content", ""))
|
||||
commands = sum(1 for m in user_messages if m.get("content", "").startswith(("/", "!")))
|
||||
|
||||
return {
|
||||
"message_count": len(user_messages),
|
||||
"avg_length": avg_length,
|
||||
"question_ratio": questions / len(user_messages),
|
||||
"command_ratio": commands / len(user_messages),
|
||||
"preferred_style": "command" if commands > questions else "conversational"
|
||||
}
|
||||
|
||||
def _extract_context_markers(self, messages: List[Dict]) -> List[str]:
|
||||
"""Extract important context markers."""
|
||||
markers = set()
|
||||
|
||||
for msg in messages:
|
||||
content = msg.get("content", "")
|
||||
|
||||
# File paths
|
||||
import re
|
||||
paths = re.findall(r'[\w/\.]+\.[\w]+', content)
|
||||
markers.update(p for p in paths if len(p) < 50)
|
||||
|
||||
# URLs
|
||||
urls = re.findall(r'https?://[^\s]+', content)
|
||||
markers.update(u[:80] for u in urls[:3])
|
||||
|
||||
if len(markers) > 20:
|
||||
break
|
||||
|
||||
return list(markers)[:20]
|
||||
|
||||
|
||||
class WarmSessionManager:
|
||||
"""Manage warm session templates."""
|
||||
|
||||
def __init__(self, template_dir: Path = None):
|
||||
self.template_dir = template_dir or Path.home() / ".hermes" / "warm_templates"
|
||||
self.template_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def save_template(self, template: WarmTemplate) -> Path:
|
||||
"""Save a warm template."""
|
||||
path = self.template_dir / f"{template.template_id}.json"
|
||||
with open(path, 'w') as f:
|
||||
json.dump(template.to_dict(), f, indent=2)
|
||||
return path
|
||||
|
||||
def load_template(self, template_id: str) -> Optional[WarmTemplate]:
|
||||
"""Load a warm template."""
|
||||
path = self.template_dir / f"{template_id}.json"
|
||||
if not path.exists():
|
||||
return None
|
||||
|
||||
try:
|
||||
with open(path, 'r') as f:
|
||||
data = json.load(f)
|
||||
return WarmTemplate.from_dict(data)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to load template: {e}")
|
||||
return None
|
||||
|
||||
def list_templates(self) -> List[Dict[str, Any]]:
|
||||
"""List all templates."""
|
||||
templates = []
|
||||
for path in self.template_dir.glob("*.json"):
|
||||
try:
|
||||
with open(path, 'r') as f:
|
||||
data = json.load(f)
|
||||
templates.append({
|
||||
"template_id": data.get("template_id"),
|
||||
"name": data.get("name"),
|
||||
"description": data.get("description"),
|
||||
"usage_count": data.get("usage_count", 0),
|
||||
"success_rate": data.get("success_rate", 0.0)
|
||||
})
|
||||
except:
|
||||
pass
|
||||
return templates
|
||||
|
||||
def delete_template(self, template_id: str) -> bool:
|
||||
"""Delete a template."""
|
||||
path = self.template_dir / f"{template_id}.json"
|
||||
if path.exists():
|
||||
path.unlink()
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class WarmSessionBootstrapper:
|
||||
"""Bootstrap warm sessions from templates."""
|
||||
|
||||
def __init__(self, manager: WarmSessionManager = None):
|
||||
self.manager = manager or WarmSessionManager()
|
||||
|
||||
def prepare_messages(
|
||||
self,
|
||||
template: WarmTemplate,
|
||||
user_message: str,
|
||||
include_examples: bool = True
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""Prepare messages for a warm session."""
|
||||
messages = []
|
||||
|
||||
# Add warm context as system message
|
||||
warm_context = self._build_warm_context(template.seed)
|
||||
if warm_context:
|
||||
messages.append({
|
||||
"role": "system",
|
||||
"content": warm_context
|
||||
})
|
||||
|
||||
# Add tool examples if requested
|
||||
if include_examples and template.seed.tool_examples:
|
||||
example_messages = self._create_example_messages(template.seed.tool_examples)
|
||||
messages.extend(example_messages)
|
||||
|
||||
# Add the actual user message
|
||||
messages.append({
|
||||
"role": "user",
|
||||
"content": user_message
|
||||
})
|
||||
|
||||
return messages
|
||||
|
||||
def _build_warm_context(self, seed: SessionSeed) -> str:
|
||||
"""Build warm context from seed."""
|
||||
parts = []
|
||||
|
||||
if seed.system_context:
|
||||
parts.append(seed.system_context)
|
||||
|
||||
if seed.context_markers:
|
||||
parts.append("\nKnown context: " + ", ".join(seed.context_markers[:10]))
|
||||
|
||||
if seed.user_patterns:
|
||||
style = seed.user_patterns.get("preferred_style", "balanced")
|
||||
parts.append(f"\nUser prefers {style} interactions.")
|
||||
|
||||
return "\n".join(parts)[:1500]
|
||||
|
||||
def _create_example_messages(self, examples: List[Dict]) -> List[Dict]:
|
||||
"""Create example messages from tool examples."""
|
||||
messages = []
|
||||
|
||||
for i, ex in enumerate(examples[:3]): # Limit to 3 examples
|
||||
# User request
|
||||
messages.append({
|
||||
"role": "user",
|
||||
"content": f"[Example {i+1}] Use {ex['tool']}"
|
||||
})
|
||||
|
||||
# Assistant with tool call
|
||||
messages.append({
|
||||
"role": "assistant",
|
||||
"content": f"I'll use {ex['tool']}.",
|
||||
"tool_calls": [{
|
||||
"id": f"example_{i}",
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": ex["tool"],
|
||||
"arguments": ex.get("arguments", "{}")
|
||||
}
|
||||
}]
|
||||
})
|
||||
|
||||
# Tool result
|
||||
messages.append({
|
||||
"role": "tool",
|
||||
"tool_call_id": f"example_{i}",
|
||||
"content": ex.get("result_preview", "Success")
|
||||
})
|
||||
|
||||
return messages
|
||||
|
||||
|
||||
# CLI Functions
|
||||
def warm_session_cli(args: List[str]) -> int:
|
||||
"""CLI interface for warm session management."""
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(description="Warm session provisioning")
|
||||
subparsers = parser.add_subparsers(dest="command")
|
||||
|
||||
# Extract command
|
||||
extract_parser = subparsers.add_parser("extract", help="Extract template from session")
|
||||
extract_parser.add_argument("session_id", help="Session ID to extract from")
|
||||
extract_parser.add_argument("--name", "-n", required=True, help="Template name")
|
||||
extract_parser.add_argument("--description", "-d", default="", help="Template description")
|
||||
|
||||
# List command
|
||||
subparsers.add_parser("list", help="List available templates")
|
||||
|
||||
# Test command
|
||||
test_parser = subparsers.add_parser("test", help="Test warm session creation")
|
||||
test_parser.add_argument("template_id", help="Template ID")
|
||||
test_parser.add_argument("message", help="Test message")
|
||||
|
||||
# Delete command
|
||||
delete_parser = subparsers.add_parser("delete", help="Delete a template")
|
||||
delete_parser.add_argument("template_id", help="Template ID to delete")
|
||||
|
||||
parsed = parser.parse_args(args)
|
||||
|
||||
if not parsed.command:
|
||||
parser.print_help()
|
||||
return 1
|
||||
|
||||
manager = WarmSessionManager()
|
||||
|
||||
if parsed.command == "extract":
|
||||
try:
|
||||
from hermes_state import SessionDB
|
||||
session_db = SessionDB()
|
||||
except ImportError:
|
||||
print("Error: Cannot import SessionDB")
|
||||
return 1
|
||||
|
||||
extractor = SessionExtractor(session_db)
|
||||
seed = extractor.extract_seed(parsed.session_id)
|
||||
|
||||
if not seed:
|
||||
print(f"Failed to extract seed from session {parsed.session_id}")
|
||||
return 1
|
||||
|
||||
template = WarmTemplate(
|
||||
template_id=f"warm_{datetime.now().strftime('%Y%m%d_%H%M%S')}",
|
||||
name=parsed.name,
|
||||
description=parsed.description,
|
||||
seed=seed,
|
||||
created_at=datetime.now().isoformat(),
|
||||
source_session_id=parsed.session_id
|
||||
)
|
||||
|
||||
path = manager.save_template(template)
|
||||
print(f"Created template: {template.template_id}")
|
||||
print(f"Saved to: {path}")
|
||||
print(f"Tool examples: {len(seed.tool_examples)}")
|
||||
print(f"Context markers: {len(seed.context_markers)}")
|
||||
return 0
|
||||
|
||||
elif parsed.command == "list":
|
||||
templates = manager.list_templates()
|
||||
|
||||
if not templates:
|
||||
print("No templates found.")
|
||||
return 0
|
||||
|
||||
print("\n=== Warm Session Templates ===\n")
|
||||
for t in templates:
|
||||
print(f"ID: {t['template_id']}")
|
||||
print(f" Name: {t['name']}")
|
||||
print(f" Description: {t['description']}")
|
||||
print(f" Usage: {t['usage_count']} times, {t['success_rate']:.0%} success")
|
||||
print()
|
||||
|
||||
return 0
|
||||
|
||||
elif parsed.command == "test":
|
||||
template = manager.load_template(parsed.template_id)
|
||||
|
||||
if not template:
|
||||
print(f"Template {parsed.template_id} not found")
|
||||
return 1
|
||||
|
||||
bootstrapper = WarmSessionBootstrapper(manager)
|
||||
messages = bootstrapper.prepare_messages(template, parsed.message)
|
||||
|
||||
print(f"\n=== Warm Session Test: {template.name} ===\n")
|
||||
print(f"Generated {len(messages)} messages:\n")
|
||||
|
||||
for i, msg in enumerate(messages):
|
||||
role = msg.get("role", "unknown")
|
||||
content = msg.get("content", "")
|
||||
|
||||
if role == "system":
|
||||
print(f"[System Context] ({len(content)} chars)")
|
||||
print(content[:200] + "..." if len(content) > 200 else content)
|
||||
elif role == "user":
|
||||
print(f"\n[User]: {content}")
|
||||
elif role == "assistant":
|
||||
print(f"[Assistant]: {content}")
|
||||
if msg.get("tool_calls"):
|
||||
for tc in msg["tool_calls"]:
|
||||
func = tc.get("function", {})
|
||||
print(f" -> {func.get('name')}({func.get('arguments', '{}')[:50]})")
|
||||
elif role == "tool":
|
||||
print(f" [Result]: {content[:100]}...")
|
||||
|
||||
return 0
|
||||
|
||||
elif parsed.command == "delete":
|
||||
if manager.delete_template(parsed.template_id):
|
||||
print(f"Deleted template: {parsed.template_id}")
|
||||
return 0
|
||||
else:
|
||||
print(f"Template {parsed.template_id} not found")
|
||||
return 1
|
||||
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
sys.exit(warm_session_cli(sys.argv[1:]))
|
||||
Reference in New Issue
Block a user