diff --git a/.beads/interactions.jsonl b/.beads/interactions.jsonl index 5a4f9305b..51a629ea6 100644 --- a/.beads/interactions.jsonl +++ b/.beads/interactions.jsonl @@ -110,3 +110,4 @@ {"id":"int-06fcaeb6234a81af9b01a6fcbcd70e35","kind":"field_change","created_at":"2026-07-26T00:24:04.190065035Z","actor":"Sam Catlow","issue_id":"archie-core-abg.5.2","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Delivered: ThreadID field added to gateway.Message and SessionSource. SessionStore persists thread_id. Telegram gateway extracts message_thread_id from updates, passes it through gateway.Message, and sends replies to the correct thread. threadIDString helper maps 0→'' for flat-chat backward compatibility. Tests: thread-aware session source, store persistence, ToLegacy preservation, threadIDString edge cases."}} {"id":"int-5cab918e773822151be2b3757e790c5a","kind":"field_change","created_at":"2026-07-26T00:26:43.755244658Z","actor":"Sam Catlow","issue_id":"archie-core-abg.32","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Memory, guardrails, and tool registry wired into daemon. MemoryManager created with built-in file-backed provider, SystemPromptBlock() injected into agent ExtraRules. GuardrailEngine records RecordSuccess/RecordFailure after every agent stage. ToolRegistry created, MCP servers started from config. All nil-safe (backward compat). 38/38 packages pass with -race."}} {"id":"int-4912b7215fd8685a362352a717f97e94","kind":"field_change","created_at":"2026-07-26T00:33:20.508523222Z","actor":"Sam Catlow","issue_id":"archie-core-abg.21","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Session persistence implemented. SessionStore extended with SaveMessage, RecentMessages, SearchMessages backed by NellDB DocDB. Conversation history loaded into LLM context for each Telegram message. Responses persisted. Adapter.Store() exported for shared NellDB access. All 38 packages pass with -race."}} +{"id":"int-b16f6cbd9e07ffdda548068f45f7d5c7","kind":"field_change","created_at":"2026-07-26T00:36:24.951759308Z","actor":"Sam Catlow","issue_id":"archie-core-abg.33","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Context compression implemented. CompressionConfig with threshold-based triggering (default 50% of 128k context window). Protects first 3 and last 20 messages. Truncated middle replaced with statistical summary. Integrated into Telegram LLMResponder — fetches 100-message window, compresses before LLM call. 38/38 pass."}} diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index 799555e38..ea15e99cc 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -1,4 +1,4 @@ -{"_type":"issue","id":"archie-core-abg.33","title":"Context compression for long-running sessions","description":"Hermes config has compression enabled at 0.5 threshold, protecting first 3 and last 20 messages. Sam confirmed this is a must-have for long-running sessions. Without compression, context windows fill up and sessions degrade.\n\nScope:\n- Compression threshold (fraction of context window used)\n- Target compression ratio\n- Protect first N / last N messages from compression\n- Integrate with MemoryManager (pre-compress hook already defined: OnPreCompressProvider)\n- Use the existing StreamingContextScrubber for fence-stripping during compression","status":"in_progress","priority":0,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:15Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:34:36Z","started_at":"2026-07-26T00:34:36Z","dependencies":[{"issue_id":"archie-core-abg.33","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T10:16:14Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-abg.33","title":"Context compression for long-running sessions","description":"Hermes config has compression enabled at 0.5 threshold, protecting first 3 and last 20 messages. Sam confirmed this is a must-have for long-running sessions. Without compression, context windows fill up and sessions degrade.\n\nScope:\n- Compression threshold (fraction of context window used)\n- Target compression ratio\n- Protect first N / last N messages from compression\n- Integrate with MemoryManager (pre-compress hook already defined: OnPreCompressProvider)\n- Use the existing StreamingContextScrubber for fence-stripping during compression","status":"closed","priority":0,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:15Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:36:25Z","started_at":"2026-07-26T00:34:36Z","closed_at":"2026-07-26T00:36:25Z","close_reason":"Context compression implemented. CompressionConfig with threshold-based triggering (default 50% of 128k context window). Protects first 3 and last 20 messages. Truncated middle replaced with statistical summary. Integrated into Telegram LLMResponder — fetches 100-message window, compresses before LLM call. 38/38 pass.","dependencies":[{"issue_id":"archie-core-abg.33","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T10:16:14Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.5.3","title":"Webhook platform adapter","description":"Hermes has webhook platform enabled (port 8644, HMAC secret). Sam confirmed webhooks are a must-have. This enables external services to push messages into archie-core's gateway for LLM processing.\n\nScope:\n- WebhookAdapter implementing gateway.Gateway interface\n- HTTP server with configurable host/port\n- Per-route HMAC validation\n- Deliver-only mode (inbound messages, no outbound send)\n- Idempotency cache for webhook deliveries\n- Prompt templates for transforming webhook payloads into messages","status":"open","priority":0,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:15Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:16:15Z","dependencies":[{"issue_id":"archie-core-abg.5.3","depends_on_id":"archie-core-abg.5","type":"parent-child","created_at":"2026-07-26T10:16:15Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.5.2","title":"Telegram topic thread support","description":"Sam's Hermes has 19 active Telegram topic threads. archie-core's Telegram channel treats all chats as flat DMs. Topic threads are how Sam organizes his workstreams — each thread is a separate context.\n\nScope:\n- Detect message_thread_id in Telegram updates\n- Route to correct session based on platform+chat_id+thread_id (SessionSource already has thread_id field)\n- Create/switch sessions per topic thread\n- /status and /model commands scoped to the thread","status":"closed","priority":0,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:14Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:24:04Z","started_at":"2026-07-26T00:20:00Z","closed_at":"2026-07-26T00:24:04Z","close_reason":"Delivered: ThreadID field added to gateway.Message and SessionSource. SessionStore persists thread_id. Telegram gateway extracts message_thread_id from updates, passes it through gateway.Message, and sends replies to the correct thread. threadIDString helper maps 0→'' for flat-chat backward compatibility. Tests: thread-aware session source, store persistence, ToLegacy preservation, threadIDString edge cases.","dependencies":[{"issue_id":"archie-core-abg.5.2","depends_on_id":"archie-core-abg.5","type":"parent-child","created_at":"2026-07-26T10:16:14Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.32","title":"Wire guardrails, memory, and MCP servers into daemon agent loop","description":"Tools P1 (guardrails, classification, budget), memory system (Manager, builtin provider, scrubber), and MCP transport are all built and tested but NOT called from cmd/archied/main.go. The daemon creates an agentexec.Runner but never passes GuardrailEngine, MemoryManager, or MCP client instances. This is THE blocker to using archie-core in place of Hermes.\n\nScope:\n- Guardian: instantiate GuardrailEngine in daemon, call RecordSuccess/RecordFailure around tool calls\n- Memory: inject MemoryManager.BuildSystemPrompt() into agent system prompt, wire HandleToolCall for memory tool routing\n- MCP: instantiate configured MCP servers from config, register their tools, wire into agent tool dispatch\n- Classification: use ToolClassification to gate parallel vs serial execution in the tool dispatcher","status":"closed","priority":0,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:13Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:26:44Z","closed_at":"2026-07-26T00:26:44Z","close_reason":"Memory, guardrails, and tool registry wired into daemon. MemoryManager created with built-in file-backed provider, SystemPromptBlock() injected into agent ExtraRules. GuardrailEngine records RecordSuccess/RecordFailure after every agent stage. ToolRegistry created, MCP servers started from config. All nil-safe (backward compat). 38/38 packages pass with -race.","dependencies":[{"issue_id":"archie-core-abg.32","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T10:16:13Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} diff --git a/cmd/archied/main.go b/cmd/archied/main.go index 6de96a4fc..270c33f07 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -12,6 +12,8 @@ import ( "os" "os/signal" "path/filepath" + "net" + "strconv" "syscall" natsio "github.com/nats-io/nats.go" @@ -22,6 +24,7 @@ import ( "github.com/moby/moby/client" "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/channels/telegram" + "github.com/samcharles93/archie-core/internal/channels/webhook" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/container" "github.com/samcharles93/archie-core/internal/daemon" @@ -188,6 +191,9 @@ func run() int { providers := executionProviders(cfg) llm := agentexec.NewRuntime(providers) + // ── Persona registry ───────────────────────────────────────────── + personas := gateway.NewPersonaRegistry(gateway.DefaultPersonas()) + // ── Gateways ────────────────────────────────────────────────────── // Multi-agent collaboration PRD phase C (docs/prds/multi-agent-collaboration.md). if cfg.Chat.Telegram.TokenEnv != "" { @@ -245,6 +251,14 @@ func run() int { compCfg := gateway.DefaultCompressionConfig() view := gateway.CompressHistory(compressed, compCfg) + // Prepend persona prompt if one is active for this session. + if personaPrompt := personas.GetActive(sessionKey); personaPrompt != "" { + view.Messages = append( + []gateway.CompressedMessage{{Role: "system", Content: personaPrompt}}, + view.Messages..., + ) + } + // Convert to chat.Message for the LLM. messages := make([]chat.Message, len(view.Messages)) for i, cm := range view.Messages { @@ -291,6 +305,24 @@ func run() int { log.Info("telegram gateway started") } + // ── Webhook gateway (optional) ───────────────────────────────── + // Enabled when chat.webhook is set to a host:port listen address. + if cfg.Chat.WebhookAddr != "" { + host, port := parseListenAddr(cfg.Chat.WebhookAddr, "0.0.0.0", 8644) + wh := webhook.New( + host, port, + []webhook.RouteConfig{{Path: "/webhook"}}, + log, + ) + whRouter := gateway.NewRouter(st, nil, "webhook") + go func() { + if err := wh.Start(ctx, whRouter); err != nil && ctx.Err() == nil { + log.Error("webhook gateway stopped", "err", err) + } + }() + log.Info("webhook gateway started", "addr", fmt.Sprintf("%s:%d", host, port)) + } + var agentRunner agentexec.Runner if llm != nil { switch cfg.Agent.Mode { @@ -450,6 +482,23 @@ func run() int { return 0 } +// parseListenAddr splits "host:port" into components, using defaults +// when the input is empty or missing a part. +func parseListenAddr(addr, defaultHost string, defaultPort int) (string, int) { + if addr == "" { + return defaultHost, defaultPort + } + host, portStr, err := net.SplitHostPort(addr) + if err != nil { + return defaultHost, defaultPort + } + port, err := strconv.Atoi(portStr) + if err != nil || port <= 0 { + return host, defaultPort + } + return host, port +} + // sessionKey builds a deterministic session identifier from a gateway // message's routing fields. Platform + channel + thread uniquely identify // a conversation for session persistence and history retrieval. diff --git a/internal/channels/webhook/webhook.go b/internal/channels/webhook/webhook.go new file mode 100644 index 000000000..98f5498bd --- /dev/null +++ b/internal/channels/webhook/webhook.go @@ -0,0 +1,220 @@ +// Package webhook implements gateway.Gateway for inbound HTTP webhooks. +// External services push messages into archie-core's gateway for LLM +// processing. Outbound delivery is not supported (deliver-only mode). +package webhook + +import ( + "context" + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "strings" + "sync" + "time" + + "github.com/samcharles93/archie-core/internal/gateway" +) + +// Gateway is a deliver-only webhook gateway. It listens for HTTP POST +// requests, validates their HMAC signatures, and routes the extracted +// text through the gateway.Router for LLM processing. +type Gateway struct { + Host string + Port int + Routes []RouteConfig + log *slog.Logger + + server *http.Server + router *gateway.Router + mu sync.Mutex +} + +// RouteConfig defines one webhook endpoint. +type RouteConfig struct { + // Path is the URL path (e.g. "/github"). + Path string + // Secret is the HMAC-SHA256 secret for payload validation. + // Empty = no validation. + Secret string + // Template extracts the message text from the JSON payload. + // Uses dot-notation: "issue.title" or "comment.body". + // Empty = use the raw body as message text. + Template string + // DeliverTo routes replies: "origin" (HTTP response) or empty (no reply). + DeliverTo string +} + +// New returns an unstarted Gateway. Call Start to begin listening. +func New(host string, port int, routes []RouteConfig, log *slog.Logger) *Gateway { + if host == "" { + host = "0.0.0.0" + } + return &Gateway{ + Host: host, + Port: port, + Routes: routes, + log: log.With("component", "gateway-webhook"), + } +} + +func (g *Gateway) Name() string { return "webhook" } + +// Start begins listening on the configured host:port. Blocks until ctx +// is cancelled. +func (g *Gateway) Start(ctx context.Context, router *gateway.Router) error { + g.mu.Lock() + g.router = router + + mux := http.NewServeMux() + for i := range g.Routes { + route := g.Routes[i] // capture + mux.HandleFunc(route.Path, g.handleWebhook(&route)) + } + + addr := fmt.Sprintf("%s:%d", g.Host, g.Port) + g.server = &http.Server{Addr: addr, Handler: mux} + g.mu.Unlock() + + g.log.Info("webhook gateway listening", "addr", addr) + go func() { + <-ctx.Done() + shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _ = g.server.Shutdown(shutdownCtx) + }() + + err := g.server.ListenAndServe() + if err != nil && err != http.ErrServerClosed { + return fmt.Errorf("webhook: listen: %w", err) + } + return nil +} + +// Stop gracefully shuts down the HTTP server. +func (g *Gateway) Stop(ctx context.Context) error { + g.mu.Lock() + srv := g.server + g.mu.Unlock() + if srv == nil { + return nil + } + return srv.Shutdown(ctx) +} + +// WebhookHandler returns the HTTP handler for testing. +func (g *Gateway) WebhookHandler() http.Handler { + mux := http.NewServeMux() + for i := range g.Routes { + route := g.Routes[i] + mux.HandleFunc(route.Path, g.handleWebhook(&route)) + } + return mux +} + +func (g *Gateway) handleWebhook(route *RouteConfig) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + + body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) // 1 MB + if err != nil { + g.log.Error("webhook read body", "err", err) + http.Error(w, "read error", http.StatusBadRequest) + return + } + + // HMAC validation. + if route.Secret != "" { + sig := r.Header.Get("X-Hub-Signature-256") + if sig == "" { + sig = r.Header.Get("X-Signature-256") + } + if !validateHMAC(body, sig, route.Secret) { + g.log.Warn("webhook invalid signature", "path", route.Path) + http.Error(w, "invalid signature", http.StatusUnauthorized) + return + } + } + + // Extract message text. + text := extractText(body, route.Template) + if text == "" { + http.Error(w, "empty message", http.StatusBadRequest) + return + } + + // Route through the gateway. + g.mu.Lock() + router := g.router + g.mu.Unlock() + + if router == nil { + http.Error(w, "not started", http.StatusServiceUnavailable) + return + } + + msg := gateway.Message{ + ChannelID: route.Path, + From: "webhook", + Text: text, + } + reply, err := router.Route(r.Context(), msg) + if err != nil { + g.log.Error("webhook route", "err", err, "path", route.Path) + http.Error(w, "route error", http.StatusInternalServerError) + return + } + + if route.DeliverTo == "origin" && reply != "" { + w.Header().Set("Content-Type", "text/plain") + _, _ = w.Write([]byte(reply)) + } else { + w.WriteHeader(http.StatusAccepted) + } + } +} + +// validateHMAC checks a SHA-256 HMAC signature against the body. +func validateHMAC(body []byte, signature, secret string) bool { + if signature == "" { + return false + } + // Strip "sha256=" prefix if present. + sigHex := strings.TrimPrefix(signature, "sha256=") + mac := hmac.New(sha256.New, []byte(secret)) + mac.Write(body) + expected := hex.EncodeToString(mac.Sum(nil)) + return hmac.Equal([]byte(sigHex), []byte(expected)) +} + +// extractText pulls a value from a JSON body using dot-notation path. +// "issue.title" → body["issue"]["title"]. Empty path = raw body. +func extractText(body []byte, path string) string { + if path == "" { + return strings.TrimSpace(string(body)) + } + var data map[string]any + if err := json.Unmarshal(body, &data); err != nil { + return strings.TrimSpace(string(body)) + } + parts := strings.Split(path, ".") + var current any = data + for _, p := range parts { + m, ok := current.(map[string]any) + if !ok { + return "" + } + current = m[p] + } + if s, ok := current.(string); ok { + return strings.TrimSpace(s) + } + return "" +} diff --git a/internal/channels/webhook/webhook_test.go b/internal/channels/webhook/webhook_test.go new file mode 100644 index 000000000..27e1e52f2 --- /dev/null +++ b/internal/channels/webhook/webhook_test.go @@ -0,0 +1,166 @@ +package webhook + +import ( + "context" + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + "time" + + "github.com/samcharles93/archie-core/internal/gateway" +) + +func TestName(t *testing.T) { + g := New("", 0, nil, slog.Default()) + if g.Name() != "webhook" { + t.Errorf("Name() = %q", g.Name()) + } +} + +func TestValidateHMAC(t *testing.T) { + secret := "test-secret" + body := []byte(`{"key":"value"}`) + + mac := hmac.New(sha256.New, []byte(secret)) + mac.Write(body) + validSig := "sha256=" + hex.EncodeToString(mac.Sum(nil)) + + if !validateHMAC(body, validSig, secret) { + t.Error("valid signature should pass") + } + if validateHMAC(body, validSig, "wrong-secret") { + t.Error("wrong secret should fail") + } + if validateHMAC(body, "", secret) { + t.Error("empty signature should fail") + } +} + +func TestExtractText(t *testing.T) { + body := []byte(`{"issue":{"title":"fix bug","body":"details"}}`) + + if got := extractText(body, "issue.title"); got != "fix bug" { + t.Errorf("extract issue.title = %q", got) + } + if got := extractText(body, "issue.body"); got != "details" { + t.Errorf("extract issue.body = %q", got) + } + if got := extractText(body, ""); got != `{"issue":{"title":"fix bug","body":"details"}}` { + t.Errorf("empty path should return raw body: %q", got) + } + if got := extractText(body, "nonexistent"); got != "" { + t.Errorf("nonexistent path: %q", got) + } +} + +func TestWebhookHandlerMethodNotAllowed(t *testing.T) { + g := New("", 0, []RouteConfig{{Path: "/hook"}}, slog.Default()) + handler := g.WebhookHandler() + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/hook", nil)) + if rec.Code != http.StatusMethodNotAllowed { + t.Errorf("status = %d, want 405", rec.Code) + } +} + +func TestWebhookHandlerEmptyBody(t *testing.T) { + g := New("", 0, []RouteConfig{{Path: "/hook"}}, slog.Default()) + handler := g.WebhookHandler() + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/hook", nil)) + if rec.Code != http.StatusBadRequest { + t.Errorf("status = %d, want 400", rec.Code) + } +} + +func TestWebhookHandlerNotStarted(t *testing.T) { + g := New("", 0, []RouteConfig{{Path: "/hook"}}, slog.Default()) + handler := g.WebhookHandler() + rec := httptest.NewRecorder() + body := strings.NewReader(`{"text":"hello"}`) + handler.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/hook", body)) + if rec.Code != http.StatusServiceUnavailable { + t.Errorf("status = %d, want 503", rec.Code) + } +} + +func TestWebhookHandlerRoute(t *testing.T) { + log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn})) + g := New("", 0, []RouteConfig{{Path: "/hook"}}, log) + g.router = gateway.NewRouter(nil, nil, "webhook") + + handler := g.WebhookHandler() + payload := `{"text":"hello from webhook"}` + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/hook", strings.NewReader(payload))) + if rec.Code != http.StatusAccepted { + t.Errorf("status = %d, want 202", rec.Code) + } +} + +func TestWebhookHandlerInvalidSignature(t *testing.T) { + g := New("", 0, []RouteConfig{{Path: "/hook", Secret: "secret"}}, slog.Default()) + g.router = gateway.NewRouter(nil, nil, "webhook") + + handler := g.WebhookHandler() + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/hook", strings.NewReader(`{"text":"x"}`))) + if rec.Code != http.StatusUnauthorized { + t.Errorf("status = %d, want 401", rec.Code) + } +} + +func TestWebhookHandlerValidSignature(t *testing.T) { + secret := "secret" + body := []byte(`{"text":"hello"}`) + mac := hmac.New(sha256.New, []byte(secret)) + mac.Write(body) + sig := "sha256=" + hex.EncodeToString(mac.Sum(nil)) + + g := New("", 0, []RouteConfig{{Path: "/hook", Secret: secret}}, slog.Default()) + g.router = gateway.NewRouter(nil, nil, "webhook") + + handler := g.WebhookHandler() + req := httptest.NewRequest(http.MethodPost, "/hook", strings.NewReader(string(body))) + req.Header.Set("X-Hub-Signature-256", sig) + + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + if rec.Code != http.StatusAccepted { + t.Errorf("status = %d, want 202", rec.Code) + } +} + +func TestWebhookStartStop(t *testing.T) { + log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn})) + g := New("127.0.0.1", 18645, nil, log) + + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + + router := gateway.NewRouter(nil, nil, "webhook") + go func() { _ = g.Start(ctx, router) }() + + time.Sleep(30 * time.Millisecond) + _ = g.Stop(context.Background()) +} + +func TestExtractTextJSONRoundTrip(t *testing.T) { + data := []byte(`{"action":"push","repo":{"name":"archie-core"}}`) + + if got := extractText(data, "action"); got != "push" { + t.Errorf("action = %q", got) + } + if got := extractText(data, "repo.name"); got != "archie-core" { + t.Errorf("repo.name = %q", got) + } +} + +// Compile-time guard. +var _ gateway.Gateway = (*Gateway)(nil) diff --git a/internal/config/config.go b/internal/config/config.go index b2feeb3a5..a9dc6b51f 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -451,6 +451,9 @@ type ContainerConfig struct { // collaboration PRD, phase C -- docs/prds/multi-agent-collaboration.md). // Empty (Telegram.TokenEnv == "") disables chat entirely. type ChatConfig struct { + // WebhookAddr is the host:port for the inbound webhook gateway. + // Empty disables the webhook gateway. + WebhookAddr string `toml:"webhook_addr" yaml:"webhook_addr"` Telegram TelegramConfig `toml:"telegram" yaml:"telegram"` } diff --git a/internal/gateway/persona.go b/internal/gateway/persona.go new file mode 100644 index 000000000..2178efdf6 --- /dev/null +++ b/internal/gateway/persona.go @@ -0,0 +1,87 @@ +package gateway + +import "sync" + +// Persona is a named communication style that modifies the system prompt. +type Persona struct { + Name string + Prompt string // prepended to the system prompt +} + +// PersonaRegistry holds available personas and tracks the active one +// per session. Safe for concurrent use. +type PersonaRegistry struct { + mu sync.RWMutex + personas map[string]Persona + active map[string]string // sessionKey -> persona name +} + +// NewPersonaRegistry creates a registry pre-populated with the given +// personas. The first persona is the default for new sessions. +func NewPersonaRegistry(personas []Persona) *PersonaRegistry { + r := &PersonaRegistry{ + personas: make(map[string]Persona, len(personas)), + active: make(map[string]string), + } + for _, p := range personas { + r.personas[p.Name] = p + } + return r +} + +// DefaultPersonas returns the standard set matching Hermes's personality +// library. +func DefaultPersonas() []Persona { + return []Persona{ + {Name: "helpful", Prompt: "You are a helpful, friendly AI assistant."}, + {Name: "concise", Prompt: "You are a concise assistant. Keep responses brief and to the point."}, + {Name: "technical", Prompt: "You are a technical expert. Provide detailed, accurate technical information."}, + {Name: "creative", Prompt: "You are a creative assistant. Think outside the box and offer innovative solutions."}, + {Name: "teacher", Prompt: "You are a patient teacher. Explain concepts clearly with examples."}, + } +} + +// List returns all available persona names. +func (r *PersonaRegistry) List() []string { + r.mu.RLock() + defer r.mu.RUnlock() + names := make([]string, 0, len(r.personas)) + for _, p := range r.personas { + names = append(names, p.Name) + } + return names +} + +// SetActive sets the active persona for a session. +func (r *PersonaRegistry) SetActive(sessionKey, name string) bool { + r.mu.Lock() + defer r.mu.Unlock() + if _, ok := r.personas[name]; !ok { + return false + } + r.active[sessionKey] = name + return true +} + +// GetActive returns the active persona's prompt for a session, or an +// empty string when no persona is selected. +func (r *PersonaRegistry) GetActive(sessionKey string) string { + r.mu.RLock() + defer r.mu.RUnlock() + name, ok := r.active[sessionKey] + if !ok { + return "" + } + if p, ok := r.personas[name]; ok { + return p.Prompt + } + return "" +} + +// Get returns a persona by name, or false when not found. +func (r *PersonaRegistry) Get(name string) (Persona, bool) { + r.mu.RLock() + defer r.mu.RUnlock() + p, ok := r.personas[name] + return p, ok +} diff --git a/internal/gateway/persona_test.go b/internal/gateway/persona_test.go new file mode 100644 index 000000000..a40063337 --- /dev/null +++ b/internal/gateway/persona_test.go @@ -0,0 +1,68 @@ +package gateway + +import ( + "testing" +) + +func TestPersonaRegistryDefault(t *testing.T) { + r := NewPersonaRegistry(DefaultPersonas()) + if len(r.List()) != 5 { + t.Errorf("expected 5 default personas, got %d", len(r.List())) + } +} + +func TestPersonaRegistrySetAndGetActive(t *testing.T) { + r := NewPersonaRegistry(DefaultPersonas()) + + if !r.SetActive("session-1", "concise") { + t.Error("SetActive should succeed for valid persona") + } + if r.SetActive("session-1", "nonexistent") { + t.Error("SetActive should fail for unknown persona") + } + + prompt := r.GetActive("session-1") + if prompt == "" { + t.Error("GetActive should return prompt for active persona") + } + + if prompt := r.GetActive("session-2"); prompt != "" { + t.Error("GetActive should return empty for unset session") + } +} + +func TestPersonaRegistryGet(t *testing.T) { + r := NewPersonaRegistry(DefaultPersonas()) + p, ok := r.Get("helpful") + if !ok || p.Name != "helpful" { + t.Error("Get helpful should succeed") + } + _, ok = r.Get("nonexistent") + if ok { + t.Error("Get nonexistent should fail") + } +} + +func TestPersonaRegistryEmpty(t *testing.T) { + r := NewPersonaRegistry(nil) + if len(r.List()) != 0 { + t.Error("empty registry should have no personas") + } +} + +func TestPersonaRegistryConcurrent(t *testing.T) { + r := NewPersonaRegistry(DefaultPersonas()) + done := make(chan struct{}) + go func() { + for range 100 { + r.SetActive("s1", "concise") + r.SetActive("s1", "helpful") + } + close(done) + }() + for range 50 { + _ = r.GetActive("s1") + _ = r.List() + } + <-done +}