Files
archie/internal/gateway/gateway.go
T
sam 6f549fe0a1 gateway: add /steer, /goal, /subgoal, and /queue chat commands
Implement session-scoped goal/subgoal/steer/queue state management
with thread-safe access and prompt injection for standing goals.

Commands:
- /steer <text> — queue a message to inject after the next tool call
- /goal [text|draft|show|pause|resume|clear|status|wait|unwait]
- /subgoal [text|remove N|clear]
- /queue (aliases /q, /bg, /btw, /background) [text|remove N|clear]

Architecture:
- SessionState in internal/gateway holds per-session goals, subgoals,
  steer queue, wait flag, and background queue
- Goals are injected into the system prompt via BuildGoalPrompt()
- Steer messages are consumed between agent tool-calling steps via a
  MaxSteps=1 loop in the daemon's respond closure
- Commands route through the existing gateway.Router with not-configured
  guards when State is nil

Closes: archie-core-alm.1
2026-07-29 03:41:05 +10:00

531 lines
18 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".
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
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
// Personas is the persona registry for /personality. When nil, the
// command returns "not configured".
Personas *PersonaRegistry
// ModelPersist persists the active model globally when --global is
// passed to /model. When nil, --global is a no-op acknowledged to
// the user.
ModelPersist func(ctx context.Context, modelRef string) error
// 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
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}
}
// Route dispatches msg and returns the reply. Gateway-local commands
// (like /status and /model) 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)
switch cmd {
case "/status":
return r.handleStatus(ctx)
case "/model":
rest := restAfter(text, cmd, r.gatewayName)
return r.handleModel(ctx, rest)
case "/personality":
rest := restAfter(text, cmd, r.gatewayName)
return r.handlePersonality(ctx, rest)
case "/spawn":
// Title is everything after "/spawn" -- keep the multi-word text.
rest := restAfter(text, cmd, r.gatewayName)
return r.handleSpawn(ctx, rest)
case "/approve":
// Reserved for dangerous-command approval (archie-core-alm.6).
// Telegram hides it from its menu/help; other gateways keep it
// wired until the new design is wired up.
return r.handleApprove(ctx, restAfter(text, cmd, r.gatewayName))
case "/cancel":
return r.handleCancel(ctx, restAfter(text, cmd, r.gatewayName))
default:
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)
}
}
// 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", "/personality"}
// 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, ""
}
// modelArgs holds the parsed flags from a /model command rest text.
type modelArgs struct {
Model string
Provider string
Global bool
Session bool
Refresh bool
}
// parseModelArgs extracts flags from rest-text after /model. Flags are
// stripped; whatever remains (after the command token) is the model ref.
func parseModelArgs(rest string) modelArgs {
fields := strings.Fields(rest)
ma := modelArgs{}
var modelParts []string
for _, f := range fields {
switch {
case f == "--global":
ma.Global = true
case f == "--session":
ma.Session = true
case f == "--refresh":
ma.Refresh = true
case strings.HasPrefix(f, "--provider"):
// Accept --provider=name and --provider name forms.
if after, ok := strings.CutPrefix(f, "--provider="); ok {
ma.Provider = after
} else if after, ok := strings.CutPrefix(f, "--provider"); ok && after == "" {
// next field is the provider value; parseModelArgs can't
// look ahead, so the caller (Telegram) will re-parse with
// full field context. The router's plain-text handler
// treats --provider as a flag without value.
ma.Provider = ""
} else {
ma.Provider = after
}
default:
modelParts = append(modelParts, f)
}
}
ma.Model = strings.Join(modelParts, " ")
return ma
}
func (r *Router) handleModel(ctx context.Context, rest string) (string, error) {
if r.Models == nil {
return "Model switching is not configured.", nil
}
ma := parseModelArgs(rest)
// --refresh: return the current active model (no catalog refresh in
// the plain-text path; Telegram handles this separately).
if ma.Refresh {
return fmt.Sprintf("Active model: %s.", r.Models.ActiveModel()), nil
}
// No model ref and no flags: list available models.
if ma.Model == "" && ma.Provider == "" {
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 [model] [--provider name] [--global|--session] [--refresh]", nil
}
var b strings.Builder
b.WriteString("Usage: /model [model] [--provider name] [--global|--session] [--refresh]\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
}
// --provider: switch provider first.
if ma.Provider != "" {
manager, ok := r.Models.(ProviderModelManager)
if !ok {
return "Provider switching is not configured.", nil
}
if err := manager.SetActiveProvider(ctx, ma.Provider); err != nil {
return fmt.Sprintf("Cannot switch provider: %v", err), nil
}
}
// Model switch.
if ma.Model != "" {
if err := r.Models.SetActiveModel(ctx, ma.Model); err != nil {
return fmt.Sprintf("Cannot switch: %v", err), nil
}
}
active := r.Models.ActiveModel()
msg := fmt.Sprintf("Active model set to %s.", active)
// Persist if --global and a model was selected.
if ma.Global && ma.Model != "" {
if r.ModelPersist != nil {
if err := r.ModelPersist(ctx, active); err != nil {
return fmt.Sprintf("Model switched to %s but persistence failed: %v", active, err), nil
}
} else {
msg += " (global persistence is not configured)"
}
}
return msg, nil
}
func (r *Router) handlePersonality(ctx context.Context, rest string) (string, error) {
if r.Personas == nil {
return "Personality switching is not configured.", nil
}
if rest == "" {
names := r.Personas.List()
if len(names) == 0 {
return "No personalities configured.", nil
}
var b strings.Builder
b.WriteString("Usage: /personality <name>\nAvailable personalities:\n")
for _, name := range names {
b.WriteString(" " + name + "\n")
}
return b.String(), nil
}
if !r.Personas.SetActive("", rest) {
return fmt.Sprintf("Unknown personality %q. Use /personality to list available personalities.", rest), nil
}
return fmt.Sprintf("Active personality set to %q.", rest), 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
}