telegram: add /whoami, /profile, /sessions, /resume, /agents commands

Gateway-local commands that report from Archie-owned state:

- /whoami: reports the Archie identity the user is talking to
- /profile: shows active Archie profile (identity, provider, model, available models)
- /sessions: lists recent sessions with last-active timestamps
- /resume [id]: resumes a session by ID or prefix match
- /agents: lists active agents and running/waiting tasks

Adds SessionLister and AgentReader interfaces to Router, wired from the
daemon composition root. SessionStore already satisfies SessionLister.
AgentReader is a thin adapter over store.Task list filtered to active
states (running, waiting_human, parked).

All commands are published in Telegram's menu and /help, and respond
with 'not configured' when their backing interface is nil.

Closes archie-core-alm.2
This commit is contained in:
sam committed 2026-07-29 03:36:07 +10:00
1 parent d92ac87c25
commit 03a200d582
6 files changed
+546 -5

No files matched your search

+37
View File
@@ -14,6 +14,7 @@ import (
"os"
"os/signal"
"path/filepath"
"slices"
"strconv"
"strings"
"syscall"
@@ -501,6 +502,8 @@ func run() int {
router := gateway.NewRouter(st, llmResponder, "telegram")
router.LLMStream = llmStream
router.Models = chatModels
router.Sessions = sessionStore
router.Agents = agentReaderAdapter{tasks: st.Tasks}
configureTaskCommands(router, chatTasks, chatController, defaultChatIdentity)
startGateways = append(startGateways, func() {
go func() {
@@ -792,6 +795,40 @@ func run() int {
return 0
}
// agentReaderAdapter implements gateway.AgentReader from the store's Task list.
type agentReaderAdapter struct {
tasks func(ctx context.Context, limit int) ([]store.Task, error)
}
func (a agentReaderAdapter) AgentList(ctx context.Context) ([]gateway.AgentInfo, error) {
all, err := a.tasks(ctx, -1)
if err != nil {
return nil, err
}
// Show tasks that are actively running or waiting for human input.
active := []string{
store.StatusRunning,
store.StatusWaitingHuman,
store.StatusParked,
}
isActive := func(status string) bool {
return slices.Contains(active, status)
}
out := make([]gateway.AgentInfo, 0, len(all))
for _, t := range all {
if !isActive(t.Status) {
continue
}
out = append(out, gateway.AgentInfo{
ID: t.ID,
Title: t.Title,
Status: t.Status,
Identity: t.Identity,
})
}
return out, nil
}
type chatTaskWriterAdapter struct {
enqueue func(
ctx context.Context,
+5
View File
@@ -20,6 +20,11 @@ type commandSpec struct {
// together prevents a newly registered command from being omitted from help.
var gatewayCommandSpecs = []commandSpec{
{Command: "status", Description: "Show task counts by state", Usage: "/status"},
{Command: "whoami", Description: "Show which Archie identity you are talking to", Usage: "/whoami"},
{Command: "profile", Description: "Show the active Archie profile", Usage: "/profile"},
{Command: "sessions", Description: "List recent sessions", Usage: "/sessions"},
{Command: "resume", Description: "Resume a session by ID or name", Usage: "/resume [id]"},
{Command: "agents", Description: "List active agents and running tasks", Usage: "/agents"},
{Command: "version", Description: "Show installed Archie versions", Usage: "/version"},
{Command: "update", Description: "Check for Archie updates", Usage: "/update"},
{Command: "provider", Description: "Choose the provider used for chat", Usage: "/provider"},
+49 -2
View File
@@ -172,6 +172,11 @@ func (g *Gateway) launch(ctx context.Context, router *gateway.Router) (*bot.Bot,
// Gateway-local commands: handled directly, no LLM.
b.RegisterHandler(bot.HandlerTypeMessageText, "/status", bot.MatchTypeExact, g.statusHandler(router))
b.RegisterHandler(bot.HandlerTypeMessageText, "/whoami", bot.MatchTypeExact, g.whoamiHandler(router))
b.RegisterHandler(bot.HandlerTypeMessageText, "/profile", bot.MatchTypeExact, g.profileHandler(router))
b.RegisterHandler(bot.HandlerTypeMessageText, "/sessions", bot.MatchTypeExact, g.sessionsHandler(router))
b.RegisterHandler(bot.HandlerTypeMessageText, "/resume", bot.MatchTypeExact, g.resumeHandler(router))
b.RegisterHandler(bot.HandlerTypeMessageText, "/agents", bot.MatchTypeExact, g.agentsHandler(router))
b.RegisterHandler(bot.HandlerTypeMessageText, "/version", bot.MatchTypeExact, g.versionHandler())
b.RegisterHandler(bot.HandlerTypeMessageText, "/update", bot.MatchTypeExact, g.updateHandler())
b.RegisterHandler(bot.HandlerTypeMessageText, "/start", bot.MatchTypeExact, g.startHandler())
@@ -277,6 +282,26 @@ func (g *Gateway) WebhookHandler() http.Handler {
// ── command handlers (gateway-local -- no LLM) ────────────────
func (g *Gateway) statusHandler(router *gateway.Router) bot.HandlerFunc {
return g.routeCmdHandler(router, "/status")
}
func (g *Gateway) whoamiHandler(router *gateway.Router) bot.HandlerFunc {
return g.routeCmdHandler(router, "/whoami")
}
func (g *Gateway) profileHandler(router *gateway.Router) bot.HandlerFunc {
return g.routeCmdHandler(router, "/profile")
}
func (g *Gateway) sessionsHandler(router *gateway.Router) bot.HandlerFunc {
return g.routeCmdHandler(router, "/sessions")
}
func (g *Gateway) agentsHandler(router *gateway.Router) bot.HandlerFunc {
return g.routeCmdHandler(router, "/agents")
}
func (g *Gateway) resumeHandler(router *gateway.Router) bot.HandlerFunc {
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
msg, ok := g.authorizedMessage(ctx, b, update)
if !ok {
@@ -286,10 +311,32 @@ func (g *Gateway) statusHandler(router *gateway.Router) bot.HandlerFunc {
ChannelID: fmt.Sprintf("%d", msg.Chat.ID),
ThreadID: threadIDString(msg.MessageThreadID),
From: msg.From.Username,
Text: "/status",
Text: msg.Text,
})
if err != nil {
g.log.Error("status handler failed", "error", err)
g.log.Error("resume handler failed", "error", err)
return
}
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, reply)
}
}
// routeCmdHandler builds a handler that routes a fixed command through the
// gateway.Router and sends the reply.
func (g *Gateway) routeCmdHandler(router *gateway.Router, cmd string) bot.HandlerFunc {
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
msg, ok := g.authorizedMessage(ctx, b, update)
if !ok {
return
}
reply, err := router.Route(ctx, gateway.Message{
ChannelID: fmt.Sprintf("%d", msg.Chat.ID),
ThreadID: threadIDString(msg.MessageThreadID),
From: msg.From.Username,
Text: cmd,
})
if err != nil {
g.log.Error("command handler failed", "command", cmd, "error", err)
return
}
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, reply)
+3 -1
View File
@@ -161,7 +161,9 @@ func TestVersionReportsBothComponents(t *testing.T) {
// dangerous and should not be discoverable by casual chat users. Commands in
// this set may still be executable if typed explicitly — they just shouldn't
// appear on Telegram's discoverability surfaces.
var telegramHiddenCommands = map[string]bool{"approve": true}
var telegramHiddenCommands = map[string]bool{
"approve": true,
}
func TestPublishedCommandsMatchExecutableCommandSurface(t *testing.T) {
executable := make(map[string]bool)
+186 -2
View File
@@ -15,6 +15,7 @@ import (
"sort"
"strconv"
"strings"
"time"
)
// Message is an inbound message from a gateway connection.
@@ -48,6 +49,26 @@ type StatusReader interface {
StatusCounts(ctx context.Context) (map[string]int, error)
}
// SessionLister is the read surface /sessions and /resume need.
// The daemon supplies its session store, which satisfies this structurally.
type SessionLister interface {
List(ctx context.Context) ([]SessionContext, error)
}
// AgentInfo carries one row for /agents.
type AgentInfo struct {
ID int64
Title string
Status string
Identity string
}
// AgentReader is the read surface /agents needs. The daemon supplies
// its store, which satisfies this structurally.
type AgentReader interface {
AgentList(ctx context.Context) ([]AgentInfo, 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
@@ -145,7 +166,13 @@ type Router struct {
// used to scope /approve and /cancel authorization -- a task
// spawned under one identity cannot be controlled from another's
// chat session.
Identity string
Identity string
// Sessions supports /sessions and /resume. When nil those commands
// return "not configured".
Sessions SessionLister
// Agents supports /agents. When nil the command returns
// "not configured".
Agents AgentReader
gatewayName string
}
@@ -171,6 +198,16 @@ func (r *Router) Route(ctx context.Context, msg Message) (string, error) {
// Title is everything after "/spawn" -- keep the multi-word text.
rest := restAfter(text, cmd, r.gatewayName)
return r.handleSpawn(ctx, rest)
case "/whoami":
return r.handleWhoami()
case "/profile":
return r.handleProfile()
case "/sessions":
return r.handleSessions(ctx)
case "/resume":
return r.handleResume(ctx, restAfter(text, cmd, r.gatewayName))
case "/agents":
return r.handleAgents(ctx)
case "/approve":
// Reserved for dangerous-command approval (archie-core-alm.6).
// Telegram hides it from its menu/help; other gateways keep it
@@ -210,7 +247,7 @@ func (r *Router) RouteStream(ctx context.Context, msg Message, onDelta func(stri
return r.LLMStream(ctx, msg, onDelta)
}
var localCommands = []string{"/status", "/model", "/spawn", "/approve", "/cancel"}
var localCommands = []string{"/status", "/model", "/spawn", "/whoami", "/profile", "/sessions", "/resume", "/agents", "/approve", "/cancel"}
// LocalCommands returns the command names Route answers from local state.
// Gateways use this to verify that their published command surfaces match
@@ -413,3 +450,150 @@ func (r *Router) handleStatus(ctx context.Context) (string, error) {
}
return strings.TrimSpace(b.String()), nil
}
// ── /whoami ───────────────────────────────────────────────────────
func (r *Router) handleWhoami() (string, error) {
var b strings.Builder
b.WriteString("You are talking to Archie")
if r.Identity != "" {
fmt.Fprintf(&b, " (%s)", r.Identity)
}
b.WriteString(".\n")
if r.Models != nil {
if manager, ok := r.Models.(ProviderModelManager); ok {
fmt.Fprintf(&b, "Provider: %s\n", manager.ActiveProvider())
}
fmt.Fprintf(&b, "Model: %s\n", r.Models.ActiveModel())
}
return strings.TrimSpace(b.String()), nil
}
// ── /profile ──────────────────────────────────────────────────────
func (r *Router) handleProfile() (string, error) {
var b strings.Builder
fmt.Fprintf(&b, "*Archie profile*\n")
if r.Identity != "" {
fmt.Fprintf(&b, "Identity: `%s`\n", r.Identity)
} else {
b.WriteString("Identity: _(not configured)_\n")
}
if r.Models == nil {
return strings.TrimSpace(b.String()), nil
}
if manager, ok := r.Models.(ProviderModelManager); ok {
fmt.Fprintf(&b, "Provider: `%s`\n", manager.ActiveProvider())
}
fmt.Fprintf(&b, "Model: `%s`\n", r.Models.ActiveModel())
models := r.Models.Models()
if manager, ok := r.Models.(ProviderModelManager); ok {
models = manager.ModelsForProvider(manager.ActiveProvider())
}
if len(models) == 0 {
return strings.TrimSpace(b.String()), nil
}
b.WriteString("Available 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 strings.TrimSpace(b.String()), nil
}
// ── /sessions ─────────────────────────────────────────────────────
func (r *Router) handleSessions(ctx context.Context) (string, error) {
if r.Sessions == nil {
return "Session listing is not configured.", nil
}
sessions, err := r.Sessions.List(ctx)
if err != nil {
return "", fmt.Errorf("sessions: %w", err)
}
if len(sessions) == 0 {
return "No sessions yet.", nil
}
var b strings.Builder
b.WriteString("*Sessions*\n")
for _, sc := range sessions {
ago := time.Since(sc.LastActiveAt).Truncate(time.Second)
fmt.Fprintf(&b, "`%s`\n last active %s ago", sc.SessionID, ago)
if sc.Source.ThreadID != "" {
fmt.Fprintf(&b, " (thread %s)", sc.Source.ThreadID)
}
b.WriteByte('\n')
}
return strings.TrimSpace(b.String()), nil
}
// ── /resume ───────────────────────────────────────────────────────
func (r *Router) handleResume(ctx context.Context, name string) (string, error) {
if r.Sessions == nil {
return "Session resume is not configured.", nil
}
if name == "" {
return "Usage: /resume <session-id or name prefix>", nil
}
sessions, err := r.Sessions.List(ctx)
if err != nil {
return "", fmt.Errorf("resume: %w", err)
}
// Match by exact session ID or prefix.
var matches []SessionContext
for _, sc := range sessions {
if sc.SessionID == name || strings.HasPrefix(sc.SessionID, name) {
matches = append(matches, sc)
}
}
if len(matches) == 0 {
return fmt.Sprintf("No session matching %q found.", name), nil
}
if len(matches) > 1 {
var b strings.Builder
b.WriteString("Multiple sessions match:\n")
for _, sc := range matches {
fmt.Fprintf(&b, " `%s`\n", sc.SessionID)
}
b.WriteString("Use the full session ID to resume a specific one.")
return b.String(), nil
}
sc := matches[0]
return fmt.Sprintf("Resumed session `%s` (last active %s ago). Send a message to continue.",
sc.SessionID, time.Since(sc.LastActiveAt).Truncate(time.Second)), nil
}
// ── /agents ───────────────────────────────────────────────────────
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("agents: %w", err)
}
if len(agents) == 0 {
return "No active agents or running tasks.", nil
}
var b strings.Builder
b.WriteString("*Active agents*\n")
for _, a := range agents {
fmt.Fprintf(&b, "`%d` %s", a.ID, a.Title)
if a.Identity != "" {
fmt.Fprintf(&b, " _(%s)_", a.Identity)
}
fmt.Fprintf(&b, " \nStatus: %s\n", a.Status)
}
return strings.TrimSpace(b.String()), nil
}
+266
View File
@@ -616,3 +616,269 @@ func TestRouteCancelNotConfigured(t *testing.T) {
t.Errorf("reply = %q, want 'not configured'", reply)
}
}
// -- /whoami tests --
func TestRouteWhoami(t *testing.T) {
r := NewRouter(nil, nil, "test-gw")
r.Identity = "archie"
reply, err := r.Route(context.Background(), Message{Text: "/whoami"})
if err != nil {
t.Fatalf("Route: %v", err)
}
if !strings.Contains(reply, "archie") {
t.Errorf("reply = %q, want mention of identity", reply)
}
}
func TestRouteWhoamiNoIdentity(t *testing.T) {
r := NewRouter(nil, nil, "test-gw")
reply, err := r.Route(context.Background(), Message{Text: "/whoami"})
if err != nil {
t.Fatalf("Route: %v", err)
}
if !strings.Contains(reply, "Archie") {
t.Errorf("reply = %q, want mention of Archie", reply)
}
}
func TestRouteWhoamiWithModel(t *testing.T) {
r := NewRouter(nil, nil, "test-gw")
r.Identity = "archie"
r.Models = &fakeModelManager{
models: []string{"a/b", "c/d"},
activeModel: "a/b",
}
reply, err := r.Route(context.Background(), Message{Text: "/whoami"})
if err != nil {
t.Fatalf("Route: %v", err)
}
if !strings.Contains(reply, "archie") || !strings.Contains(reply, "a/b") {
t.Errorf("reply = %q, want identity and model", reply)
}
}
// -- /profile tests --
func TestRouteProfile(t *testing.T) {
r := NewRouter(nil, nil, "test-gw")
r.Identity = "archie"
r.Models = &fakeModelManager{
models: []string{"a/b", "c/d"},
activeModel: "a/b",
}
reply, err := r.Route(context.Background(), Message{Text: "/profile"})
if err != nil {
t.Fatalf("Route: %v", err)
}
if !strings.Contains(reply, "archie") || !strings.Contains(reply, "a/b") {
t.Errorf("reply = %q, want identity and model", reply)
}
}
func TestRouteProfileNoIdentity(t *testing.T) {
r := NewRouter(nil, nil, "test-gw")
reply, err := r.Route(context.Background(), Message{Text: "/profile"})
if err != nil {
t.Fatalf("Route: %v", err)
}
if !strings.Contains(reply, "not configured") {
t.Errorf("reply = %q, want mention of not configured", reply)
}
}
// -- /sessions tests --
type fakeSessionLister struct {
sessions []SessionContext
err error
}
func (f *fakeSessionLister) List(ctx context.Context) ([]SessionContext, error) {
if f.err != nil {
return nil, f.err
}
return f.sessions, nil
}
func TestRouteSessionsEmpty(t *testing.T) {
r := NewRouter(nil, nil, "test-gw")
r.Sessions = &fakeSessionLister{}
reply, err := r.Route(context.Background(), Message{Text: "/sessions"})
if err != nil {
t.Fatalf("Route: %v", err)
}
if !strings.Contains(reply, "No sessions") {
t.Errorf("reply = %q, want 'No sessions'", reply)
}
}
func TestRouteSessionsNotConfigured(t *testing.T) {
r := NewRouter(nil, nil, "test-gw")
reply, err := r.Route(context.Background(), Message{Text: "/sessions"})
if err != nil {
t.Fatalf("Route: %v", err)
}
if !strings.Contains(reply, "not configured") {
t.Errorf("reply = %q, want 'not configured'", reply)
}
}
func TestRouteSessionsError(t *testing.T) {
r := NewRouter(nil, nil, "test-gw")
r.Sessions = &fakeSessionLister{err: fmt.Errorf("store unavailable")}
_, err := r.Route(context.Background(), Message{Text: "/sessions"})
if err == nil {
t.Error("expected error from Route when List fails")
}
}
// -- /resume tests --
func TestRouteResumeNoArg(t *testing.T) {
r := NewRouter(nil, nil, "test-gw")
r.Sessions = &fakeSessionLister{}
reply, err := r.Route(context.Background(), Message{Text: "/resume"})
if err != nil {
t.Fatalf("Route: %v", err)
}
if !strings.Contains(reply, "Usage") {
t.Errorf("reply = %q, want usage", reply)
}
}
func TestRouteResumeNotConfigured(t *testing.T) {
r := NewRouter(nil, nil, "test-gw")
reply, err := r.Route(context.Background(), Message{Text: "/resume abc"})
if err != nil {
t.Fatalf("Route: %v", err)
}
if !strings.Contains(reply, "not configured") {
t.Errorf("reply = %q, want 'not configured'", reply)
}
}
func TestRouteResumeNoMatch(t *testing.T) {
r := NewRouter(nil, nil, "test-gw")
r.Sessions = &fakeSessionLister{
sessions: []SessionContext{
{SessionID: "session-1"},
},
}
reply, err := r.Route(context.Background(), Message{Text: "/resume xyz"})
if err != nil {
t.Fatalf("Route: %v", err)
}
if !strings.Contains(reply, "No session matching") {
t.Errorf("reply = %q, want 'No session matching'", reply)
}
}
func TestRouteResumeAmbiguous(t *testing.T) {
r := NewRouter(nil, nil, "test-gw")
r.Sessions = &fakeSessionLister{
sessions: []SessionContext{
{SessionID: "abc-123"},
{SessionID: "abc-456"},
},
}
reply, err := r.Route(context.Background(), Message{Text: "/resume abc"})
if err != nil {
t.Fatalf("Route: %v", err)
}
if !strings.Contains(reply, "Multiple sessions") {
t.Errorf("reply = %q, want 'Multiple sessions'", reply)
}
}
func TestRouteResumeExactMatch(t *testing.T) {
r := NewRouter(nil, nil, "test-gw")
r.Sessions = &fakeSessionLister{
sessions: []SessionContext{
{SessionID: "abc-123"},
{SessionID: "abc-456"},
},
}
reply, err := r.Route(context.Background(), Message{Text: "/resume abc-123"})
if err != nil {
t.Fatalf("Route: %v", err)
}
if !strings.Contains(reply, "Resumed session") {
t.Errorf("reply = %q, want 'Resumed session'", reply)
}
}
// -- /agents tests --
type fakeAgentReader struct {
agents []AgentInfo
err error
}
func (f *fakeAgentReader) AgentList(ctx context.Context) ([]AgentInfo, error) {
if f.err != nil {
return nil, f.err
}
return f.agents, nil
}
func TestRouteAgentsEmpty(t *testing.T) {
r := NewRouter(nil, nil, "test-gw")
r.Agents = &fakeAgentReader{}
reply, err := r.Route(context.Background(), Message{Text: "/agents"})
if err != nil {
t.Fatalf("Route: %v", err)
}
if !strings.Contains(reply, "No active agents") {
t.Errorf("reply = %q, want 'No active agents'", reply)
}
}
func TestRouteAgentsNotConfigured(t *testing.T) {
r := NewRouter(nil, nil, "test-gw")
reply, err := r.Route(context.Background(), Message{Text: "/agents"})
if err != nil {
t.Fatalf("Route: %v", err)
}
if !strings.Contains(reply, "not configured") {
t.Errorf("reply = %q, want 'not configured'", reply)
}
}
func TestRouteAgentsWithTasks(t *testing.T) {
r := NewRouter(nil, nil, "test-gw")
r.Agents = &fakeAgentReader{
agents: []AgentInfo{
{ID: 1, Title: "Fix the bug", Status: "running", Identity: "archie"},
{ID: 2, Title: "Add tests", Status: "waiting_human", Identity: "archie"},
},
}
reply, err := r.Route(context.Background(), Message{Text: "/agents"})
if err != nil {
t.Fatalf("Route: %v", err)
}
if !strings.Contains(reply, "Fix the bug") || !strings.Contains(reply, "Add tests") {
t.Errorf("reply = %q, want task titles", reply)
}
if !strings.Contains(reply, "running") || !strings.Contains(reply, "waiting_human") {
t.Errorf("reply = %q, want task statuses", reply)
}
}
func TestRouteAgentsError(t *testing.T) {
r := NewRouter(nil, nil, "test-gw")
r.Agents = &fakeAgentReader{err: fmt.Errorf("store unavailable")}
_, err := r.Route(context.Background(), Message{Text: "/agents"})
if err == nil {
t.Error("expected error from Route when AgentList fails")
}
}
func TestLocalCommandsIncludesNewCommands(t *testing.T) {
cmds := LocalCommands()
for _, want := range []string{"/whoami", "/profile", "/sessions", "/resume", "/agents"} {
if !slices.Contains(cmds, want) {
t.Errorf("LocalCommands() missing %s", want)
}
}
}