Files
archie/internal/gateway/gateway.go
T
sam cf2254213d gateway: restore /whoami /profile /sessions /resume /agents handlers
These five command handlers were dropped during parallel merges of the
Telegram workers; the Router fields they depend on (Identity, Models,
Sessions, Agents) were already in place.
2026-07-29 11:10:34 +10:00

624 lines
21 KiB
Go

// Package gateway defines the persistent-connection layer between archie
// and its users. Each gateway implementation (Telegram, web UI, Discord,
// etc.) owns its connection lifecycle and delegates message dispatch to a
// shared CommandRouter.
//
// The router distinguishes gateway-local commands -- handled directly
// without the LLM (model changes, status queries, restart) -- from
// general messages that need LLM processing.
package gateway
import (
"context"
"fmt"
"slices"
"sort"
"strconv"
"strings"
)
// Message is an inbound message from a gateway connection.
type Message struct {
// ChannelID identifies the conversation within the channel (e.g. a
// Telegram chat ID). Replies are sent back to this ID.
ChannelID string
// ThreadID identifies the topic thread within the conversation, for
// platforms that support threading (Telegram supergroup topics,
// Slack threads, Discord forum posts). Empty for flat chats.
ThreadID string
// From identifies the sender (channel-specific: username, user ID).
From string
// Text is the raw message text, including any leading slash command.
Text string
}
// A Gateway owns a persistent connection to a chat channel. Start blocks;
// the gateway should remain running until ctx is cancelled or Stop is
// called.
type Gateway interface {
Name() string
Start(ctx context.Context, router *Router) error
Stop(ctx context.Context) error
}
// StatusReader is the read-only query surface gateway-local commands
// like /status need. The daemon supplies its store, which satisfies this
// structurally.
type StatusReader interface {
StatusCounts(ctx context.Context) (map[string]int, error)
}
// LLMResponder routes a message to the LLM and returns the reply. When
// nil (not yet wired -- see abg.13), non-command messages get a static
// "LLM not configured" response. Gateways call this for any message the
// router did not handle directly.
type LLMResponder func(ctx context.Context, msg Message) (string, error)
// LLMStreamResponder is the streaming counterpart of LLMResponder. It
// reports the reply as it is generated by calling onDelta with each new
// text fragment, and returns the complete reply when the turn finishes.
//
// It is optional: a gateway that cannot render partial output, or a
// deployment whose provider does not stream, simply leaves it nil and the
// Router falls back to the blocking LLMResponder. onDelta may be called
// from the generating goroutine and must not block for long -- adapters
// should throttle their own network writes rather than stall the stream.
type LLMStreamResponder func(ctx context.Context, msg Message, onDelta func(string)) (string, error)
// ModelManager provides access to available models and allows switching the
// active LLM model. The daemon supplies an implementation backed by its
// runtime provider catalog. When nil on a Router, /model returns a
// "not configured" message.
type ModelManager interface {
// Models returns all available model references in "provider/model" format.
Models() []string
// ActiveModel returns the currently active model reference.
// Returns empty string when no model is active.
ActiveModel() string
// SetActiveModel switches the active model. Returns an error if the
// reference is unknown.
SetActiveModel(ctx context.Context, ref string) error
}
// ProviderModelManager is the optional provider-aware extension used by
// gateways that offer a provider selector before model selection.
type ProviderModelManager interface {
ModelManager
Providers() []string
ActiveProvider() string
ModelsForProvider(provider string) []string
SetActiveProvider(ctx context.Context, provider string) error
}
// SpawnRequest is a chat-originated task creation request. Repo and
// Workflow are optional -- empty means "the daemon's configured
// default for this identity".
type SpawnRequest struct {
Title string
Repo string // "owner/name"; empty = identity's default repo
Workflow string // empty = daemon's default workflow routing
Identity string // the identity spawning this task; propagated from Router.Identity
}
// TaskCreator creates a native (non-forge-backed) task from a chat
// command. The daemon supplies an implementation backed by the store.
// When nil on a Router, /spawn returns "not configured". CreateTask
// must return the task's real, durable database ID -- never a
// synthetic or fabricated value.
type TaskCreator interface {
CreateTask(ctx context.Context, req SpawnRequest) (taskID int64, err error)
}
// TaskController approves or cancels a chat-originated task. Both
// methods must enforce authorization (identity must own the task) and
// valid state transitions; see gateway.tasks.go's StoreTaskController
// for the reference implementation. When nil on a Router, /approve and
// /cancel return "not configured".
// AgentInfo is a lightweight agent summary for /agents.
type AgentInfo struct {
ID int64
Title string
Status string
Identity string
}
// AgentReader is the read surface /agents uses.
type AgentReader interface {
AgentList(ctx context.Context) ([]AgentInfo, error)
}
type TaskController interface {
// Approve moves a waiting_human task back to queued. Returns an
// error (surfaced to the user, not the LLM) if the task doesn't
// exist, isn't owned by identity, or isn't in waiting_human.
Approve(ctx context.Context, taskID int64, identity string) error
// Cancel moves an active (non-terminal, non-running) task to a
// rejected/cancelled terminal state. Returns an error if the task
// doesn't exist, isn't owned by identity, or is already terminal
// or actively running.
Cancel(ctx context.Context, taskID int64, identity string) error
}
// Router dispatches inbound messages. Gateway-local commands (like
// /status) are handled directly. Everything else is routed to the LLM
// responder. Gateway implementations call Route on every inbound
// message.
type Router struct {
Store StatusReader
Models ModelManager // nil = /model not configured
// ModelPersist persists the active model selection so it survives
// restarts (e.g. writing back to identity config). nil = not configured.
ModelPersist func(ctx context.Context, modelRef string) error
// Personas holds the available personality registry for /personality.
Personas *PersonaRegistry
Tasks TaskCreator // nil = /spawn not configured
Controller TaskController // nil = /approve and /cancel not configured
LLM LLMResponder // nil = LLM not wired yet
// LLMStream is the optional streaming responder. When set, adapters
// that can render partial output (see RouteStream) show the reply as
// it generates; when nil, everything falls back to LLM.
LLMStream LLMStreamResponder
// Identity is the archie identity this router belongs to (empty in
// single-identity deployments). Propagated into SpawnRequest and
// used to scope /approve and /cancel authorization -- a task
// spawned under one identity cannot be controlled from another's
// chat session.
Identity string
// Sessions persists session metadata and conversation history.
// When set, session lifecycle commands (/new, /branch, /title,
// /undo, /retry, /compress) are available. When nil, those
// commands report "not configured".
Sessions SessionStore
Agents AgentReader // nil = /agents not configured
sessionTracker *sessionTracker
gatewayName string
}
// NewRouter returns a Router. llm is optional -- when nil, non-command
// messages get a "not configured" response.
func NewRouter(store StatusReader, llm LLMResponder, gatewayName string) *Router {
return &Router{Store: store, LLM: llm, gatewayName: gatewayName}
}
// InitSessions wires the session store and starts tracking sessions.
// Must be called before session commands are used. Idempotent.
func (r *Router) InitSessions(sessions SessionStore) {
r.Sessions = sessions
r.sessionTracker = newSessionTracker(sessions)
}
// Route dispatches msg and returns the reply. Gateway-local commands
// are handled directly; everything else goes to the LLM responder.
func (r *Router) Route(ctx context.Context, msg Message) (string, error) {
text := strings.TrimSpace(msg.Text)
cmd, _ := parseCmd(text, r.gatewayName)
if reply, handled, err := r.dispatchLocal(ctx, msg, text, cmd); handled {
return reply, err
}
if strings.HasPrefix(cmd, "/") {
return fmt.Sprintf("Unknown command %s. Try /help.", cmd), nil
}
if r.LLM == nil {
return "I'm running but LLM processing isn't wired yet. Try /status.", nil
}
return r.LLM(ctx, msg)
}
// dispatchLocal handles recognized local commands. Returns (reply,
// true) when the command was recognized and handled.
func (r *Router) dispatchLocal(ctx context.Context, msg Message, text, cmd string) (string, bool, error) {
rest := restAfter(text, cmd, r.gatewayName)
switch cmd {
case "/status":
reply, err := r.handleStatus(ctx)
return reply, true, err
case "/model":
_, arg := parseCmd(text, "")
reply, err := r.handleModel(ctx, arg)
return reply, true, err
case "/spawn":
reply, err := r.handleSpawn(ctx, rest)
return reply, true, err
case "/approve":
reply, err := r.handleApprove(ctx, rest)
return reply, true, err
case "/cancel":
reply, err := r.handleCancel(ctx, rest)
return reply, true, err
case "/start":
reply, err := r.handleStart(ctx, msg)
return reply, true, err
case "/whoami":
reply, err := r.handleWhoami(ctx)
return reply, true, err
case "/profile":
reply, err := r.handleProfile(ctx)
return reply, true, err
case "/sessions":
reply, err := r.handleSessions(ctx)
return reply, true, err
case "/resume":
reply, err := r.handleResume(ctx, msg, rest)
return reply, true, err
case "/agents":
reply, err := r.handleAgents(ctx)
return reply, true, err
}
return r.dispatchSessionCommand(ctx, msg, cmd, rest)
}
// dispatchSessionCommand handles the session-lifecycle command group
// (/new, /topic, /retry, /undo, /title, /branch, /compress and their
// aliases). Split out from dispatchLocal to keep cyclomatic complexity
// down.
func (r *Router) dispatchSessionCommand(ctx context.Context, msg Message, cmd, rest string) (string, bool, error) {
switch cmd {
case "/new", "/reset":
reply, err := r.handleNew(ctx, msg, rest)
return reply, true, err
case "/topic":
reply, err := r.handleTopic(ctx, msg, rest)
return reply, true, err
case "/retry":
reply, err := r.handleRetry(ctx, msg)
return reply, true, err
case "/undo":
reply, err := r.handleUndo(ctx, msg, rest)
return reply, true, err
case "/title":
reply, err := r.handleTitle(ctx, msg, rest)
return reply, true, err
case "/branch", "/fork":
reply, err := r.handleBranch(ctx, msg, rest)
return reply, true, err
case "/compress", "/compact":
reply, err := r.handleCompress(ctx, msg, rest)
return reply, true, err
}
return "", false, nil
}
// RouteStream is Route for adapters that can render a reply progressively.
// onDelta receives each new fragment of an LLM reply as it is generated;
// the complete reply is returned as usual.
//
// Only free-text messages stream. Gateway-local commands (/status, /model,
// …) answer from local state in a single step, so they return through the
// normal path with no delta callbacks. When no streaming responder is
// configured, RouteStream is exactly Route -- callers get the whole reply
// at the end and simply never see a delta, so an adapter can always call
// RouteStream without checking first.
func (r *Router) RouteStream(ctx context.Context, msg Message, onDelta func(string)) (string, error) {
if r.LLMStream == nil || onDelta == nil {
return r.Route(ctx, msg)
}
cmd, _ := parseCmd(strings.TrimSpace(msg.Text), r.gatewayName)
if isLocalCommand(cmd) || strings.HasPrefix(cmd, "/") {
return r.Route(ctx, msg)
}
return r.LLMStream(ctx, msg, onDelta)
}
var localCommands = []string{
"/status", "/model", "/spawn", "/approve", "/cancel",
"/new", "/reset", "/topic", "/retry", "/undo",
"/title", "/branch", "/fork", "/compress", "/compact",
"/whoami", "/profile", "/sessions", "/resume", "/agents",
}
// LocalCommands returns the command names Route answers from local state.
// Gateways use this to verify that their published command surfaces match
// the executable router surface.
func LocalCommands() []string {
return slices.Clone(localCommands)
}
// isLocalCommand reports whether cmd is answered from local state by
// Route rather than handed to the LLM.
func isLocalCommand(cmd string) bool {
return slices.Contains(localCommands, cmd)
}
// parseCmd extracts the command name from text, stripping an optional
// @gateway mention from the command token, and returns the command and
// its first argument.
func parseCmd(text, gatewayName string) (cmd, arg string) {
fields := strings.Fields(text)
if len(fields) == 0 {
return "", ""
}
raw := fields[0]
if gatewayName != "" {
suffix := "@" + gatewayName
raw = strings.TrimSuffix(raw, suffix)
}
if len(fields) > 1 {
return raw, fields[1]
}
return raw, ""
}
func (r *Router) handleModel(ctx context.Context, arg string) (string, error) {
if r.Models == nil {
return "Model switching is not configured.", nil
}
if arg == "" {
models := r.Models.Models()
if manager, ok := r.Models.(ProviderModelManager); ok {
models = manager.ModelsForProvider(manager.ActiveProvider())
}
if len(models) == 0 {
return "No models configured.\nUsage: /model <provider/model>", nil
}
var b strings.Builder
b.WriteString("Usage: /model <provider/model>\nAvailable models:\n")
active := r.Models.ActiveModel()
for _, m := range models {
if m == active {
fmt.Fprintf(&b, " %s (active)\n", m)
} else {
fmt.Fprintf(&b, " %s\n", m)
}
}
return b.String(), nil
}
if err := r.Models.SetActiveModel(ctx, arg); err != nil {
return fmt.Sprintf("Cannot switch: %v", err), nil
}
return fmt.Sprintf("Active model set to %s.", arg), nil
}
// restAfter returns the text after the command token, stripping the
// optional @gateway mention. E.g. for "/spawn Fix the bug", returns
// "Fix the bug".
func restAfter(text, cmd, gatewayName string) string {
s := text
if gatewayName != "" {
s = strings.TrimPrefix(s, cmd+"@"+gatewayName)
}
s = strings.TrimPrefix(s, cmd)
return strings.TrimSpace(s)
}
// handleSpawn parses optional leading identity, repo, and workflow tokens
// off rest, treating whatever remains as the task title.
func (r *Router) handleSpawn(ctx context.Context, rest string) (string, error) {
if r.Tasks == nil {
return "Task creation is not configured.", nil
}
req := SpawnRequest{Identity: r.Identity}
fields := strings.Fields(rest)
i := 0
for i < len(fields) {
if after, ok := strings.CutPrefix(fields[i], "identity="); ok {
req.Identity = after
i++
continue
}
if after, ok := strings.CutPrefix(fields[i], "repo="); ok {
req.Repo = after
i++
continue
}
if after, ok := strings.CutPrefix(fields[i], "workflow="); ok {
req.Workflow = after
i++
continue
}
break // remaining fields are all title
}
req.Title = strings.TrimSpace(strings.Join(fields[i:], " "))
if req.Title == "" {
return "Usage: /spawn [identity=name] [repo=owner/name] [workflow=name] <title>", nil
}
id, err := r.Tasks.CreateTask(ctx, req)
if err != nil {
return fmt.Sprintf("Failed to create task: %v", err), nil
}
return fmt.Sprintf("Created task %d: %s", id, req.Title), nil
}
// parseTaskID parses a chat command argument as a task database ID.
func parseTaskID(arg string) (int64, error) {
if arg == "" {
return 0, fmt.Errorf("missing task ID")
}
id, err := strconv.ParseInt(arg, 10, 64)
if err != nil {
return 0, fmt.Errorf("%q is not a valid task ID", arg)
}
return id, nil
}
func (r *Router) handleApprove(ctx context.Context, rest string) (string, error) {
if r.Controller == nil {
return "Task control is not configured.", nil
}
identity, arg := parseTaskControl(rest, r.Identity)
id, err := parseTaskID(arg)
if err != nil {
return "Usage: /approve [identity=name] <task-id>", nil //nolint:nilerr // chat commands report problems as text to the human, never as Go errors, which would surface as a gateway fault
}
if err := r.Controller.Approve(ctx, id, identity); err != nil {
return fmt.Sprintf("Cannot approve task %d: %v", id, err), nil
}
return fmt.Sprintf("Task %d approved and requeued.", id), nil
}
func (r *Router) handleCancel(ctx context.Context, rest string) (string, error) {
if r.Controller == nil {
return "Task control is not configured.", nil
}
identity, arg := parseTaskControl(rest, r.Identity)
id, err := parseTaskID(arg)
if err != nil {
return "Usage: /cancel [identity=name] <task-id>", nil //nolint:nilerr // chat commands report problems as text to the human, never as Go errors, which would surface as a gateway fault
}
if err := r.Controller.Cancel(ctx, id, identity); err != nil {
return fmt.Sprintf("Cannot cancel task %d: %v", id, err), nil
}
return fmt.Sprintf("Task %d cancelled.", id), nil
}
func parseTaskControl(rest, defaultIdentity string) (identity, taskID string) {
fields := strings.Fields(rest)
identity = defaultIdentity
if len(fields) > 0 && strings.HasPrefix(fields[0], "identity=") {
identity = strings.TrimPrefix(fields[0], "identity=")
fields = fields[1:]
}
if len(fields) != 1 {
return identity, ""
}
return identity, fields[0]
}
func (r *Router) handleStatus(ctx context.Context) (string, error) {
if r.Store == nil {
return "store not configured", nil
}
counts, err := r.Store.StatusCounts(ctx)
if err != nil {
return "", fmt.Errorf("status: %w", err)
}
if len(counts) == 0 && r.Models == nil {
return "No tasks yet.", nil
}
statuses := make([]string, 0, len(counts))
for s := range counts {
statuses = append(statuses, s)
}
sort.Strings(statuses)
var b strings.Builder
if len(statuses) == 0 {
b.WriteString("No tasks yet.\n")
} else {
b.WriteString("Task status:\n")
for _, s := range statuses {
fmt.Fprintf(&b, " %s: %d\n", s, counts[s])
}
}
if r.Models != nil {
if manager, ok := r.Models.(ProviderModelManager); ok {
fmt.Fprintf(&b, "\nProvider: %s\n", manager.ActiveProvider())
}
fmt.Fprintf(&b, "Model: %s\n", r.Models.ActiveModel())
}
return strings.TrimSpace(b.String()), nil
}
func (r *Router) handleWhoami(ctx context.Context) (string, error) {
if r.Identity == "" {
return "I'm Archie, running without a configured identity.", nil
}
var b strings.Builder
fmt.Fprintf(&b, "I'm %s.", r.Identity)
if r.Models != nil {
if active := r.Models.ActiveModel(); active != "" {
fmt.Fprintf(&b, " Running %s.", active)
}
}
return b.String(), nil
}
func (r *Router) handleProfile(ctx context.Context) (string, error) {
if r.Identity == "" {
return "Profile is not configured (no identity set).", nil
}
var b strings.Builder
fmt.Fprintf(&b, "Identity: %s\n", r.Identity)
if r.Models != nil {
fmt.Fprintf(&b, "Model: %s\n", r.Models.ActiveModel())
}
return strings.TrimSpace(b.String()), nil
}
func (r *Router) handleSessions(ctx context.Context) (string, error) {
if r.Sessions == nil {
return "Session management is not configured.", nil
}
sessions, err := r.Sessions.List(ctx)
if err != nil {
return "", fmt.Errorf("list sessions: %w", err)
}
if len(sessions) == 0 {
return "No sessions.", nil
}
var b strings.Builder
b.WriteString("Sessions:\n")
for _, s := range sessions {
prefix := s.SessionID[:min(8, len(s.SessionID))]
title := s.Title
if title == "" {
title = "(untitled)"
}
fmt.Fprintf(&b, " %s — %s\n", prefix, title)
}
return strings.TrimSpace(b.String()), nil
}
// handleResume switches the active session for the current channel+thread
// to the session whose ID matches or is uniquely prefixed by arg.
func (r *Router) handleResume(ctx context.Context, msg Message, arg string) (string, error) {
arg = strings.TrimSpace(arg)
if arg == "" {
return "Usage: /resume <session-id>", nil
}
if r.Sessions == nil {
return "Session management is not configured.", nil
}
sessions, err := r.Sessions.List(ctx)
if err != nil {
return "", fmt.Errorf("list sessions: %w", err)
}
for _, s := range sessions {
if s.SessionID == arg {
return r.resumeSession(msg, s), nil
}
}
var matches []SessionContext
for _, s := range sessions {
if strings.HasPrefix(s.SessionID, arg) {
matches = append(matches, s)
}
}
switch len(matches) {
case 0:
return fmt.Sprintf("No session matching %q.", arg), nil
case 1:
return r.resumeSession(msg, matches[0]), nil
default:
return fmt.Sprintf("Multiple sessions match %q; be more specific.", arg), nil
}
}
func (r *Router) resumeSession(msg Message, s SessionContext) string {
if r.sessionTracker != nil {
r.sessionTracker.setActive(msg.ChannelID, msg.ThreadID, s.SessionID)
}
return fmt.Sprintf("Resumed session %s.", s.SessionID)
}
func (r *Router) handleAgents(ctx context.Context) (string, error) {
if r.Agents == nil {
return "Agent listing is not configured.", nil
}
agents, err := r.Agents.AgentList(ctx)
if err != nil {
return "", fmt.Errorf("list agents: %w", err)
}
if len(agents) == 0 {
return "No active agents.", nil
}
var b strings.Builder
b.WriteString("Active agents:\n")
for _, a := range agents {
fmt.Fprintf(&b, " #%d %s — %s (%s)\n", a.ID, a.Title, a.Status, a.Identity)
}
return strings.TrimSpace(b.String()), nil
}