Keep personal notes private by default and require review before publishing shared notes. Restore backups and replay forgotten notes in one transaction, and retain the installed release when an unattended rollback could bring back forgotten notes.
284 lines
10 KiB
Go
284 lines
10 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. Every read and write
|
|
// names the person the turn acts as: the scope of a note comes from the turn's
|
|
// owner, never from the model.
|
|
type Memory interface {
|
|
Notes(ctx context.Context, owner string, class memory.Class) ([]memory.Note, error)
|
|
Remember(ctx context.Context, owner, text string) (memory.Note, error)
|
|
Forget(ctx context.Context, owner string, id uuid.UUID) (bool, error)
|
|
// Propose records a note for an administrator to publish to the
|
|
// organisation. Chat never publishes one itself.
|
|
Propose(ctx context.Context, owner, text string) (memory.Note, 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. People gives the principal a turn acts
|
|
// as, its conversation's owner, and Access decides what that principal may
|
|
// do through a tool.
|
|
type Deps struct {
|
|
People governance.PrincipalSource
|
|
Access governance.Authorizer
|
|
Settings Settings
|
|
Toolbox Toolbox
|
|
Judge Judge
|
|
Approver Approver
|
|
Memory Memory
|
|
Runs Runs
|
|
Notifier Notifier
|
|
}
|
|
|
|
// conversations is the chat store: every conversation, turn and held action.
|
|
// A read or change made for a person names them as owner, and finds only
|
|
// their own conversations.
|
|
type conversations interface {
|
|
sessionStore
|
|
turnStore
|
|
eventStore
|
|
actionStore
|
|
}
|
|
|
|
type sessionStore interface {
|
|
CreateSession(ctx context.Context, orgID, owner string, id uuid.UUID) (store.Session, error)
|
|
Sessions(ctx context.Context, orgID, owner string, limit int) ([]store.Session, error)
|
|
Session(ctx context.Context, orgID, owner string, id uuid.UUID) (store.Session, error)
|
|
Rename(ctx context.Context, orgID, owner string, id uuid.UUID, title string) error
|
|
TitleIfUntitled(ctx context.Context, orgID string, id uuid.UUID, title string) error
|
|
DeleteSession(ctx context.Context, orgID, owner string, id uuid.UUID) error
|
|
Taint(ctx context.Context, orgID, owner string, id uuid.UUID) error
|
|
SessionTainted(ctx context.Context, orgID, owner string, id uuid.UUID) (bool, error)
|
|
}
|
|
|
|
type turnStore interface {
|
|
AddTurn(ctx context.Context, orgID, owner string, t store.Turn) (store.Turn, error)
|
|
Turns(ctx context.Context, orgID, owner string, sessionID uuid.UUID) ([]store.Turn, error)
|
|
Turn(ctx context.Context, orgID, owner string, id uuid.UUID) (store.Turn, error)
|
|
TurnOwner(ctx context.Context, id uuid.UUID) (string, bool, error)
|
|
Claim(ctx context.Context) (store.Turn, bool, error)
|
|
Finish(ctx context.Context, id uuid.UUID, state, reply, reasoning, failure string) error
|
|
RequestCancel(ctx context.Context, orgID, owner string, id uuid.UUID) (bool, error)
|
|
Interrupted(ctx context.Context, reason string) ([]uuid.UUID, error)
|
|
}
|
|
|
|
type eventStore interface {
|
|
History(ctx context.Context, sessionID uuid.UUID, before int64, limit int) ([]store.Turn, error)
|
|
AddEvent(ctx context.Context, turnID uuid.UUID, kind string, data jsontext.Value) (int64, error)
|
|
Events(ctx context.Context, turnID uuid.UUID, after int64) ([]store.Event, error)
|
|
EventsOf(ctx context.Context, sessionID uuid.UUID, kinds []string) ([]store.Event, error)
|
|
}
|
|
|
|
type actionStore interface {
|
|
PutAction(ctx context.Context, orgID string, a store.Action) (store.Action, error)
|
|
Answer(ctx context.Context, turnID uuid.UUID, key, state string, answer []byte) (bool, error)
|
|
Open(ctx context.Context) ([]store.Action, error)
|
|
Move(ctx context.Context, id uuid.UUID, from, to, result string) (bool, error)
|
|
Escalated(ctx context.Context, id uuid.UUID, step int, due time.Time) error
|
|
}
|
|
|
|
// Module owns one organisation's conversations.
|
|
type Module struct {
|
|
orgID string
|
|
store conversations
|
|
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() }
|
|
|
|
// OwnerTopic is the hub topic an owner's readers follow for actions settled
|
|
// in their conversations after the turn that held them ended.
|
|
func OwnerTopic(owner string) string { return "chat-owner:" + owner }
|