Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions pkg/agent/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -458,15 +458,19 @@ func (cb *ContextBuilder) LoadBootstrapFiles() string {
//
// See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
// See: https://platform.openai.com/docs/guides/prompt-caching
func (cb *ContextBuilder) buildDynamicContext(channel, chatID string) string {
func (cb *ContextBuilder) buildDynamicContext(channel, chatID, chatName string) string {
now := time.Now().Format("2006-01-02 15:04 (Monday)")
rt := fmt.Sprintf("%s %s, Go %s", runtime.GOOS, runtime.GOARCH, runtime.Version())

var sb strings.Builder
fmt.Fprintf(&sb, "## Current Time\n%s\n\n## Runtime\n%s", now, rt)

if channel != "" && chatID != "" {
fmt.Fprintf(&sb, "\n\n## Current Session\nChannel: %s\nChat ID: %s", channel, chatID)
if chatName != "" {
fmt.Fprintf(&sb, "\n\n## Current Session\nChannel: %s\nChat ID: %s (%s)", channel, chatID, chatName)
} else {
fmt.Fprintf(&sb, "\n\n## Current Session\nChannel: %s\nChat ID: %s", channel, chatID)
}
}

return sb.String()
Expand All @@ -477,7 +481,7 @@ func (cb *ContextBuilder) BuildMessages(
summary string,
currentMessage string,
media []string,
channel, chatID string,
channel, chatID, chatName string,
) []providers.Message {
messages := []providers.Message{}

Expand All @@ -493,7 +497,7 @@ func (cb *ContextBuilder) BuildMessages(
staticPrompt := cb.BuildSystemPromptWithCache()

// Build short dynamic context (time, runtime, session) — changes per request
dynamicCtx := cb.buildDynamicContext(channel, chatID)
dynamicCtx := cb.buildDynamicContext(channel, chatID, chatName)

// Compose a single system message: static (cached) + dynamic + optional summary.
// Keeping all system content in one message ensures every provider adapter can
Expand Down
22 changes: 19 additions & 3 deletions pkg/agent/context_cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ func TestSingleSystemMessage(t *testing.T) {

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
msgs := cb.BuildMessages(tt.history, tt.summary, tt.message, nil, "test", "chat1")
msgs := cb.BuildMessages(tt.history, tt.summary, tt.message, nil, "test", "chat1", "")

systemCount := 0
for _, m := range msgs {
Expand Down Expand Up @@ -576,7 +576,7 @@ func TestConcurrentBuildSystemPromptWithCache(t *testing.T) {
}

// Also exercise BuildMessages concurrently
msgs := cb.BuildMessages(nil, "", "hello", nil, "test", "chat")
msgs := cb.BuildMessages(nil, "", "hello", nil, "test", "chat", "")
if len(msgs) < 2 {
errs <- "BuildMessages returned fewer than 2 messages"
return
Expand Down Expand Up @@ -664,6 +664,22 @@ func BenchmarkBuildMessagesWithCache(b *testing.B) {

b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = cb.BuildMessages(history, "summary", "new message", nil, "cli", "test")
_ = cb.BuildMessages(history, "summary", "new message", nil, "cli", "test", "")
}
}

func TestBuildMessages_IncludesChatNameInDynamicContext(t *testing.T) {
tmpDir := setupWorkspace(t, map[string]string{
"IDENTITY.md": "# Identity\nTest agent.",
})
defer os.RemoveAll(tmpDir)

cb := NewContextBuilder(tmpDir)
msgs := cb.BuildMessages(nil, "", "hello", nil, "discord", "1234567890", "#general")
if len(msgs) == 0 {
t.Fatal("expected messages")
}
if !strings.Contains(msgs[0].Content, "Chat ID: 1234567890 (#general)") {
t.Fatalf("dynamic context missing chat name: %q", msgs[0].Content)
}
}
6 changes: 5 additions & 1 deletion pkg/agent/loop.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ type processOptions struct {
SessionKey string // Session identifier for history/context
Channel string // Target channel for tool execution
ChatID string // Target chat ID for tool execution
ChatName string // Optional human-readable chat/channel name
UserMessage string // User message content (may include prefix)
Media []string // media:// refs from inbound message
DefaultResponse string // Response when LLM returns empty
Expand All @@ -70,6 +71,7 @@ const (
defaultResponse = "I've completed processing but have no response to give. Increase `max_tool_iterations` in config.json."
sessionKeyAgentPrefix = "agent:"
metadataKeyAccountID = "account_id"
metadataKeyChatName = "chat_name"
metadataKeyGuildID = "guild_id"
metadataKeyTeamID = "team_id"
metadataKeyParentPeerKind = "parent_peer_kind"
Expand Down Expand Up @@ -735,6 +737,7 @@ func (al *AgentLoop) processMessage(ctx context.Context, msg bus.InboundMessage)
SessionKey: sessionKey,
Channel: msg.Channel,
ChatID: msg.ChatID,
ChatName: inboundMetadata(msg, metadataKeyChatName),
UserMessage: msg.Content,
Media: msg.Media,
DefaultResponse: defaultResponse,
Expand Down Expand Up @@ -879,6 +882,7 @@ func (al *AgentLoop) runAgentLoop(
opts.Media,
opts.Channel,
opts.ChatID,
opts.ChatName,
)

// Resolve media:// refs: images→base64 data URLs, non-images→local paths in content
Expand Down Expand Up @@ -1150,7 +1154,7 @@ func (al *AgentLoop) runLLMIteration(
newSummary := agent.Sessions.GetSummary(opts.SessionKey)
messages = agent.ContextBuilder.BuildMessages(
newHistory, newSummary, "",
nil, opts.Channel, opts.ChatID,
nil, opts.Channel, opts.ChatID, opts.ChatName,
)
continue
}
Expand Down
18 changes: 18 additions & 0 deletions pkg/channels/discord/discord.go
Original file line number Diff line number Diff line change
Expand Up @@ -459,10 +459,28 @@ func (c *DiscordChannel) handleMessage(s *discordgo.Session, m *discordgo.Messag
"channel_id": m.ChannelID,
"is_dm": fmt.Sprintf("%t", m.GuildID == ""),
}
if channelName := c.resolveChannelName(m.ChannelID); channelName != "" {
metadata["chat_name"] = channelName
}

c.HandleMessage(c.ctx, peer, m.ID, senderID, m.ChannelID, content, mediaPaths, metadata, sender)
}

func (c *DiscordChannel) resolveChannelName(channelID string) string {
if c == nil || c.session == nil || strings.TrimSpace(channelID) == "" {
return ""
}
if c.session.State != nil {
if ch, err := c.session.State.Channel(channelID); err == nil && ch != nil && strings.TrimSpace(ch.Name) != "" {
return strings.TrimSpace(ch.Name)
}
}
if ch, err := c.session.Channel(channelID); err == nil && ch != nil && strings.TrimSpace(ch.Name) != "" {
return strings.TrimSpace(ch.Name)
}
return ""
}

// startTyping starts a continuous typing indicator loop for the given chatID.
// It stops any existing typing loop for that chatID before starting a new one.
func (c *DiscordChannel) startTyping(chatID string) {
Expand Down
23 changes: 23 additions & 0 deletions pkg/channels/discord/discord_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,26 @@ func TestApplyDiscordProxy_InvalidProxyURL(t *testing.T) {
t.Fatal("applyDiscordProxy() expected error for invalid proxy URL, got nil")
}
}

func TestResolveChannelName_FromState(t *testing.T) {
session, err := discordgo.New("Bot test-token")
if err != nil {
t.Fatalf("discordgo.New() error: %v", err)
}
session.State = discordgo.NewState()
if err := session.State.GuildAdd(&discordgo.Guild{ID: "guild-1"}); err != nil {
t.Fatalf("GuildAdd() error: %v", err)
}
if err := session.State.ChannelAdd(&discordgo.Channel{
ID: "123",
GuildID: "guild-1",
Name: "general",
}); err != nil {
t.Fatalf("ChannelAdd() error: %v", err)
}

ch := &DiscordChannel{session: session}
if got := ch.resolveChannelName("123"); got != "general" {
t.Fatalf("resolveChannelName() = %q, want %q", got, "general")
}
}
148 changes: 129 additions & 19 deletions pkg/channels/telegram/telegram.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"regexp"
"strconv"
"strings"
"sync"
"time"

"github.com/mymmrac/telego"
Expand Down Expand Up @@ -41,14 +42,23 @@ var (
type TelegramChannel struct {
*channels.BaseChannel
bot *telego.Bot
bh *th.BotHandler
bh telegramBotHandler
bhMu sync.Mutex
config *config.Config
chatIDs map[string]int64
ctx context.Context
cancel context.CancelFunc

registerFunc func(context.Context, []commands.Definition) error
commandRegCancel context.CancelFunc
startPollingFunc func(context.Context) (<-chan telego.Update, error)
newHandlerFunc func(<-chan telego.Update) (telegramBotHandler, error)
sleepFunc func(context.Context, time.Duration) bool
}

type telegramBotHandler interface {
Start() error
StopWithContext(context.Context) error
}

func NewTelegramChannel(cfg *config.Config, bus *bus.MessageBus) (*TelegramChannel, error) {
Expand Down Expand Up @@ -107,24 +117,18 @@ func (c *TelegramChannel) Start(ctx context.Context) error {

c.ctx, c.cancel = context.WithCancel(ctx)

updates, err := c.bot.UpdatesViaLongPolling(c.ctx, &telego.GetUpdatesParams{
Timeout: 30,
})
updates, err := c.startLongPolling(c.ctx)
if err != nil {
c.cancel()
return fmt.Errorf("failed to start long polling: %w", err)
}

bh, err := th.NewBotHandler(c.bot, updates)
bh, err := c.newBotHandler(updates)
if err != nil {
c.cancel()
return fmt.Errorf("failed to create bot handler: %w", err)
}
c.bh = bh

bh.HandleMessage(func(ctx *th.Context, message telego.Message) error {
return c.handleMessage(ctx, &message)
}, th.AnyMessage())
c.setBotHandler(bh)

c.SetRunning(true)
logger.InfoCF("telegram", "Telegram bot connected", map[string]any{
Expand All @@ -133,13 +137,7 @@ func (c *TelegramChannel) Start(ctx context.Context) error {

c.startCommandRegistration(c.ctx, commands.BuiltinDefinitions())

go func() {
if err = bh.Start(); err != nil {
logger.ErrorCF("telegram", "Bot handler failed", map[string]any{
"error": err.Error(),
})
}
}()
go c.runPollingLoop(c.ctx, bh)

return nil
}
Expand All @@ -149,8 +147,8 @@ func (c *TelegramChannel) Stop(ctx context.Context) error {
c.SetRunning(false)

// Stop the bot handler
if c.bh != nil {
_ = c.bh.StopWithContext(ctx)
if bh := c.currentBotHandler(); bh != nil {
_ = bh.StopWithContext(ctx)
}

// Cancel our context (stops long polling)
Expand All @@ -164,6 +162,118 @@ func (c *TelegramChannel) Stop(ctx context.Context) error {
return nil
}

func (c *TelegramChannel) startLongPolling(ctx context.Context) (<-chan telego.Update, error) {
if c.startPollingFunc != nil {
return c.startPollingFunc(ctx)
}
return c.bot.UpdatesViaLongPolling(ctx, &telego.GetUpdatesParams{
Timeout: 30,
})
}

func (c *TelegramChannel) newBotHandler(updates <-chan telego.Update) (telegramBotHandler, error) {
if c.newHandlerFunc != nil {
return c.newHandlerFunc(updates)
}

bh, err := th.NewBotHandler(c.bot, updates)
if err != nil {
return nil, err
}
bh.HandleMessage(func(ctx *th.Context, message telego.Message) error {
return c.handleMessage(ctx, &message)
}, th.AnyMessage())
return bh, nil
}

func (c *TelegramChannel) setBotHandler(bh telegramBotHandler) {
c.bhMu.Lock()
defer c.bhMu.Unlock()
c.bh = bh
}

func (c *TelegramChannel) currentBotHandler() telegramBotHandler {
c.bhMu.Lock()
defer c.bhMu.Unlock()
return c.bh
}

func (c *TelegramChannel) sleep(ctx context.Context, delay time.Duration) bool {
if c.sleepFunc != nil {
return c.sleepFunc(ctx, delay)
}
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-ctx.Done():
return false
case <-timer.C:
return true
}
}

func (c *TelegramChannel) runPollingLoop(ctx context.Context, bh telegramBotHandler) {
backoff := time.Second
for {
if err := bh.Start(); err != nil && ctx.Err() == nil {
logger.ErrorCF("telegram", "Bot handler failed", map[string]any{
"error": err.Error(),
})
}
if ctx.Err() != nil {
return
}

logger.WarnC("telegram", "Updates channel closed, restarting long polling")
if !c.sleep(ctx, backoff) {
return
}

for {
updates, err := c.startLongPolling(ctx)
if err != nil {
logger.ErrorCF("telegram", "Failed to restart long polling", map[string]any{
"error": err.Error(),
"retry_after": backoff.String(),
})
if backoff < 30*time.Second {
backoff *= 2
if backoff > 30*time.Second {
backoff = 30 * time.Second
}
}
if !c.sleep(ctx, backoff) {
return
}
continue
}

nextHandler, err := c.newBotHandler(updates)
if err != nil {
logger.ErrorCF("telegram", "Failed to recreate bot handler", map[string]any{
"error": err.Error(),
"retry_after": backoff.String(),
})
if backoff < 30*time.Second {
backoff *= 2
if backoff > 30*time.Second {
backoff = 30 * time.Second
}
}
if !c.sleep(ctx, backoff) {
return
}
continue
}

c.setBotHandler(nextHandler)
bh = nextHandler
backoff = time.Second
break
}
}
}

func (c *TelegramChannel) Send(ctx context.Context, msg bus.OutboundMessage) error {
if !c.IsRunning() {
return channels.ErrNotRunning
Expand Down
Loading