1064 lines
35 KiB
Go
1064 lines
35 KiB
Go
// Package gateway routes chat messages from channel adapters to local
|
|
// commands or the LLM.
|
|
package gateway
|
|
|
|
import (
|
|
"cmp"
|
|
"context"
|
|
"fmt"
|
|
"log/slog"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
"unicode"
|
|
|
|
"github.com/samcharles93/archie-core/internal/domain/access"
|
|
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
|
"github.com/samcharles93/archie-core/internal/ratelimit"
|
|
"github.com/samcharles93/archie-core/internal/releaseupdate"
|
|
"github.com/samcharles93/archie-core/internal/taskstate"
|
|
)
|
|
|
|
// Lifecycle receives adapter-owned startup facts.
|
|
type Lifecycle = messaging.Lifecycle
|
|
|
|
// 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, lifecycle Lifecycle) 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, in Inbound) (string, error)
|
|
|
|
// LLMStreamResponder is the streaming form of LLMResponder: it reports text
|
|
// fragments and tool calls to stream and returns the full reply. Optional;
|
|
// stream must not block for long.
|
|
type LLMStreamResponder func(ctx context.Context, in Inbound, stream TurnStream) (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 {
|
|
ModelsFor(ctx context.Context) ([]string, error)
|
|
ActiveAlias(ctx context.Context) string
|
|
ModelFor(ctx context.Context) (string, error)
|
|
SetActiveModel(ctx context.Context, selection string) error
|
|
}
|
|
|
|
// ModelDetails is the catalog metadata rendered after an interactive model
|
|
// selection. Limits are zero when the upstream catalog does not publish them.
|
|
type ModelDetails = messaging.ModelDetails
|
|
|
|
// DetailedModelManager is the optional catalog-aware extension used by rich
|
|
// model selectors. Runtime routing remains on ModelManager.
|
|
type DetailedModelManager interface {
|
|
ModelManager
|
|
ModelDetails(ref string) (ModelDetails, bool)
|
|
}
|
|
|
|
type ProviderDisplayNamer interface {
|
|
ProviderDisplayName(provider string) string
|
|
}
|
|
|
|
// UpdateService is the shared release workflow used by chat adapters. The
|
|
// recipient id scopes deferrals; each adapter chooses its own stable id.
|
|
type UpdateService interface {
|
|
Check(context.Context, int64) (releaseupdate.Snapshot, error)
|
|
Defer(context.Context, int64, releaseupdate.Snapshot) error
|
|
Install(context.Context, releaseupdate.Snapshot, releaseupdate.InstallMeta, func(string)) (releaseupdate.Result, error)
|
|
CanInstall() bool
|
|
}
|
|
|
|
// AgentInfo is an 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_approval 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_approval.
|
|
Approve(ctx context.Context, taskID int64, identity string) error
|
|
// Cancel cancels an active task owned by identity. It errors if the task is
|
|
// missing, not owned or already terminal.
|
|
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
|
|
Tasks TaskCreator // nil = /spawn not configured
|
|
Controller TaskController // nil = /approve and /cancel not configured
|
|
Settings *messaging.SettingsCommand
|
|
// TaskLister backs /tasks: the live work view (id, title, status,
|
|
// workflow/stage, age). nil = /tasks not configured.
|
|
TaskLister ChatTaskLister
|
|
// Health backs /status' daemon-health section (broker, worker pool,
|
|
// channels, chat model, last poll). nil = this process wired no health
|
|
// source, in which case /status omits the section rather than
|
|
// reporting a value it does not have.
|
|
Health HealthSource
|
|
LLM LLMResponder // nil = LLM not wired yet
|
|
// LLMStream is the optional streaming responder. When set, the streamed
|
|
// chat adapter (internal/gateway/chat_local.go) shows the reply as it
|
|
// generates; when nil, everything falls back to LLM.
|
|
LLMStream LLMStreamResponder
|
|
// Identity is this router's archie identity; it scopes spawned tasks and task
|
|
// control. Empty in single-identity deployments.
|
|
Identity string
|
|
// Version is shown by the shared /version command when supplied by the
|
|
// composition root. Empty means version information is unavailable.
|
|
Version string
|
|
// Updates handles the shared /update command. Nil means unavailable.
|
|
Updates UpdateService
|
|
// 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
|
|
// Titles proposes display titles for untitled sessions (see
|
|
// TitleGenerator). Nil disables automatic title generation; when set,
|
|
// the router asks for a title after a successful turn on a session
|
|
// that still has none, in the background, and persists the result.
|
|
Titles TitleGenerator
|
|
// Log is the optional logger for the best-effort background title
|
|
// path. Nil drops those diagnostics silently; nothing on this path is
|
|
// important enough to fail the turn over.
|
|
Log *slog.Logger
|
|
// Limiter enforces a per-(gateway, source) inbound budget, keyed by
|
|
// sender. Nil disables it.
|
|
Limiter *ratelimit.Limiter
|
|
// Dedup declines a redelivered platform message inside its TTL. Nil disables
|
|
// it.
|
|
Dedup *MessageDeduplicator
|
|
// Batches coalesces rapid text fragments from one sender into one turn,
|
|
// after the per-message gates. Nil disables it.
|
|
Batches *TextBatchAggregator
|
|
// SlashAccess gates slash commands by sender role. Nil leaves every
|
|
// command available, which is the pre-policy behaviour; a composition
|
|
// that configures an allowlist sets it so an admin-only command cannot
|
|
// run for a sender the policy does not name (see slash_access.go).
|
|
SlashAccess *SlashAccessPolicy
|
|
// SlashDenials records each refused slash command for audit. Optional:
|
|
// nil still refuses and still writes the refusal to Log, it only means
|
|
// the deployment keeps no durable record of it.
|
|
SlashDenials SlashDenialRecorder
|
|
sessionTracker *sessionTracker
|
|
gatewayName string
|
|
// titlingMu guards titling, the set of sessions with a title proposal
|
|
// in flight (see claimTitleInFlight). Zero value is ready to use.
|
|
titlingMu sync.Mutex
|
|
titling map[string]struct{}
|
|
}
|
|
|
|
// 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,
|
|
Dedup: NewMessageDeduplicator(0, 0, nil),
|
|
Batches: NewTextBatchAggregator(0, 0, 0, nil, nil),
|
|
}
|
|
}
|
|
|
|
// 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)
|
|
}
|
|
|
|
// SessionTracker exposes the session tracker so that tool constructors
|
|
// (SessionTools) can bind session_resume to the active session without
|
|
// reaching into the Router's unexported fields.
|
|
func (r *Router) SessionTracker() *sessionTracker {
|
|
return r.sessionTracker
|
|
}
|
|
|
|
// rateLimitReply is returned to a sender who has exceeded their inbound
|
|
// budget, in place of normal dispatch.
|
|
const rateLimitReply = "You're sending messages too quickly. Please wait a moment and try again."
|
|
|
|
// checkRateLimit reports whether in is over its sender's inbound budget.
|
|
// A nil Limiter (rate limiting not configured) or no sender always allows.
|
|
func (r *Router) checkRateLimit(in Inbound) (blocked bool) {
|
|
key := in.Message.SenderID
|
|
if r.Limiter == nil || key == "" {
|
|
return false
|
|
}
|
|
return !r.Limiter.Allow(r.gatewayName, key)
|
|
}
|
|
|
|
// 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, in Inbound) (string, error) {
|
|
reply, _, err := r.RouteResult(ctx, in)
|
|
return reply, err
|
|
}
|
|
|
|
// RouteResult is Route plus whether the sender hit its inbound rate limit.
|
|
func (r *Router) RouteResult(ctx context.Context, in Inbound) (reply string, rateLimited bool, err error) {
|
|
if r.duplicateDelivery(in) {
|
|
return dedupReply, false, nil
|
|
}
|
|
if r.checkRateLimit(in) {
|
|
return rateLimitReply, true, nil
|
|
}
|
|
ready, mine, err := r.CollectTurn(ctx, in)
|
|
if err != nil {
|
|
return "", false, err
|
|
}
|
|
if !mine {
|
|
// A covered fragment: the batch's one turn answers the batch through
|
|
// the call that dispatched it. This caller renders nothing of its
|
|
// own; where the reply leaves as text (email is the only such
|
|
// channel today), nothing is sent rather than the join sent twice.
|
|
return "", false, nil
|
|
}
|
|
reply, err = r.route(ctx, ready)
|
|
return reply, false, err
|
|
}
|
|
|
|
// duplicateDelivery reports whether in repeats a delivery inside the dedup
|
|
// window and records it. It runs before the rate limit. Nil Dedup never
|
|
// blocks.
|
|
func (r *Router) duplicateDelivery(in Inbound) bool {
|
|
return r.Dedup != nil && !r.Dedup.Admit(in)
|
|
}
|
|
|
|
// CollectTurn hands a gated inbound to the text batcher and returns the
|
|
// payload this call must dispatch. Nil Batches passes through.
|
|
func (r *Router) CollectTurn(ctx context.Context, in Inbound) (Inbound, bool, error) {
|
|
if r.Batches == nil {
|
|
return in, true, nil
|
|
}
|
|
return r.Batches.Collect(ctx, in)
|
|
}
|
|
|
|
// route is Route's continuation once the caller has already cleared the
|
|
// rate-limit check (or is deliberately skipping it, as streamTurn's
|
|
// local-command fallthrough and the streamed adapter's degraded-to-non-
|
|
// streaming path do, to avoid charging one message twice).
|
|
func (r *Router) route(ctx context.Context, in Inbound) (string, error) {
|
|
ctx = r.turnContext(ctx, in)
|
|
text := strings.TrimSpace(in.Message.Text)
|
|
cmd, _ := parseCmd(text, r.gatewayName)
|
|
|
|
// The command gate runs before any dispatch, so a refused command
|
|
// executes none of its handler -- not even the part that would read the
|
|
// argument or reach the model.
|
|
if reply, refused := r.checkSlashAccess(ctx, in, cmd); refused {
|
|
return reply, nil
|
|
}
|
|
|
|
if reply, handled, err := r.dispatchLocal(ctx, in.Message, r.sessionPlatform(in), 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
|
|
}
|
|
reply, err := r.LLM(ctx, in)
|
|
if err == nil {
|
|
r.maybeAutoTitle(ctx, in.Message)
|
|
}
|
|
return reply, err
|
|
}
|
|
|
|
// dispatchLocal handles recognized local commands. Returns (reply,
|
|
// true) when the command was recognized and handled.
|
|
func (r *Router) dispatchLocal(ctx context.Context, msg messaging.Message, platform, 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 "/tasks":
|
|
reply, err := r.handleTasks(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 "/settings":
|
|
actor := ""
|
|
if principal, ok := access.PrincipalFromContext(ctx); ok {
|
|
actor = string(principal.IdentityID)
|
|
}
|
|
return r.Settings.Execute(ctx, actor, rest), true, nil
|
|
case "/start":
|
|
reply, err := r.handleStart()
|
|
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
|
|
}
|
|
return r.dispatchLocalMisc(ctx, msg, platform, cmd, rest)
|
|
}
|
|
|
|
// dispatchLocalMisc handles the remaining recognized local commands not
|
|
// covered by dispatchLocal's first switch. Split out to keep cyclomatic
|
|
// complexity down.
|
|
func (r *Router) dispatchLocalMisc(ctx context.Context, msg messaging.Message, platform, cmd, rest string) (string, bool, error) {
|
|
switch cmd {
|
|
case "/sessions":
|
|
reply, err := r.handleSessions(ctx, msg)
|
|
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
|
|
case "/help":
|
|
return r.helpText(), true, nil
|
|
case "/version":
|
|
return r.handleVersion(), true, nil
|
|
case "/update":
|
|
return r.handleUpdateCheck(ctx), true, nil
|
|
}
|
|
return r.dispatchSessionCommand(ctx, msg, platform, cmd, rest)
|
|
}
|
|
|
|
// handleVersion reports the configured build version.
|
|
func (r *Router) handleVersion() string {
|
|
if r.Version == "" {
|
|
return "Version information is not configured."
|
|
}
|
|
return r.Version
|
|
}
|
|
|
|
// handleUpdateCheck reports the latest available update snapshot.
|
|
func (r *Router) handleUpdateCheck(ctx context.Context) string {
|
|
if r.Updates == nil {
|
|
return "Updates are not configured."
|
|
}
|
|
snapshot, err := r.Updates.Check(ctx, 0)
|
|
if err != nil {
|
|
return fmt.Sprintf("Could not check for updates: %v", err)
|
|
}
|
|
return releaseupdate.FormatSnapshot(snapshot)
|
|
}
|
|
|
|
// 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 messaging.Message, platform, cmd, rest string) (string, bool, error) {
|
|
switch cmd {
|
|
case "/new", "/reset":
|
|
reply, err := r.handleNew(ctx, msg, platform, rest)
|
|
return reply, true, err
|
|
case "/topic":
|
|
reply, err := r.handleTopic(ctx, msg, platform, 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, platform, rest)
|
|
return reply, true, err
|
|
case "/compress", "/compact":
|
|
reply, err := r.handleCompress(ctx, msg, rest)
|
|
return reply, true, err
|
|
case "/delete":
|
|
reply, err := r.handleDelete(ctx, msg, rest)
|
|
return reply, true, err
|
|
}
|
|
return "", false, nil
|
|
}
|
|
|
|
// streamTurn dispatches one streamed turn whose gates and batching already
|
|
// ran in the adapter's prelude.
|
|
func (r *Router) streamTurn(ctx context.Context, in Inbound, stream TurnStream) (string, error) {
|
|
ctx = r.turnContext(ctx, in)
|
|
if r.LLMStream == nil || stream == nil {
|
|
return r.route(ctx, in)
|
|
}
|
|
cmd, _ := parseCmd(strings.TrimSpace(in.Message.Text), r.gatewayName)
|
|
if isLocalCommand(cmd) || strings.HasPrefix(cmd, "/") {
|
|
return r.route(ctx, in)
|
|
}
|
|
reply, err := r.LLMStream(ctx, in, stream)
|
|
if err == nil {
|
|
r.maybeAutoTitle(ctx, in.Message)
|
|
}
|
|
return reply, err
|
|
}
|
|
|
|
// 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(messaging.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, err := r.Models.ModelsFor(ctx)
|
|
if err != nil {
|
|
return fmt.Sprintf("Cannot list models: %v", err), nil
|
|
}
|
|
if len(models) == 0 {
|
|
return "No models configured.\nUsage: /model <alias|provider/model>", nil
|
|
}
|
|
var b strings.Builder
|
|
b.WriteString("Usage: /model <alias|provider/model>\nAvailable models:\n")
|
|
active, _ := r.Models.ModelFor(ctx)
|
|
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, Origin: originFrom(ctx)}
|
|
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)
|
|
}
|
|
report := HealthReport{}
|
|
if r.Health != nil {
|
|
report = r.Health.Health()
|
|
}
|
|
return formatStatus(ctx, counts, report, r.Models, time.Now()), nil
|
|
}
|
|
|
|
// handleTasks answers /tasks: the live view of this identity's work, with
|
|
// enough identity and state to act on it. This is the division of labour
|
|
// /status used to blur -- /status now reports health, /tasks reports work.
|
|
func (r *Router) handleTasks(ctx context.Context) (string, error) {
|
|
if r.TaskLister == nil {
|
|
return "task list not configured", nil
|
|
}
|
|
tasks, err := r.TaskLister.ListChatTasks(ctx, r.Identity, defaultTaskListLimit)
|
|
if err != nil {
|
|
return "", fmt.Errorf("tasks: %w", err)
|
|
}
|
|
return formatTasks(tasks, time.Now()), nil
|
|
}
|
|
|
|
// reportLineBreak is a Markdown hard line break.
|
|
const reportLineBreak = " \n"
|
|
|
|
// parkReasonMaxRunes bounds the park reason shown per task. A reason carries
|
|
// whatever the failing stage reported, which for a lint or test gate is a
|
|
// whole tool log; unbounded, one parked task pushes every other task out of
|
|
// the reply.
|
|
const parkReasonMaxRunes = 160
|
|
|
|
// summarizeParkReason reduces a park reason to one readable line: the first
|
|
// non-empty line, bounded. The full reason stays on the task, which /task and
|
|
// the dashboard show in full -- this is the list view.
|
|
func summarizeParkReason(reason string) string {
|
|
line := reason
|
|
if first, _, ok := strings.Cut(reason, "\n"); ok {
|
|
line = first
|
|
}
|
|
line = strings.TrimSpace(line)
|
|
if line == "" {
|
|
line = strings.TrimSpace(reason)
|
|
}
|
|
runes := []rune(line)
|
|
if len(runes) <= parkReasonMaxRunes {
|
|
return line
|
|
}
|
|
return strings.TrimSpace(string(runes[:parkReasonMaxRunes])) + "..."
|
|
}
|
|
|
|
// formatTasks renders each task's id, title, status, workflow/stage and age
|
|
// since its last transition.
|
|
func formatTasks(tasks []ChatTaskSummary, now time.Time) string {
|
|
var b strings.Builder
|
|
b.WriteString("🗂 Archie tasks\n\n")
|
|
if len(tasks) == 0 {
|
|
b.WriteString("No tasks yet\n")
|
|
return strings.TrimSpace(b.String())
|
|
}
|
|
sortTasksByPriority(tasks)
|
|
for _, t := range tasks {
|
|
icon, label := "•", formatCustomStatus(t.Status)
|
|
if d, ok := taskStateDisplays[t.Status]; ok {
|
|
icon, label = d.icon, d.label
|
|
}
|
|
fmt.Fprintf(&b, "%s #%d %s%s", icon, t.ID, t.Title, reportLineBreak)
|
|
fmt.Fprintf(&b, " %s", label)
|
|
if t.Workflow != "" {
|
|
fmt.Fprintf(&b, " · %s", t.Workflow)
|
|
}
|
|
if t.Attempt > 1 {
|
|
fmt.Fprintf(&b, " · attempt %d", t.Attempt)
|
|
}
|
|
if age := relativeAge(t.UpdatedAt, now); age != "" {
|
|
fmt.Fprintf(&b, " · updated %s", age)
|
|
}
|
|
if t.Status == taskstate.Parked && t.ParkReason != "" {
|
|
fmt.Fprintf(&b, "%s ↳ %s", reportLineBreak, summarizeParkReason(t.ParkReason))
|
|
}
|
|
b.WriteString("\n\n")
|
|
}
|
|
return strings.TrimSpace(b.String())
|
|
}
|
|
|
|
type taskStateDisplay struct {
|
|
icon string
|
|
label string
|
|
}
|
|
|
|
var taskStateDisplays = map[string]taskStateDisplay{
|
|
taskstate.Running: {icon: "▶", label: "Running"},
|
|
taskstate.WaitingApproval: {icon: "👤", label: "Waiting"},
|
|
taskstate.Parked: {icon: "⏸", label: "Parked"},
|
|
taskstate.Queued: {icon: "⏳", label: "Queued"},
|
|
taskstate.PROpen: {icon: "🔀", label: "PR open"},
|
|
taskstate.Merged: {icon: "✅", label: "Merged"},
|
|
taskstate.Completed: {icon: "✅", label: "Completed"},
|
|
taskstate.Rejected: {icon: "❌", label: "Rejected"},
|
|
taskstate.Declined: {icon: "🚫", label: "Declined"},
|
|
"declined": {icon: "🚫", label: "Declined"},
|
|
taskstate.Dead: {icon: "🛑", label: "Dead"},
|
|
}
|
|
|
|
var statusOrder = []string{
|
|
taskstate.Running,
|
|
taskstate.WaitingApproval,
|
|
taskstate.Parked,
|
|
taskstate.Queued,
|
|
taskstate.PROpen,
|
|
taskstate.Merged,
|
|
taskstate.Completed,
|
|
taskstate.Rejected,
|
|
taskstate.Declined,
|
|
"declined",
|
|
taskstate.Dead,
|
|
}
|
|
|
|
// sortTasksByPriority stably orders running, then waiting, then parked
|
|
// tasks, with terminal tasks last.
|
|
func sortTasksByPriority(tasks []ChatTaskSummary) {
|
|
orderMap := make(map[string]int, len(statusOrder))
|
|
for i, s := range statusOrder {
|
|
orderMap[s] = i
|
|
}
|
|
slices.SortStableFunc(tasks, func(a, b ChatTaskSummary) int {
|
|
idxA, okA := orderMap[a.Status]
|
|
idxB, okB := orderMap[b.Status]
|
|
if okA && okB {
|
|
return cmp.Compare(idxA, idxB)
|
|
}
|
|
if okA {
|
|
return -1
|
|
}
|
|
if okB {
|
|
return 1
|
|
}
|
|
return strings.Compare(a.Status, b.Status)
|
|
})
|
|
}
|
|
|
|
func formatCustomStatus(s string) string {
|
|
s = strings.TrimSpace(strings.ReplaceAll(s, "_", " "))
|
|
if s == "" {
|
|
return "Unknown"
|
|
}
|
|
r := []rune(s)
|
|
r[0] = unicode.ToUpper(r[0])
|
|
return string(r)
|
|
}
|
|
|
|
var knownProviderNames = map[string]string{
|
|
"openai": "OpenAI",
|
|
"openrouter": "OpenRouter",
|
|
"anthropic": "Anthropic",
|
|
"deepseek": "DeepSeek",
|
|
"google": "Google",
|
|
"ollama": "Ollama",
|
|
"github": "GitHub",
|
|
"gh": "GitHub",
|
|
"groq": "Groq",
|
|
"together": "Together",
|
|
"bedrock": "Bedrock",
|
|
"azure": "Azure",
|
|
}
|
|
|
|
func formatProviderName(provider string) string {
|
|
trimmed := strings.TrimSpace(provider)
|
|
if trimmed == "" {
|
|
return ""
|
|
}
|
|
if name, ok := knownProviderNames[strings.ToLower(trimmed)]; ok {
|
|
return name
|
|
}
|
|
if strings.ToLower(trimmed) == trimmed {
|
|
r := []rune(trimmed)
|
|
r[0] = unicode.ToUpper(r[0])
|
|
return string(r)
|
|
}
|
|
return trimmed
|
|
}
|
|
|
|
func extractRuntimeInfo(ctx context.Context, models ModelManager) (provider, model string) {
|
|
if models == nil {
|
|
return "", ""
|
|
}
|
|
model, err := models.ModelFor(ctx)
|
|
if err != nil {
|
|
return "", "unavailable: " + err.Error()
|
|
}
|
|
model = strings.TrimSpace(model)
|
|
if model != "" {
|
|
if p, _, ok := strings.Cut(model, "/"); ok {
|
|
provider = p
|
|
}
|
|
}
|
|
if pdn, ok := models.(ProviderDisplayNamer); ok && provider != "" {
|
|
if name := strings.TrimSpace(pdn.ProviderDisplayName(provider)); name != "" {
|
|
return name, model
|
|
}
|
|
}
|
|
return formatProviderName(provider), model
|
|
}
|
|
|
|
// formatRuntimeSection appends the active provider and model as two more
|
|
// report lines. They are not given a section header of their own: /status is
|
|
// four facts, and a header for the last two made a short report read like a
|
|
// document.
|
|
func formatRuntimeSection(b *strings.Builder, provider, model string) {
|
|
if provider == "" && model == "" {
|
|
b.WriteString("Runtime: not configured")
|
|
return
|
|
}
|
|
if provider == "" {
|
|
provider = "not configured"
|
|
}
|
|
if model == "" {
|
|
model = "not configured"
|
|
}
|
|
fmt.Fprintf(b, "Provider: %s%sModel: %s", provider, reportLineBreak, model)
|
|
}
|
|
|
|
// formatStatus renders the queue summary, the health sections the process
|
|
// can report, and the runtime block.
|
|
func formatStatus(ctx context.Context, counts map[string]int, report HealthReport, models ModelManager, now time.Time) string {
|
|
var b strings.Builder
|
|
b.WriteString("📊 Archie status\n\n")
|
|
b.WriteString(formatQueueDepth(counts))
|
|
b.WriteString(reportLineBreak)
|
|
if health := formatHealth(report, now); health != "" {
|
|
b.WriteString(health)
|
|
b.WriteString(reportLineBreak)
|
|
}
|
|
|
|
provider, model := extractRuntimeInfo(ctx, models)
|
|
formatRuntimeSection(&b, provider, model)
|
|
|
|
return b.String()
|
|
}
|
|
|
|
// formatQueueDepth summarizes in-flight work as one line: how many tasks
|
|
// are running, waiting on a human reply, or parked. Queued and terminal
|
|
// states are excluded -- neither is a health concern an operator needs
|
|
// /status to surface.
|
|
func formatQueueDepth(counts map[string]int) string {
|
|
running := counts[taskstate.Running]
|
|
waiting := counts[taskstate.WaitingApproval]
|
|
parked := counts[taskstate.Parked]
|
|
inFlight := running + waiting + parked
|
|
if inFlight == 0 {
|
|
return "Queue: idle"
|
|
}
|
|
var parts []string
|
|
if running > 0 {
|
|
parts = append(parts, fmt.Sprintf("%d running", running))
|
|
}
|
|
if waiting > 0 {
|
|
parts = append(parts, fmt.Sprintf("%d waiting on an operator", waiting))
|
|
}
|
|
if parked > 0 {
|
|
parts = append(parts, fmt.Sprintf("%d parked", parked))
|
|
}
|
|
return fmt.Sprintf("Queue: %d in flight (%s)", inFlight, strings.Join(parts, ", "))
|
|
}
|
|
|
|
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.ModelFor(ctx); active != "" {
|
|
fmt.Fprintf(&b, " Running %s.", active)
|
|
}
|
|
}
|
|
return b.String(), nil
|
|
}
|
|
|
|
func (r *Router) handleProfile(ctx context.Context) (string, error) {
|
|
var b strings.Builder
|
|
identity := r.Identity
|
|
if identity == "" {
|
|
identity = "not configured"
|
|
}
|
|
fmt.Fprintf(&b, "Identity: %s\n", identity)
|
|
if r.Models != nil {
|
|
model, err := r.Models.ModelFor(ctx)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
fmt.Fprintf(&b, "Model: %s\n", model)
|
|
}
|
|
return strings.TrimSpace(b.String()), nil
|
|
}
|
|
|
|
func (r *Router) handleSessions(ctx context.Context, msg messaging.Message) (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)
|
|
}
|
|
active := ""
|
|
if r.sessionTracker != nil {
|
|
active = r.sessionTracker.getActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
|
|
}
|
|
return renderSessionList(sessions, active, time.Now()), nil
|
|
}
|
|
|
|
// renderSessionList formats sessions (already newest-first) as the
|
|
// /sessions reply: a count header, then one numbered, column-aligned row
|
|
// per session carrying an 8-character id prefix, its title, and a
|
|
// recency suffix. The active session (matched by ID) is marked.
|
|
func renderSessionList(sessions []SessionContext, active string, now time.Time) string {
|
|
if len(sessions) == 0 {
|
|
return "No sessions."
|
|
}
|
|
maxTitle := 0
|
|
for _, s := range sessions {
|
|
if l := len([]rune(sessionDisplayTitle(s))); l > maxTitle {
|
|
maxTitle = l
|
|
}
|
|
}
|
|
numW := len(strconv.Itoa(len(sessions)))
|
|
var b strings.Builder
|
|
fmt.Fprintf(&b, "Sessions (%d):\n", len(sessions))
|
|
for i, s := range sessions {
|
|
meta := relativeAge(sessionRecency(s), now)
|
|
if s.SessionID == active {
|
|
meta = "active · " + meta
|
|
}
|
|
fmt.Fprintf(&b, " %*d. %s %-*s · %s\n",
|
|
numW, i+1, shortSessionID(s.SessionID), maxTitle+1, sessionDisplayTitle(s), meta)
|
|
}
|
|
return strings.TrimSpace(b.String())
|
|
}
|
|
|
|
// shortSessionIDLen is how much of a session ID listings show. UUIDs are
|
|
// shown in full; only longer keys are abbreviated.
|
|
const shortSessionIDLen = 36
|
|
|
|
// shortSessionID abbreviates a session ID on a rune boundary.
|
|
func shortSessionID(id string) string {
|
|
if r := []rune(id); len(r) > shortSessionIDLen {
|
|
return string(r[:shortSessionIDLen])
|
|
}
|
|
return id
|
|
}
|
|
|
|
// resolveSessionRef finds the session an exact ID or unique prefix names. It
|
|
// returns (nil, false) for no match and (nil, true) for an ambiguous prefix.
|
|
func resolveSessionRef(sessions []SessionContext, ref string) (match *SessionContext, ambiguous bool) {
|
|
for i, s := range sessions {
|
|
if s.SessionID == ref {
|
|
return &sessions[i], false
|
|
}
|
|
}
|
|
var found *SessionContext
|
|
for i, s := range sessions {
|
|
if !strings.HasPrefix(s.SessionID, ref) {
|
|
continue
|
|
}
|
|
if found != nil {
|
|
return nil, true
|
|
}
|
|
found = &sessions[i]
|
|
}
|
|
return found, false
|
|
}
|
|
|
|
// sessionDisplayTitle is the title a session is shown under, falling
|
|
// back to the standard placeholder when none has been set or generated.
|
|
func sessionDisplayTitle(sc SessionContext) string {
|
|
if sc.Title != "" {
|
|
return sc.Title
|
|
}
|
|
return "(untitled)"
|
|
}
|
|
|
|
// relativeAge renders an instant as a short human age ("5m ago") for
|
|
// session listings. The zero time renders as an empty string.
|
|
func relativeAge(t, now time.Time) string {
|
|
if t.IsZero() {
|
|
return ""
|
|
}
|
|
d := now.Sub(t)
|
|
switch {
|
|
case d < time.Minute:
|
|
return "just now"
|
|
case d < time.Hour:
|
|
return fmt.Sprintf("%dm ago", int(d.Minutes()))
|
|
case d < 24*time.Hour:
|
|
return fmt.Sprintf("%dh ago", int(d.Hours()))
|
|
case d < 7*24*time.Hour:
|
|
return fmt.Sprintf("%dd ago", int(d.Hours()/24))
|
|
default:
|
|
return t.Format("Jan 2")
|
|
}
|
|
}
|
|
|
|
// 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 messaging.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)
|
|
}
|
|
match, ambiguous := resolveSessionRef(sessions, arg)
|
|
switch {
|
|
case ambiguous:
|
|
return fmt.Sprintf("Multiple sessions match %q; be more specific.", arg), nil
|
|
case match == nil:
|
|
return fmt.Sprintf("No session matching %q.", arg), nil
|
|
}
|
|
return r.resumeSession(msg, *match), nil
|
|
}
|
|
|
|
func (r *Router) resumeSession(msg messaging.Message, s SessionContext) string {
|
|
if r.sessionTracker != nil {
|
|
r.sessionTracker.setActive(msg.ConversationID.ChannelID, msg.ConversationID.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
|
|
}
|
|
|
|
func (r *Router) helpText() string {
|
|
return "Send a message to chat with Archie. Available commands:\n" + strings.Join(LocalCommands(), " ")
|
|
}
|