docs/prds/execution-tree-state-machine.md: step_executions (0017) is now the
durable per-step record; the dashboard's run detail (GET /api/tasks/{id}/
attempts) still folded stage_start/stage_finish events into a rail by hand,
and tasks.stage duplicated what StartStep/FinishStep already record properly.
Added the missing read:
- ListSteps(execution_id, attempt) -- attempt 0 lists every attempt of the
execution, oldest first, so the rail renders every attempt from one call.
New storecontract.StepReader (separate from StepRecorder: this is a
dashboard/API/dispatch action per the PRD's wire contract, never
task-scoped-grant callable), postgresdb.ListStepExecutions, staterpc
client/server/values.go plumbing, wired through state_store.go's Deps and
archieui/compose.go's Server.Steps the same optional-capability pattern
every other dashboard read uses.
- internal/webui/api_tasks_attempts.go: stageViewsFromSteps replaces
foldStages/finishStage/stageOutcome. Attempt bounds, event_count and which
attempt numbers exist stay sourced from events (an attempt can carry
events -- agent calls -- with no step), only the stage list itself moves.
The wire JSON contract is unchanged, so no frontend change was needed;
`task ui` confirms ui/dist still matches a fresh build.
- A running step past the task's own current attempt reads interrupted, not
running: RecoverStale (archie-core, still open per #1214) is what corrects
a crashed run's stale "running" row, and until it does this is the honest
read rather than trusting a row that may be stale.
Dropped tasks.stage and every reader, no fallback:
- Migration 0018 drops the column; tasks.sql's INSERT/UPDATE/RETURNING lists
and the sqlc-generated code no longer carry it.
- workflow.Task.Stage is gone; workflow.Run's in-flight "which stage is this"
bookkeeping moves to TaskContext.Stage (execution-time only, never
persisted -- park/finish's event tagging is its only reader).
- pb.Task.stage (wire field 10) is `[deprecated = true]`, not deleted (never
reuse a field number); staterpc's taskProto/taskValue no longer map it.
- taskactions.Task.Stage and the retry event's "previous_stage" data field
are gone: the operator-action package had no reader for the column beyond
echoing it.
- The chat /tasks command's per-task "workflow/stage" display drops to
workflow-only (ChatTaskSummary.Stage removed, workflowStage() deleted):
it was a genuine reader with no replacement in scope for this change.
Read the archie-web-ui skill and the state-store/daemon docs/development
pages first, per instruction. Stayed out of cancel/stop code throughout
(Pi's concurrent CancelExecution work); the only shared files touched
(workflow.go, daemon-adjacent SQL) got the smallest possible diff.
1117 lines
38 KiB
Go
1117 lines
38 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 (
|
|
"cmp"
|
|
"context"
|
|
"fmt"
|
|
"log/slog"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
"unicode"
|
|
|
|
"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 counterpart of LLMResponder. It
|
|
// reports the turn's progress -- text fragments and completed tool calls
|
|
// -- to stream as it is generated, 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. stream is 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, 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 {
|
|
// 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
|
|
}
|
|
|
|
// 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
|
|
}
|
|
|
|
// 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 task to a terminal state through the one
|
|
// cancel path (docs/prds/execution-tree-state-machine.md): the store
|
|
// records the cancellation first, and the runtime delivers it by
|
|
// cancelling the run's in-memory context where this process owns one.
|
|
// Returns an error if the task doesn't exist, isn't owned by identity,
|
|
// or is 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
|
|
// Personas holds the available personality registry for /personality.
|
|
Personas *PersonaRegistry
|
|
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, 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
|
|
// 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
|
|
// Restart requests a scoped chat-adapter reload. It deliberately does not
|
|
// restart the daemon; Telegram's /restart has this same boundary.
|
|
Restart func(context.Context) error
|
|
// 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 when set.
|
|
// Nil disables rate limiting entirely. A message is charged against
|
|
// Inbound.BudgetKey when the channel set one (a webhook route, which
|
|
// has a stable source but no person), else against Message.SenderID.
|
|
// A message with neither is never limited: there is no key to charge
|
|
// it against.
|
|
Limiter *ratelimit.Limiter
|
|
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}
|
|
}
|
|
|
|
// 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 source's inbound budget.
|
|
// A nil Limiter (rate limiting not configured) or no key to charge the
|
|
// message against (see inboundBudgetKey) always allows.
|
|
func (r *Router) checkRateLimit(in Inbound) (blocked bool) {
|
|
key := inboundBudgetKey(in)
|
|
if r.Limiter == nil || key == "" {
|
|
return false
|
|
}
|
|
return !r.Limiter.Allow(r.gatewayName, key)
|
|
}
|
|
|
|
// inboundBudgetKey returns the key this message's inbound budget is charged
|
|
// against: the channel's own transport budget key when it set one, else the
|
|
// per-person SenderID. The two are deliberately distinct -- SenderID means
|
|
// "who sent this", and a channel whose SenderID is not a person (a webhook
|
|
// route path) must not put it there, because several consumers read that
|
|
// field as a user identity (docs/prds/memory-engine-unification.md §3).
|
|
func inboundBudgetKey(in Inbound) string {
|
|
if in.BudgetKey != "" {
|
|
return in.BudgetKey
|
|
}
|
|
return in.Message.SenderID
|
|
}
|
|
|
|
// 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 was blocked by its inbound
|
|
// rate limit. A caller with a human reading the reply (chat channels) can
|
|
// ignore the flag and treat the reply text as usual; a caller with no human
|
|
// there (a webhook) needs it to answer with a proper rejection instead of
|
|
// echoing the rate-limit prose as a successful delivery, or accepting an
|
|
// event that was actually dropped (archie-core-1173).
|
|
func (r *Router) RouteResult(ctx context.Context, in Inbound) (reply string, rateLimited bool, err error) {
|
|
if r.checkRateLimit(in) {
|
|
return rateLimitReply, true, nil
|
|
}
|
|
reply, err = r.route(ctx, in)
|
|
return reply, false, err
|
|
}
|
|
|
|
// route is Route's continuation once the caller has already cleared the
|
|
// rate-limit check (or is deliberately skipping it, as RouteStream's
|
|
// local-command fallthrough does to avoid charging one message twice).
|
|
func (r *Router) route(ctx context.Context, in Inbound) (string, error) {
|
|
text := strings.TrimSpace(in.Message.Text)
|
|
cmd, _ := parseCmd(text, r.gatewayName)
|
|
|
|
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":
|
|
return r.Settings.Execute(ctx, "", rest), true, nil
|
|
case "/start":
|
|
reply, err := r.handleStart()
|
|
return reply, true, err
|
|
case "/whoami":
|
|
reply, err := r.handleWhoami()
|
|
return reply, true, err
|
|
case "/profile":
|
|
reply, err := r.handleProfile()
|
|
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 "/personality":
|
|
reply, err := r.handlePersonality(ctx, msg, rest)
|
|
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
|
|
case "/restart":
|
|
return r.handleRestartAdapter(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)
|
|
}
|
|
|
|
// handleRestartAdapter reloads the chat adapter.
|
|
func (r *Router) handleRestartAdapter(ctx context.Context) string {
|
|
if r.Restart == nil {
|
|
return "Chat adapter restart is not configured."
|
|
}
|
|
if err := r.Restart(ctx); err != nil {
|
|
return fmt.Sprintf("Could not restart the chat adapter: %v", err)
|
|
}
|
|
return "Chat adapter reload requested."
|
|
}
|
|
|
|
// 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
|
|
}
|
|
|
|
// RouteStream is Route for adapters that can render a reply progressively.
|
|
// stream receives each new fragment of an LLM reply as it is generated, plus
|
|
// each completed tool call, in the order the model produced them; 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, in Inbound, stream TurnStream) (string, error) {
|
|
if r.LLMStream == nil || stream == nil {
|
|
return r.Route(ctx, in)
|
|
}
|
|
if r.checkRateLimit(in) {
|
|
return rateLimitReply, nil
|
|
}
|
|
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 := 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)
|
|
}
|
|
report := HealthReport{}
|
|
if r.Health != nil {
|
|
report = r.Health.Health()
|
|
}
|
|
return formatStatus(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 ends a line of a line-oriented report. A chat report is a
|
|
// list of facts, not prose, so every one of its newlines is a real break;
|
|
// plain "\n" is CommonMark's soft wrap, which a Markdown-rendering channel
|
|
// joins into one run-on paragraph (see the Telegram renderer's
|
|
// markdownBlockParser).
|
|
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 with enough identity and state to act on
|
|
// it: id, title, status, workflow/stage, and age since its last
|
|
// transition -- so a task that is running but stuck (old UpdatedAt) reads
|
|
// differently from one making progress (recent UpdatedAt), which a bare
|
|
// status count could never distinguish.
|
|
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.WaitingHuman: {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.WaitingHuman,
|
|
taskstate.Parked,
|
|
taskstate.Queued,
|
|
taskstate.PROpen,
|
|
taskstate.Merged,
|
|
taskstate.Completed,
|
|
taskstate.Rejected,
|
|
taskstate.Declined,
|
|
"declined",
|
|
taskstate.Dead,
|
|
}
|
|
|
|
// sortTasksByPriority orders tasks so the ones an operator would look for
|
|
// first -- running, then waiting on them, then parked -- lead the list,
|
|
// with terminal states (merged, rejected, dead, ...) trailing. It is
|
|
// stable, so within one status group the lister's own recency order
|
|
// survives.
|
|
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(models ModelManager) (provider, model string) {
|
|
if models == nil {
|
|
return "", ""
|
|
}
|
|
model = strings.TrimSpace(models.ActiveModel())
|
|
if pmm, ok := models.(ProviderModelManager); ok {
|
|
provider = strings.TrimSpace(pmm.ActiveProvider())
|
|
}
|
|
if provider == "" && 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 formats daemon health into a clean, mobile-friendly summary:
|
|
// the aggregate queue line, then the health section (broker, worker pool,
|
|
// channels, chat model, last poll) from whatever the process could truthfully
|
|
// report, then the runtime block.
|
|
//
|
|
// It deliberately does not itemize tasks -- that is /tasks' job -- so it
|
|
// reduces the task counts to one aggregate health signal (is work backing
|
|
// up) rather than duplicating /tasks' per-task list.
|
|
func formatStatus(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(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.WaitingHuman]
|
|
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 you", 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() (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() (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, 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 the chat surfaces show. It
|
|
// is also the shorthand /resume and /delete are given back, so every
|
|
// listing must truncate to the same width.
|
|
// UUIDv7 stores its timestamp at the front, so no fixed shorter prefix is
|
|
// guaranteed to distinguish sessions. UUID session references therefore use
|
|
// all 36 characters. The limit only abbreviates longer legacy/non-UUID keys.
|
|
const shortSessionIDLen = 36
|
|
|
|
// shortSessionID renders the abbreviated form of a session ID used
|
|
// wherever a session is listed.
|
|
//
|
|
// Truncation is on a rune boundary: slicing bytes could split a
|
|
// multi-byte channel-ID-derived session key mid-rune and emit invalid
|
|
// UTF-8. UUID keys are ASCII, so this only differs for the exotic cases --
|
|
// where it must stay well-formed.
|
|
func shortSessionID(id string) string {
|
|
if r := []rune(id); len(r) > shortSessionIDLen {
|
|
return string(r[:shortSessionIDLen])
|
|
}
|
|
return id
|
|
}
|
|
|
|
// resolveSessionRef resolves an operator-supplied session reference
|
|
// against a session list, the way /resume and /delete both accept one.
|
|
//
|
|
// An exact ID wins outright -- a full ID names one session unambiguously
|
|
// even when it is also the prefix of a longer one -- otherwise the
|
|
// reference must be a prefix of exactly one session. It returns (nil,
|
|
// false) when nothing matches and (nil, true) when more than one session
|
|
// shares the 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
|
|
}
|