Files
archie/internal/gateway/turn.go
T
sam 0d73f2fa5a feat(chat): show tool calls inline and stream replies into one message
Chat returned only the final answer, so a wrong tool choice, a
hallucinated action, or a footgun like `systemctl stop` against
`restart` was invisible from the conversation. Only text deltas were
threaded through the turn, and tool calls executed inside Generate with
nowhere to report.

Replace the delta callback with gateway.TurnStream, which carries text
fragments and completed tool calls on one ordered path from the model
loop to the channel. The sequence is the point: a tool line that
overtakes the sentence it interrupted describes a turn that never
happened. Text-only callers use gateway.DeltaFunc and are unaffected.

A tool is reported on its result, never on its call  --  the call part
carries no outcome yet, so reporting both would list every tool twice,
once with nothing to say.

Telegram renders it behind [chat.telegram] show_tool_calls, off by
default: this is debugging visibility, and it narrates every internal
step to provide it. The dashboard always shows it, being the operator's
own observability surface; its tool lines are live-only and are not
persisted with the conversation.

The Telegram live reply changes mechanism, and with it what a frame
MEANS. It used to stream through sendMessageDraft: drafts are ephemeral
30-second previews, so a tool call longer than that outlived the
preview, and successive frames were observed concatenated with their
cursors intact. It now sends one real message and edits it. An update
used to be "the next preview of the answer"; it is now "the whole
answer as it currently stands, replacing what is there". The cursor is
appended at render time and never stored, so exactly one exists and
always at the end, and a frame too long for one message is cut to its
tail rather than rejected outright.

A stopped or failed turn now edits the cursor away instead of leaving
it blinking on a message nothing will finish. That cleanup runs on a
live context because turnCtx is already dead, and it runs on both
failure branches: ai-sdk raises an aborted stream as ErrAborted with
ctx.Err() formatted in rather than wrapped, so errors.Is cannot be
trusted to tell a /stop from a fault.

Closes #467
2026-08-14 02:36:12 +10:00

404 lines
13 KiB
Go

