feat: establish Archie identity and use stable callback tokens

This commit is contained in:
sam committed 2026-07-27 11:03:40 +10:00
1 parent ec8534dfe2
commit 329776de9c
12 files changed
+246 -59

No files matched your search

+1
View File
@@ -149,3 +149,4 @@
{"id":"int-992125ccd2337e4407963a7e70651acb","kind":"field_change","created_at":"2026-07-26T19:26:24.561475744Z","actor":"Sam Catlow","issue_id":"archie-core-abg.16.35","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Shipped in e600cfa. Temporarily reopened after seeing a Telegram transcript where /restart fell through to the LLM, then Sam clarified that transcript predates deployment; no regression evidence."}}
{"id":"int-6d6e840984054dec54aee42bb99042a5","kind":"field_change","created_at":"2026-07-26T19:29:37.633205149Z","actor":"Sam Catlow","issue_id":"archie-core-abg.17.43","extra":{"field":"status","new_value":"open","old_value":"in_progress"}}
{"id":"int-e370a7bbd16c6f091d318dc5520481ef","kind":"field_change","created_at":"2026-07-26T19:29:37.633258328Z","actor":"Sam Catlow","issue_id":"archie-core-abg.17.43","extra":{"field":"assignee","new_value":"","old_value":"Sam Catlow"}}
{"id":"int-98886b5c0eed086effa6684ec75bbb48","kind":"field_change","created_at":"2026-07-26T20:33:10.385698708Z","actor":"Sam Catlow","issue_id":"archie-core-3ro","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Shipped locally: Telegram calls the assistant Archie rather than Gateway; restart copy is Archie-facing; new sessions receive and preserve an Archie baseline identity; model selector shows provider in the header and provider-free model names; successful selections acknowledge the chosen model; model/provider callbacks use stable tokens so stale keyboards cannot select a different option. task check and lint pass; fresh review clean."}}
+1
View File
@@ -53,6 +53,7 @@
{"_type":"issue","id":"archie-core-abg.18","title":"[EPIC] Memory: pluggable provider architecture with file-backed persistence","description":"Pluggable memory system to match Hermes parity:\\n\\n1. **MemoryProvider interface**: Abstract interface with methods for initialize(), get_tool_schemas(), prefetch(), sync_turn(), and optional lifecycle hooks (on_session_end, on_session_switch, on_pre_compress, on_memory_write).\\n\\n2. **Built-in file-backed memory**: MEMORY.md and USER.md stored per-session/profile. LLM-callable memory tool with add/replace/remove actions. Frozen snapshot at session start (preserves prefix cache), immediate disk write on updates. Section-sign delimited entries with substring matching.\\n\\n3. **MemoryManager**: Orchestrates built-in + at most one external provider. Background serialized write executor. Prefetch with timeout (8s). Streaming context scrubber that strips injected memory spans from model output.\\n\\nRef: docs/prds/hermes-gap-analysis.md section 4","acceptance_criteria":"An external memory provider (e.g. Honcho, Mem0) can be plugged in via config. The built-in memory tool persists across sessions. Conversation context is recalled on session resume.","status":"open","priority":0,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:22Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:02:22Z","dependencies":[{"issue_id":"archie-core-abg.18","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:02:22Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.16","title":"[EPIC] Gateway: rich message model, adapter lifecycle, session management","description":"Foundational gateway infrastructure to match Hermes parity. Three interdependent pieces:\\n\\n1. **Message model**: Replace the 3-field Message struct with a rich MessageEvent (MessageType enum: text/photo/video/audio/voice/document/sticker/command, media_urls, reply_to context, metadata dict, source). This is the wire type every adapter produces.\\n\\n2. **Adapter lifecycle**: Replace the 3-method Gateway interface with a BasePlatformAdapter interface: connect()/disconnect()/send() as required methods, plus optional overrides for typing indicators, edit/delete, image/voice/video/document send, interactive UX (clarify buttons, approval dialogs). Capability flags (supports_code_blocks, splits_long_messages, supports_async_delivery).\\n\\n3. **Session management**: SessionSource struct (platform, chat_id, chat_type, user_id, thread_id, guild_id, profile), AsyncSessionStore for persistent session storage, SessionContext for system prompt injection.\\n\\nAll three blocks together enable adding new platforms as plugins without touching core gateway code.\\n\\nRef: docs/prds/hermes-gap-analysis.md sections 1-2","acceptance_criteria":"New adapters can be added by implementing a Go interface with connect/disconnect/send + optional media methods. Messages carry full metadata through the pipeline. Sessions persist across gateway restarts.","status":"open","priority":0,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:21Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:02:21Z","dependencies":[{"issue_id":"archie-core-abg.16","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:02:21Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-jfg","title":"Spawned archie-agent containers not on daemon's docker network — can't reach NATS","description":"Root cause of 'agent still failing on the server': archied's container.Pool.Acquire creates archie-agent containers via the Docker SDK with no NetworkMode set, so Docker attaches them to the default bridge network. archied and nats run on the compose-created 'archie-core_default' network instead, so the spawned container's hostname resolution for 'nats' (from NATS_URL=nats://nats:4222) fails and archie-agent can't connect. Confirmed on carina host logs: archied logs show repeating 'taskrun request failed err=\"nats: no responders available for request\"' for every task, containers created and destroyed within ~1.5s (consistent with archie-agent's NATS client failing fast). Fixed by detecting the daemon's own container's network in NewPool (selfNetwork, via ContainerInspect on os.Hostname()) and setting HostConfig.NetworkMode on spawned containers to match.","status":"closed","priority":0,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-24T03:10:26Z","created_by":"Sam Catlow","updated_at":"2026-07-25T13:04:34Z","closed_at":"2026-07-25T13:04:34Z","close_reason":"Fix already implemented and verified: selfNetwork() in internal/container/pool.go detects the daemon's own container network via ContainerInspect(os.Hostname()) and Acquire() sets HostConfig.NetworkMode to match, so spawned archie-agent containers join the same compose network as nats. Build and internal/container tests pass.","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-3ro","title":"Make Archie the user-facing identity","description":"Remove internal gateway terminology from Telegram replies and establish an Archie default system prompt so chat does not drift into generic assistant identity.","acceptance_criteria":"Telegram help and restart copy call the assistant Archie; default chat persona identifies Archie and forbids unverified claims or vendor impersonation; tests and task check pass.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T20:24:07Z","created_by":"Sam Catlow","updated_at":"2026-07-26T20:33:10Z","started_at":"2026-07-26T20:24:08Z","closed_at":"2026-07-26T20:33:10Z","close_reason":"Shipped locally: Telegram calls the assistant Archie rather than Gateway; restart copy is Archie-facing; new sessions receive and preserve an Archie baseline identity; model selector shows provider in the header and provider-free model names; successful selections acknowledge the chosen model; model/provider callbacks use stable tokens so stale keyboards cannot select a different option. task check and lint pass; fresh review clean.","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-ubl","title":"Durable scheduled agent tasks backed by Archie's task queue","description":"Add first-class one-shot, interval, and cron scheduling for Telegram agents. The scheduler decides when work is due but never executes an LLM or shell inline: it atomically enqueues a normal durable Archie task under the originating identity, and existing workers execute it with the usual tool, sandbox, lifecycle, and observability policies. Expose typed agent tools and Telegram management surfaces for create/list/status/pause/resume/delete/run-now, with delivery back to the originating chat.","acceptance_criteria":"Schedules support one-shot timestamps, fixed intervals, and cron expressions with explicit timezone. Definitions and execution history survive daemon restarts. Due firing uses an atomic lease/idempotency key so concurrent daemons and crash recovery do not duplicate a scheduled occurrence. Scheduler callbacks only enqueue normal tasks; they never run agents or shell commands inline. Each schedule records owner identity, origin chat/thread, prompt/task payload, enabled capability policy, overlap policy, next run, last result, and delivery state. Authorized users can create/list/status/pause/resume/delete/run-now from chat and equivalent typed agent tools. Missed-run, long-running overlap, clock/DST, cancellation, queue failure, execution failure, and delivery failure semantics are explicit and tested with a fake clock. Cron-spawned tasks cannot recursively create schedules unless explicitly authorized. Library selection is documented and does not replace Archie's durable queue semantics.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T20:05:57Z","created_by":"Sam Catlow","updated_at":"2026-07-26T20:05:57Z","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-4sr","title":"Gateway: unknown slash commands must not reach the LLM","description":"Unknown slash commands currently fall through to free-text LLM chat, causing fabricated command behavior such as /memories claims and false statements about files or model identity. Make slash command recognition deterministic and answer unknown commands locally with guidance to /help, while preserving free-text chat and supported Telegram bootstrap commands.","acceptance_criteria":"Any unrecognized leading slash command is answered locally and never invokes or streams from the LLM. The reply identifies the command as unknown and points to /help. Recognized commands and ordinary free text retain existing behavior. Telegram /start has an explicit deterministic behavior. Tests cover unknown commands with arguments and @gateway mentions, streaming routing, /start, and LLM non-invocation.","status":"in_progress","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T19:55:37Z","created_by":"Sam Catlow","updated_at":"2026-07-26T19:55:41Z","started_at":"2026-07-26T19:55:41Z","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-1d4","title":"Telegram: provider selector filters model choices","description":"Add an authorized native /provider inline selector. The selected provider scopes /model so only configured model references belonging to that provider are shown; e.g. openrouter/openai/gpt-5.6 must not appear under provider openai. Selecting a provider establishes a valid active model for that provider when necessary, and /status reports active provider and model.","acceptance_criteria":"/provider displays configured providers as an inline keyboard and marks the active provider. Authorized callbacks switch provider; unauthorized, malformed, stale, and duplicate callbacks fail safely. /model shows only models whose first reference segment matches the selected provider and uses unambiguous labels. Switching provider leaves the chat responder on a valid model from that provider. /status includes active provider and full model reference. Menu/help/executable parity and concurrent access are tested.","status":"in_progress","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T19:55:36Z","created_by":"Sam Catlow","updated_at":"2026-07-26T19:55:40Z","started_at":"2026-07-26T19:55:40Z","dependency_count":0,"dependent_count":0,"comment_count":0}
+2 -2
View File
@@ -26,7 +26,7 @@ var gatewayCommandSpecs = []commandSpec{
{Command: "spawn", Description: "Create a tracked task", Usage: "/spawn [identity=name] [repo=owner/name] [workflow=name] <title>"},
{Command: "approve", Description: "Approve and requeue a waiting task", Usage: "/approve [identity=name] <task-id>"},
{Command: "cancel", Description: "Cancel a queued or waiting task", Usage: "/cancel [identity=name] <task-id>"},
{Command: "restart", Description: "Restart the gateway and reload its config", Usage: "/restart"},
{Command: "restart", Description: "Reload Archie and its configuration", Usage: "/restart"},
{Command: "help", Description: "Show this guide", Usage: "/help"},
}
@@ -45,7 +45,7 @@ var gatewayCommands = func() []models.BotCommand {
func gatewayHelpText() string {
var help strings.Builder
help.WriteString("🤖 **Archie Gateway**\n\n")
help.WriteString("🤖 **Archie**\n\n")
help.WriteString("Send a message to chat with Archie. Replies stream into Telegram as they are generated.\n\n")
help.WriteString("**Commands**\n")
for _, spec := range gatewayCommandSpecs {
+52 -19
View File
@@ -2,8 +2,8 @@ package telegram
import (
"context"
"crypto/sha256"
"fmt"
"strconv"
"strings"
"github.com/go-telegram/bot"
@@ -42,7 +42,7 @@ func (g *Gateway) sendModelSelector(
params := &bot.SendMessageParams{
ChatID: msg.Chat.ID,
Text: modelSelectorText(router.Models.ActiveModel()),
ReplyMarkup: modelSelectorKeyboard(router.Models),
ReplyMarkup: g.modelSelectorKeyboard(router.Models),
}
if msg.MessageThreadID != 0 {
params.MessageThreadID = msg.MessageThreadID
@@ -54,12 +54,17 @@ func (g *Gateway) sendModelSelector(
func modelSelectorText(active string) string {
if active == "" {
return "Choose a model:"
return "Select a model:"
}
return "Choose a model:\nActive: " + active
provider, _, ok := strings.Cut(active, "/")
if !ok {
return "Select a model:\nActive: " + active
}
return "Select a model:\nCurrent Provider: " + providerDisplayName(provider) +
"\nActive: " + modelDisplayName(active, provider)
}
func modelSelectorKeyboard(manager gateway.ModelManager) *models.InlineKeyboardMarkup {
func (g *Gateway) modelSelectorKeyboard(manager gateway.ModelManager) *models.InlineKeyboardMarkup {
active := manager.ActiveModel()
available := selectableModels(manager)
activeProvider := ""
@@ -67,22 +72,51 @@ func modelSelectorKeyboard(manager gateway.ModelManager) *models.InlineKeyboardM
activeProvider = providerManager.ActiveProvider()
}
rows := make([][]models.InlineKeyboardButton, 0, len(available))
for index, model := range available {
label := model
if activeProvider != "" {
label = strings.TrimPrefix(model, activeProvider+"/")
}
for _, model := range available {
label := modelDisplayName(model, activeProvider)
if model == active {
label = "✓ " + model
label = "✓ " + label
}
rows = append(rows, []models.InlineKeyboardButton{{
Text: label,
CallbackData: modelCallbackPrefix + strconv.Itoa(index),
CallbackData: g.modelCallbackToken(model),
}})
}
return &models.InlineKeyboardMarkup{InlineKeyboard: rows}
}
// modelCallbackToken records a stable model identity for an inline button.
// A positional index is unsafe: provider changes can reorder the selectable
// list after Telegram has rendered the keyboard.
func (g *Gateway) modelCallbackToken(model string) string {
sum := sha256.Sum256([]byte(model))
// 192 bits keeps the callback well below Telegram's 64-byte limit while
// making a collision infeasible for a configured model catalog.
token := fmt.Sprintf("%s%x", modelCallbackPrefix, sum[:24])
g.modelMu.Lock()
g.modelCallbacks[token] = model
g.modelMu.Unlock()
return token
}
func (g *Gateway) modelForCallback(token string) (string, bool) {
g.modelMu.RLock()
defer g.modelMu.RUnlock()
model, ok := g.modelCallbacks[token]
return model, ok
}
// modelDisplayName removes routing/provider prefixes from a model reference.
// The selected provider is already shown in the selector heading; repeating it
// in every button makes provider-aware selection needlessly noisy.
func modelDisplayName(ref, provider string) string {
name := strings.TrimPrefix(ref, provider+"/")
if slash := strings.LastIndexByte(name, '/'); slash >= 0 {
name = name[slash+1:]
}
return name
}
func selectableModels(manager gateway.ModelManager) []string {
if providerManager, ok := manager.(gateway.ProviderModelManager); ok {
return providerManager.ModelsForProvider(providerManager.ActiveProvider())
@@ -110,20 +144,19 @@ func (g *Gateway) handleModelCallback(
return
}
indexText := strings.TrimPrefix(query.Data, modelCallbackPrefix)
index, err := strconv.Atoi(indexText)
available := selectableModels(router.Models)
if err != nil || index < 0 || index >= len(available) {
selected, ok := g.modelForCallback(query.Data)
if !ok {
g.answerModelCallback(ctx, b, query.ID, "That model selection is no longer valid.", true)
return
}
selected := available[index]
if err := router.Models.SetActiveModel(ctx, selected); err != nil {
g.answerModelCallback(ctx, b, query.ID, fmt.Sprintf("Cannot switch: %v", err), true)
return
}
g.answerModelCallback(ctx, b, query.ID, "Active model: "+selected, false)
provider, _, _ := strings.Cut(selected, "/")
g.answerModelCallback(ctx, b, query.ID,
"The model has been changed to: "+modelDisplayName(selected, provider), false)
g.updateModelSelector(ctx, b, query, router.Models)
}
@@ -151,7 +184,7 @@ func (g *Gateway) updateModelSelector(
) {
params := &bot.EditMessageTextParams{
Text: modelSelectorText(manager.ActiveModel()),
ReplyMarkup: modelSelectorKeyboard(manager),
ReplyMarkup: g.modelSelectorKeyboard(manager),
}
switch {
case query.Message.Message != nil:
+73 -5
View File
@@ -155,6 +155,9 @@ func TestModelCommandShowsInlineSelector(t *testing.T) {
if !found {
t.Fatalf("/model did not send an inline keyboard; requests: %#v", *requests)
}
if got := modelSelectorText("deepseek/deepseek-v4-pro"); got != "Select a model:\nCurrent Provider: DeepSeek\nActive: deepseek-v4-pro" {
t.Errorf("model selector text = %q", got)
}
if got := len(markup.InlineKeyboard); got != len(manager.models) {
t.Fatalf("keyboard rows = %d, want %d", got, len(manager.models))
}
@@ -163,8 +166,8 @@ func TestModelCommandShowsInlineSelector(t *testing.T) {
t.Fatalf("keyboard row %d has %d buttons, want 1", index, len(row))
}
button := row[0]
if button.CallbackData != fmt.Sprintf("model:%d", index) {
t.Errorf("button %d callback = %q", index, button.CallbackData)
if !strings.HasPrefix(button.CallbackData, modelCallbackPrefix) || button.CallbackData == fmt.Sprintf("model:%d", index) {
t.Errorf("button %d callback = %q, want a stable model token", index, button.CallbackData)
}
_, modelLabel, _ := strings.Cut(manager.models[index], "/")
if !strings.Contains(button.Text, modelLabel) {
@@ -174,6 +177,11 @@ func TestModelCommandShowsInlineSelector(t *testing.T) {
if !strings.HasPrefix(markup.InlineKeyboard[1][0].Text, "✓ ") {
t.Errorf("active model button is not marked: %q", markup.InlineKeyboard[1][0].Text)
}
for _, row := range markup.InlineKeyboard {
if strings.Contains(row[0].Text, "provider/") {
t.Errorf("model button must not repeat the provider: %q", row[0].Text)
}
}
}
func TestProviderCommandFiltersSubsequentModelSelector(t *testing.T) {
@@ -207,11 +215,12 @@ func TestProviderCommandFiltersSubsequentModelSelector(t *testing.T) {
}
*requests = nil
providerCallback := providerMarkup.InlineKeyboard[1][0].CallbackData
g.defaultHandler(router)(context.Background(), b, &models.Update{
CallbackQuery: &models.CallbackQuery{
ID: "provider-callback",
From: models.User{ID: allowedUserID},
Data: "provider:1",
Data: providerCallback,
Message: models.MaybeInaccessibleMessage{
Type: models.MaybeInaccessibleMessageTypeMessage,
Message: &models.Message{ID: 9, Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate}},
@@ -248,6 +257,32 @@ func TestProviderCommandFiltersSubsequentModelSelector(t *testing.T) {
}
}
func TestProviderCallbackHonoursTheProviderRenderedInTheSelector(t *testing.T) {
const allowedUserID = int64(42)
manager := &modelManagerStub{
models: []string{"openai/gpt-5.6", "openrouter/openai/gpt-5.6"},
active: "openai/gpt-5.6",
}
router := gateway.NewRouter(nil, nil, "telegram")
router.Models = manager
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
b, _ := newTelegramTestBot(t)
markup := g.providerSelectorKeyboard(manager)
renderedCallback := markup.InlineKeyboard[0][0].CallbackData
manager.models = []string{"deepseek/deepseek-v4-pro", "openai/gpt-5.6", "openrouter/openai/gpt-5.6"}
g.handleProviderCallback(context.Background(), b, &models.Update{CallbackQuery: &models.CallbackQuery{
ID: "callback-id",
From: models.User{ID: allowedUserID},
Data: renderedCallback,
}}, router)
if got := manager.ActiveProvider(); got != "openai" {
t.Errorf("stale selector chose %q, want the originally rendered provider", got)
}
}
func TestModelCallbackSwitchesAndUpdatesSelector(t *testing.T) {
const allowedUserID = int64(42)
manager := &modelManagerStub{
@@ -263,7 +298,7 @@ func TestModelCallbackSwitchesAndUpdatesSelector(t *testing.T) {
CallbackQuery: &models.CallbackQuery{
ID: "callback-id",
From: models.User{ID: allowedUserID},
Data: "model:1",
Data: g.modelCallbackToken("provider/beta"),
Message: models.MaybeInaccessibleMessage{
Type: models.MaybeInaccessibleMessageTypeMessage,
Message: &models.Message{ID: 9, Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate}},
@@ -276,7 +311,12 @@ func TestModelCallbackSwitchesAndUpdatesSelector(t *testing.T) {
}
var answered, edited bool
for _, request := range *requests {
answered = answered || request.method == "answerCallbackQuery"
if request.method == "answerCallbackQuery" {
answered = true
if got := request.form["text"]; got != "The model has been changed to: beta" {
t.Errorf("selection acknowledgement = %q", got)
}
}
edited = edited || request.method == "editMessageText"
}
if !answered || !edited {
@@ -284,6 +324,34 @@ func TestModelCallbackSwitchesAndUpdatesSelector(t *testing.T) {
}
}
func TestModelCallbackHonoursTheModelRenderedInTheSelector(t *testing.T) {
const allowedUserID = int64(42)
manager := &modelManagerStub{
models: []string{"openai/gpt-5.6", "openrouter/openai/gpt-5.6"},
active: "openai/gpt-5.6",
}
router := gateway.NewRouter(nil, nil, "telegram")
router.Models = manager
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
b, _ := newTelegramTestBot(t)
markup := g.modelSelectorKeyboard(manager)
renderedCallback := markup.InlineKeyboard[0][0].CallbackData
if err := manager.SetActiveProvider(context.Background(), "openrouter"); err != nil {
t.Fatal(err)
}
g.handleModelCallback(context.Background(), b, &models.Update{CallbackQuery: &models.CallbackQuery{
ID: "callback-id",
From: models.User{ID: allowedUserID},
Data: renderedCallback,
}}, router)
if got := manager.ActiveModel(); got != "openai/gpt-5.6" {
t.Errorf("stale selector chose %q, want the originally rendered model", got)
}
}
func TestModelCallbackRejectsUnauthorizedAndMalformedSelections(t *testing.T) {
const allowedUserID = int64(42)
tests := []struct {
+24 -11
View File
@@ -2,8 +2,8 @@ package telegram
import (
"context"
"crypto/sha256"
"fmt"
"strconv"
"strings"
"github.com/go-telegram/bot"
@@ -37,7 +37,7 @@ func (g *Gateway) sendProviderSelector(
params := &bot.SendMessageParams{
ChatID: msg.Chat.ID,
Text: providerSelectorText(manager.ActiveProvider()),
ReplyMarkup: providerSelectorKeyboard(manager),
ReplyMarkup: g.providerSelectorKeyboard(manager),
}
if msg.MessageThreadID != 0 {
params.MessageThreadID = msg.MessageThreadID
@@ -54,23 +54,39 @@ func providerSelectorText(active string) string {
return "Choose a provider:\nActive: " + providerDisplayName(active)
}
func providerSelectorKeyboard(manager gateway.ProviderModelManager) *models.InlineKeyboardMarkup {
func (g *Gateway) providerSelectorKeyboard(manager gateway.ProviderModelManager) *models.InlineKeyboardMarkup {
active := manager.ActiveProvider()
providers := manager.Providers()
rows := make([][]models.InlineKeyboardButton, 0, len(providers))
for index, provider := range providers {
for _, provider := range providers {
label := providerDisplayName(provider)
if provider == active {
label = "✓ " + label
}
rows = append(rows, []models.InlineKeyboardButton{{
Text: label,
CallbackData: providerCallbackPrefix + strconv.Itoa(index),
CallbackData: g.providerCallbackToken(provider),
}})
}
return &models.InlineKeyboardMarkup{InlineKeyboard: rows}
}
func (g *Gateway) providerCallbackToken(provider string) string {
sum := sha256.Sum256([]byte(provider))
token := fmt.Sprintf("%s%x", providerCallbackPrefix, sum[:24])
g.providerMu.Lock()
g.providerCallbacks[token] = provider
g.providerMu.Unlock()
return token
}
func (g *Gateway) providerForCallback(token string) (string, bool) {
g.providerMu.RLock()
defer g.providerMu.RUnlock()
provider, ok := g.providerCallbacks[token]
return provider, ok
}
func providerDisplayName(provider string) string {
switch strings.ToLower(provider) {
case "openai":
@@ -110,14 +126,11 @@ func (g *Gateway) handleProviderCallback(
g.answerModelCallback(ctx, b, query.ID, "Provider switching is not configured.", true)
return
}
indexText := strings.TrimPrefix(query.Data, providerCallbackPrefix)
index, err := strconv.Atoi(indexText)
providers := manager.Providers()
if err != nil || index < 0 || index >= len(providers) {
selected, ok := g.providerForCallback(query.Data)
if !ok {
g.answerModelCallback(ctx, b, query.ID, "That provider selection is no longer valid.", true)
return
}
selected := providers[index]
if err := manager.SetActiveProvider(ctx, selected); err != nil {
g.answerModelCallback(ctx, b, query.ID, fmt.Sprintf("Cannot switch: %v", err), true)
return
@@ -134,7 +147,7 @@ func (g *Gateway) updateProviderSelector(
) {
params := &bot.EditMessageTextParams{
Text: providerSelectorText(manager.ActiveProvider()),
ReplyMarkup: providerSelectorKeyboard(manager),
ReplyMarkup: g.providerSelectorKeyboard(manager),
}
switch {
case query.Message.Message != nil:
+1 -1
View File
@@ -30,7 +30,7 @@ func (g *Gateway) restartHandler() bot.HandlerFunc {
// Acknowledge on the current instance: it is about to be torn
// down, and the relaunched one confirms completion.
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "🔄 Restarting gateway…")
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "🔄 Reloading Archie…")
// Hand off to the supervisor rather than tearing down from inside
// this handler, which runs on the very bot being stopped. Never
@@ -1,10 +1,35 @@
package telegram
import (
"context"
"encoding/json"
"log/slog"
"testing"
"github.com/go-telegram/bot/models"
)
func TestRestartAcknowledgesArchie(t *testing.T) {
g := New("1:test", "", "", []int64{42}, slog.Default())
b, requests := newTelegramTestBot(t)
g.restartHandler()(context.Background(), b, &models.Update{Message: &models.Message{
From: &models.User{ID: 42},
Chat: models.Chat{ID: 7, Type: models.ChatTypePrivate},
}})
if len(*requests) != 1 {
t.Fatalf("restart acknowledgement = %#v", *requests)
}
var rich models.InputRichMessage
if err := json.Unmarshal([]byte((*requests)[0].form["rich_message"]), &rich); err != nil {
t.Fatal(err)
}
if rich.Markdown != "🔄 Reloading Archie…" {
t.Fatalf("restart acknowledgement = %#v, want Archie wording", *requests)
}
}
// The restart channel is buffered so a handler can hand off without
// blocking: the handler runs on the very bot the supervisor is about to
// stop, so blocking there would deadlock the restart it just asked for.
+16 -9
View File
@@ -12,6 +12,7 @@ import (
"runtime/debug"
"slices"
"strings"
"sync"
"time"
"github.com/go-telegram/bot"
@@ -43,8 +44,12 @@ type Gateway struct {
// restartCh carries /restart requests from a bot handler to the
// supervisor loop in Start. Buffered so a handler never blocks.
restartCh chan restartRequest
pendingRestart *restartRequest
restartCh chan restartRequest
pendingRestart *restartRequest
modelMu sync.RWMutex
modelCallbacks map[string]string
providerMu sync.RWMutex
providerCallbacks map[string]string
log *slog.Logger
bot *bot.Bot
@@ -64,12 +69,14 @@ type ReleaseAnnouncer interface {
// processing.
func New(token, webhookURL, webhookSecret string, allowedUserIDs []int64, log *slog.Logger) *Gateway {
return &Gateway{
Token: token,
WebhookURL: webhookURL,
WebhookSecret: webhookSecret,
AllowedUserIDs: allowedUserIDs,
restartCh: make(chan restartRequest, 1),
log: log.With("component", "gateway-telegram"),
Token: token,
WebhookURL: webhookURL,
WebhookSecret: webhookSecret,
AllowedUserIDs: allowedUserIDs,
restartCh: make(chan restartRequest, 1),
modelCallbacks: make(map[string]string),
providerCallbacks: make(map[string]string),
log: log.With("component", "gateway-telegram"),
}
}
@@ -96,7 +103,7 @@ func (g *Gateway) Start(ctx context.Context, router *gateway.Router) error {
}
// Confirm to whoever asked, now that the new instance can send.
if req := g.pendingRestart; req != nil {
g.sendMessage(runCtx, b, req.chatID, req.threadID, "✅ Gateway restarted.")
g.sendMessage(runCtx, b, req.chatID, req.threadID, "✅ Archie reloaded.")
g.pendingRestart = nil
}
@@ -82,11 +82,25 @@ func TestHelpDescribesPublishedCommandsAndChat(t *testing.T) {
if strings.Contains(sentText, "not yet wired") {
t.Errorf("help text still claims working LLM chat is not wired:\n%s", sentText)
}
if !strings.Contains(sentText, "🤖 **Archie**") {
t.Errorf("help should identify Archie directly:\n%s", sentText)
}
if strings.Contains(sentText, "Archie Gateway") {
t.Errorf("help must not expose internal gateway terminology:\n%s", sentText)
}
if !strings.Contains(strings.ToLower(sentText), "chat") {
t.Errorf("help text does not describe free-text chat:\n%s", sentText)
}
}
func TestTelegramUserFacingCommandCopyDoesNotCallArchieAGateway(t *testing.T) {
for _, spec := range gatewayCommandSpecs {
if strings.Contains(strings.ToLower(spec.Description), "gateway") {
t.Errorf("/%s exposes internal gateway terminology: %q", spec.Command, spec.Description)
}
}
}
func TestStartHasDeterministicGatewayResponse(t *testing.T) {
const allowedUserID = int64(42)
g := New("1:test", "", "", []int64{allowedUserID}, slog.Default())
+26 -8
View File
@@ -11,9 +11,10 @@ type Persona struct {
// PersonaRegistry holds available personas and tracks the active one
// per session. Safe for concurrent use.
type PersonaRegistry struct {
mu sync.RWMutex
personas map[string]Persona
active map[string]string // sessionKey -> persona name
mu sync.RWMutex
personas map[string]Persona
active map[string]string // sessionKey -> persona name
defaultName string
}
// NewPersonaRegistry creates a registry pre-populated with the given
@@ -23,16 +24,26 @@ func NewPersonaRegistry(personas []Persona) *PersonaRegistry {
personas: make(map[string]Persona, len(personas)),
active: make(map[string]string),
}
for _, p := range personas {
for index, p := range personas {
r.personas[p.Name] = p
if index == 0 {
r.defaultName = p.Name
}
}
return r
}
// DefaultPersonas returns the standard set matching Hermes's personality
// library.
// DefaultPersonas returns Archie as the baseline identity followed by
// optional communication styles.
func DefaultPersonas() []Persona {
return []Persona{
{
Name: "archie",
Prompt: "You are Archie, Sam's capable coding and project assistant. " +
"Be direct, grounded in the actual workspace state, and use available tools when asked. " +
"Do not claim tools, files, memories, actions, or results you have not verified. " +
"Do not impersonate another assistant, provider, or vendor.",
},
{Name: "helpful", Prompt: "You are a helpful, friendly AI assistant."},
{Name: "concise", Prompt: "You are a concise assistant. Keep responses brief and to the point."},
{Name: "technical", Prompt: "You are a technical expert. Provide detailed, accurate technical information."},
@@ -69,13 +80,20 @@ func (r *PersonaRegistry) GetActive(sessionKey string) string {
r.mu.RLock()
defer r.mu.RUnlock()
name, ok := r.active[sessionKey]
if !ok {
name = r.defaultName
}
p, ok := r.personas[name]
if !ok {
return ""
}
if p, ok := r.personas[name]; ok {
if name == r.defaultName {
return p.Prompt
}
return ""
if baseline, ok := r.personas[r.defaultName]; ok && baseline.Prompt != "" {
return baseline.Prompt + "\n\n" + p.Prompt
}
return p.Prompt
}
// Get returns a persona by name, or false when not found.
+11 -4
View File
@@ -1,13 +1,17 @@
package gateway
import (
"strings"
"testing"
)
func TestPersonaRegistryDefault(t *testing.T) {
r := NewPersonaRegistry(DefaultPersonas())
if len(r.List()) != 5 {
t.Errorf("expected 5 default personas, got %d", len(r.List()))
if len(r.List()) != 6 {
t.Errorf("expected 6 default personas, got %d", len(r.List()))
}
if prompt := r.GetActive("new-session"); !strings.Contains(prompt, "You are Archie") {
t.Errorf("new sessions must receive Archie's identity prompt, got %q", prompt)
}
}
@@ -25,9 +29,12 @@ func TestPersonaRegistrySetAndGetActive(t *testing.T) {
if prompt == "" {
t.Error("GetActive should return prompt for active persona")
}
if !strings.Contains(prompt, "You are Archie") || !strings.Contains(prompt, "concise assistant") {
t.Errorf("selected styles must modify Archie's baseline identity, got %q", prompt)
}
if prompt := r.GetActive("session-2"); prompt != "" {
t.Error("GetActive should return empty for unset session")
if prompt := r.GetActive("session-2"); !strings.Contains(prompt, "You are Archie") {
t.Errorf("GetActive should return the Archie default for unset sessions, got %q", prompt)
}
}