archie-core-alm.4: extend /model and add /personality to Telegram

Extend /model command to support:
- /model [model] (direct switch)
- --provider <name> (provider switch)
- --global (persist scope, with ModelPersist callback)
- --session (explicit session scope, default)
- --refresh (show current active model)

Add /personality command:
- /personality lists available personalities with inline keyboard
- /personality <name> switches directly
- Callback handling for inline keyboard selection

Router changes:
- Add Personas field (wired to PersonaRegistry in main.go)
- Add ModelPersist callback for --global persistence
- Route /personality as a local command
- Extend handleModel to accept full rest text with flag parsing
This commit is contained in:
sam committed 2026-07-29 03:36:33 +10:00
1 parent d92ac87c25
commit 52633833f5
6 files changed
+427 -14

No files matched your search

+1
View File
@@ -501,6 +501,7 @@ func run() int {
router := gateway.NewRouter(st, llmResponder, "telegram")
router.LLMStream = llmStream
router.Models = chatModels
router.Personas = personas
configureTaskCommands(router, chatTasks, chatController, defaultChatIdentity)
startGateways = append(startGateways, func() {
go func() {
+3 -2
View File
@@ -23,14 +23,15 @@ var gatewayCommandSpecs = []commandSpec{
{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"},
{Command: "model", Description: "Show the model selector or switch directly", Usage: "/model [provider/model]"},
{Command: "model", Description: "Show the model selector or switch directly", Usage: "/model [model] [--provider name] [--global|--session] [--refresh]"},
{Command: "personality", Description: "Set the conversation personality", Usage: "/personality [name]"},
{Command: "spawn", Description: "Create a tracked task", Usage: "/spawn [identity=name] [repo=owner/name] [workflow=name] <title>"},
{Command: "cancel", Description: "Cancel a queued or waiting task", Usage: "/cancel [identity=name] <task-id>"},
{Command: "restart", Description: "Reload Archie and its configuration", Usage: "/restart"},
{Command: "help", Description: "See what Archie can do", Usage: "/help"},
}
var telegramOnlyCommands = []string{"provider", "restart", "help", "version", "update"}
var telegramOnlyCommands = []string{"provider", "restart", "help", "version", "update", "personality"}
var gatewayCommands = func() []models.BotCommand {
commands := make([]models.BotCommand, 0, len(gatewayCommandSpecs))
+145
View File
@@ -23,6 +23,151 @@ func isModelSelectorRequest(text string) bool {
return command == "/model"
}
// isModelCommand checks whether text is a /model command, with or without
// arguments. When the user provides a model ref or flags, the inline
// selector is skipped and the command is handled directly.
func isModelCommand(text string) bool {
fields := strings.Fields(text)
if len(fields) == 0 {
return false
}
command, _, _ := strings.Cut(fields[0], "@")
return command == "/model"
}
// parseModelRest extracts model, provider, and scope flags from the text
// after the /model command token. It handles --provider=<name>,
// --provider <name>, --global, --session, and --refresh.
func parseModelRest(rest string) (model, provider string, global, session, refresh bool) {
fields := strings.Fields(rest)
var modelParts []string
for i := 0; i < len(fields); i++ {
f := fields[i]
switch {
case f == "--global":
global = true
case f == "--session":
session = true
case f == "--refresh":
refresh = true
case strings.HasPrefix(f, "--provider"):
if after, ok := strings.CutPrefix(f, "--provider="); ok && after != "" {
provider = after
} else if after == "--provider" {
// Look ahead for the provider value.
if i+1 < len(fields) && !strings.HasPrefix(fields[i+1], "--") {
i++
provider = strings.TrimPrefix(fields[i], "--provider=")
if provider == fields[i] {
provider = fields[i]
}
}
} else {
provider = after
}
default:
modelParts = append(modelParts, f)
}
}
model = strings.Join(modelParts, " ")
return
}
// handleModelCommand handles /model with arguments, performing direct
// model/provider switching, scope selection, and model refresh.
func (g *Gateway) handleModelCommand(
ctx context.Context,
b *bot.Bot,
msg *models.Message,
router *gateway.Router,
) {
if router.Models == nil {
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Model switching is not configured.")
return
}
text := strings.TrimSpace(msg.Text)
fields := strings.Fields(text)
// fields[0] is "/model" (possibly with @bot mention); rest is everything
// after it.
rest := ""
if len(fields) > 1 {
// Reconstruct rest by joining everything after the command token.
// We can't use strings.Join because fields splits by whitespace.
cmdToken := fields[0]
if _, after, ok := strings.Cut(text, cmdToken); ok {
rest = strings.TrimSpace(after)
}
}
model, provider, global, _, refresh := parseModelRest(rest)
// --refresh: no-op for now (catalog is loaded at startup). Show current.
if refresh {
active := router.Models.ActiveModel()
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
fmt.Sprintf("Active model: %s.", modelDisplayName(active, "")))
return
}
// --provider without a specific model: switch provider only.
if provider != "" && model == "" {
manager, ok := router.Models.(gateway.ProviderModelManager)
if !ok {
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Provider switching is not configured.")
return
}
if err := manager.SetActiveProvider(ctx, provider); err != nil {
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
fmt.Sprintf("Cannot switch provider: %v", err))
return
}
active := router.Models.ActiveModel()
p, _, _ := strings.Cut(active, "/")
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
fmt.Sprintf("Provider changed to %s.", providerDisplayName(p)))
return
}
// --provider with a model: set provider, then model.
if provider != "" && model != "" {
if manager, ok := router.Models.(gateway.ProviderModelManager); ok {
_ = manager.SetActiveProvider(ctx, provider)
}
}
// Switch model.
if model != "" {
if err := router.Models.SetActiveModel(ctx, model); err != nil {
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
fmt.Sprintf("Cannot switch: %v", err))
return
}
active := router.Models.ActiveModel()
p, _, _ := strings.Cut(active, "/")
result := fmt.Sprintf("Model changed to %s.", modelDisplayName(active, p))
if global {
if router.ModelPersist != nil {
if err := router.ModelPersist(ctx, active); err != nil {
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
fmt.Sprintf("Model switched to %s but persistence failed: %v",
modelDisplayName(active, p), err))
return
}
result += " (persisted globally)"
} else {
result += " (global persistence is not configured)"
}
}
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, result)
return
}
// Neither model nor provider: delegate to inline selector.
g.sendModelSelector(ctx, b, msg, router)
}
func (g *Gateway) sendModelSelector(
ctx context.Context,
b *bot.Bot,
+143
View File
@@ -0,0 +1,143 @@
package telegram
import (
"context"
"fmt"
"strings"
"github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
"github.com/samcharles93/archie-core/internal/gateway"
)
const personalityCallbackPrefix = "personality:"
func isPersonalityRequest(text string) bool {
fields := strings.Fields(text)
if len(fields) == 0 {
return false
}
command, _, _ := strings.Cut(fields[0], "@")
return command == "/personality"
}
func (g *Gateway) handlePersonalityCommand(
ctx context.Context,
b *bot.Bot,
msg *models.Message,
router *gateway.Router,
) {
if router.Personas == nil {
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
"Personality switching is not configured.")
return
}
text := strings.TrimSpace(msg.Text)
fields := strings.Fields(text)
if len(fields) == 1 {
// No args: show inline keyboard.
g.sendPersonalitySelector(ctx, b, msg, router)
return
}
// Direct switch by name.
name := strings.ToLower(fields[1])
if !router.Personas.SetActive("", name) {
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
fmt.Sprintf("Unknown personality %q. Use /personality to browse.", name))
return
}
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
fmt.Sprintf("Personality set to %q.", name))
}
func (g *Gateway) sendPersonalitySelector(
ctx context.Context,
b *bot.Bot,
msg *models.Message,
router *gateway.Router,
) {
names := router.Personas.List()
if len(names) == 0 {
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
"No personalities configured.")
return
}
params := &bot.SendMessageParams{
ChatID: msg.Chat.ID,
Text: "Choose a personality:",
ReplyMarkup: g.personalityKeyboard(router.Personas),
}
if msg.MessageThreadID != 0 {
params.MessageThreadID = msg.MessageThreadID
}
if _, err := b.SendMessage(ctx, params); err != nil {
g.log.Error("send personality selector failed", "error", err)
}
}
func (g *Gateway) personalityKeyboard(registry *gateway.PersonaRegistry) *models.InlineKeyboardMarkup {
names := registry.List()
rows := make([][]models.InlineKeyboardButton, 0, len(names))
for _, name := range names {
rows = append(rows, []models.InlineKeyboardButton{{
Text: name,
CallbackData: personalityCallbackPrefix + name,
}})
}
return &models.InlineKeyboardMarkup{InlineKeyboard: rows}
}
func (g *Gateway) handlePersonalityCallback(
ctx context.Context,
b *bot.Bot,
update *models.Update,
router *gateway.Router,
) {
query := update.CallbackQuery
if query == nil {
return
}
if !g.isSenderAllowed(query.From.ID) {
g.log.Warn("personality callback from unauthorized sender",
"user_id", query.From.ID)
g.answerModelCallback(ctx, b, query.ID,
"You are not authorised to use this bot.", true)
return
}
if router.Personas == nil {
g.answerModelCallback(ctx, b, query.ID,
"Personality switching is not configured.", true)
return
}
name := strings.TrimPrefix(query.Data, personalityCallbackPrefix)
if !router.Personas.SetActive("", name) {
g.answerModelCallback(ctx, b, query.ID,
fmt.Sprintf("Unknown personality %q.", name), true)
return
}
g.answerModelCallback(ctx, b, query.ID,
fmt.Sprintf("Personality set to %q.", name), false)
// Update the selector message to acknowledge the selection.
params := &bot.EditMessageTextParams{
Text: fmt.Sprintf("Personality set to %q.", name),
}
switch {
case query.Message.Message != nil:
params.ChatID = query.Message.Message.Chat.ID
params.MessageID = query.Message.Message.ID
case query.InlineMessageID != "":
params.InlineMessageID = query.InlineMessageID
default:
return
}
if _, err := b.EditMessageText(ctx, params); err != nil {
g.log.Warn("update personality selector failed", "error", err)
}
}
+10 -2
View File
@@ -334,6 +334,8 @@ func (g *Gateway) defaultHandler(router *gateway.Router) bot.HandlerFunc {
g.handleProviderCallback(ctx, b, update, router)
case strings.HasPrefix(update.CallbackQuery.Data, modelCallbackPrefix):
g.handleModelCallback(ctx, b, update, router)
case strings.HasPrefix(update.CallbackQuery.Data, personalityCallbackPrefix):
g.handlePersonalityCallback(ctx, b, update, router)
case strings.HasPrefix(update.CallbackQuery.Data, updateCallbackPrefix):
g.handleUpdateCallback(ctx, b, update)
}
@@ -348,12 +350,18 @@ func (g *Gateway) defaultHandler(router *gateway.Router) bot.HandlerFunc {
g.sendModelSelector(ctx, b, msg, router)
return
}
if isModelCommand(msg.Text) {
g.handleModelCommand(ctx, b, msg, router)
return
}
if isProviderSelectorRequest(msg.Text) {
g.sendProviderSelector(ctx, b, msg, router)
return
}
// An LLM turn takes many seconds. Stream it into a draft so the
if isPersonalityRequest(msg.Text) {
g.handlePersonalityCommand(ctx, b, msg, router)
return
}
// reply appears as it is written; the typing indicator covers the
// gap before the first token and any non-streaming path.
stopTyping := g.startTyping(ctx, b, msg.Chat.ID, msg.MessageThreadID)
+125 -10
View File
@@ -140,6 +140,13 @@ type Router struct {
// that can render partial output (see RouteStream) show the reply as
// it generates; when nil, everything falls back to LLM.
LLMStream LLMStreamResponder
// Personas is the persona registry for /personality. When nil, the
// command returns "not configured".
Personas *PersonaRegistry
// ModelPersist persists the active model globally when --global is
// passed to /model. When nil, --global is a no-op acknowledged to
// the user.
ModelPersist func(ctx context.Context, modelRef string) error
// Identity is the archie identity this router belongs to (empty in
// single-identity deployments). Propagated into SpawnRequest and
// used to scope /approve and /cancel authorization -- a task
@@ -160,13 +167,17 @@ func NewRouter(store StatusReader, llm LLMResponder, gatewayName string) *Router
// else goes to the LLM responder.
func (r *Router) Route(ctx context.Context, msg Message) (string, error) {
text := strings.TrimSpace(msg.Text)
cmd, arg := parseCmd(text, r.gatewayName)
cmd, _ := parseCmd(text, r.gatewayName)
switch cmd {
case "/status":
return r.handleStatus(ctx)
case "/model":
return r.handleModel(ctx, arg)
rest := restAfter(text, cmd, r.gatewayName)
return r.handleModel(ctx, rest)
case "/personality":
rest := restAfter(text, cmd, r.gatewayName)
return r.handlePersonality(ctx, rest)
case "/spawn":
// Title is everything after "/spawn" -- keep the multi-word text.
rest := restAfter(text, cmd, r.gatewayName)
@@ -210,7 +221,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", "/approve", "/cancel", "/personality"}
// LocalCommands returns the command names Route answers from local state.
// Gateways use this to verify that their published command surfaces match
@@ -244,20 +255,73 @@ func parseCmd(text, gatewayName string) (cmd, arg string) {
return raw, ""
}
func (r *Router) handleModel(ctx context.Context, arg string) (string, error) {
// modelArgs holds the parsed flags from a /model command rest text.
type modelArgs struct {
Model string
Provider string
Global bool
Session bool
Refresh bool
}
// parseModelArgs extracts flags from rest-text after /model. Flags are
// stripped; whatever remains (after the command token) is the model ref.
func parseModelArgs(rest string) modelArgs {
fields := strings.Fields(rest)
ma := modelArgs{}
var modelParts []string
for _, f := range fields {
switch {
case f == "--global":
ma.Global = true
case f == "--session":
ma.Session = true
case f == "--refresh":
ma.Refresh = true
case strings.HasPrefix(f, "--provider"):
// Accept --provider=name and --provider name forms.
if after, ok := strings.CutPrefix(f, "--provider="); ok {
ma.Provider = after
} else if after, ok := strings.CutPrefix(f, "--provider"); ok && after == "" {
// next field is the provider value; parseModelArgs can't
// look ahead, so the caller (Telegram) will re-parse with
// full field context. The router's plain-text handler
// treats --provider as a flag without value.
ma.Provider = ""
} else {
ma.Provider = after
}
default:
modelParts = append(modelParts, f)
}
}
ma.Model = strings.Join(modelParts, " ")
return ma
}
func (r *Router) handleModel(ctx context.Context, rest string) (string, error) {
if r.Models == nil {
return "Model switching is not configured.", nil
}
if arg == "" {
ma := parseModelArgs(rest)
// --refresh: return the current active model (no catalog refresh in
// the plain-text path; Telegram handles this separately).
if ma.Refresh {
return fmt.Sprintf("Active model: %s.", r.Models.ActiveModel()), nil
}
// No model ref and no flags: list available models.
if ma.Model == "" && ma.Provider == "" {
models := r.Models.Models()
if manager, ok := r.Models.(ProviderModelManager); ok {
models = manager.ModelsForProvider(manager.ActiveProvider())
}
if len(models) == 0 {
return "No models configured.\nUsage: /model <provider/model>", nil
return "No models configured.\nUsage: /model [model] [--provider name] [--global|--session] [--refresh]", nil
}
var b strings.Builder
b.WriteString("Usage: /model <provider/model>\nAvailable models:\n")
b.WriteString("Usage: /model [model] [--provider name] [--global|--session] [--refresh]\nAvailable models:\n")
active := r.Models.ActiveModel()
for _, m := range models {
if m == active {
@@ -268,10 +332,61 @@ func (r *Router) handleModel(ctx context.Context, arg string) (string, error) {
}
return b.String(), nil
}
if err := r.Models.SetActiveModel(ctx, arg); err != nil {
return fmt.Sprintf("Cannot switch: %v", err), nil
// --provider: switch provider first.
if ma.Provider != "" {
manager, ok := r.Models.(ProviderModelManager)
if !ok {
return "Provider switching is not configured.", nil
}
if err := manager.SetActiveProvider(ctx, ma.Provider); err != nil {
return fmt.Sprintf("Cannot switch provider: %v", err), nil
}
}
return fmt.Sprintf("Active model set to %s.", arg), nil
// Model switch.
if ma.Model != "" {
if err := r.Models.SetActiveModel(ctx, ma.Model); err != nil {
return fmt.Sprintf("Cannot switch: %v", err), nil
}
}
active := r.Models.ActiveModel()
msg := fmt.Sprintf("Active model set to %s.", active)
// Persist if --global and a model was selected.
if ma.Global && ma.Model != "" {
if r.ModelPersist != nil {
if err := r.ModelPersist(ctx, active); err != nil {
return fmt.Sprintf("Model switched to %s but persistence failed: %v", active, err), nil
}
} else {
msg += " (global persistence is not configured)"
}
}
return msg, nil
}
func (r *Router) handlePersonality(ctx context.Context, rest string) (string, error) {
if r.Personas == nil {
return "Personality switching is not configured.", nil
}
if rest == "" {
names := r.Personas.List()
if len(names) == 0 {
return "No personalities configured.", nil
}
var b strings.Builder
b.WriteString("Usage: /personality <name>\nAvailable personalities:\n")
for _, name := range names {
b.WriteString(" " + name + "\n")
}
return b.String(), nil
}
if !r.Personas.SetActive("", rest) {
return fmt.Sprintf("Unknown personality %q. Use /personality to list available personalities.", rest), nil
}
return fmt.Sprintf("Active personality set to %q.", rest), nil
}
// restAfter returns the text after the command token, stripping the