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>
This commit is contained in:
samandCopilot committed 2026-11-19 19:40:44 +11:00
1 parent a0d14090ef
commit cbfcd43018
21 files changed
+2863 -8

No files matched your search

+216
View File
@@ -0,0 +1,216 @@
package chat
import (
"context"
"encoding/json"
"encoding/json/jsontext"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"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"
)
// Action states.
const (
actionWaiting = "waiting"
actionApproved = "approved"
actionRunning = "running"
actionSucceeded = "succeeded"
actionFailed = "failed"
actionUnknown = "unknown"
actionDenied = "denied"
actionExpired = "expired"
)
// Signal takes the answer to an approval a chat turn asked for. It reports
// false when id is not a chat turn, so the caller passes the answer on to the
// run waiting on it. The answer is stored before anything runs; the work loop
// runs an approved action once.
func (m *Module) Signal(ctx context.Context, id uuid.UUID, key string, payload jsontext.Value) (bool, error) {
ours, err := m.store.IsTurn(ctx, id)
if err != nil || !ours {
return false, err
}
var answer approvals.Answer
if err := json.Unmarshal(payload, &answer); err != nil {
return true, fmt.Errorf("decode approval answer: %w", err)
}
state := actionDenied
if answer.Approved {
state = actionApproved
}
answered, err := m.store.Answer(ctx, id, key, state, payload)
if err != nil || !answered {
return true, err
}
if !answer.Approved {
m.record(ctx, id, kindAction, ActionDone{RequestID: answer.RequestID, State: actionDenied})
m.hub.Publish(hub.Note{Topic: sessionTopic})
}
m.poke()
return true, nil
}
// settleActions escalates or expires actions nobody answered in time and runs
// the approved ones. An action found running was started by a process that
// stopped: it may have taken effect, so it is never started again.
func (m *Module) settleActions(ctx context.Context) {
d, ok := m.uses()
if !ok {
return
}
open, err := m.store.Open(ctx)
if err != nil {
if ctx.Err() == nil {
m.log.ErrorContext(ctx, "list held chat actions", "error", err)
}
return
}
for _, a := range open {
var err error
switch a.State {
case actionWaiting:
if time.Now().After(a.StepDue) {
err = m.escalate(ctx, d, a)
}
case actionApproved:
err = m.runApproved(ctx, d, a)
case actionRunning:
err = m.settled(ctx, d, a, actionRunning, actionUnknown,
"It was started before Archie restarted and its outcome is unknown; it may have taken effect and won't run again.")
}
if err != nil {
m.log.ErrorContext(ctx, "settle chat action", "action", a.ID, "request", a.RequestID, "error", err)
}
}
}
// escalate passes an unanswered action to the next step of its path, or
// expires it after the last.
func (m *Module) escalate(ctx context.Context, d Deps, a store.Action) error {
var path []governance.PathStep
if err := json.Unmarshal(a.Path, &path); err != nil {
return fmt.Errorf("decode escalation path: %w", err)
}
next := a.Step + 1
if next < len(path) {
if err := d.Approver.Escalate(ctx, a.RequestID, next, path[next]); err != nil {
return err
}
return m.store.Escalated(ctx, a.ID, next, time.Now().Add(path[next].Deadline()))
}
if err := d.Approver.Expire(ctx, a.RequestID); err != nil {
return err
}
return m.settled(ctx, d, a, actionWaiting, actionExpired, "Nobody answered before the last deadline, so it didn't run.")
}
// runApproved judges an approved action again and runs it once. An approval
// for an action that has since changed or become stricter is discarded, and
// the operator asks again.
func (m *Module) runApproved(ctx context.Context, d Deps, a store.Action) error {
var (
held judgement.Decision
answer approvals.Answer
)
if err := json.Unmarshal(a.Decision, &held); err != nil {
return fmt.Errorf("decode decision: %w", err)
}
if err := json.Unmarshal(a.Answer, &answer); err != nil {
return fmt.Errorf("decode answer: %w", err)
}
fresh, err := d.Judge.Assess(ctx, judgement.Request{
RunID: a.TurnID, Key: held.Key + ":again", Connector: held.Action.Connector, Action: held.Action.Name,
Input: held.Action.Input, Workflow: principal,
})
if err != nil {
// Nothing runs that wasn't judged again; the operator asks again.
return m.settled(ctx, d, a, actionApproved, actionFailed, "It couldn't be judged again before running: "+err.Error())
}
if why := invalidated(held, fresh); why != "" {
if err := d.Approver.Discard(ctx, a.RequestID, why); err != nil {
return err
}
return m.settled(ctx, d, a, actionApproved, actionFailed, "The approval no longer holds: "+why+". Ask Archie again.")
}
started, err := m.store.Move(ctx, a.ID, actionApproved, actionRunning, "")
if err != nil || !started {
return err
}
var out string
if fresh.Level.Runs() {
out, err = d.Judge.Execute(ctx, fresh, fresh.Action.Input, a.Key)
} else {
if err := d.Approver.Accept(ctx, a.RequestID); err != nil {
return err
}
out, err = d.Judge.ExecuteApproved(ctx, held, answer.Approval(held), held.Action.Input, a.Key)
}
switch {
case errors.Is(err, connectors.ErrOutcomeUnknown):
return m.settled(ctx, d, a, actionRunning, actionUnknown, "It was started and its outcome is unknown; it may have taken effect: "+err.Error())
case err != nil:
return m.settled(ctx, d, a, actionRunning, actionFailed, err.Error())
}
return m.settled(ctx, d, a, actionRunning, actionSucceeded, out)
}
// invalidated says why an approval no longer covers the action as judged now,
// or nothing when it still does.
func invalidated(approved, fresh judgement.Decision) string {
switch {
case fresh.Level == judgement.Never:
return "it is now refused: " + fresh.Reason
case fresh.Level.Runs():
return ""
case fresh.Action.Target != approved.Action.Target:
return "its target changed since it was approved"
case fresh.Action.Effect != approved.Action.Effect:
return "its effect changed since it was approved"
case fresh.Level > approved.Level:
return "judgement is stricter than when it was approved: now " + fresh.Level.String()
}
return ""
}
// settled records what became of an action, shows it in its conversation and
// tells the people notifications go to. The notification names no run: a
// chat turn isn't one.
func (m *Module) settled(ctx context.Context, d Deps, a store.Action, from, to, result string) error {
moved, err := m.store.Move(ctx, a.ID, from, to, result)
if err != nil || !moved {
return err
}
done := ActionDone{RequestID: a.RequestID, State: to, Result: truncateRunes(result, outputMaxRunes)}
m.record(ctx, a.TurnID, kindAction, done)
m.hub.Publish(hub.Note{Topic: sessionTopic})
var held judgement.Decision
_ = json.Unmarshal(a.Decision, &held)
return d.Notifier.Notify(ctx, deliveries.Notification{
Key: "chat:" + a.ID.String() + ":" + to,
Title: actionTitle(to) + ": " + held.Action.Connector + " " + held.Action.Name,
Body: result,
})
}
func actionTitle(state string) string {
switch state {
case actionSucceeded:
return "Approved action ran"
case actionExpired:
return "Approval timed out"
case actionUnknown:
return "An action's outcome is unknown"
default:
return "Approved action didn't run"
}
}
+406
View File
@@ -0,0 +1,406 @@
package chat
import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
"github.com/samcharles93/archie-core/internal/platform/hub"
"github.com/samcharles93/archie-core/modules/chat/internal/store"
)
const (
sessionPage = 100
maxTextRunes = 32000
heartbeat = 15 * time.Second
)
// Register adds the chat API.
func (m *Module) Register(api huma.API) {
tags := []string{"Chat"}
huma.Register(api, huma.Operation{
OperationID: "list-chat-sessions", Method: http.MethodGet, Path: "/api/chat/sessions",
Summary: "List conversations, most recently active first, with the model that answers", Tags: tags,
}, m.listSessions)
huma.Register(api, huma.Operation{
OperationID: "create-chat-session", Method: http.MethodPost, Path: "/api/chat/sessions",
Summary: "Start a conversation", Tags: tags, DefaultStatus: http.StatusCreated,
}, m.createSession)
huma.Register(api, huma.Operation{
OperationID: "rename-chat-session", Method: http.MethodPatch, Path: "/api/chat/sessions/{id}",
Summary: "Rename a conversation", Tags: tags,
}, m.renameSession)
huma.Register(api, huma.Operation{
OperationID: "delete-chat-session", Method: http.MethodDelete, Path: "/api/chat/sessions/{id}",
Summary: "Delete a conversation and its turns", Tags: tags, DefaultStatus: http.StatusNoContent,
}, m.deleteSession)
huma.Register(api, huma.Operation{
OperationID: "list-chat-turns", Method: http.MethodGet, Path: "/api/chat/sessions/{id}/turns",
Summary: "List a conversation's turns with what each did", Tags: tags,
}, m.listTurns)
huma.Register(api, huma.Operation{
OperationID: "send-chat-turn", Method: http.MethodPost, Path: "/api/chat/sessions/{id}/turns",
Summary: "Send a message; it is stored, then answered after the turns before it", Tags: tags,
DefaultStatus: http.StatusAccepted,
}, m.sendTurn)
huma.Register(api, huma.Operation{
OperationID: "get-chat-turn", Method: http.MethodGet, Path: "/api/chat/turns/{id}",
Summary: "Get one turn with what it did", Tags: tags,
}, m.getTurn)
huma.Register(api, huma.Operation{
OperationID: "cancel-chat-turn", Method: http.MethodPost, Path: "/api/chat/turns/{id}/cancel",
Summary: "Stop a turn that is queued or running", Tags: tags,
}, m.cancelTurn)
huma.Register(api, huma.Operation{
OperationID: "stream-chat-turn", Method: http.MethodGet, Path: "/api/chat/turns/{id}/events",
Summary: "Stream what a turn records, from a cursor, until it ends", Tags: tags,
Responses: map[string]*huma.Response{"200": {
Description: "Server-sent events, one data frame per recorded event: {\"seq\", \"type\", ...}. " +
"Types are reasoning, delta, tool, navigate, approval, action, done, error and cancelled; " +
"the stream ends after done, error or cancelled.",
Content: map[string]*huma.MediaType{"text/event-stream": {Schema: &huma.Schema{Type: huma.TypeString}}},
}},
}, m.streamTurn)
}
// Sessions is the conversation list with the model that answers turns.
type Sessions struct {
Sessions []Session `json:"sessions"`
ActiveModel string `json:"active_model"`
ModelError string `json:"model_error,omitzero"`
}
func (m *Module) listSessions(ctx context.Context, _ *struct{}) (*httpapi.Reply[Sessions], error) {
rows, err := m.store.Sessions(ctx, m.orgID, sessionPage)
if err != nil {
m.log.ErrorContext(ctx, "list chat sessions", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't list conversations")
}
out := Sessions{Sessions: make([]Session, 0, len(rows))}
for _, r := range rows {
out.Sessions = append(out.Sessions, sessionOf(r))
}
if d, ok := m.uses(); ok {
if model, err := d.Settings.AgentModelForAlias(ctx, ""); err != nil {
out.ModelError = err.Error()
} else {
out.ActiveModel = model.Model
}
}
return httpapi.OK(out), nil
}
func (m *Module) createSession(ctx context.Context, _ *struct{}) (*httpapi.Reply[Session], error) {
s, err := m.store.CreateSession(ctx, m.orgID, uuid.New())
if err != nil {
m.log.ErrorContext(ctx, "create chat session", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't start a conversation")
}
return httpapi.OK(sessionOf(s)), nil
}
type idInput struct {
ID string `path:"id" format:"uuid"`
}
type renameInput struct {
ID string `path:"id" format:"uuid"`
Body struct {
Title string `json:"title" maxLength:"120"`
}
}
func (m *Module) renameSession(ctx context.Context, in *renameInput) (*httpapi.Reply[Session], error) {
id, err := uuid.Parse(in.ID)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, "id is a conversation id")
}
if err := m.store.Rename(ctx, m.orgID, id, strings.TrimSpace(in.Body.Title)); err != nil {
return nil, m.failed(ctx, err, "rename the conversation")
}
s, err := m.store.Session(ctx, m.orgID, id)
if err != nil {
return nil, m.failed(ctx, err, "read the conversation")
}
return httpapi.OK(sessionOf(s)), nil
}
func (m *Module) deleteSession(ctx context.Context, in *idInput) (*struct{}, error) {
id, err := uuid.Parse(in.ID)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, "id is a conversation id")
}
turns, err := m.store.Turns(ctx, m.orgID, id)
if err != nil {
return nil, m.failed(ctx, err, "read the conversation")
}
for _, t := range turns {
if !finished(t.State) {
return nil, huma.NewError(http.StatusConflict, "stop the conversation's turns before deleting it")
}
}
if err := m.store.DeleteSession(ctx, m.orgID, id); err != nil {
return nil, m.failed(ctx, err, "delete the conversation")
}
return nil, nil
}
func (m *Module) listTurns(ctx context.Context, in *idInput) (*httpapi.Reply[[]Turn], error) {
id, err := uuid.Parse(in.ID)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, "id is a conversation id")
}
if _, err := m.store.Session(ctx, m.orgID, id); err != nil {
return nil, m.failed(ctx, err, "read the conversation")
}
rows, err := m.store.Turns(ctx, m.orgID, id)
if err != nil {
return nil, m.failed(ctx, err, "list the conversation's turns")
}
events, err := m.store.EventsOf(ctx, id, []string{kindTool, kindNavigate, kindApproval, kindAction})
if err != nil {
return nil, m.failed(ctx, err, "list what the turns did")
}
byTurn := map[uuid.UUID][]store.Event{}
for _, e := range events {
byTurn[e.TurnID] = append(byTurn[e.TurnID], e)
}
out := make([]Turn, 0, len(rows))
for _, r := range rows {
out = append(out, turnOf(r, byTurn[r.ID]))
}
return httpapi.OK(out), nil
}
func (m *Module) getTurn(ctx context.Context, in *idInput) (*httpapi.Reply[Turn], error) {
id, err := uuid.Parse(in.ID)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, "id is a turn id")
}
t, err := m.store.Turn(ctx, m.orgID, id)
if err != nil {
return nil, m.failed(ctx, err, "read the turn")
}
events, err := m.store.Events(ctx, id, 0)
if err != nil {
return nil, m.failed(ctx, err, "read what the turn did")
}
return httpapi.OK(turnOf(t, events)), nil
}
// turnOf is a turn with what its recorded events say it did.
func turnOf(r store.Turn, events []store.Event) Turn {
t := Turn{
ID: r.ID, SessionID: r.SessionID, Seq: r.Seq, State: r.State, Text: r.Text, Page: r.Page, PageLabel: r.PageLabel,
Reply: r.Reply, Reasoning: r.Reasoning, Error: r.Error, CreatedAt: r.CreatedAt,
Tools: []ToolCall{}, Approvals: []Approval{}, Actions: []ActionDone{}, Navigate: []Navigation{},
}
if r.FinishedAt.Valid {
t.FinishedAt = &r.FinishedAt.Time
}
for _, e := range events {
var err error
switch e.Kind {
case kindTool:
var v ToolCall
if err = decodeData(e.Data, &v); err == nil {
t.Tools = append(t.Tools, v)
}
case kindNavigate:
var v Navigation
if err = decodeData(e.Data, &v); err == nil {
t.Navigate = append(t.Navigate, v)
}
case kindApproval:
var v Approval
if err = decodeData(e.Data, &v); err == nil {
t.Approvals = append(t.Approvals, v)
}
case kindAction:
var v ActionDone
if err = decodeData(e.Data, &v); err == nil {
t.Actions = append(t.Actions, v)
}
}
}
return t
}
type sendInput struct {
ID string `path:"id" format:"uuid"`
Body struct {
Text string `json:"text" minLength:"1"`
// Page is the dashboard path the operator asked from, and PageLabel
// the name the page goes by.
Page string `json:"page,omitempty" maxLength:"500"`
PageLabel string `json:"page_label,omitempty" maxLength:"200"`
}
}
func (m *Module) sendTurn(ctx context.Context, in *sendInput) (*httpapi.Reply[Turn], error) {
id, err := uuid.Parse(in.ID)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, "id is a conversation id")
}
text := strings.TrimSpace(in.Body.Text)
switch {
case text == "":
return nil, huma.NewError(http.StatusBadRequest, "a message needs text")
case utf8.RuneCountInString(text) > maxTextRunes:
return nil, huma.NewError(http.StatusBadRequest, fmt.Sprintf("a message is at most %d characters", maxTextRunes))
}
t, err := m.store.AddTurn(ctx, m.orgID, store.Turn{
ID: uuid.New(), SessionID: id, Text: text, Page: in.Body.Page, PageLabel: in.Body.PageLabel,
})
if err != nil {
return nil, m.failed(ctx, err, "send the message")
}
m.poke()
return httpapi.OK(turnOf(t, nil)), nil
}
func (m *Module) cancelTurn(ctx context.Context, in *idInput) (*httpapi.Reply[Turn], error) {
id, err := uuid.Parse(in.ID)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, "id is a turn id")
}
wasQueued, err := m.store.RequestCancel(ctx, m.orgID, id)
if err != nil {
return nil, m.failed(ctx, err, "stop the turn")
}
if wasQueued {
m.record(ctx, id, kindCancelled, map[string]any{"text": ""})
}
m.mu.Lock()
stop := m.running[id]
m.mu.Unlock()
if stop != nil {
stop()
}
t, err := m.store.Turn(ctx, m.orgID, id)
if err != nil {
return nil, m.failed(ctx, err, "read the turn")
}
return httpapi.OK(turnOf(t, nil)), nil
}
type streamInput struct {
ID string `path:"id" format:"uuid"`
After string `query:"after" doc:"Only events after this seq; every event by default"`
}
// streamTurn replays a turn's recorded events after the cursor, then follows
// new ones until the turn ends. A reader that reconnects passes its last seq
// and misses nothing.
func (m *Module) streamTurn(_ context.Context, in *streamInput) (*huma.StreamResponse, error) {
id, err := uuid.Parse(in.ID)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, "id is a turn id")
}
var after int64
if in.After != "" {
if after, err = strconv.ParseInt(in.After, 10, 64); err != nil || after < 0 {
return nil, huma.NewError(http.StatusBadRequest, "after is an event seq")
}
}
return &huma.StreamResponse{Body: func(hc huma.Context) { m.serveEvents(hc, id, after) }}, nil //nolint:contextcheck // a stream takes its context from the response it writes, which ends with the request
}
// serveEvents streams a turn's events to one reader.
func (m *Module) serveEvents(hc huma.Context, id uuid.UUID, after int64) {
ctx := hc.Context()
w := hc.BodyWriter()
flusher, ok := w.(http.Flusher)
if !ok {
hc.SetStatus(http.StatusInternalServerError)
return
}
switch _, err := m.store.Turn(ctx, m.orgID, id); {
case errors.Is(err, store.ErrNotFound):
hc.SetStatus(http.StatusNotFound)
return
case err != nil:
m.log.ErrorContext(ctx, "chat: read the turn", "error", err)
hc.SetStatus(http.StatusInternalServerError)
return
}
notes, stop := m.hub.Subscribe(topic(id))
defer stop()
hc.SetHeader("Content-Type", "text/event-stream")
hc.SetHeader("Cache-Control", "no-store")
hc.SetStatus(http.StatusOK)
flusher.Flush()
m.follow(ctx, id, after, notes, func(frame string) bool {
if _, err := fmt.Fprint(w, frame); err != nil {
return false
}
flusher.Flush()
return true
})
}
// follow writes a turn's events after the cursor until the turn ends, the
// reader leaves or a write fails.
func (m *Module) follow(ctx context.Context, id uuid.UUID, after int64, notes <-chan hub.Note, write func(string) bool) {
tick := time.NewTicker(heartbeat)
defer tick.Stop()
for {
events, err := m.store.Events(ctx, id, after)
if err != nil {
if ctx.Err() == nil {
m.log.ErrorContext(ctx, "read chat events", "turn", id, "error", err)
}
return
}
for _, e := range events {
after = e.Seq
if !write(frame(e)) {
return
}
if e.Kind == kindDone || e.Kind == kindError || e.Kind == kindCancelled {
return
}
}
select {
case <-ctx.Done():
return
case _, ok := <-notes:
if !ok {
return
}
case <-tick.C:
if !write(": keepalive\n\n") {
return
}
}
}
}
// frame is one event as a server-sent event: its data with its seq and type.
func frame(e store.Event) string {
data := strings.TrimSpace(string(e.Data))
head := fmt.Sprintf(`{"seq":%d,"type":%q`, e.Seq, e.Kind)
if data != "{}" && strings.HasPrefix(data, "{") {
head += "," + data[1:]
} else {
head += "}"
}
return "id: " + strconv.FormatInt(e.Seq, 10) + "\ndata: " + head + "\n\n"
}
func (m *Module) failed(ctx context.Context, err error, what string) error {
if errors.Is(err, store.ErrNotFound) {
return huma.NewError(http.StatusNotFound, "not found")
}
m.log.ErrorContext(ctx, "chat: "+what, "error", err)
return huma.NewError(http.StatusInternalServerError, "couldn't "+what)
}
+227
View File
@@ -0,0 +1,227 @@
// 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"
+394
View File
@@ -0,0 +1,394 @@
// Package store holds the chat module's SQL: conversations, their turns, what
// each turn streamed, and the actions its agent proposed.
package store
import (
"context"
"database/sql"
"encoding/json/jsontext"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
)
// ErrNotFound means there is no such session, turn or action.
var ErrNotFound = errors.New("not found")
// Session is one conversation.
type Session struct {
ID uuid.UUID `db:"id"`
Title string `db:"title"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
}
// Turn is one operator message and the reply to it.
type Turn struct {
Seq int64 `db:"seq"`
ID uuid.UUID `db:"id"`
SessionID uuid.UUID `db:"session_id"`
State string `db:"state"`
Text string `db:"text"`
Page string `db:"page"`
PageLabel string `db:"page_label"`
Reply string `db:"reply"`
Reasoning string `db:"reasoning"`
Error string `db:"error"`
Cancel bool `db:"cancel"`
CreatedAt time.Time `db:"created_at"`
StartedAt sql.NullTime `db:"started_at"`
FinishedAt sql.NullTime `db:"finished_at"`
}
// Event is one thing a turn streamed.
type Event struct {
Seq int64 `db:"seq"`
TurnID uuid.UUID `db:"turn_id"`
Kind string `db:"kind"`
Data jsontext.Value `db:"data"`
CreatedAt time.Time `db:"created_at"`
}
// Action is an action judgement held for approval.
type Action struct {
ID uuid.UUID `db:"id"`
TurnID uuid.UUID `db:"turn_id"`
Key string `db:"key"`
Decision jsontext.Value `db:"decision"`
RequestID uuid.UUID `db:"request_id"`
Path jsontext.Value `db:"path"`
Step int `db:"step"`
StepDue time.Time `db:"step_due"`
State string `db:"state"`
Answer []byte `db:"answer"`
Result string `db:"result"`
}
// Store is the chat module's Postgres store.
type Store struct {
db *sqlx.DB
}
// New returns a store on db.
func New(db *sqlx.DB) *Store { return &Store{db: db} }
const turnColumns = `seq, id, session_id, state, text, page, page_label, reply, reasoning, error, cancel, created_at, started_at, finished_at`
// CreateSession stores a new conversation.
func (s *Store) CreateSession(ctx context.Context, orgID string, id uuid.UUID) (Session, error) {
var out Session
if err := s.db.GetContext(ctx, &out, `
INSERT INTO chat.sessions (id, org_id) VALUES ($1, $2)
RETURNING id, title, created_at, updated_at`, id, orgID); err != nil {
return Session{}, fmt.Errorf("create session: %w", err)
}
return out, nil
}
// Sessions lists the conversations, most recently active first.
func (s *Store) Sessions(ctx context.Context, orgID string, limit int) ([]Session, error) {
var out []Session
if err := s.db.SelectContext(ctx, &out, `
SELECT id, title, created_at, updated_at FROM chat.sessions
WHERE org_id = $1 ORDER BY updated_at DESC LIMIT $2`, orgID, limit); err != nil {
return nil, fmt.Errorf("list sessions: %w", err)
}
return out, nil
}
// Session returns one conversation.
func (s *Store) Session(ctx context.Context, orgID string, id uuid.UUID) (Session, error) {
var out Session
err := s.db.GetContext(ctx, &out, `
SELECT id, title, created_at, updated_at FROM chat.sessions WHERE org_id = $1 AND id = $2`, orgID, id)
if errors.Is(err, sql.ErrNoRows) {
return Session{}, ErrNotFound
}
if err != nil {
return Session{}, fmt.Errorf("read session: %w", err)
}
return out, nil
}
// Rename sets a conversation's title.
func (s *Store) Rename(ctx context.Context, orgID string, id uuid.UUID, title string) error {
res, err := s.db.ExecContext(ctx, `UPDATE chat.sessions SET title = $3 WHERE org_id = $1 AND id = $2`, orgID, id, title)
return affected(res, err, "rename session")
}
// TitleIfUntitled sets a title only on a conversation that has none, so a
// generated title never replaces one the operator chose.
func (s *Store) TitleIfUntitled(ctx context.Context, orgID string, id uuid.UUID, title string) error {
if _, err := s.db.ExecContext(ctx, `
UPDATE chat.sessions SET title = $3 WHERE org_id = $1 AND id = $2 AND title = ''`, orgID, id, title); err != nil {
return fmt.Errorf("title session: %w", err)
}
return nil
}
// DeleteSession removes a conversation with its turns.
func (s *Store) DeleteSession(ctx context.Context, orgID string, id uuid.UUID) error {
res, err := s.db.ExecContext(ctx, `DELETE FROM chat.sessions WHERE org_id = $1 AND id = $2`, orgID, id)
return affected(res, err, "delete session")
}
// AddTurn stores a turn as queued and marks its conversation active.
func (s *Store) AddTurn(ctx context.Context, orgID string, t Turn) (Turn, error) {
tx, err := s.db.BeginTxx(ctx, nil)
if err != nil {
return Turn{}, fmt.Errorf("begin: %w", err)
}
defer func() { _ = tx.Rollback() }()
res, err := tx.ExecContext(ctx, `UPDATE chat.sessions SET updated_at = now() WHERE org_id = $1 AND id = $2`, orgID, t.SessionID)
if err := affected(res, err, "touch session"); err != nil {
return Turn{}, err
}
var out Turn
if err := tx.GetContext(ctx, &out, `
INSERT INTO chat.turns (id, org_id, session_id, state, text, page, page_label)
VALUES ($1, $2, $3, 'queued', $4, $5, $6)
RETURNING `+turnColumns, t.ID, orgID, t.SessionID, t.Text, t.Page, t.PageLabel); err != nil {
return Turn{}, fmt.Errorf("add turn: %w", err)
}
if err := tx.Commit(); err != nil {
return Turn{}, fmt.Errorf("commit turn: %w", err)
}
return out, nil
}
// Turns returns a conversation's turns, oldest first.
func (s *Store) Turns(ctx context.Context, orgID string, sessionID uuid.UUID) ([]Turn, error) {
var out []Turn
if err := s.db.SelectContext(ctx, &out, `
SELECT `+turnColumns+` FROM chat.turns WHERE org_id = $1 AND session_id = $2 ORDER BY seq`, orgID, sessionID); err != nil {
return nil, fmt.Errorf("list turns: %w", err)
}
return out, nil
}
// Turn returns one turn.
func (s *Store) Turn(ctx context.Context, orgID string, id uuid.UUID) (Turn, error) {
var out Turn
err := s.db.GetContext(ctx, &out, `SELECT `+turnColumns+` FROM chat.turns WHERE org_id = $1 AND id = $2`, orgID, id)
if errors.Is(err, sql.ErrNoRows) {
return Turn{}, ErrNotFound
}
if err != nil {
return Turn{}, fmt.Errorf("read turn: %w", err)
}
return out, nil
}
// IsTurn reports whether id is a chat turn.
func (s *Store) IsTurn(ctx context.Context, id uuid.UUID) (bool, error) {
var ok bool
if err := s.db.GetContext(ctx, &ok, `SELECT EXISTS (SELECT 1 FROM chat.turns WHERE id = $1)`, id); err != nil {
return false, fmt.Errorf("find turn: %w", err)
}
return ok, nil
}
// Claim starts the oldest queued turn of a conversation with no turn running,
// so a conversation's turns run one at a time in the order they were sent.
func (s *Store) Claim(ctx context.Context) (Turn, bool, error) {
var out Turn
err := s.db.GetContext(ctx, &out, `
UPDATE chat.turns SET state = 'running', started_at = now()
WHERE id = (
SELECT t.id FROM chat.turns t
WHERE t.state = 'queued' AND NOT t.cancel AND NOT EXISTS (
SELECT 1 FROM chat.turns r WHERE r.session_id = t.session_id AND r.state = 'running')
AND NOT EXISTS (
SELECT 1 FROM chat.turns q WHERE q.session_id = t.session_id AND q.state = 'queued' AND q.seq < t.seq)
ORDER BY t.seq LIMIT 1 FOR UPDATE SKIP LOCKED)
RETURNING `+turnColumns)
if errors.Is(err, sql.ErrNoRows) {
return Turn{}, false, nil
}
if err != nil {
return Turn{}, false, fmt.Errorf("claim turn: %w", err)
}
return out, true, nil
}
// Finish ends a running turn with its outcome.
func (s *Store) Finish(ctx context.Context, id uuid.UUID, state, reply, reasoning, failure string) error {
if _, err := s.db.ExecContext(ctx, `
UPDATE chat.turns SET state = $2, reply = $3, reasoning = $4, error = $5, finished_at = now()
WHERE id = $1 AND state IN ('queued', 'running')`, id, state, reply, reasoning, failure); err != nil {
return fmt.Errorf("finish turn: %w", err)
}
return nil
}
// RequestCancel asks a turn to stop. A queued turn is cancelled at once and
// reported true; a running one stops when its worker sees the request.
func (s *Store) RequestCancel(ctx context.Context, orgID string, id uuid.UUID) (bool, error) {
var state string
err := s.db.GetContext(ctx, &state, `
UPDATE chat.turns SET cancel = true,
state = CASE WHEN state = 'queued' THEN 'cancelled' ELSE state END,
finished_at = CASE WHEN state = 'queued' THEN now() ELSE finished_at END
WHERE org_id = $1 AND id = $2 RETURNING state`, orgID, id)
if errors.Is(err, sql.ErrNoRows) {
return false, ErrNotFound
}
if err != nil {
return false, fmt.Errorf("cancel turn: %w", err)
}
return state == "cancelled", nil
}
// Interrupted fails every turn left running by a process that stopped, and
// returns them.
func (s *Store) Interrupted(ctx context.Context, reason string) ([]uuid.UUID, error) {
var out []uuid.UUID
if err := s.db.SelectContext(ctx, &out, `
UPDATE chat.turns SET state = 'failed', error = $1, finished_at = now()
WHERE state = 'running' RETURNING id`, reason); err != nil {
return nil, fmt.Errorf("fail interrupted turns: %w", err)
}
return out, nil
}
// History returns a conversation's finished turns before the turn seq, oldest
// first, at most limit of them.
func (s *Store) History(ctx context.Context, sessionID uuid.UUID, before int64, limit int) ([]Turn, error) {
var out []Turn
if err := s.db.SelectContext(ctx, &out, `
SELECT * FROM (
SELECT `+turnColumns+` FROM chat.turns
WHERE session_id = $1 AND seq < $2 AND state IN ('succeeded', 'failed', 'cancelled')
ORDER BY seq DESC LIMIT $3) recent
ORDER BY seq`, sessionID, before, limit); err != nil {
return nil, fmt.Errorf("read history: %w", err)
}
return out, nil
}
// AddEvent records what a turn streamed and returns its position.
func (s *Store) AddEvent(ctx context.Context, turnID uuid.UUID, kind string, data jsontext.Value) (int64, error) {
var seq int64
if err := s.db.GetContext(ctx, &seq, `
INSERT INTO chat.events (turn_id, kind, data) VALUES ($1, $2, $3) RETURNING seq`, turnID, kind, data); err != nil {
return 0, fmt.Errorf("record event: %w", err)
}
return seq, nil
}
// Events returns a turn's events after seq, oldest first.
func (s *Store) Events(ctx context.Context, turnID uuid.UUID, after int64) ([]Event, error) {
var out []Event
if err := s.db.SelectContext(ctx, &out, `
SELECT seq, turn_id, kind, data, created_at FROM chat.events
WHERE turn_id = $1 AND seq > $2 ORDER BY seq`, turnID, after); err != nil {
return nil, fmt.Errorf("list events: %w", err)
}
return out, nil
}
// EventsOf returns the events of the kinds given for a conversation's turns,
// oldest first.
func (s *Store) EventsOf(ctx context.Context, sessionID uuid.UUID, kinds []string) ([]Event, error) {
query, args, err := sqlx.In(`
SELECT e.seq, e.turn_id, e.kind, e.data, e.created_at FROM chat.events e
JOIN chat.turns t ON t.id = e.turn_id
WHERE t.session_id = ? AND e.kind IN (?) ORDER BY e.seq`, sessionID, kinds)
if err != nil {
return nil, err
}
var out []Event
if err := s.db.SelectContext(ctx, &out, s.db.Rebind(query), args...); err != nil {
return nil, fmt.Errorf("list session events: %w", err)
}
return out, nil
}
// PutAction stores an action held for approval unless the turn already has
// one under its key, and returns the stored one either way.
func (s *Store) PutAction(ctx context.Context, orgID string, a Action) (Action, error) {
if _, err := s.db.ExecContext(ctx, `
INSERT INTO chat.actions (id, org_id, turn_id, key, decision, request_id, path, step_due, state)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'waiting')
ON CONFLICT (turn_id, key) DO NOTHING`,
a.ID, orgID, a.TurnID, a.Key, a.Decision, a.RequestID, a.Path, a.StepDue); err != nil {
return Action{}, fmt.Errorf("record held action: %w", err)
}
return s.actionBy(ctx, `turn_id = $1 AND key = $2`, a.TurnID, a.Key)
}
const actionColumns = `id, turn_id, key, decision, request_id, path, step, step_due, state, answer, result`
func (s *Store) actionBy(ctx context.Context, where string, args ...any) (Action, error) {
var out Action
err := s.db.GetContext(ctx, &out, `SELECT `+actionColumns+` FROM chat.actions WHERE `+where, args...)
if errors.Is(err, sql.ErrNoRows) {
return Action{}, ErrNotFound
}
if err != nil {
return Action{}, fmt.Errorf("read action: %w", err)
}
return out, nil
}
// Answer records the answer to a waiting action under its turn and key, and
// reports whether it was waiting.
func (s *Store) Answer(ctx context.Context, turnID uuid.UUID, key, state string, answer []byte) (bool, error) {
res, err := s.db.ExecContext(ctx, `
UPDATE chat.actions SET state = $3, answer = $4 WHERE turn_id = $1 AND key = $2 AND state = 'waiting'`,
turnID, key, state, answer)
if err != nil {
return false, fmt.Errorf("answer action: %w", err)
}
n, err := res.RowsAffected()
return n > 0, err
}
// Open returns the actions still to settle: waiting for an answer, approved
// and not yet started, or started.
func (s *Store) Open(ctx context.Context) ([]Action, error) {
var out []Action
if err := s.db.SelectContext(ctx, &out, `
SELECT `+actionColumns+` FROM chat.actions WHERE state IN ('waiting', 'approved', 'running') ORDER BY created_at`); err != nil {
return nil, fmt.Errorf("list open actions: %w", err)
}
return out, nil
}
// Move changes an action from one state to another and reports whether it was
// in the first.
func (s *Store) Move(ctx context.Context, id uuid.UUID, from, to, result string) (bool, error) {
res, err := s.db.ExecContext(ctx, `
UPDATE chat.actions SET state = $3, result = $4 WHERE id = $1 AND state = $2`, id, from, to, result)
if err != nil {
return false, fmt.Errorf("move action: %w", err)
}
n, err := res.RowsAffected()
return n > 0, err
}
// Escalated records that a waiting action moved to the next step of its path.
func (s *Store) Escalated(ctx context.Context, id uuid.UUID, step int, due time.Time) error {
if _, err := s.db.ExecContext(ctx, `
UPDATE chat.actions SET step = $2, step_due = $3 WHERE id = $1 AND state = 'waiting'`, id, step, due); err != nil {
return fmt.Errorf("escalate action: %w", err)
}
return nil
}
func affected(res sql.Result, err error, what string) error {
if err != nil {
return fmt.Errorf("%s: %w", what, err)
}
n, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("%s: %w", what, err)
}
if n == 0 {
return ErrNotFound
}
return nil
}
+72
View File
@@ -0,0 +1,72 @@
package chat
import (
"encoding/json"
"strings"
"github.com/samcharles93/archie-core/internal/webhookguard"
)
const (
parametersMaxRunes = 2000
outputMaxRunes = 16000
redactedParameterValue = "[redacted]"
)
// summarizeParameters returns a bounded JSON shape of a tool's input with the
// values of credential-like keys redacted, for the transcript.
func summarizeParameters(input string) string {
if strings.TrimSpace(input) == "" {
return ""
}
decoder := json.NewDecoder(strings.NewReader(input))
decoder.UseNumber()
var value any
if err := decoder.Decode(&value); err != nil {
return "[unavailable]"
}
value = redactParameters(value, false)
encoded, err := json.Marshal(value)
if err != nil {
return "[unavailable]"
}
return truncateRunes(string(encoded), parametersMaxRunes)
}
func redactParameters(value any, sensitive bool) any {
if sensitive {
return redactedParameterValue
}
switch typed := value.(type) {
case map[string]any:
for key, child := range typed {
typed[key] = redactParameters(child, sensitiveKey(key))
}
return typed
case []any:
for i, child := range typed {
typed[i] = redactParameters(child, sensitive)
}
return typed
default:
return value
}
}
func sensitiveKey(key string) bool {
normalized := strings.NewReplacer("-", "_", " ", "_").Replace(strings.ToLower(key))
for _, marker := range webhookguard.SensitiveKeyMarkers {
if strings.Contains(normalized, marker) {
return true
}
}
return false
}
func truncateRunes(s string, limit int) string {
runes := []rune(s)
if len(runes) <= limit {
return s
}
return string(runes[:limit-1]) + "…"
}
+263
View File
@@ -0,0 +1,263 @@
package chat
import (
"context"
"encoding/json"
"encoding/json/jsontext"
"errors"
"fmt"
"regexp"
"slices"
"strings"
"github.com/google/uuid"
"github.com/samcharles93/ai-sdk/core"
"github.com/samcharles93/archie-core/internal/platform/prompts"
"github.com/samcharles93/archie-core/modules/chat/internal/store"
"github.com/samcharles93/archie-core/modules/connectors"
"github.com/samcharles93/archie-core/modules/judgement"
)
// principal is who hard rules see acting when the chat agent calls an action.
const principal = "chat"
// unsafeToolChars are those a model API refuses in a tool name.
var unsafeToolChars = regexp.MustCompile(`[^a-zA-Z0-9_-]`)
func toolName(connector, name string) string {
return unsafeToolChars.ReplaceAllString(connector+"_"+name, "_")
}
// tools is what the agent may call on turn t: every connector lookup, action
// and MCP tool a run may call, and the dashboard's own reads.
func (m *Module) tools(d Deps, t store.Turn) core.ToolSet {
set := core.ToolSet{}
for _, decl := range d.Toolbox.Declarations() {
name := toolName(decl.Connector, decl.Name)
set[name] = &core.Tool{
Name: name, Description: decl.Description, Parameters: []byte(decl.Schema),
Execute: func(ctx context.Context, input string) (string, error) {
return m.call(ctx, d, t, decl, jsontext.Value(input))
},
}
}
for _, tool := range m.builtins(d, t) {
set[tool.Name] = tool
}
return set
}
func toolSummaries(set core.ToolSet) []prompts.ChatTool {
out := make([]prompts.ChatTool, 0, len(set))
for _, t := range set {
out = append(out, prompts.ChatTool{Name: t.Name, Description: t.Description})
}
slices.SortFunc(out, func(a, b prompts.ChatTool) int { return strings.Compare(a.Name, b.Name) })
return out
}
// call runs a lookup, or judges an action and runs it only as decided. An
// action judgement holds is put to people and comes back to the agent as
// waiting for approval rather than as a failure.
func (m *Module) call(ctx context.Context, d Deps, t store.Turn, decl connectors.Declaration, input jsontext.Value) (string, error) {
tool, ok := d.Toolbox.Tool(decl.Connector)
if !ok {
return "", fmt.Errorf("%q isn't running", decl.Connector)
}
if decl.Kind == connectors.KindLookup {
out, found, err := tool.Lookup(ctx, decl.Name, input)
switch {
case err != nil:
return "", err
case !found:
return "not found", nil
}
return out, nil
}
key := uuid.NewString()
decision, err := d.Judge.Assess(ctx, judgement.Request{
RunID: t.ID, Key: key, Connector: decl.Connector, Action: decl.Name, Input: input, Workflow: principal,
})
if err != nil {
return "", err
}
out, err := d.Judge.Execute(ctx, decision, input, key)
switch {
case errors.Is(err, judgement.ErrHeld):
return m.hold(ctx, d, t, decision)
case errors.Is(err, connectors.ErrOutcomeUnknown):
return "", fmt.Errorf("the action was started and its outcome is unknown; it may have taken effect, so don't run it again: %w", err)
case err != nil:
return "", err
}
return out, nil
}
// hold puts an action judgement held to the first step of its escalation
// path and shows the request in the conversation.
func (m *Module) hold(ctx context.Context, d Deps, t store.Turn, decision judgement.Decision) (string, error) {
path, err := d.Settings.EscalationPath(ctx, decision.Owner(), decision.Level == judgement.Escalate)
if err != nil {
return "", fmt.Errorf("find who approves %s %s: %w", decision.Action.Connector, decision.Action.Name, err)
}
key := waitKey(decision.Key)
request, err := d.Approver.Ask(ctx, t.ID, key, decision, path)
if err != nil {
return "", fmt.Errorf("ask for approval: %w", err)
}
rawDecision, err := json.Marshal(decision)
if err != nil {
return "", err
}
rawPath, err := json.Marshal(path)
if err != nil {
return "", err
}
if _, err := m.store.PutAction(ctx, m.orgID, store.Action{
ID: uuid.New(), TurnID: t.ID, Key: key, Decision: rawDecision, RequestID: request.ID,
Path: rawPath, StepDue: request.StepDeadline,
}); err != nil {
return "", err
}
m.record(ctx, t.ID, kindApproval, Approval{
RequestID: request.ID, Action: decision.Action.Connector + " " + decision.Action.Name,
Summary: request.Summary, Level: decision.Level.String(), Deadline: request.StepDeadline,
})
return fmt.Sprintf("held at %s for approval and not run: %s. The operator answers on the approval card in this conversation; don't call it again.",
decision.Level, heldBecause(decision)), nil
}
// heldBecause lists what held a decision back, for the agent.
func heldBecause(d judgement.Decision) string {
var parts []string
for _, v := range d.Verdicts {
if v.Advisory || v.Ceiling != d.Level {
continue
}
for _, f := range v.Findings {
parts = append(parts, v.Guard+": "+f.Text)
}
}
if len(parts) == 0 {
return "no guard allowed it to run unattended"
}
return strings.Join(parts, "; ")
}
// waitKey is the key an approval answer comes back under.
func waitKey(key string) string { return "approval:" + key }
// builtins are the dashboard reads the agent may make: runs, pending
// approvals, what it remembers, and opening a page for the operator.
func (m *Module) builtins(d Deps, t store.Turn) []*core.Tool {
return []*core.Tool{
typedTool("run_list", "List the most recent workflow runs, newest first, with their state and error.",
`{"type":"object","properties":{"limit":{"type":"integer","minimum":1,"maximum":100}}}`,
func(ctx context.Context, in struct {
Limit int `json:"limit"`
},
) (any, error) {
if in.Limit <= 0 || in.Limit > 100 {
in.Limit = 20
}
return d.Runs.Recent(ctx, m.orgID, in.Limit)
}),
typedTool("run_get", "Read one workflow run with its result.",
`{"type":"object","properties":{"id":{"type":"string","format":"uuid"}},"required":["id"]}`,
func(ctx context.Context, in struct {
ID uuid.UUID `json:"id"`
},
) (any, error) {
run, ok, err := d.Runs.Run(ctx, m.orgID, in.ID)
if err != nil || !ok {
return "no such run", err
}
return run, nil
}),
typedTool("approval_list", "List the approval requests waiting for an answer.", `{"type":"object","properties":{}}`,
func(ctx context.Context, _ struct{}) (any, error) {
pending, err := d.Approver.Pending(ctx)
views := make([]any, 0, len(pending))
for _, p := range pending {
views = append(views, p.View())
}
return views, err
}),
typedTool("memory_list", "List the facts you remember across conversations, with their ids.", `{"type":"object","properties":{}}`,
func(ctx context.Context, _ struct{}) (any, error) { return d.Memory.Notes(ctx) }),
typedTool("memory_save", "Remember a durable fact the operator told you, for later conversations. One fact per call, in a sentence.",
`{"type":"object","properties":{"text":{"type":"string"}},"required":["text"]}`,
func(ctx context.Context, in struct {
Text string `json:"text"`
},
) (any, error) {
n, err := d.Memory.Remember(ctx, in.Text)
return "remembered as " + n.ID.String(), err
}),
typedTool("memory_forget", "Forget a remembered fact by its id.",
`{"type":"object","properties":{"id":{"type":"string","format":"uuid"}},"required":["id"]}`,
func(ctx context.Context, in struct {
ID uuid.UUID `json:"id"`
},
) (any, error) {
ok, err := d.Memory.Forget(ctx, in.ID)
if !ok {
return "nothing is remembered under that id", err
}
return "forgotten", err
}),
typedTool("dashboard_navigate", "Offer the operator a link to a dashboard page, such as /runs/ID or /classes.",
`{"type":"object","properties":{"path":{"type":"string"},"label":{"type":"string"}},"required":["path"]}`,
func(ctx context.Context, in Navigation) (any, error) {
if !dashboardPath(in.Path) {
return nil, fmt.Errorf("%q isn't a dashboard page", in.Path)
}
if in.Label == "" {
in.Label = in.Path
}
m.record(ctx, t.ID, kindNavigate, in)
return "offered the operator a link to " + in.Path, nil
}),
}
}
// typedTool is a tool whose input decodes into In and whose result is text,
// or JSON when it isn't a string.
func typedTool[In any](name, description, schema string, run func(context.Context, In) (any, error)) *core.Tool {
return core.NewTool(name, description, jsontext.Value(schema), func(ctx context.Context, input string) (string, error) {
var in In
if strings.TrimSpace(input) != "" {
if err := json.Unmarshal([]byte(input), &in); err != nil {
return "", fmt.Errorf("read the input: %w", err)
}
}
out, err := run(ctx, in)
if err != nil {
return "", err
}
if text, ok := out.(string); ok {
return text, nil
}
raw, err := json.Marshal(out)
return string(raw), err
})
}
// dashboardPages are the dashboard's top-level pages.
var dashboardPages = []string{
"composer", "runs", "unmatched", "events", "classes", "people", "controls",
"extensions", "sources", "triggers", "credentials", "settings",
}
var pageID = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:-]*$`)
// dashboardPath accepts a top-level page or one item under it, and nothing
// that could leave the dashboard.
func dashboardPath(path string) bool {
parts := strings.Split(strings.TrimPrefix(path, "/"), "/")
if !strings.HasPrefix(path, "/") || len(parts) > 2 || !slices.Contains(dashboardPages, parts[0]) {
return false
}
return len(parts) == 1 || pageID.MatchString(parts[1])
}
+26
View File
@@ -0,0 +1,26 @@
package chat
import "testing"
// TestDashboardPathStaysInTheDashboard guards the link the agent can offer
// the operator: it must never lead off the dashboard or outside its pages.
func TestDashboardPathStaysInTheDashboard(t *testing.T) {
cases := map[string]bool{
"/runs": true,
"/runs/0b8f6c1e-4a7e-4f6d": true,
"/classes/github:merge_pr": true,
"//evil.example/runs": false,
"https://evil.example/runs": false,
"javascript:alert(1)": false,
"/runs/../settings": false,
"/runs/a/b": false,
"/runs/..": false,
"/admin": false,
"runs": false,
}
for path, want := range cases {
if got := dashboardPath(path); got != want {
t.Errorf("dashboardPath(%q) = %v, want %v", path, got, want)
}
}
}
+387
View File
@@ -0,0 +1,387 @@
package chat
import (
"context"
"encoding/json"
"encoding/json/jsontext"
"errors"
"fmt"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
"github.com/samcharles93/ai-sdk/chat"
"github.com/samcharles93/ai-sdk/core"
"github.com/samcharles93/archie-core/internal/platform/hub"
"github.com/samcharles93/archie-core/internal/platform/prompts"
"github.com/samcharles93/archie-core/modules/chat/internal/store"
)
const (
// maxConcurrentTurns bounds the conversations answered at once.
maxConcurrentTurns = 4
// historyTurns is how many earlier turns a turn's model sees.
historyTurns = 20
// maxSteps bounds the model calls one turn makes.
maxSteps = 16
// turnTimeout ends a turn that never finishes.
turnTimeout = 10 * time.Minute
// flushEvery is how often streamed text is recorded while it arrives.
flushEvery = 150 * time.Millisecond
poll = 2 * time.Second
)
// Work answers queued turns and settles held actions until ctx ends. Turns a
// stopped process left running are failed first, visibly, since the reply they
// were streaming is gone.
func (m *Module) Work(ctx context.Context) {
m.recover(ctx)
slots := make(chan struct{}, maxConcurrentTurns)
tick := time.NewTicker(poll)
defer tick.Stop()
for {
m.settleActions(ctx)
m.startTurns(ctx, slots)
select {
case <-ctx.Done():
// Wait for the turns in flight to record how they ended.
for range maxConcurrentTurns {
slots <- struct{}{}
}
return
case <-m.wake:
case <-tick.C:
}
}
}
// startTurns starts queued turns while there are free slots.
func (m *Module) startTurns(ctx context.Context, slots chan struct{}) {
for {
select {
case slots <- struct{}{}:
default:
return
}
t, ok, err := m.store.Claim(ctx)
if err != nil || !ok {
<-slots
if err != nil && ctx.Err() == nil {
m.log.ErrorContext(ctx, "claim chat turn", "error", err)
}
return
}
go func() {
defer func() { <-slots; m.poke() }()
m.answer(ctx, t)
}()
}
}
func (m *Module) poke() {
select {
case m.wake <- struct{}{}:
default:
}
}
func (m *Module) recover(ctx context.Context) {
const reason = "Archie restarted before this turn finished. Send it again."
ids, err := m.store.Interrupted(ctx, reason)
if err != nil {
m.log.ErrorContext(ctx, "fail interrupted chat turns", "error", err)
return
}
for _, id := range ids {
m.record(ctx, id, kindError, map[string]any{"text": reason})
}
}
// record stores one streamed event and tells the turn's live readers.
func (m *Module) record(ctx context.Context, turnID uuid.UUID, kind string, data any) {
raw, err := json.Marshal(data)
if err != nil {
m.log.ErrorContext(ctx, "encode chat event", "turn", turnID, "kind", kind, "error", err)
return
}
seq, err := m.store.AddEvent(context.WithoutCancel(ctx), turnID, kind, raw)
if err != nil {
m.log.ErrorContext(ctx, "record chat event", "turn", turnID, "kind", kind, "error", err)
return
}
m.hub.Publish(hub.Note{Topic: topic(turnID), Seq: seq})
}
// answer runs one turn to its end and records how it ended.
func (m *Module) answer(parent context.Context, t store.Turn) {
ctx, cancel := context.WithTimeout(parent, turnTimeout)
defer cancel()
m.mu.Lock()
m.running[t.ID] = cancel
m.mu.Unlock()
defer func() {
m.mu.Lock()
delete(m.running, t.ID)
m.mu.Unlock()
}()
reply, reasoning, err := m.generate(ctx, t)
done := context.WithoutCancel(ctx)
cur, rerr := m.store.Turn(done, m.orgID, t.ID)
stopped := rerr == nil && cur.Cancel
switch {
case stopped:
m.finish(done, t.ID, stateCancelled, reply, reasoning, "")
m.record(done, t.ID, kindCancelled, map[string]any{"text": reply})
case err != nil:
msg := failure(ctx, err)
if parent.Err() != nil {
msg = "Archie stopped before this turn finished. Send it again."
}
m.log.ErrorContext(done, "chat turn failed", "turn", t.ID, "error", err)
m.finish(done, t.ID, stateFailed, reply, reasoning, msg)
m.record(done, t.ID, kindError, map[string]any{"text": msg})
default:
m.finish(done, t.ID, stateSucceeded, reply, reasoning, "")
m.record(done, t.ID, kindDone, map[string]any{"text": reply})
m.title(done, t, reply)
}
}
func (m *Module) finish(ctx context.Context, id uuid.UUID, state, reply, reasoning, failure string) {
if err := m.store.Finish(ctx, id, state, reply, reasoning, failure); err != nil {
m.log.ErrorContext(ctx, "finish chat turn", "turn", id, "error", err)
}
}
// failure is what the operator is told about a failed turn.
func failure(ctx context.Context, err error) string {
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
return fmt.Sprintf("The turn ran for %s without finishing and was stopped.", turnTimeout)
}
return err.Error()
}
// generate streams the model's answer to t, recording every part as it comes,
// and returns the reply and the thinking behind it.
func (m *Module) generate(ctx context.Context, t store.Turn) (string, string, error) {
d, ok := m.uses()
if !ok {
return "", "", errors.New("chat isn't ready yet")
}
model, err := d.Settings.AgentModelForAlias(ctx, "")
if err != nil {
return "", "", fmt.Errorf("no agent model is configured: %w", err)
}
provider, info, err := d.Settings.AgentProvider(ctx, model)
if err != nil {
return "", "", fmt.Errorf("agent model %s: %w", model.Model, err)
}
history, err := m.store.History(ctx, t.SessionID, t.Seq, historyTurns)
if err != nil {
return "", "", err
}
tools := m.tools(d, t)
system := prompts.ChatSystem(prompts.ChatContext{
Tools: toolSummaries(tools), Channel: "dashboard", Page: page(t), Model: model.Model,
SessionID: t.SessionID.String(), Memory: m.memoryBlock(ctx, d), Now: time.Now(),
})
stream, err := core.StreamText(ctx, provider, core.GenerateOptions{
Model: model.Model, ModelInfo: info, System: system, Messages: conversation(history, t),
Tools: tools, MaxSteps: maxSteps,
})
if err != nil {
return "", "", fmt.Errorf("start the reply: %w", err)
}
reply, reasoning, streamErr := m.drain(ctx, t.ID, stream.FullStream)
if _, err := stream.FinishReason(); err != nil && streamErr == nil {
streamErr = err
}
return reply, reasoning, streamErr
}
func page(t store.Turn) string {
switch {
case t.PageLabel != "" && t.Page != "":
return t.PageLabel + " (" + t.Page + ")"
default:
return t.Page
}
}
// conversation is the turns before t and t itself, as model messages.
func conversation(history []store.Turn, t store.Turn) []chat.Message {
out := make([]chat.Message, 0, 2*len(history)+1)
for _, h := range history {
out = append(out, chat.Message{Role: chat.RoleUser, Content: h.Text})
reply := h.Reply
switch {
case h.State == stateFailed && reply == "":
reply = "(this turn failed: " + h.Error + ")"
case h.State == stateCancelled && reply == "":
reply = "(the operator stopped this turn before a reply)"
}
if reply != "" {
out = append(out, chat.Message{Role: chat.RoleAssistant, Content: reply})
}
}
return append(out, chat.Message{Role: chat.RoleUser, Content: t.Text})
}
func (m *Module) memoryBlock(ctx context.Context, d Deps) string {
notes, err := d.Memory.Notes(ctx)
if err != nil {
m.log.WarnContext(ctx, "read memory for chat", "error", err)
return ""
}
lines := make([]string, 0, len(notes))
for _, n := range notes {
lines = append(lines, "- ["+n.ID.String()+"] "+n.Text)
}
return strings.Join(lines, "\n")
}
// pendingCall is a tool call waiting for its result.
type pendingCall struct {
name, parameters string
started time.Time
offset int
}
// drained is what a turn's stream has produced so far. Text and thinking are
// buffered between flushes, so a fast stream isn't one row per token.
type drained struct {
m *Module
turnID uuid.UUID
reply, reasoning strings.Builder
textBuf, thinkBuf strings.Builder
runes int
pending map[string]pendingCall
err error
}
func (s *drained) flush(ctx context.Context) {
if s.thinkBuf.Len() > 0 {
s.m.record(ctx, s.turnID, kindReasoning, map[string]any{"text": s.thinkBuf.String()})
s.thinkBuf.Reset()
}
if s.textBuf.Len() > 0 {
s.m.record(ctx, s.turnID, kindDelta, map[string]any{"text": s.textBuf.String()})
s.textBuf.Reset()
}
}
func (s *drained) take(ctx context.Context, part core.StreamPart) {
switch part.Type {
case core.StreamPartReasoningDelta:
s.reasoning.WriteString(part.ReasoningDelta)
s.thinkBuf.WriteString(part.ReasoningDelta)
case core.StreamPartTextDelta:
s.reply.WriteString(part.TextDelta)
s.textBuf.WriteString(part.TextDelta)
s.runes += utf8.RuneCountInString(part.TextDelta)
case core.StreamPartToolCall:
if c := part.ToolCall; c != nil {
s.pending[c.ToolCallID] = pendingCall{
name: c.ToolName, parameters: summarizeParameters(c.Input), started: time.Now(), offset: s.runes,
}
}
case core.StreamPartToolResult:
if r := part.ToolResult; r != nil {
s.flush(ctx)
call := s.pending[r.ToolCallID]
delete(s.pending, r.ToolCallID)
s.m.record(ctx, s.turnID, kindTool, toolCall(r, call))
}
case core.StreamPartError:
if part.Error != nil {
s.err = part.Error
}
case core.StreamPartAbort:
if s.err == nil {
s.err = context.Canceled
}
}
}
// drain consumes the whole stream, recording reasoning, reply text and each
// finished tool call. The stream's writes are synchronous, so it is read to
// its close whatever happens, or the producer stalls.
func (m *Module) drain(ctx context.Context, turnID uuid.UUID, parts <-chan core.StreamPart) (string, string, error) {
s := &drained{m: m, turnID: turnID, pending: map[string]pendingCall{}}
tick := time.NewTicker(flushEvery)
defer tick.Stop()
for {
select {
case <-tick.C:
s.flush(ctx)
case part, ok := <-parts:
if !ok {
s.flush(ctx)
return s.reply.String(), s.reasoning.String(), s.err
}
s.take(ctx, part)
}
}
}
func toolCall(r *core.ToolResult, call pendingCall) ToolCall {
name := r.ToolName
if name == "" {
name = call.name
}
out := ToolCall{
ID: r.ToolCallID, Name: name, Parameters: call.parameters, Output: truncateRunes(r.Output, outputMaxRunes),
TextOffset: call.offset,
}
if r.Error != "" {
out.Output, out.Failed = truncateRunes(r.Error, outputMaxRunes), true
}
if !call.started.IsZero() {
out.DurationMS = time.Since(call.started).Milliseconds()
}
return out
}
// title names an untitled conversation after its first answered exchange.
// It is a proposal: a failure leaves the conversation untitled.
func (m *Module) title(ctx context.Context, t store.Turn, reply string) {
s, err := m.store.Session(ctx, m.orgID, t.SessionID)
if err != nil || s.Title != "" {
return
}
d, ok := m.uses()
if !ok {
return
}
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
model, err := d.Settings.AgentModelForAlias(ctx, "")
if err != nil {
return
}
provider, info, err := d.Settings.AgentProvider(ctx, model)
if err != nil {
return
}
res, err := core.GenerateText(ctx, provider, core.GenerateOptions{
Model: model.Model, ModelInfo: info, System: prompts.SessionTitle(),
Prompt: "Operator: " + truncateRunes(t.Text, 2000) + "\n\nArchie: " + truncateRunes(reply, 2000),
})
if err != nil {
m.log.WarnContext(ctx, "title chat session", "session", t.SessionID, "error", err)
return
}
title := strings.Trim(strings.TrimSpace(res.Text), `"'.`)
if title == "" || strings.EqualFold(title, "NONE") || utf8.RuneCountInString(title) > 80 {
return
}
if err := m.store.TitleIfUntitled(ctx, m.orgID, t.SessionID, title); err != nil {
m.log.WarnContext(ctx, "title chat session", "session", t.SessionID, "error", err)
}
}
// decodeData reads an event's data into v.
func decodeData(raw jsontext.Value, v any) error { return json.Unmarshal(raw, v) }
+46
View File
@@ -0,0 +1,46 @@
package store
import (
"context"
"fmt"
"time"
"github.com/google/uuid"
)
// Note is one remembered fact.
type Note struct {
ID uuid.UUID `db:"id"`
Text string `db:"text"`
CreatedAt time.Time `db:"created_at"`
}
// AddNote stores a fact.
func (s *Store) AddNote(ctx context.Context, orgID string, n Note) error {
if _, err := s.db.ExecContext(ctx, `
INSERT INTO memory.notes (id, org_id, text) VALUES ($1, $2, $3)`, n.ID, orgID, n.Text); err != nil {
return fmt.Errorf("remember note: %w", err)
}
return nil
}
// Notes returns the remembered facts, oldest first.
func (s *Store) Notes(ctx context.Context, orgID string, limit int) ([]Note, error) {
var out []Note
if err := s.db.SelectContext(ctx, &out, `
SELECT id, text, created_at FROM memory.notes WHERE org_id = $1
ORDER BY created_at LIMIT $2`, orgID, limit); err != nil {
return nil, fmt.Errorf("list notes: %w", err)
}
return out, nil
}
// DeleteNote forgets a fact and reports whether it existed.
func (s *Store) DeleteNote(ctx context.Context, orgID string, id uuid.UUID) (bool, error) {
res, err := s.db.ExecContext(ctx, `DELETE FROM memory.notes WHERE org_id = $1 AND id = $2`, orgID, id)
if err != nil {
return false, fmt.Errorf("forget note: %w", err)
}
n, err := res.RowsAffected()
return n > 0, err
}
+3 -1
View File
@@ -89,11 +89,13 @@ type ledger interface {
type Module struct {
orgID string
ledger ledger
notes noteStore
}
// NewModule returns the memory module for orgID.
func NewModule(db *sqlx.DB, orgID string) *Module {
return &Module{orgID: orgID, ledger: store.New(db)}
s := store.New(db)
return &Module{orgID: orgID, ledger: s, notes: s}
}
var unsafeCause = regexp.MustCompile(`[^a-z0-9]+`)
+60
View File
@@ -0,0 +1,60 @@
package memory
import (
"context"
"errors"
"strings"
"time"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/modules/memory/internal/store"
)
// maxNotes bounds the facts a conversation is given, so memory can't crowd
// out the conversation itself.
const maxNotes = 200
// Note is a fact the operator asked Archie to remember across conversations.
type Note struct {
ID uuid.UUID `json:"id"`
Text string `json:"text"`
CreatedAt time.Time `json:"created_at"`
}
type noteStore interface {
AddNote(ctx context.Context, orgID string, n store.Note) error
Notes(ctx context.Context, orgID string, limit int) ([]store.Note, error)
DeleteNote(ctx context.Context, orgID string, id uuid.UUID) (bool, error)
}
// Remember stores a fact and returns it.
func (m *Module) Remember(ctx context.Context, text string) (Note, error) {
text = strings.TrimSpace(text)
if text == "" {
return Note{}, errors.New("a note needs text")
}
n := store.Note{ID: uuid.New(), Text: text, CreatedAt: time.Now().UTC()}
if err := m.notes.AddNote(ctx, m.orgID, n); err != nil {
return Note{}, err
}
return Note(n), nil
}
// Notes returns the remembered facts, oldest first.
func (m *Module) Notes(ctx context.Context) ([]Note, error) {
rows, err := m.notes.Notes(ctx, m.orgID, maxNotes)
if err != nil {
return nil, err
}
out := make([]Note, 0, len(rows))
for _, r := range rows {
out = append(out, Note(r))
}
return out, nil
}
// Forget removes a fact and reports whether there was one.
func (m *Module) Forget(ctx context.Context, id uuid.UUID) (bool, error) {
return m.notes.DeleteNote(ctx, m.orgID, id)
}
+22
View File
@@ -360,3 +360,25 @@ func entry(s store.Recorded) TrailEntry {
}
return e
}
// Recent returns orgID's latest runs, newest first.
func (e *Engine) Recent(ctx context.Context, orgID string, limit int) ([]RunView, error) {
runs, err := e.db.Recent(ctx, orgID, limit)
if err != nil {
return nil, err
}
out := make([]RunView, 0, len(runs))
for _, s := range runs {
out = append(out, view(s, nil))
}
return out, nil
}
// Run returns one run with its result; ok is false when there is no such run.
func (e *Engine) Run(ctx context.Context, orgID string, id uuid.UUID) (RunView, bool, error) {
d, ok, err := e.db.Detail(ctx, orgID, id)
if err != nil || !ok {
return RunView{}, ok, err
}
return view(d.Summary, d.Result), true, nil
}