Compare commits
1 Commits
burn/255-1
...
feat/505-s
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ddec887b75 |
9
deploy/synapse/.gitignore
vendored
9
deploy/synapse/.gitignore
vendored
@@ -1,9 +0,0 @@
|
||||
# Secrets — never commit
|
||||
.env
|
||||
synapse-credentials.env
|
||||
|
||||
# Backups
|
||||
backups/
|
||||
|
||||
# Generated config backups
|
||||
homeserver.yaml.bak
|
||||
@@ -1,82 +0,0 @@
|
||||
# Synapse Homeserver — Docker Compose Stack
|
||||
# Matrix Phase 1: Deploy Synapse on Ezra VPS
|
||||
#
|
||||
# Usage:
|
||||
# cd deploy/synapse
|
||||
# ./setup.sh # first-time deploy (generates config + keys)
|
||||
# docker compose up -d # start
|
||||
# docker compose logs -f # follow logs
|
||||
# docker compose down # stop
|
||||
#
|
||||
# Secrets:
|
||||
# Never commit .env to version control.
|
||||
# setup.sh generates secrets automatically.
|
||||
|
||||
services:
|
||||
synapse-db:
|
||||
image: postgres:16-alpine
|
||||
container_name: synapse-db
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- synapse_db:/var/lib/postgresql/data
|
||||
environment:
|
||||
POSTGRES_USER: synapse
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
|
||||
POSTGRES_INITDB_ARGS: "--encoding=UTF8 --lc-collate=C --lc-ctype=C"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U synapse"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
networks:
|
||||
- synapse_net
|
||||
logging:
|
||||
driver: "json-file"
|
||||
options:
|
||||
max-size: "20m"
|
||||
max-file: "3"
|
||||
|
||||
synapse:
|
||||
image: matrixdotorg/synapse:latest
|
||||
container_name: synapse
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
synapse-db:
|
||||
condition: service_healthy
|
||||
volumes:
|
||||
- synapse_data:/data
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
SYNAPSE_CONFIG_PATH: /data/homeserver.yaml
|
||||
ports:
|
||||
- "127.0.0.1:8008:8008" # Client-server API (localhost only)
|
||||
- "8448:8448" # Federation (public)
|
||||
networks:
|
||||
- synapse_net
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-fSs", "http://localhost:8008/health"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 30s
|
||||
logging:
|
||||
driver: "json-file"
|
||||
options:
|
||||
max-size: "50m"
|
||||
max-file: "5"
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "2.0"
|
||||
memory: 2G
|
||||
reservations:
|
||||
memory: 512M
|
||||
|
||||
volumes:
|
||||
synapse_data:
|
||||
synapse_db:
|
||||
|
||||
networks:
|
||||
synapse_net:
|
||||
driver: bridge
|
||||
@@ -1,101 +0,0 @@
|
||||
# Synapse Homeserver Configuration
|
||||
# Generated by setup.sh — edit with care.
|
||||
#
|
||||
# Docs: https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html
|
||||
|
||||
# Server name — your Matrix domain (e.g. matrix.example.com)
|
||||
server_name: "SERVER_NAME_PLACEHOLDER"
|
||||
|
||||
# Signing key — generated by setup.sh
|
||||
signing_key_path: "/data/signing.key"
|
||||
|
||||
# Trusted key servers (empty = trust only ourselves for our own keys)
|
||||
trusted_key_servers: []
|
||||
|
||||
# Report stats to matrix.org (no for sovereignty)
|
||||
report_stats: false
|
||||
|
||||
# Listeners
|
||||
listeners:
|
||||
- port: 8008
|
||||
tls: false
|
||||
type: http
|
||||
x_forwarded: true
|
||||
resources:
|
||||
- names: [client, federation]
|
||||
compress: false
|
||||
|
||||
# Database — PostgreSQL
|
||||
database:
|
||||
name: psycopg2
|
||||
args:
|
||||
user: synapse
|
||||
password: "${POSTGRES_PASSWORD}"
|
||||
database: synapse
|
||||
host: synapse-db
|
||||
cp_min: 5
|
||||
cp_max: 10
|
||||
|
||||
# Media store
|
||||
media_store_path: "/data/media_store"
|
||||
|
||||
# Upload limits
|
||||
max_upload_size: "50M"
|
||||
|
||||
# URL previews (disable to reduce attack surface)
|
||||
url_preview_enabled: false
|
||||
|
||||
# Enable room list publishing
|
||||
enable_room_list_search: true
|
||||
|
||||
# Turn off public registration by default (create users via admin API)
|
||||
enable_registration: false
|
||||
enable_registration_without_verification: false
|
||||
|
||||
# Rate limiting
|
||||
rc_message:
|
||||
per_second: 0.2
|
||||
burst_count: 10
|
||||
|
||||
rc_registration:
|
||||
per_second: 0.1
|
||||
burst_count: 3
|
||||
|
||||
rc_login:
|
||||
address:
|
||||
per_second: 0.05
|
||||
burst_count: 2
|
||||
account:
|
||||
per_second: 0.05
|
||||
burst_count: 2
|
||||
failed_attempts:
|
||||
per_second: 0.15
|
||||
burst_count: 3
|
||||
|
||||
# Retention — keep messages for 90 days by default
|
||||
retention:
|
||||
enabled: true
|
||||
default_policy:
|
||||
min_lifetime: 1d
|
||||
max_lifetime: 90d
|
||||
|
||||
# Logging
|
||||
log_config: "/data/log.config"
|
||||
|
||||
# Metrics (optional — enable if running Prometheus)
|
||||
enable_metrics: false
|
||||
|
||||
# Presence
|
||||
use_presence: true
|
||||
|
||||
# Federation
|
||||
federation_verify_certificates: true
|
||||
federation_sender_instances: 1
|
||||
|
||||
# Appservice config directory
|
||||
app_service_config_files: []
|
||||
|
||||
# Experimental features
|
||||
experimental_features:
|
||||
# MSC3440: Threading support
|
||||
msc3440_enabled: true
|
||||
@@ -1,33 +0,0 @@
|
||||
# Synapse logging configuration
|
||||
# https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html#log_config
|
||||
|
||||
version: 1
|
||||
|
||||
formatters:
|
||||
precise:
|
||||
format: '%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(request)s - %(message)s'
|
||||
|
||||
handlers:
|
||||
console:
|
||||
class: logging.StreamHandler
|
||||
formatter: precise
|
||||
level: INFO
|
||||
stream: ext://sys.stdout
|
||||
|
||||
file:
|
||||
class: logging.handlers.RotatingFileHandler
|
||||
formatter: precise
|
||||
filename: /data/homeserver.log
|
||||
maxBytes: 104857600 # 100MB
|
||||
backupCount: 3
|
||||
level: INFO
|
||||
|
||||
loggers:
|
||||
synapse.storage.SQL:
|
||||
level: WARNING
|
||||
synapse.http.client:
|
||||
level: INFO
|
||||
|
||||
root:
|
||||
level: INFO
|
||||
handlers: [console, file]
|
||||
@@ -1,131 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Synapse Homeserver — Management Utilities
|
||||
# Usage: ./manage.sh <command>
|
||||
#
|
||||
# Commands:
|
||||
# status Show container status and health
|
||||
# restart Restart Synapse (preserves data)
|
||||
# logs Tail Synapse logs
|
||||
# create-user <username> <password> [admin]
|
||||
# backup Create timestamped backup of data volumes
|
||||
# update Pull latest Synapse image and recreate
|
||||
# teardown Stop and remove everything (DESTRUCTIVE)
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
cd "$SCRIPT_DIR"
|
||||
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
CYAN='\033[0;36m'
|
||||
NC='\033[0m'
|
||||
|
||||
info() { echo -e "${GREEN}[MANAGE]${NC} $*"; }
|
||||
warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
|
||||
error() { echo -e "${RED}[ERROR]${NC} $*"; exit 1; }
|
||||
|
||||
COMMAND="${1:-help}"
|
||||
|
||||
case "$COMMAND" in
|
||||
status)
|
||||
info "Container status:"
|
||||
docker compose ps
|
||||
echo ""
|
||||
info "Synapse health:"
|
||||
curl -sfS http://127.0.0.1:8008/health && echo "" || echo "Not responding"
|
||||
echo ""
|
||||
info "Disk usage:"
|
||||
docker system df -v 2>/dev/null | grep -E "synapse|VOLUME" || true
|
||||
;;
|
||||
|
||||
restart)
|
||||
info "Restarting Synapse..."
|
||||
docker compose restart synapse
|
||||
info "Waiting for health check..."
|
||||
sleep 5
|
||||
curl -sfS http://127.0.0.1:8008/health && echo "" && info "Synapse is healthy" || warn "Not responding yet"
|
||||
;;
|
||||
|
||||
logs)
|
||||
shift
|
||||
LINES="${1:-100}"
|
||||
info "Tailing Synapse logs (last $LINES lines)..."
|
||||
docker compose logs -f --tail="$LINES" synapse
|
||||
;;
|
||||
|
||||
create-user)
|
||||
USERNAME="${2:?Usage: manage.sh create-user <username> <password> [admin]}"
|
||||
PASSWORD="${3:?Usage: manage.sh create-user <username> <password> [admin]}"
|
||||
IS_ADMIN="${4:-false}"
|
||||
info "Creating user @$USERNAME..."
|
||||
ADMIN_FLAG=""
|
||||
if [ "$IS_ADMIN" = "admin" ] || [ "$IS_ADMIN" = "true" ]; then
|
||||
ADMIN_FLAG="--admin"
|
||||
fi
|
||||
docker compose exec -T synapse register_new_matrix_user \
|
||||
http://localhost:8008 \
|
||||
-c /data/homeserver.yaml \
|
||||
-u "$USERNAME" \
|
||||
-p "$PASSWORD" \
|
||||
$ADMIN_FLAG \
|
||||
--no-extra-prompt
|
||||
;;
|
||||
|
||||
backup)
|
||||
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
|
||||
BACKUP_DIR="./backups/${TIMESTAMP}"
|
||||
mkdir -p "$BACKUP_DIR"
|
||||
info "Backing up PostgreSQL..."
|
||||
docker compose exec -T synapse-db pg_dump -U synapse > "${BACKUP_DIR}/synapse_db.sql"
|
||||
info "Backing up Synapse data volume..."
|
||||
docker run --rm \
|
||||
-v synapse_data:/source:ro \
|
||||
-v "$(pwd)/${BACKUP_DIR}:/backup" \
|
||||
alpine tar czf /backup/synapse_data.tar.gz -C /source .
|
||||
info "Backup complete: $BACKUP_DIR"
|
||||
ls -lh "$BACKUP_DIR"
|
||||
;;
|
||||
|
||||
update)
|
||||
info "Pulling latest Synapse image..."
|
||||
docker compose pull synapse
|
||||
info "Recreating containers..."
|
||||
docker compose up -d --force-recreate synapse
|
||||
info "Waiting for health..."
|
||||
sleep 10
|
||||
curl -sfS http://127.0.0.1:8008/health && echo "" && info "Updated and healthy" || warn "Check logs"
|
||||
;;
|
||||
|
||||
teardown)
|
||||
echo -e "${RED}WARNING: This will stop and remove all Synapse containers and volumes.${NC}"
|
||||
echo -e "${RED}ALL DATA WILL BE LOST. This cannot be undone.${NC}"
|
||||
echo ""
|
||||
read -p "Type 'yes-delete-everything' to confirm: " CONFIRM
|
||||
if [ "$CONFIRM" = "yes-delete-everything" ]; then
|
||||
info "Stopping containers..."
|
||||
docker compose down -v
|
||||
info "Removing volumes..."
|
||||
docker volume rm synapse_data synapse_db 2>/dev/null || true
|
||||
info "Teardown complete."
|
||||
else
|
||||
info "Aborted."
|
||||
fi
|
||||
;;
|
||||
|
||||
help|*)
|
||||
echo "Synapse Homeserver Management"
|
||||
echo ""
|
||||
echo "Usage: ./manage.sh <command>"
|
||||
echo ""
|
||||
echo "Commands:"
|
||||
echo " status Show container status and health"
|
||||
echo " restart Restart Synapse"
|
||||
echo " logs [lines] Tail Synapse logs (default: 100)"
|
||||
echo " create-user <u> <p> [admin] Create a new Matrix user"
|
||||
echo " backup Backup database + data volume"
|
||||
echo " update Pull latest image and recreate"
|
||||
echo " teardown Stop and remove everything (DESTRUCTIVE)"
|
||||
;;
|
||||
esac
|
||||
@@ -1,211 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Synapse Homeserver — One-Shot Setup Script
|
||||
# Matrix Phase 1: Deploy Synapse on Ezra VPS
|
||||
#
|
||||
# Usage:
|
||||
# ./setup.sh <server_name> [admin_user] [admin_password]
|
||||
#
|
||||
# Example:
|
||||
# ./setup.sh matrix.timmy-time.xyz hermes-bot 'secure-pass-123'
|
||||
#
|
||||
# What it does:
|
||||
# 1. Generates .env with secrets
|
||||
# 2. Prepares homeserver.yaml with correct server name
|
||||
# 3. Generates signing key
|
||||
# 4. Starts Synapse + PostgreSQL via Docker Compose
|
||||
# 5. Waits for Synapse to be healthy
|
||||
# 6. Registers admin user + bot account
|
||||
# 7. Outputs Matrix credentials for hermes-agent
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
cd "$SCRIPT_DIR"
|
||||
|
||||
# --- Colors ---
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
CYAN='\033[0;36m'
|
||||
NC='\033[0m'
|
||||
|
||||
info() { echo -e "${GREEN}[SETUP]${NC} $*"; }
|
||||
warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
|
||||
error() { echo -e "${RED}[ERROR]${NC} $*"; exit 1; }
|
||||
|
||||
# --- Args ---
|
||||
SERVER_NAME="${1:?Usage: $0 <server_name> [admin_user] [admin_password]}"
|
||||
ADMIN_USER="${2:-timmy-admin}"
|
||||
ADMIN_PASS="${3:-$(openssl rand -hex 16)}"
|
||||
BOT_USER="${4:-hermes-bot}"
|
||||
BOT_PASS="${5:-$(openssl rand -hex 16)}"
|
||||
|
||||
echo -e "${CYAN}"
|
||||
echo "╔══════════════════════════════════════════════════╗"
|
||||
echo "║ Synapse Homeserver — Matrix Phase 1 Deploy ║"
|
||||
echo "╚══════════════════════════════════════════════════╝"
|
||||
echo -e "${NC}"
|
||||
info "Server name: $SERVER_NAME"
|
||||
info "Admin user: @$ADMIN_USER:$SERVER_NAME"
|
||||
info "Bot user: @$BOT_USER:$SERVER_NAME"
|
||||
echo ""
|
||||
|
||||
# --- Preflight ---
|
||||
info "Preflight checks..."
|
||||
command -v docker >/dev/null 2>&1 || error "docker not found. Install Docker first."
|
||||
command -v docker compose version >/dev/null 2>&1 || error "docker compose not found. Install Docker Compose plugin."
|
||||
info "Docker: $(docker --version | head -1)"
|
||||
info "Compose: $(docker compose version | head -1)"
|
||||
|
||||
# --- Generate .env ---
|
||||
info "Generating .env..."
|
||||
POSTGRES_PASSWORD=$(openssl rand -hex 24)
|
||||
REGISTRATION_SECRET=$(openssl rand -hex 16)
|
||||
|
||||
cat > .env <<EOF
|
||||
# Synapse deployment — generated $(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
# DO NOT COMMIT THIS FILE
|
||||
|
||||
POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
|
||||
SYNAPSE_SERVER_NAME=${SERVER_NAME}
|
||||
SYNAPSE_REPORT_STATS=no
|
||||
REGISTRATION_SECRET=${REGISTRATION_SECRET}
|
||||
EOF
|
||||
chmod 600 .env
|
||||
info ".env written with secure permissions"
|
||||
|
||||
# --- Prepare homeserver.yaml ---
|
||||
info "Preparing homeserver.yaml..."
|
||||
sed -i.bak "s/SERVER_NAME_PLACEHOLDER/${SERVER_NAME}/g" homeserver.yaml
|
||||
rm -f homeserver.yaml.bak
|
||||
info "Server name set to: $SERVER_NAME"
|
||||
|
||||
# --- Generate signing key ---
|
||||
info "Generating signing key..."
|
||||
# Synapse will generate its own key on first run if missing
|
||||
# But we pre-create the data volume structure
|
||||
docker volume create synapse_data >/dev/null 2>&1 || true
|
||||
docker volume create synapse_db >/dev/null 2>&1 || true
|
||||
|
||||
# --- Start the stack ---
|
||||
info "Starting Synapse + PostgreSQL..."
|
||||
docker compose up -d
|
||||
|
||||
# --- Wait for Synapse to be healthy ---
|
||||
info "Waiting for Synapse to start (up to 120s)..."
|
||||
MAX_WAIT=120
|
||||
ELAPSED=0
|
||||
while [ $ELAPSED -lt $MAX_WAIT ]; do
|
||||
if curl -sfS http://127.0.0.1:8008/health >/dev/null 2>&1; then
|
||||
info "Synapse is healthy!"
|
||||
break
|
||||
fi
|
||||
sleep 3
|
||||
ELAPSED=$((ELAPSED + 3))
|
||||
if [ $((ELAPSED % 15)) -eq 0 ]; then
|
||||
info "Still waiting... (${ELAPSED}s)"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ $ELAPSED -ge $MAX_WAIT ]; then
|
||||
warn "Synapse did not respond within ${MAX_WAIT}s. Check logs:"
|
||||
echo " docker compose logs synapse"
|
||||
error "Aborting registration."
|
||||
fi
|
||||
|
||||
# --- Register admin user ---
|
||||
info "Registering admin user @$ADMIN_USER:$SERVER_NAME..."
|
||||
docker compose exec -T synapse register_new_matrix_user \
|
||||
http://localhost:8008 \
|
||||
-c /data/homeserver.yaml \
|
||||
-u "$ADMIN_USER" \
|
||||
-p "$ADMIN_PASS" \
|
||||
--admin \
|
||||
--no-extra-prompt 2>&1 || {
|
||||
# User might already exist if re-running
|
||||
warn "Admin user registration returned non-zero (may already exist)"
|
||||
}
|
||||
|
||||
# --- Register bot user ---
|
||||
info "Registering bot user @$BOT_USER:$SERVER_NAME..."
|
||||
docker compose exec -T synapse register_new_matrix_user \
|
||||
http://localhost:8008 \
|
||||
-c /data/homeserver.yaml \
|
||||
-u "$BOT_USER" \
|
||||
-p "$BOT_PASS" \
|
||||
--no-admin \
|
||||
--no-extra-prompt 2>&1 || {
|
||||
warn "Bot user registration returned non-zero (may already exist)"
|
||||
}
|
||||
|
||||
# --- Get bot access token ---
|
||||
info "Acquiring bot access token..."
|
||||
BOT_TOKEN_RESPONSE=$(curl -sfS -X POST "http://127.0.0.1:8008/_matrix/client/v3/login" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d "{
|
||||
\"type\": \"m.login.password\",
|
||||
\"identifier\": {
|
||||
\"type\": \"m.id.user\",
|
||||
\"user\": \"${BOT_USER}\"
|
||||
},
|
||||
\"password\": \"${BOT_PASS}\",
|
||||
\"device_name\": \"Hermes Agent\"
|
||||
}")
|
||||
|
||||
BOT_ACCESS_TOKEN=$(echo "$BOT_TOKEN_RESPONSE" | python3 -c "import sys,json; print(json.load(sys.stdin)['access_token'])" 2>/dev/null || echo "FAILED_TO_EXTRACT")
|
||||
BOT_DEVICE_ID=$(echo "$BOT_TOKEN_RESPONSE" | python3 -c "import sys,json; print(json.load(sys.stdin)['device_id'])" 2>/dev/null || echo "UNKNOWN")
|
||||
|
||||
if [ "$BOT_ACCESS_TOKEN" = "FAILED_TO_EXTRACT" ]; then
|
||||
warn "Could not extract bot access token automatically."
|
||||
warn "Login manually: curl -X POST http://127.0.0.1:8008/_matrix/client/v3/login ..."
|
||||
fi
|
||||
|
||||
# --- Write credentials file ---
|
||||
CREDENTIALS_FILE="synapse-credentials.env"
|
||||
cat > "$CREDENTIALS_FILE" <<EOF
|
||||
# Synapse Credentials — generated $(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
# Add these to hermes-agent's ~/.hermes/.env
|
||||
|
||||
# Matrix integration
|
||||
MATRIX_HOMESERVER=http://${SERVER_NAME}:8008
|
||||
MATRIX_ACCESS_TOKEN=${BOT_ACCESS_TOKEN}
|
||||
MATRIX_USER_ID=@${BOT_USER}:${SERVER_NAME}
|
||||
MATRIX_DEVICE_ID=${BOT_DEVICE_ID}
|
||||
MATRIX_ENCRYPTION=true
|
||||
|
||||
# Admin credentials (for user management)
|
||||
SYNAPSE_ADMIN_USER=@${ADMIN_USER}:${SERVER_NAME}
|
||||
SYNAPSE_ADMIN_PASSWORD=${ADMIN_PASS}
|
||||
|
||||
# Bot credentials
|
||||
SYNAPSE_BOT_USER=@${BOT_USER}:${SERVER_NAME}
|
||||
SYNAPSE_BOT_PASSWORD=${BOT_PASS}
|
||||
EOF
|
||||
chmod 600 "$CREDENTIALS_FILE"
|
||||
info "Credentials written to: $CREDENTIALS_FILE"
|
||||
|
||||
# --- Summary ---
|
||||
echo ""
|
||||
echo -e "${GREEN}╔══════════════════════════════════════════════════╗${NC}"
|
||||
echo -e "${GREEN}║ Synapse Deployed Successfully! ║${NC}"
|
||||
echo -e "${GREEN}╚══════════════════════════════════════════════════╝${NC}"
|
||||
echo ""
|
||||
echo -e " Server: ${CYAN}https://${SERVER_NAME}${NC}"
|
||||
echo -e " Client API: ${CYAN}http://127.0.0.1:8008${NC}"
|
||||
echo -e " Federation: ${CYAN}https://${SERVER_NAME}:8448${NC}"
|
||||
echo ""
|
||||
echo -e " Admin: ${YELLOW}@${ADMIN_USER}:${SERVER_NAME}${NC}"
|
||||
echo -e " Bot: ${YELLOW}@${BOT_USER}:${SERVER_NAME}${NC}"
|
||||
echo -e " Bot Token: ${YELLOW}${BOT_ACCESS_TOKEN:0:20}...${NC}"
|
||||
echo ""
|
||||
echo -e " Credentials: ${CYAN}${SCRIPT_DIR}/${CREDENTIALS_FILE}${NC}"
|
||||
echo ""
|
||||
echo -e "${GREEN}Next steps:${NC}"
|
||||
echo " 1. Point DNS: ${SERVER_NAME} → $(curl -s ifconfig.me 2>/dev/null || echo '<VPS_IP>')"
|
||||
echo " 2. Set up TLS: nginx/certbot reverse proxy for :8008 and :8448"
|
||||
echo " 3. Copy credentials to hermes-agent: cp ${CREDENTIALS_FILE} ~/.hermes/.env"
|
||||
echo " 4. Start hermes: hermes gateway --platform matrix"
|
||||
echo ""
|
||||
echo " Manage: docker compose logs -f | docker compose restart | docker compose down"
|
||||
echo " Users: docker compose exec synapse register_new_matrix_user http://localhost:8008 -c /data/homeserver.yaml -u <user> -p <pass>"
|
||||
echo ""
|
||||
@@ -1,251 +0,0 @@
|
||||
# Synapse Homeserver Deployment Guide
|
||||
|
||||
## Matrix Phase 1: Deploy Synapse on Ezra VPS
|
||||
|
||||
Part of [Epic #269: Matrix Integration — Sovereign Messaging for Timmy](https://forge.alexanderwhitestone.com/Timmy_Foundation/hermes-agent/issues/269).
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ Ezra VPS (143.198.27.163) │
|
||||
│ │
|
||||
│ ┌──────────┐ ┌─────────────────────────┐ │
|
||||
│ │ Nginx │────▶│ Synapse (Docker) │ │
|
||||
│ │ :443→8008│ │ Client API: localhost:8008│ │
|
||||
│ │ :8448→8448│ │ Federation: 0.0.0.0:8448│ │
|
||||
│ └──────────┘ └──────────┬──────────────┘ │
|
||||
│ │ │
|
||||
│ ┌────────▼──────────┐ │
|
||||
│ │ PostgreSQL 16 │ │
|
||||
│ │ (Docker volume) │ │
|
||||
│ └───────────────────┘ │
|
||||
│ │
|
||||
│ ┌──────────────────────────────────────────┐ │
|
||||
│ │ hermes-agent (gateway) │ │
|
||||
│ │ MATRIX_HOMESERVER=http://localhost:8008 │ │
|
||||
│ └──────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Docker + Docker Compose plugin on Ezra VPS
|
||||
- SSH access: `ssh root@143.198.27.163`
|
||||
- DNS A record pointing to the VPS IP
|
||||
- (Recommended) Nginx + Certbot for TLS termination
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# SSH into Ezra
|
||||
ssh root@143.198.27.163
|
||||
|
||||
# Clone hermes-agent (if not present)
|
||||
cd /root
|
||||
git clone https://forge.alexanderwhitestone.com/Timmy_Foundation/hermes-agent.git
|
||||
cd hermes-agent/deploy/synapse
|
||||
|
||||
# Deploy Synapse
|
||||
chmod +x setup.sh
|
||||
./setup.sh matrix.timmy-time.xyz
|
||||
|
||||
# This will:
|
||||
# 1. Generate .env with database password
|
||||
# 2. Prepare homeserver.yaml
|
||||
# 3. Start Synapse + PostgreSQL via Docker Compose
|
||||
# 4. Wait for health
|
||||
# 5. Register admin + bot accounts
|
||||
# 6. Acquire bot access token
|
||||
# 7. Write synapse-credentials.env
|
||||
```
|
||||
|
||||
## Step-by-Step
|
||||
|
||||
### 1. DNS Configuration
|
||||
|
||||
Point your Matrix domain to Ezra's IP:
|
||||
|
||||
```
|
||||
Type Name Value
|
||||
A matrix 143.198.27.163
|
||||
```
|
||||
|
||||
Federation uses SRV records for port discovery, but direct `:8448` works without them.
|
||||
|
||||
### 2. Deploy Synapse
|
||||
|
||||
```bash
|
||||
cd /root/hermes-agent/deploy/synapse
|
||||
./setup.sh matrix.timmy-time.xyz hermes-bot 'your-secure-password'
|
||||
```
|
||||
|
||||
Arguments:
|
||||
| Arg | Default | Description |
|
||||
|-----|---------|-------------|
|
||||
| `server_name` | (required) | Matrix domain (e.g., `matrix.timmy-time.xyz`) |
|
||||
| `admin_user` | `timmy-admin` | Admin account username |
|
||||
| `admin_password` | (random) | Admin account password |
|
||||
| `bot_user` | `hermes-bot` | Bot account username |
|
||||
| `bot_password` | (random) | Bot account password |
|
||||
|
||||
### 3. TLS Termination (Nginx)
|
||||
|
||||
Install Nginx + Certbot:
|
||||
|
||||
```bash
|
||||
apt install -y nginx certbot python3-certbot-nginx
|
||||
|
||||
# Client-server API
|
||||
cat > /etc/nginx/sites-available/matrix <<'EOF'
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name matrix.timmy-time.xyz;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/matrix.timmy-time.xyz/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/matrix.timmy-time.xyz/privkey.pem;
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:8008;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
client_max_body_size 50M;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 8448 ssl http2;
|
||||
server_name matrix.timmy-time.xyz;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/matrix.timmy-time.xyz/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/matrix.timmy-time.xyz/privkey.pem;
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:8008;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
}
|
||||
EOF
|
||||
|
||||
ln -sf /etc/nginx/sites-available/matrix /etc/nginx/sites-enabled/
|
||||
nginx -t && systemctl reload nginx
|
||||
|
||||
# Get cert
|
||||
certbot --nginx -d matrix.timmy-time.xyz
|
||||
```
|
||||
|
||||
### 4. Wire Hermes Agent
|
||||
|
||||
Copy the generated credentials to hermes-agent's environment:
|
||||
|
||||
```bash
|
||||
# From synapse-credentials.env, add to ~/.hermes/.env:
|
||||
MATRIX_HOMESERVER=https://matrix.timmy-time.xyz
|
||||
MATRIX_ACCESS_TOKEN=<from synapse-credentials.env>
|
||||
MATRIX_USER_ID=@hermes-bot:matrix.timmy-time.xyz
|
||||
MATRIX_DEVICE_ID=<from synapse-credentials.env>
|
||||
MATRIX_ENCRYPTION=true
|
||||
```
|
||||
|
||||
Then start the gateway:
|
||||
|
||||
```bash
|
||||
hermes gateway --platform matrix
|
||||
```
|
||||
|
||||
### 5. Verify
|
||||
|
||||
```bash
|
||||
# Check Synapse health
|
||||
curl -s https://matrix.timmy-time.xyz/_matrix/client/versions
|
||||
|
||||
# Check federation
|
||||
curl -s https://matrix.timmy-time.xyz:8448/_matrix/federation/v1/version
|
||||
|
||||
# Check bot is connected
|
||||
# (should appear online in Element or any Matrix client)
|
||||
```
|
||||
|
||||
## Management
|
||||
|
||||
Use the management script for day-to-day operations:
|
||||
|
||||
```bash
|
||||
cd /root/hermes-agent/deploy/synapse
|
||||
|
||||
./manage.sh status # container health
|
||||
./manage.sh logs # tail logs
|
||||
./manage.sh restart # restart Synapse
|
||||
./manage.sh backup # backup DB + data
|
||||
./manage.sh update # pull latest image
|
||||
./manage.sh create-user alice 'password123'
|
||||
./manage.sh create-user admin 'secret' admin
|
||||
```
|
||||
|
||||
## Backups
|
||||
|
||||
```bash
|
||||
./manage.sh backup
|
||||
# Creates: backups/YYYYMMDD_HHMMSS/
|
||||
# ├── synapse_db.sql (PostgreSQL dump)
|
||||
# └── synapse_data.tar.gz (media store + keys)
|
||||
```
|
||||
|
||||
Automate with cron:
|
||||
|
||||
```bash
|
||||
# Daily backup at 3 AM
|
||||
0 3 * * * cd /root/hermes-agent/deploy/synapse && ./manage.sh backup >> /var/log/synapse-backup.log 2>&1
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Synapse won't start
|
||||
```bash
|
||||
docker compose logs synapse
|
||||
# Common: PostgreSQL not ready. Wait for healthcheck.
|
||||
```
|
||||
|
||||
### Bot can't connect
|
||||
```bash
|
||||
# Verify token is valid
|
||||
curl -H "Authorization: Bearer $MATRIX_ACCESS_TOKEN" \
|
||||
https://matrix.timmy-time.xyz/_matrix/client/v3/account/whoami
|
||||
```
|
||||
|
||||
### Federation not working
|
||||
```bash
|
||||
# Check port 8448 is open
|
||||
ss -tlnp | grep 8448
|
||||
# Check firewall
|
||||
ufw status
|
||||
```
|
||||
|
||||
### High memory usage
|
||||
```bash
|
||||
# Check resource limits in docker-compose.yml
|
||||
docker stats synapse
|
||||
# Tune in homeserver.yaml: event_cache_size, caches
|
||||
```
|
||||
|
||||
## Security Notes
|
||||
|
||||
- Registration is disabled by default (`enable_registration: false`)
|
||||
- Rate limiting is enforced on login, registration, and messages
|
||||
- Federation certificate verification is enabled
|
||||
- `.env` and `synapse-credentials.env` are `chmod 600`
|
||||
- Client API binds to `127.0.0.1` only (use Nginx for public access)
|
||||
- Consider: firewall rules, fail2ban, regular backups
|
||||
|
||||
## References
|
||||
|
||||
- [Synapse Documentation](https://matrix-org.github.io/synapse/latest/)
|
||||
- [Matrix Spec](https://spec.matrix.org/)
|
||||
- [Epic #269: Matrix Integration](https://forge.alexanderwhitestone.com/Timmy_Foundation/hermes-agent/issues/269)
|
||||
- [Issue #272: Deploy Synapse on Ezra](https://forge.alexanderwhitestone.com/Timmy_Foundation/hermes-agent/issues/272)
|
||||
- [Hermes Matrix Setup Guide](docs/matrix-setup.md)
|
||||
188
tests/tools/test_session_templates.py
Normal file
188
tests/tools/test_session_templates.py
Normal file
@@ -0,0 +1,188 @@
|
||||
"""Tests for session templates (code-first seeding)."""
|
||||
|
||||
import json
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from tools.session_templates import (
|
||||
SessionTemplate,
|
||||
SessionTemplates,
|
||||
TaskType,
|
||||
ToolCallExample,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tmp_templates(tmp_path):
|
||||
return SessionTemplates(templates_dir=tmp_path / "templates")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Task type classification
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestClassifyTaskType:
|
||||
def test_code_dominant(self, tmp_templates):
|
||||
calls = [
|
||||
{"name": "execute_code"}, {"name": "execute_code"},
|
||||
{"name": "execute_code"}, {"name": "read_file"},
|
||||
]
|
||||
assert tmp_templates.classify_task_type(calls) == TaskType.CODE
|
||||
|
||||
def test_file_dominant(self, tmp_templates):
|
||||
calls = [
|
||||
{"name": "read_file"}, {"name": "write_file"},
|
||||
{"name": "patch"}, {"name": "read_file"},
|
||||
{"name": "execute_code"},
|
||||
]
|
||||
assert tmp_templates.classify_task_type(calls) == TaskType.FILE
|
||||
|
||||
def test_research_dominant(self, tmp_templates):
|
||||
calls = [
|
||||
{"name": "web_search"}, {"name": "web_fetch"},
|
||||
{"name": "web_search"}, {"name": "read_file"},
|
||||
]
|
||||
assert tmp_templates.classify_task_type(calls) == TaskType.RESEARCH
|
||||
|
||||
def test_mixed_no_dominant(self, tmp_templates):
|
||||
calls = [
|
||||
{"name": "execute_code"}, {"name": "read_file"},
|
||||
{"name": "web_search"},
|
||||
]
|
||||
assert tmp_templates.classify_task_type(calls) == TaskType.MIXED
|
||||
|
||||
def test_empty_returns_mixed(self, tmp_templates):
|
||||
assert tmp_templates.classify_task_type([]) == TaskType.MIXED
|
||||
|
||||
def test_threshold_is_60_percent(self, tmp_templates):
|
||||
# 59% code (5/9) should be MIXED
|
||||
calls = [{"name": "execute_code"}] * 5 + [{"name": "read_file"}] * 4
|
||||
assert tmp_templates.classify_task_type(calls) == TaskType.MIXED
|
||||
|
||||
# 60% code (6/10) should be CODE
|
||||
calls = [{"name": "execute_code"}] * 6 + [{"name": "read_file"}] * 4
|
||||
assert tmp_templates.classify_task_type(calls) == TaskType.CODE
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Template CRUD
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestTemplateCRUD:
|
||||
def test_save_and_list(self, tmp_templates):
|
||||
template = SessionTemplate(
|
||||
name="test-code",
|
||||
task_type=TaskType.CODE,
|
||||
examples=[
|
||||
ToolCallExample(tool_name="execute_code", args={"code": "print('hi')"}, success=True),
|
||||
],
|
||||
created_at="2026-01-01T00:00:00Z",
|
||||
)
|
||||
tmp_templates.save_template(template)
|
||||
|
||||
templates = tmp_templates.list_templates()
|
||||
assert len(templates) == 1
|
||||
assert templates[0].name == "test-code"
|
||||
assert templates[0].task_type == TaskType.CODE
|
||||
|
||||
def test_list_filter_by_type(self, tmp_templates):
|
||||
tmp_templates.save_template(SessionTemplate(name="t1", task_type=TaskType.CODE, examples=[]))
|
||||
tmp_templates.save_template(SessionTemplate(name="t2", task_type=TaskType.FILE, examples=[]))
|
||||
|
||||
code_templates = tmp_templates.list_templates(TaskType.CODE)
|
||||
assert len(code_templates) == 1
|
||||
assert code_templates[0].name == "t1"
|
||||
|
||||
def test_delete(self, tmp_templates):
|
||||
tmp_templates.save_template(SessionTemplate(name="delete-me", task_type=TaskType.CODE, examples=[]))
|
||||
assert tmp_templates.delete_template("delete-me") is True
|
||||
assert len(tmp_templates.list_templates()) == 0
|
||||
|
||||
def test_delete_nonexistent(self, tmp_templates):
|
||||
assert tmp_templates.delete_template("nope") is False
|
||||
|
||||
def test_get_template_returns_best(self, tmp_templates):
|
||||
tmp_templates.save_template(SessionTemplate(
|
||||
name="low-usage", task_type=TaskType.CODE, examples=[], usage_count=1,
|
||||
))
|
||||
tmp_templates.save_template(SessionTemplate(
|
||||
name="high-usage", task_type=TaskType.CODE, examples=[], usage_count=5,
|
||||
))
|
||||
best = tmp_templates.get_template(TaskType.CODE)
|
||||
assert best.name == "high-usage"
|
||||
|
||||
def test_get_template_returns_none_if_empty(self, tmp_templates):
|
||||
assert tmp_templates.get_template(TaskType.CODE) is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Template injection
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestInjectIntoMessages:
|
||||
def test_injects_after_system(self, tmp_templates):
|
||||
template = SessionTemplate(
|
||||
name="test-inject",
|
||||
task_type=TaskType.CODE,
|
||||
examples=[
|
||||
ToolCallExample(
|
||||
tool_name="execute_code",
|
||||
args={"code": "x=1"},
|
||||
result_preview="1",
|
||||
success=True,
|
||||
),
|
||||
],
|
||||
)
|
||||
messages = [
|
||||
{"role": "system", "content": "You are Timmy."},
|
||||
{"role": "user", "content": "Hello"},
|
||||
]
|
||||
result = tmp_templates.inject_into_messages(template, messages)
|
||||
|
||||
# Should have: system, template system note, assistant tool call, tool result, user
|
||||
assert len(result) == 5
|
||||
assert result[0]["role"] == "system"
|
||||
assert "Session Template" in result[1]["content"]
|
||||
assert result[2]["role"] == "assistant"
|
||||
assert result[3]["role"] == "tool"
|
||||
assert result[4]["role"] == "user"
|
||||
|
||||
def test_skips_failed_examples(self, tmp_templates):
|
||||
template = SessionTemplate(
|
||||
name="test-fail",
|
||||
task_type=TaskType.CODE,
|
||||
examples=[
|
||||
ToolCallExample(tool_name="execute_code", args={}, success=False),
|
||||
ToolCallExample(tool_name="read_file", args={"path": "x"}, success=True),
|
||||
],
|
||||
)
|
||||
messages = [{"role": "system", "content": "sys"}]
|
||||
result = tmp_templates.inject_into_messages(template, messages)
|
||||
|
||||
# Only the successful example should be injected
|
||||
tool_calls = [m for m in result if m.get("role") == "assistant" and m.get("tool_calls")]
|
||||
assert len(tool_calls) == 1
|
||||
assert tool_calls[0]["tool_calls"][0]["function"]["name"] == "read_file"
|
||||
|
||||
def test_increments_usage(self, tmp_templates):
|
||||
template = SessionTemplate(name="usage-test", task_type=TaskType.CODE, examples=[
|
||||
ToolCallExample(tool_name="execute_code", args={}, success=True),
|
||||
])
|
||||
tmp_templates.save_template(template)
|
||||
|
||||
tmp_templates.inject_into_messages(template, [{"role": "system", "content": "x"}])
|
||||
assert template.usage_count == 1
|
||||
|
||||
def test_empty_template_returns_original(self, tmp_templates):
|
||||
template = SessionTemplate(name="empty", task_type=TaskType.CODE, examples=[])
|
||||
messages = [{"role": "user", "content": "hi"}]
|
||||
result = tmp_templates.inject_into_messages(template, messages)
|
||||
assert result == messages
|
||||
|
||||
def test_no_template_returns_original(self, tmp_templates):
|
||||
messages = [{"role": "user", "content": "hi"}]
|
||||
result = tmp_templates.inject_into_messages(None, messages)
|
||||
assert result == messages
|
||||
418
tools/session_templates.py
Normal file
418
tools/session_templates.py
Normal file
@@ -0,0 +1,418 @@
|
||||
"""
|
||||
Session templates for code-first seeding.
|
||||
|
||||
Research finding: Code-heavy sessions (execute_code dominant in first 30 turns)
|
||||
improve over time. File-heavy sessions degrade. The key is deterministic
|
||||
feedback loops, not arbitrary context.
|
||||
|
||||
This module provides:
|
||||
1. Task type classification (CODE, FILE, RESEARCH, MIXED)
|
||||
2. Template extraction from completed sessions
|
||||
3. Template storage (~/.hermes/session-templates/)
|
||||
4. Template injection into new sessions
|
||||
5. CLI interface for template management
|
||||
|
||||
Closes #329.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from enum import Enum
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Constants
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
HERMES_HOME = Path(os.environ.get("HERMES_HOME", str(Path.home() / ".hermes")))
|
||||
TEMPLATES_DIR = HERMES_HOME / "session-templates"
|
||||
SESSIONS_DB = HERMES_HOME / "state.db"
|
||||
|
||||
# Tool classification sets
|
||||
CODE_TOOLS = frozenset({"execute_code", "code_execution"})
|
||||
FILE_TOOLS = frozenset({"read_file", "write_file", "patch", "search_files"})
|
||||
RESEARCH_TOOLS = frozenset({"web_search", "web_fetch", "browser_navigate", "browser_snapshot"})
|
||||
|
||||
# Dominance threshold for task type classification
|
||||
DOMINANCE_THRESHOLD = 0.6
|
||||
|
||||
# Default max examples to extract per template
|
||||
DEFAULT_MAX_EXAMPLES = 10
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Data model
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TaskType(str, Enum):
|
||||
CODE = "code"
|
||||
FILE = "file"
|
||||
RESEARCH = "research"
|
||||
MIXED = "mixed"
|
||||
|
||||
|
||||
@dataclass
|
||||
class ToolCallExample:
|
||||
"""A single tool call with its result, used as a template example."""
|
||||
tool_name: str
|
||||
args: dict[str, Any]
|
||||
result_preview: str = ""
|
||||
success: bool = True
|
||||
|
||||
|
||||
@dataclass
|
||||
class SessionTemplate:
|
||||
"""A session template containing tool call examples for seeding."""
|
||||
name: str
|
||||
task_type: TaskType
|
||||
examples: list[ToolCallExample] = field(default_factory=list)
|
||||
source_session_id: str = ""
|
||||
created_at: str = ""
|
||||
usage_count: int = 0
|
||||
description: str = ""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Core logic
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class SessionTemplates:
|
||||
"""Manages session templates for code-first seeding."""
|
||||
|
||||
def __init__(self, templates_dir: Optional[Path] = None):
|
||||
self.templates_dir = templates_dir or TEMPLATES_DIR
|
||||
self.templates_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def classify_task_type(self, tool_calls: list[dict[str, Any]]) -> TaskType:
|
||||
"""Classify a session's task type based on tool call patterns.
|
||||
|
||||
Uses 60% threshold for dominant type.
|
||||
"""
|
||||
if not tool_calls:
|
||||
return TaskType.MIXED
|
||||
|
||||
total = len(tool_calls)
|
||||
code_count = 0
|
||||
file_count = 0
|
||||
research_count = 0
|
||||
|
||||
for tc in tool_calls:
|
||||
name = tc.get("name", tc.get("tool_name", "")).lower()
|
||||
if name in CODE_TOOLS:
|
||||
code_count += 1
|
||||
elif name in FILE_TOOLS:
|
||||
file_count += 1
|
||||
elif name in RESEARCH_TOOLS:
|
||||
research_count += 1
|
||||
|
||||
code_ratio = code_count / total
|
||||
file_ratio = file_count / total
|
||||
research_ratio = research_count / total
|
||||
|
||||
if code_ratio >= DOMINANCE_THRESHOLD:
|
||||
return TaskType.CODE
|
||||
if file_ratio >= DOMINANCE_THRESHOLD:
|
||||
return TaskType.FILE
|
||||
if research_ratio >= DOMINANCE_THRESHOLD:
|
||||
return TaskType.RESEARCH
|
||||
return TaskType.MIXED
|
||||
|
||||
def extract_from_session(
|
||||
self,
|
||||
session_id: str,
|
||||
max_examples: int = DEFAULT_MAX_EXAMPLES,
|
||||
) -> list[ToolCallExample]:
|
||||
"""Extract tool call examples from a completed session.
|
||||
|
||||
Reads from the SQLite session database.
|
||||
"""
|
||||
examples: list[ToolCallExample] = []
|
||||
|
||||
db_path = SESSIONS_DB
|
||||
if not db_path.exists():
|
||||
return examples
|
||||
|
||||
try:
|
||||
conn = sqlite3.connect(str(db_path))
|
||||
conn.row_factory = sqlite3.Row
|
||||
|
||||
rows = conn.execute(
|
||||
"SELECT messages FROM sessions WHERE session_id = ? ORDER BY created_at DESC LIMIT 1",
|
||||
(session_id,),
|
||||
).fetchone()
|
||||
|
||||
if not rows:
|
||||
conn.close()
|
||||
return examples
|
||||
|
||||
messages = json.loads(rows["messages"])
|
||||
|
||||
# Extract tool calls from assistant messages
|
||||
for msg in messages:
|
||||
if msg.get("role") != "assistant":
|
||||
continue
|
||||
tool_calls = msg.get("tool_calls", [])
|
||||
if not tool_calls:
|
||||
continue
|
||||
|
||||
for tc in tool_calls:
|
||||
if len(examples) >= max_examples:
|
||||
break
|
||||
|
||||
fn = tc.get("function", {})
|
||||
name = fn.get("name", "")
|
||||
if not name:
|
||||
continue
|
||||
|
||||
try:
|
||||
args = json.loads(fn.get("arguments", "{}"))
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
args = {}
|
||||
|
||||
# Find the corresponding tool result
|
||||
result_preview = ""
|
||||
success = True
|
||||
tc_id = tc.get("id", "")
|
||||
|
||||
for result_msg in messages:
|
||||
if (result_msg.get("role") == "tool"
|
||||
and result_msg.get("tool_call_id") == tc_id):
|
||||
content = result_msg.get("content", "")
|
||||
result_preview = str(content)[:200]
|
||||
# Heuristic: errors contain common failure markers
|
||||
if any(marker in result_preview.lower() for marker in ("error", "failed", "traceback", "exception")):
|
||||
success = False
|
||||
break
|
||||
|
||||
examples.append(ToolCallExample(
|
||||
tool_name=name,
|
||||
args=args,
|
||||
result_preview=result_preview,
|
||||
success=success,
|
||||
))
|
||||
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return examples
|
||||
|
||||
def create_template(
|
||||
self,
|
||||
session_id: str,
|
||||
name: Optional[str] = None,
|
||||
description: str = "",
|
||||
max_examples: int = DEFAULT_MAX_EXAMPLES,
|
||||
) -> Optional[SessionTemplate]:
|
||||
"""Create a template from a session's tool call history."""
|
||||
examples = self.extract_from_session(session_id, max_examples)
|
||||
if not examples:
|
||||
return None
|
||||
|
||||
tool_calls_for_type = [{"name": e.tool_name} for e in examples]
|
||||
task_type = self.classify_task_type(tool_calls_for_type)
|
||||
|
||||
template_name = name or f"{task_type.value}_{session_id[:8]}"
|
||||
|
||||
from datetime import datetime
|
||||
template = SessionTemplate(
|
||||
name=template_name,
|
||||
task_type=task_type,
|
||||
examples=examples,
|
||||
source_session_id=session_id,
|
||||
created_at=datetime.utcnow().isoformat() + "Z",
|
||||
description=description or f"Auto-extracted from {session_id}",
|
||||
)
|
||||
|
||||
self.save_template(template)
|
||||
return template
|
||||
|
||||
def save_template(self, template: SessionTemplate) -> Path:
|
||||
"""Save a template to disk."""
|
||||
path = self.templates_dir / f"{template.name}.json"
|
||||
data = {
|
||||
"name": template.name,
|
||||
"task_type": template.task_type.value,
|
||||
"examples": [asdict(e) for e in template.examples],
|
||||
"source_session_id": template.source_session_id,
|
||||
"created_at": template.created_at,
|
||||
"usage_count": template.usage_count,
|
||||
"description": template.description,
|
||||
}
|
||||
path.write_text(json.dumps(data, indent=2, sort_keys=True) + "\n")
|
||||
return path
|
||||
|
||||
def get_template(self, task_type: TaskType) -> Optional[SessionTemplate]:
|
||||
"""Get the best template for a given task type."""
|
||||
templates = self.list_templates(task_type)
|
||||
if not templates:
|
||||
return None
|
||||
|
||||
# Prefer templates with more usage (proven useful)
|
||||
templates.sort(key=lambda t: t.usage_count, reverse=True)
|
||||
return templates[0]
|
||||
|
||||
def list_templates(self, task_type: Optional[TaskType] = None) -> list[SessionTemplate]:
|
||||
"""List all templates, optionally filtered by type."""
|
||||
templates: list[SessionTemplate] = []
|
||||
|
||||
for path in sorted(self.templates_dir.glob("*.json")):
|
||||
try:
|
||||
data = json.loads(path.read_text())
|
||||
examples = [ToolCallExample(**e) for e in data.get("examples", [])]
|
||||
template = SessionTemplate(
|
||||
name=data["name"],
|
||||
task_type=TaskType(data["task_type"]),
|
||||
examples=examples,
|
||||
source_session_id=data.get("source_session_id", ""),
|
||||
created_at=data.get("created_at", ""),
|
||||
usage_count=data.get("usage_count", 0),
|
||||
description=data.get("description", ""),
|
||||
)
|
||||
if task_type is None or template.task_type == task_type:
|
||||
templates.append(template)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
return templates
|
||||
|
||||
def delete_template(self, name: str) -> bool:
|
||||
"""Delete a template by name."""
|
||||
path = self.templates_dir / f"{name}.json"
|
||||
if path.exists():
|
||||
path.unlink()
|
||||
return True
|
||||
return False
|
||||
|
||||
def inject_into_messages(
|
||||
self,
|
||||
template: SessionTemplate,
|
||||
messages: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Inject template examples into a session's messages.
|
||||
|
||||
Inserts tool call examples after system messages to establish
|
||||
feedback loops early.
|
||||
"""
|
||||
if not template or not template.examples:
|
||||
return messages
|
||||
|
||||
# Build injection messages
|
||||
injection: list[dict[str, Any]] = []
|
||||
|
||||
# System note about the template
|
||||
injection.append({
|
||||
"role": "system",
|
||||
"content": (
|
||||
f"[Session Template: '{template.name}' ({template.task_type.value})]\n"
|
||||
f"The following are examples of successful tool calls from a similar session. "
|
||||
f"Use them as patterns for your own tool usage."
|
||||
),
|
||||
})
|
||||
|
||||
# Add example tool call/result pairs
|
||||
for ex in template.examples:
|
||||
if not ex.success:
|
||||
continue # Only inject successful examples
|
||||
|
||||
injection.append({
|
||||
"role": "assistant",
|
||||
"content": None,
|
||||
"tool_calls": [{
|
||||
"id": f"template_{template.name}_{ex.tool_name}",
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": ex.tool_name,
|
||||
"arguments": json.dumps(ex.args),
|
||||
},
|
||||
}],
|
||||
})
|
||||
injection.append({
|
||||
"role": "tool",
|
||||
"tool_call_id": f"template_{template.name}_{ex.tool_name}",
|
||||
"content": ex.result_preview or "(example result)",
|
||||
})
|
||||
|
||||
# Find insertion point: after system messages
|
||||
insert_idx = 0
|
||||
for i, msg in enumerate(messages):
|
||||
if msg.get("role") == "system":
|
||||
insert_idx = i + 1
|
||||
else:
|
||||
break
|
||||
|
||||
# Insert
|
||||
result = messages[:insert_idx] + injection + messages[insert_idx:]
|
||||
|
||||
# Update usage count
|
||||
template.usage_count += 1
|
||||
self.save_template(template)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CLI
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _cli():
|
||||
"""Simple CLI for session template management."""
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
parser = argparse.ArgumentParser(description="Session template management")
|
||||
sub = parser.add_subparsers(dest="command")
|
||||
|
||||
# list
|
||||
list_cmd = sub.add_parser("list", help="List templates")
|
||||
list_cmd.add_argument("--type", choices=["code", "file", "research", "mixed"])
|
||||
|
||||
# create
|
||||
create_cmd = sub.add_parser("create", help="Create template from session")
|
||||
create_cmd.add_argument("session_id", help="Session ID to extract from")
|
||||
create_cmd.add_argument("--name", help="Template name")
|
||||
create_cmd.add_argument("--max-examples", type=int, default=10)
|
||||
|
||||
# delete
|
||||
delete_cmd = sub.add_parser("delete", help="Delete template")
|
||||
delete_cmd.add_argument("name", help="Template name")
|
||||
|
||||
args = parser.parse_args()
|
||||
tm = SessionTemplates()
|
||||
|
||||
if args.command == "list":
|
||||
task_type = TaskType(args.type) if args.type else None
|
||||
templates = tm.list_templates(task_type)
|
||||
if not templates:
|
||||
print("No templates found.")
|
||||
return
|
||||
for t in templates:
|
||||
print(f" {t.name:30s} {t.task_type.value:10s} {len(t.examples)} examples, used {t.usage_count}x")
|
||||
|
||||
elif args.command == "create":
|
||||
template = tm.create_template(args.session_id, name=args.name, max_examples=args.max_examples)
|
||||
if template:
|
||||
print(f"Created template: {template.name} ({template.task_type.value}, {len(template.examples)} examples)")
|
||||
else:
|
||||
print(f"No tool calls found in session {args.session_id}")
|
||||
sys.exit(1)
|
||||
|
||||
elif args.command == "delete":
|
||||
if tm.delete_template(args.name):
|
||||
print(f"Deleted template: {args.name}")
|
||||
else:
|
||||
print(f"Template not found: {args.name}")
|
||||
sys.exit(1)
|
||||
|
||||
else:
|
||||
parser.print_help()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
_cli()
|
||||
Reference in New Issue
Block a user