package gateway
import (
"context"
"errors"
"fmt"
"log/slog"
"sync"
"time"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/tools"
)
// TurnModel prepares provider-specific tools and executes one completed chat
// generation. The gateway owns the conversation lifecycle; the composition
// root implements this seam over the selected model runtime.
type TurnModel interface {
Prepare(ctx context.Context, model string, extra []tools.ToolEntry) (PreparedTurnModel, error)
}
// PreparedTurnModel is a provider-specific generation plan. Preparation is
// separate from generation because the gateway needs tool metadata before it
// can calculate the conversation budget and render the system prompt.
type PreparedTurnModel interface {
ToolSummaries() []ToolSummary
ToolSchemaTokens() int
// Generate runs the turn, reporting progress to stream as it goes.
// stream is nil when the caller cannot render partial output; an
// implementation must then generate without reporting anything.
Generate(ctx context.Context, request TurnModelRequest, stream TurnStream) (string, error)
}
// TurnModelRequest is the provider-neutral request assembled by the gateway.
// Messages include the system prompt as their first entry.
type TurnModelRequest struct {
Messages []CompressedMessage
MaxTokens int
}
// PersonaPromptSource supplies the active persona prompt for a session.
type PersonaPromptSource interface {
GetActive(sessionID string) string
}
// TurnEventPublisher receives completed primary chat-turn events.
type TurnEventPublisher interface {
Publish(events.Event)
}
// TurnReplayStore provides a durable source-ID lookup for redeliveries that
// have fallen outside the recent model-context window. It is optional for
// compatibility with small test stores; production session stores implement
// it so retries do not depend on retaining old context.
type TurnReplayStore interface {
FindPriorReply(ctx context.Context, sessionID, sourceID, identity string) (string, error)
}
var defaultTurnOwnerID = NewTurnID()
const defaultTurnPersistenceTimeout = 5 * time.Second
// TurnRunnerConfig contains the dependencies for one channel's chat turn
// runner. The runner is channel-neutral apart from the channel name used in
// prompts, session tools, and completion events.
type TurnRunnerConfig struct {
Router *Router
Sessions SessionStore
Models ModelManager
Personas PersonaPromptSource
Model TurnModel
Ledger TurnLedger
OwnerID string
PersistenceTimeout time.Duration
TaskLister ChatTaskLister
Tasks TaskCreator
TaskLogs ChatTaskLogReader
TaskIdentity string
Bus TurnEventPublisher
BotUser string
Channel string
Operator string
Log *slog.Logger
}
// TurnRunner owns one chat turn from session resolution through model
// generation and message persistence. Channel adapters delegate to it through
// Router.LLM and Router.LLMStream compatibility callbacks.
type TurnRunner struct {
TurnRunnerConfig
recoveryMu sync.Mutex
recovered bool
}
// NewTurnRunner constructs a chat turn runner.
func NewTurnRunner(cfg TurnRunnerConfig) *TurnRunner {
if cfg.Ledger == nil {
cfg.Ledger, _ = cfg.Sessions.(TurnLedger)
}
if cfg.OwnerID == "" {
cfg.OwnerID = defaultTurnOwnerID
}
if cfg.PersistenceTimeout <= 0 {
cfg.PersistenceTimeout = defaultTurnPersistenceTimeout
}
return &TurnRunner{TurnRunnerConfig: cfg}
}
// Recover marks turns from a previous process as failed and retryable. It is
// intended to run during composition before the channel starts accepting
// messages; Run also calls the same guard for small embedders and tests.
func (r *TurnRunner) Recover(ctx context.Context) error {
return r.recoverTurns(ctx)
}
// Respond adapts the runner to Router.LLM.
func (r *TurnRunner) Respond(ctx context.Context, msg Message) (string, error) {
return r.Run(ctx, msg, nil)
}
// RespondStream adapts the runner to Router.LLMStream.
func (r *TurnRunner) RespondStream(ctx context.Context, msg Message, stream TurnStream) (string, error) {
return r.Run(ctx, msg, stream)
}
// Run executes one turn, reporting progress to stream. A completed duplicate
// source message replays its durable response without invoking the model
// again; the replay reaches stream as one whole-text fragment, since there is
// no generation left to watch.
//
// stream may be nil, which means the caller renders only the returned reply.
func (r *TurnRunner) Run(ctx context.Context, msg Message, stream TurnStream) (string, error) {
if r.Router == nil {
return "", fmt.Errorf("chat turn router is not configured")
}
if r.Sessions == nil {
return "", fmt.Errorf("chat turn session store is not configured")
}
if r.Ledger == nil {
return "", fmt.Errorf("chat turn ledger is not configured")
}
if r.Models == nil {
return "", fmt.Errorf("chat turn model manager is not configured")
}
if r.Model == nil {
return "", fmt.Errorf("chat turn model is not configured")
}
if err := r.recoverTurns(ctx); err != nil {
return "", fmt.Errorf("recover chat turns: %w", err)
}
sessionID, err := r.Router.ResolveSessionKey(ctx, msg)
if err != nil {
return "", fmt.Errorf("resolve chat session: %w", err)
}
turnID, err := r.canonicalTurnID(ctx, sessionID, msg.SourceID)
if err != nil {
return "", fmt.Errorf("resolve canonical turn ID: %w", err)
}
if turnID == "" {
turnID = NewTurnID()
}
turn, claim, err := r.Ledger.ClaimTurn(ctx, TurnRecord{
TurnID: turnID,
SessionID: sessionID,
SourceID: msg.SourceID,
Status: TurnStatusAccepted,
OwnerID: r.OwnerID,
})
if err != nil {
return "", fmt.Errorf("claim chat turn: %w", err)
}
switch claim {
case TurnClaimCompleted:
if stream != nil && turn.ResponseText != "" {
stream.Delta(turn.ResponseText)
}
return turn.ResponseText, nil
case TurnClaimInProgress:
return "", fmt.Errorf("%w: %s", ErrTurnInProgress, turn.TurnID)
}
history, err := r.Sessions.RecentMessages(ctx, sessionID, 100)
if err != nil {
return "", r.failTurn(ctx, turn, fmt.Errorf("load chat history: %w", err))
}
prior := PriorReply(history, sessionID, msg.SourceID, r.BotUser)
if prior == "" && msg.SourceID != "" {
if replayStore, ok := r.Sessions.(TurnReplayStore); ok {
prior, err = replayStore.FindPriorReply(ctx, sessionID, msg.SourceID, r.BotUser)
if err != nil {
return "", r.failTurn(ctx, turn, fmt.Errorf("find prior chat reply: %w", err))
}
}
}
if prior != "" {
turn.Status = TurnStatusCompleted
turn.ResponseText = prior
turn.Error = ""
turn.UpdatedAt = time.Now().UTC()
if err := r.saveTurn(ctx, turn); err != nil {
return "", r.failTurn(ctx, turn, fmt.Errorf("save replayed chat turn: %w", err))
}
if r.Log != nil {
r.Log.Info("replaying the reply to a redelivered message",
"session", sessionID, "source_id", msg.SourceID)
}
if stream != nil {
stream.Delta(prior)
}
return prior, nil
}
msg.MessageID = messageIDForTurn(sessionID, msg)
if turn.InputMessageID == "" {
if err := r.Sessions.SaveMessage(ctx, sessionID, msg); err != nil {
return "", r.failTurn(ctx, turn, fmt.Errorf("save inbound chat message: %w", err))
}
turn.InputMessageID = msg.MessageID
turn.UpdatedAt = time.Now().UTC()
if err := r.saveTurn(ctx, turn); err != nil {
return "", r.failTurn(ctx, turn, fmt.Errorf("save chat turn input: %w", err))
}
} else {
msg.MessageID = turn.InputMessageID
}
if !messageInHistory(history, msg.SourceID) {
history = append(history, msg)
}
compressed := compressTurnHistory(history, r.BotUser)
extraTools := append(
TaskTools(r.TaskLister, r.Tasks, r.TaskLogs, r.TaskIdentity),
SessionTools(r.Sessions, r.Router.SessionTracker(), r.Channel, msg)...,
)
modelName := r.Models.ActiveModel()
prepared, err := r.Model.Prepare(ctx, modelName, extraTools)
if err != nil {
return "", r.failTurn(ctx, turn, fmt.Errorf("build chat model: %w", err))
}
if prepared == nil {
return "", r.failTurn(ctx, turn, fmt.Errorf("build chat model: empty preparation"))
}
toolInfo := prepared.ToolSummaries()
persona := ""
if r.Personas != nil {
persona = r.Personas.GetActive(sessionID)
}
systemPrompt := BuildSystemPrompt(SystemPromptConfig{
Persona: persona,
Tools: toolInfo,
Channel: r.Channel,
Model: modelName,
SessionID: sessionID,
Now: time.Now(),
Operator: r.Operator,
})
modelDetails := ModelDetails{}
if detailed, ok := r.Models.(DetailedModelManager); ok {
modelDetails, _ = detailed.ModelDetails(modelName)
}
compression, err := CompressionConfigForModel(
modelDetails,
EstimateTokens(systemPrompt)+prepared.ToolSchemaTokens(),
)
if err != nil {
return "", r.failTurn(ctx, turn, fmt.Errorf("derive chat context budget: %w", err))
}
if r.Log != nil && modelDetails.ContextWindow <= 0 {
r.Log.Warn("chat model has no context metadata; using compatibility compression budget",
"model", modelName)
}
view := CompressHistory(compressed, compression)
if r.Log != nil {
r.Log.Info("chat turn",
"session", sessionID,
"channel", msg.ChannelID,
"thread", msg.ThreadID,
"history_messages", len(history),
"model", modelName,
"context_window", modelDetails.ContextWindow,
"prompt_budget", compression.MaxPromptTokens)
}
view.Messages = append(
[]CompressedMessage{{Role: "system", Content: systemPrompt}}, view.Messages...,
)
text, err := prepared.Generate(ctx, TurnModelRequest{
Messages: view.Messages,
MaxTokens: modelDetails.MaxOutputTokens,
}, stream)
if err != nil {
return "", r.failTurn(ctx, turn, err)
}
assistant := Message{MessageID: assistantMessageIDForTurn(turn.TurnID), From: r.BotUser, Text: text}
if err := r.Sessions.SaveMessage(ctx, sessionID, assistant); err != nil {
return "", r.failTurn(ctx, turn, fmt.Errorf("save outbound chat message: %w", err))
}
turn.Status = TurnStatusCompleted
turn.AssistantMessageID = assistant.MessageID
turn.ResponseText = text
turn.Error = ""
turn.UpdatedAt = time.Now().UTC()
if err := r.saveTurn(ctx, turn); err != nil {
return "", r.failTurn(ctx, turn, fmt.Errorf("save completed chat turn: %w", err))
}
if r.Bus != nil {
r.Bus.Publish(events.Event{
Kind: events.KindTurnCompleted,
Detail: sessionID,
Data: map[string]any{"session": sessionID, "channel": r.Channel},
})
}
return text, nil
}
// canonicalTurnID preserves a matching identifier written by the legacy
// separator encoding. A legacy collision belonging to a different
// session/source pair is ignored in favour of the injective identifier.
func (r *TurnRunner) canonicalTurnID(ctx context.Context, sessionID, sourceID string) (string, error) {
current := CanonicalTurnID(sessionID, sourceID)
if current == "" {
return "", nil
}
legacy := legacyCanonicalTurnID(sessionID, sourceID)
if current == legacy {
return current, nil
}
turn, ok, err := r.Ledger.GetTurn(ctx, legacy)
if err != nil {
return "", err
}
if ok && turn.SessionID == sessionID && turn.SourceID == sourceID {
return legacy, nil
}
return current, nil
}
func (r *TurnRunner) failTurn(ctx context.Context, turn TurnRecord, cause error) error {
if errors.Is(cause, context.Canceled) {
turn.Status = TurnStatusCancelled
} else {
turn.Status = TurnStatusFailed
}
turn.Error = cause.Error()
turn.UpdatedAt = time.Now().UTC()
if err := r.saveTurn(ctx, turn); err != nil {
return errors.Join(cause, fmt.Errorf("save failed chat turn: %w", err))
}
return cause
}
func (r *TurnRunner) recoverTurns(ctx context.Context) error {
r.recoveryMu.Lock()
defer r.recoveryMu.Unlock()
if r.recovered {
return nil
}
if err := r.Ledger.RecoverTurns(ctx, r.OwnerID); err != nil {
return err
}
r.recovered = true
return nil
}
func (r *TurnRunner) saveTurn(ctx context.Context, turn TurnRecord) error {
persistCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), r.PersistenceTimeout)
defer cancel()
return r.Ledger.SaveTurn(persistCtx, turn)
}
func messageIDForTurn(sessionID string, msg Message) string {
if msg.MessageID != "" {
return msg.MessageID
}
if id := CanonicalMessageID(sessionID, msg.SourceID); id != "" {
return id
}
return NewTurnID()
}
func messageInHistory(history []Message, sourceID string) bool {
if sourceID == "" {
return false
}
for _, stored := range history {
if stored.SourceID == sourceID {
return true
}
}
return false
}
func compressTurnHistory(history []Message, botUser string) []CompressedMessage {
compressed := make([]CompressedMessage, 0, len(history))
for _, message := range history {
role := "user"
if message.From == botUser {
role = "assistant"
}
compressed = append(compressed, CompressedMessage{Role: role, Content: message.Text})
}
return compressed
}