Files
archie/modules/chat/chat.go
T
samandCopilot cbfcd43018 feat(chat): add the chat module to the archie binary (#2018)
Conversations are the chat module's own tables. A turn is stored before it
is acknowledged, runs after the turns before it in its session, and records
everything it streams, so a reader replays it from a cursor. The agent uses
the configured agent model, the same connector tools as a run and the
dashboard's own reads; every action is judged, and one judgement holds is
put to people through approvals and run once when approved. A restart fails
the turns it interrupted visibly and never restarts a started action.

Conversation memory is a set of notes in the memory module. The chat
prompts are copied from internal/prompts (chat-system.tmpl, soul.md,
session-title.md) into internal/platform/prompts while the gateway still
reads them; the tool parameter redaction is copied from
internal/domain/messaging/tool_parameters.go.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-19 19:40:44 +11:00

228 lines
7.3 KiB
Go

// Package chat is the conversation between the operator and Archie: sessions,
// their turns, and the agent that answers each turn with the same tools and
// judgement a workflow run uses. A turn is stored before it is acknowledged
// and everything it streams is recorded, so a reader that reconnects replays
// it and a restart loses nothing it reported.
package chat
import (
"context"
"encoding/json/jsontext"
"log/slog"
"sync"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/samcharles93/ai-sdk/chat"
"github.com/samcharles93/archie-core/internal/platform/hub"
"github.com/samcharles93/archie-core/modules/approvals"
"github.com/samcharles93/archie-core/modules/chat/internal/store"
"github.com/samcharles93/archie-core/modules/connectors"
"github.com/samcharles93/archie-core/modules/deliveries"
"github.com/samcharles93/archie-core/modules/governance"
"github.com/samcharles93/archie-core/modules/judgement"
"github.com/samcharles93/archie-core/modules/memory"
"github.com/samcharles93/archie-core/modules/runs"
)
// Settings provides the agent model and the escalation path approvals follow.
type Settings interface {
AgentModelForAlias(ctx context.Context, alias string) (governance.Model, error)
AgentProvider(ctx context.Context, model governance.Model) (chat.Provider, chat.ModelInfo, error)
EscalationPath(ctx context.Context, owner string, needAuthority bool) ([]governance.PathStep, error)
}
// Toolbox is where the agent finds the connector lookups and actions and the
// MCP server tools it may call.
type Toolbox interface {
Declarations() []connectors.Declaration
Tool(name string) (connectors.Tool, bool)
}
// Judge decides whether an action runs, and runs only what it decided.
type Judge interface {
Assess(ctx context.Context, req judgement.Request) (judgement.Decision, error)
Execute(ctx context.Context, d judgement.Decision, input jsontext.Value, key string) (string, error)
ExecuteApproved(ctx context.Context, d judgement.Decision, a judgement.Approval, input jsontext.Value, key string) (string, error)
}
// Approver puts actions judgement held to people, escalates them along the
// path and expires them after its last deadline.
type Approver interface {
Ask(ctx context.Context, runID uuid.UUID, key string, d judgement.Decision, path []governance.PathStep) (approvals.Request, error)
Escalate(ctx context.Context, id uuid.UUID, step int, to governance.PathStep) error
Expire(ctx context.Context, id uuid.UUID) error
Accept(ctx context.Context, id uuid.UUID) error
Discard(ctx context.Context, id uuid.UUID, because string) error
Pending(ctx context.Context) ([]approvals.Request, error)
}
// Memory is what Archie remembers across conversations.
type Memory interface {
Notes(ctx context.Context) ([]memory.Note, error)
Remember(ctx context.Context, text string) (memory.Note, error)
Forget(ctx context.Context, id uuid.UUID) (bool, error)
}
// Runs reads workflow runs.
type Runs interface {
Recent(ctx context.Context, orgID string, limit int) ([]runs.RunView, error)
Run(ctx context.Context, orgID string, id uuid.UUID) (runs.RunView, bool, error)
}
// Notifier tells people what came of an approved action.
type Notifier interface {
Notify(ctx context.Context, n deliveries.Notification) error
}
// Deps is what a turn's agent uses.
type Deps struct {
Settings Settings
Toolbox Toolbox
Judge Judge
Approver Approver
Memory Memory
Runs Runs
Notifier Notifier
}
// Module owns one organisation's conversations.
type Module struct {
orgID string
store *store.Store
log *slog.Logger
hub *hub.Hub
wake chan struct{}
mu sync.Mutex
deps *Deps
running map[uuid.UUID]context.CancelFunc
}
// NewModule returns the chat module for orgID. Live readers of a turn are
// told through h when it records something.
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, h *hub.Hub) *Module {
return &Module{
orgID: orgID, store: store.New(db), log: log, hub: h,
wake: make(chan struct{}, 1), running: map[uuid.UUID]context.CancelFunc{},
}
}
// Use gives the module what its agent uses. Approvals wake the module, so it
// is built before them and given them here.
func (m *Module) Use(d Deps) {
m.mu.Lock()
defer m.mu.Unlock()
m.deps = &d
}
func (m *Module) uses() (Deps, bool) {
m.mu.Lock()
defer m.mu.Unlock()
if m.deps == nil {
return Deps{}, false
}
return *m.deps, true
}
// Session is a conversation as the API shows it.
type Session struct {
ID uuid.UUID `json:"session_id"`
Title string `json:"title"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func sessionOf(s store.Session) Session {
return Session{ID: s.ID, Title: s.Title, CreatedAt: s.CreatedAt, UpdatedAt: s.UpdatedAt}
}
// Turn is one message and its reply as the API shows it. Tools, approvals
// and actions are what the turn did, in the order it did them.
type Turn struct {
ID uuid.UUID `json:"id"`
SessionID uuid.UUID `json:"session_id"`
Seq int64 `json:"seq"`
State string `json:"state"`
Text string `json:"text"`
Page string `json:"page,omitzero"`
PageLabel string `json:"page_label,omitzero"`
Reply string `json:"reply"`
Reasoning string `json:"reasoning,omitzero"`
Error string `json:"error,omitzero"`
Tools []ToolCall `json:"tool_calls"`
Approvals []Approval `json:"approvals"`
Actions []ActionDone `json:"actions"`
Navigate []Navigation `json:"navigate"`
CreatedAt time.Time `json:"created_at"`
FinishedAt *time.Time `json:"finished_at,omitzero"`
}
// ToolCall is one tool the agent called and what came of it.
type ToolCall struct {
ID string `json:"id"`
Name string `json:"name"`
Parameters string `json:"parameters"`
Output string `json:"text"`
Failed bool `json:"failed,omitzero"`
DurationMS int64 `json:"duration_ms"`
TextOffset int `json:"text_offset"`
}
// Approval is an action judgement held and put to people.
type Approval struct {
RequestID uuid.UUID `json:"request_id"`
Action string `json:"action"`
Summary string `json:"summary"`
Level string `json:"level"`
Deadline time.Time `json:"deadline"`
}
// ActionDone is what became of an action after its approval was answered.
type ActionDone struct {
RequestID uuid.UUID `json:"request_id"`
State string `json:"state"`
Result string `json:"result,omitzero"`
}
// Navigation is a dashboard page the agent opened for the operator.
type Navigation struct {
Path string `json:"path"`
Label string `json:"label"`
}
// Event kinds a turn streams.
const (
kindReasoning = "reasoning"
kindDelta = "delta"
kindTool = "tool"
kindNavigate = "navigate"
kindApproval = "approval"
kindAction = "action"
kindDone = "done"
kindError = "error"
kindCancelled = "cancelled"
)
// Turn states.
const (
stateQueued = "queued"
stateRunning = "running"
stateSucceeded = "succeeded"
stateFailed = "failed"
stateCancelled = "cancelled"
)
func finished(state string) bool {
return state == stateSucceeded || state == stateFailed || state == stateCancelled
}
// topic is the hub topic a turn's live readers follow.
func topic(turnID uuid.UUID) string { return "chat:" + turnID.String() }
// sessionTopic is the hub topic a conversation's readers follow for actions
// settled after its turns ended.
const sessionTopic = "chat"