A conversation gets a persisted tainted flag (migration 00040), set the first time output from a tool whose declaration trust level is not "trusted" enters the turn, before that output reaches the model. The flag is only ever set, never cleared, so later turns and resumed processes inherit it. In a tainted conversation every non-read-only action is raised to a floor of propose_and_wait, so the existing hold path renders the approval card with the exact judged action; read-only lookups still run, and a hard-rule refusal stays a refusal. An unreadable taint state or a failed taint write fails closed. Trust levels live on connectors.Declaration; unknown levels are untrusted.
279 lines
10 KiB
Go
279 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.
|
|
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. 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 }
|