diff --git a/internal/app/archie/run.go b/internal/app/archie/run.go index 364bf5569..0dc314ff4 100644 --- a/internal/app/archie/run.go +++ b/internal/app/archie/run.go @@ -20,11 +20,15 @@ import ( "github.com/samcharles93/archie-core/internal/buildinfo" "github.com/samcharles93/archie-core/internal/platform/health" "github.com/samcharles93/archie-core/internal/platform/httpjson" + "github.com/samcharles93/archie-core/internal/platform/hub" "github.com/samcharles93/archie-core/internal/platform/pg" "github.com/samcharles93/archie-core/modules/connectors" + "github.com/samcharles93/archie-core/modules/dashboard" + "github.com/samcharles93/archie-core/modules/deliveries" "github.com/samcharles93/archie-core/modules/events" "github.com/samcharles93/archie-core/modules/governance" "github.com/samcharles93/archie-core/modules/runs" + "github.com/samcharles93/archie-core/ui" ) const shutdownGrace = 10 * time.Second @@ -70,13 +74,19 @@ func Run(ctx context.Context, configPath string) error { checks.Register("connectors", conns.Ready) conns.Routes(mux, guard) + live := hub.New() + tell := deliveries.NewModule(db, log.With("module", "deliveries"), orgID, live) + tell.Routes(mux, guard) + engine := runs.New(db, log.With("module", "runs"), runs.Options{Owner: owner()}) // A workflow takes its context from the run handle, as a handler takes it // from the request. - engine.Register("investigate", runs.Investigate(settings, conns)) //nolint:contextcheck // see above + engine.Register("investigate", runs.Investigate(settings, conns, tell)) //nolint:contextcheck // see above hear := events.NewModule(db, log.With("module", "events"), orgID, conns, engine) hear.Routes(mux, guard) + engine.Routes(mux, guard, orgID, hear) + dashboard.Routes(mux, ui.DistDirFS) ctx, stop := context.WithCancel(ctx) defer stop() @@ -94,7 +104,7 @@ func Run(ctx context.Context, configPath string) error { const orgID = "default" // schemas are the module schemas the runtime role is granted DML on. -var schemas = []string{"runs", "connectors", "events", "governance"} +var schemas = []string{"runs", "connectors", "events", "governance", "deliveries"} // owner names this process in run leases. func owner() string { diff --git a/internal/platform/hub/hub.go b/internal/platform/hub/hub.go new file mode 100644 index 000000000..3742ceeca --- /dev/null +++ b/internal/platform/hub/hub.go @@ -0,0 +1,61 @@ +// Package hub fans notifications out to live subscribers, such as a +// dashboard's stream. A note carries only what changed, never work: a +// subscriber that falls behind is cut off and resyncs from its cursor, so +// nothing depends on a note arriving. +package hub + +import "sync" + +// buffer is how many notes a subscriber may fall behind before it is cut off. +const buffer = 32 + +// Note says something on a topic changed. Seq is the stream position a +// subscriber reads from to catch up. +type Note struct { + Topic string `json:"topic"` + Seq int64 `json:"seq"` +} + +// Hub holds the live subscribers. +type Hub struct { + mu sync.Mutex + subs map[chan Note]string +} + +// New returns an empty hub. +func New() *Hub { return &Hub{subs: map[chan Note]string{}} } + +// Publish sends n to every subscriber of its topic. A subscriber whose buffer +// is full is closed rather than waited for. +func (h *Hub) Publish(n Note) { + h.mu.Lock() + defer h.mu.Unlock() + for ch, topic := range h.subs { + if topic != n.Topic { + continue + } + select { + case ch <- n: + default: + delete(h.subs, ch) + close(ch) + } + } +} + +// Subscribe returns a channel of notes on topic, closed if the subscriber +// falls behind, and a function that ends the subscription. +func (h *Hub) Subscribe(topic string) (<-chan Note, func()) { + ch := make(chan Note, buffer) + h.mu.Lock() + h.subs[ch] = topic + h.mu.Unlock() + return ch, func() { + h.mu.Lock() + defer h.mu.Unlock() + if _, ok := h.subs[ch]; ok { + delete(h.subs, ch) + close(ch) + } + } +} diff --git a/internal/platform/pg/migrations/00006_deliveries.sql b/internal/platform/pg/migrations/00006_deliveries.sql new file mode 100644 index 000000000..a8e5c52bb --- /dev/null +++ b/internal/platform/pg/migrations/00006_deliveries.sql @@ -0,0 +1,23 @@ +-- +goose Up +CREATE SCHEMA deliveries; + +-- A message is one notification on one channel. The composer reads its +-- messages straight from here; channels that send (Telegram) get delivery +-- attempts when they land. +CREATE TABLE deliveries.messages ( + seq bigserial PRIMARY KEY, + id uuid NOT NULL UNIQUE, + org_id text NOT NULL, + channel text NOT NULL CHECK (channel IN ('composer')), + kind text NOT NULL CHECK (kind IN ('notification')), + run_id uuid, + title text NOT NULL, + body text NOT NULL, + -- key makes a notification idempotent: a replayed step can't send twice. + key text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + UNIQUE (org_id, channel, key) +); + +-- +goose Down +DROP SCHEMA deliveries CASCADE; diff --git a/internal/platform/prompts/investigate.md b/internal/platform/prompts/investigate.md index 9fbd8aa98..3fd3bd80b 100644 --- a/internal/platform/prompts/investigate.md +++ b/internal/platform/prompts/investigate.md @@ -9,6 +9,10 @@ Your tools only read. Use them to find out what happened and why. Don't guess at facts a tool could tell you, and don't call a tool to learn something you already know. +The event is a claim, not a fact. Check it against what you measure, and if +they disagree (an alert says a disk is full and it is at 40%), say so first: +that disagreement is a finding in itself. + When you're done, reply with your findings in plain text: - What happened, in one or two sentences. diff --git a/modules/dashboard/dashboard.go b/modules/dashboard/dashboard.go new file mode 100644 index 000000000..3446aeddf --- /dev/null +++ b/modules/dashboard/dashboard.go @@ -0,0 +1,44 @@ +// Package dashboard serves the single binary's SPA: archie.html and its +// assets from the embedded build. Every other route belongs to a module. +package dashboard + +import ( + "io/fs" + "net/http" + "strings" + + "github.com/samcharles93/archie-core/internal/platform/httpjson" +) + +const page = "archie.html" + +// Routes serves the SPA from dist on mux. A path under /api/ that no module +// claimed is a JSON 404, never the page. With no build embedded, the page +// says how to build it. +func Routes(mux *http.ServeMux, dist fs.FS) { + mux.HandleFunc("/api/", func(w http.ResponseWriter, _ *http.Request) { + httpjson.Error(w, http.StatusNotFound, "no such route") + }) + if dist == nil { + mux.HandleFunc("GET /", func(w http.ResponseWriter, _ *http.Request) { + http.Error(w, "this binary was built without the dashboard; run task ui and rebuild", http.StatusNotFound) + }) + return + } + files := http.FileServerFS(dist) + mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { + name := strings.TrimPrefix(r.URL.Path, "/") + if name != "" && name != "index.html" && name != page { + if info, err := fs.Stat(dist, name); err == nil && !info.IsDir() { + if strings.HasPrefix(name, "assets/") { + w.Header().Set("Cache-Control", "public, max-age=31536000, immutable") + } + files.ServeHTTP(w, r) + return + } + } + // Every other path is a route inside the SPA. + w.Header().Set("Cache-Control", "no-store") + http.ServeFileFS(w, r, dist, page) + }) +} diff --git a/modules/deliveries/deliveries.go b/modules/deliveries/deliveries.go new file mode 100644 index 000000000..51988975d --- /dev/null +++ b/modules/deliveries/deliveries.go @@ -0,0 +1,159 @@ +// Package deliveries carries what Archie tells people: notifications now, and +// approval requests and their answers with judgement. The composer, the chat +// box in the dashboard, is the first channel: its messages are rows a client +// reads from a cursor, with a live stream that only says when to read. +package deliveries + +import ( + "context" + "errors" + "fmt" + "log/slog" + "net/http" + "strconv" + "time" + + "github.com/google/uuid" + "github.com/jmoiron/sqlx" + + "github.com/samcharles93/archie-core/internal/platform/httpjson" + "github.com/samcharles93/archie-core/internal/platform/hub" + "github.com/samcharles93/archie-core/modules/deliveries/internal/store" +) + +const ( + channelComposer = "composer" + topicComposer = "composer" + pageSize = 100 + heartbeat = 25 * time.Second +) + +// Notification is something a run tells people: what happened, what was done, +// what is needed. +type Notification struct { + RunID uuid.UUID + // Key makes the notification idempotent; a workflow passes its step key so + // a replayed step doesn't notify twice. + Key string + Title string + Body string +} + +// Message is a composer message as the API shows it. +type Message struct { + Seq int64 `json:"seq"` + ID uuid.UUID `json:"id"` + Kind string `json:"kind"` + RunID *uuid.UUID `json:"run_id,omitzero"` + Title string `json:"title"` + Body string `json:"body"` + CreatedAt time.Time `json:"created_at"` +} + +// Module delivers one organisation's notifications. +type Module struct { + orgID string + store *store.Store + hub *hub.Hub + log *slog.Logger +} + +// NewModule returns the deliveries module for orgID, announcing new messages +// on h. +func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, h *hub.Hub) *Module { + return &Module{orgID: orgID, store: store.New(db), hub: h, log: log} +} + +// Notify delivers n on every channel. Delivering the same key again changes +// nothing. +func (m *Module) Notify(ctx context.Context, n Notification) error { + if n.Key == "" { + return errors.New("a notification needs a key") + } + seq, created, err := m.store.Insert(ctx, store.Message{ + ID: uuid.New(), OrgID: m.orgID, Channel: channelComposer, Kind: "notification", + RunID: uuid.NullUUID{UUID: n.RunID, Valid: n.RunID != uuid.Nil}, Title: n.Title, Body: n.Body, Key: n.Key, + }) + if err != nil { + return err + } + if created { + m.hub.Publish(hub.Note{Topic: topicComposer, Seq: seq}) + } + return nil +} + +// Routes adds the composer API to mux behind guard. +func (m *Module) Routes(mux *http.ServeMux, guard func(http.Handler) http.Handler) { + mux.Handle("GET /api/composer/messages", guard(http.HandlerFunc(m.messages))) + mux.Handle("GET /api/composer/stream", guard(http.HandlerFunc(m.stream))) +} + +// messages returns the newest page, or the messages after ?after=seq. +func (m *Module) messages(w http.ResponseWriter, r *http.Request) { + var ( + rows []store.Message + err error + ) + if after := r.URL.Query().Get("after"); after != "" { + seq, perr := strconv.ParseInt(after, 10, 64) + if perr != nil || seq < 0 { + httpjson.Error(w, http.StatusBadRequest, "after is a message seq") + return + } + rows, err = m.store.After(r.Context(), m.orgID, channelComposer, seq, pageSize) + } else { + rows, err = m.store.Latest(r.Context(), m.orgID, channelComposer, pageSize) + } + if err != nil { + m.log.ErrorContext(r.Context(), "list composer messages", "error", err) + httpjson.Error(w, http.StatusInternalServerError, "couldn't list messages") + return + } + out := make([]Message, 0, len(rows)) + for _, row := range rows { + msg := Message{Seq: row.Seq, ID: row.ID, Kind: row.Kind, Title: row.Title, Body: row.Body, CreatedAt: row.CreatedAt} + if row.RunID.Valid { + msg.RunID = &row.RunID.UUID + } + out = append(out, msg) + } + httpjson.Write(w, http.StatusOK, out) +} + +// stream sends a server-sent event each time a composer message lands. It +// carries only the new seq: the client reads the messages themselves. A +// client that falls behind is cut off and reconnects with its cursor. +func (m *Module) stream(w http.ResponseWriter, r *http.Request) { + flusher, ok := w.(http.Flusher) + if !ok { + httpjson.Error(w, http.StatusInternalServerError, "streaming unsupported") + return + } + notes, stop := m.hub.Subscribe(topicComposer) + defer stop() + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(http.StatusOK) + flusher.Flush() + tick := time.NewTicker(heartbeat) + defer tick.Stop() + for { + select { + case <-r.Context().Done(): + return + case <-tick.C: + if _, err := fmt.Fprint(w, ": keepalive\n\n"); err != nil { + return + } + case n, ok := <-notes: + if !ok { + return + } + if _, err := fmt.Fprintf(w, "event: message\ndata: {\"seq\":%d}\n\n", n.Seq); err != nil { + return + } + } + flusher.Flush() + } +} diff --git a/modules/deliveries/internal/store/store.go b/modules/deliveries/internal/store/store.go new file mode 100644 index 000000000..3ba294bca --- /dev/null +++ b/modules/deliveries/internal/store/store.go @@ -0,0 +1,86 @@ +// Package store holds the deliveries module's SQL: the messages each channel +// carries. +package store + +import ( + "context" + "database/sql" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "github.com/jmoiron/sqlx" +) + +// Message is one notification on one channel. +type Message struct { + Seq int64 `db:"seq"` + ID uuid.UUID `db:"id"` + OrgID string `db:"org_id"` + Channel string `db:"channel"` + Kind string `db:"kind"` + RunID uuid.NullUUID `db:"run_id"` + Title string `db:"title"` + Body string `db:"body"` + Key string `db:"key"` + CreatedAt time.Time `db:"created_at"` +} + +// Store is the deliveries 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} } + +// Insert stores m unless a message with its key exists on its channel, and +// returns the stored message's position either way. +func (s *Store) Insert(ctx context.Context, m Message) (int64, bool, error) { + var seq int64 + err := s.db.GetContext(ctx, &seq, ` + INSERT INTO deliveries.messages (id, org_id, channel, kind, run_id, title, body, key) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8) + ON CONFLICT (org_id, channel, key) DO NOTHING + RETURNING seq`, m.ID, m.OrgID, m.Channel, m.Kind, m.RunID, m.Title, m.Body, m.Key) + if errors.Is(err, sql.ErrNoRows) { + err = s.db.GetContext(ctx, &seq, ` + SELECT seq FROM deliveries.messages WHERE org_id = $1 AND channel = $2 AND key = $3`, + m.OrgID, m.Channel, m.Key) + if err != nil { + return 0, false, fmt.Errorf("read existing message: %w", err) + } + return seq, false, nil + } + if err != nil { + return 0, false, fmt.Errorf("insert message: %w", err) + } + return seq, true, nil +} + +// After returns a channel's messages after seq, oldest first. +func (s *Store) After(ctx context.Context, orgID, channel string, seq int64, limit int) ([]Message, error) { + var out []Message + if err := s.db.SelectContext(ctx, &out, ` + SELECT seq, id, org_id, channel, kind, run_id, title, body, key, created_at + FROM deliveries.messages WHERE org_id = $1 AND channel = $2 AND seq > $3 + ORDER BY seq LIMIT $4`, orgID, channel, seq, limit); err != nil { + return nil, fmt.Errorf("list messages: %w", err) + } + return out, nil +} + +// Latest returns a channel's newest messages, oldest first. +func (s *Store) Latest(ctx context.Context, orgID, channel string, limit int) ([]Message, error) { + var out []Message + if err := s.db.SelectContext(ctx, &out, ` + SELECT * FROM ( + SELECT seq, id, org_id, channel, kind, run_id, title, body, key, created_at + FROM deliveries.messages WHERE org_id = $1 AND channel = $2 + ORDER BY seq DESC LIMIT $3) latest + ORDER BY seq`, orgID, channel, limit); err != nil { + return nil, fmt.Errorf("list messages: %w", err) + } + return out, nil +} diff --git a/modules/events/events.go b/modules/events/events.go index 9bb7dc09d..50da50206 100644 --- a/modules/events/events.go +++ b/modules/events/events.go @@ -175,6 +175,18 @@ func (m *Module) dispatch(tx *sqlx.Tx, e store.Event) (bool, error) { return matched, nil } +// Origin returns the event and trigger that started a run. +func (m *Module) Origin(ctx context.Context, runID uuid.UUID) (runs.Origin, bool, error) { + o, ok, err := m.store.OriginOf(ctx, m.orgID, runID) + if err != nil || !ok { + return runs.Origin{}, ok, err + } + return runs.Origin{ + EventID: o.EventID, Source: o.Source, Type: o.Type, Fields: o.Fields, + ReceivedAt: o.ReceivedAt, Trigger: o.Trigger, Filter: o.Filter, + }, true, nil +} + func runInput(e store.Event) jsontext.Value { input, err := json.Marshal(map[string]any{"event": map[string]any{ "id": e.ID, "source": e.Source, "type": e.Type, "fields": e.Fields, "occurred_at": e.OccurredAt.Time, diff --git a/modules/events/internal/store/store.go b/modules/events/internal/store/store.go index 021cab546..c35ecb569 100644 --- a/modules/events/internal/store/store.go +++ b/modules/events/internal/store/store.go @@ -210,3 +210,33 @@ func (s *Store) Recent(ctx context.Context, orgID string, limit int) ([]Event, e } return out, nil } + +// Origin is the event and trigger that started a run. +type Origin struct { + EventID uuid.UUID `db:"event_id"` + Source string `db:"source"` + Type string `db:"type"` + Fields jsontext.Value `db:"fields"` + ReceivedAt time.Time `db:"received_at"` + Trigger string `db:"trigger"` + Filter jsontext.Value `db:"filter"` +} + +// OriginOf returns what started a run; ok is false when no trigger did. +func (s *Store) OriginOf(ctx context.Context, orgID string, runID uuid.UUID) (Origin, bool, error) { + var o Origin + err := s.db.GetContext(ctx, &o, ` + SELECT e.id AS event_id, e.source, e.type, e.fields, e.received_at, d.trigger, + COALESCE(t.filter, '{}') AS filter + FROM events.dispatches d + JOIN events.events e ON e.id = d.event_id + LEFT JOIN events.triggers t ON t.org_id = e.org_id AND t.name = d.trigger + WHERE e.org_id = $1 AND d.run_id = $2`, orgID, runID) + if errors.Is(err, sql.ErrNoRows) { + return Origin{}, false, nil + } + if err != nil { + return Origin{}, false, fmt.Errorf("read run origin: %w", err) + } + return o, true, nil +} diff --git a/modules/runs/internal/store/store.go b/modules/runs/internal/store/store.go index 7dcf25e65..16a3cf9de 100644 --- a/modules/runs/internal/store/store.go +++ b/modules/runs/internal/store/store.go @@ -249,6 +249,68 @@ func (s *Store) CancelRequested(ctx context.Context, id uuid.UUID) (bool, error) return requested, nil } +// Summary is a run as a list shows it. +type Summary struct { + ID uuid.UUID `db:"id"` + Workflow string `db:"workflow"` + State string `db:"state"` + Attempts int `db:"attempts"` + Error sql.NullString `db:"error"` + CreatedAt time.Time `db:"created_at"` + FinishedAt sql.NullTime `db:"finished_at"` +} + +// Detail is a run with its input and result. +type Detail struct { + Summary + Input jsontext.Value `db:"input"` + Result jsontext.Value `db:"result"` +} + +// Recorded is a step with the time it was recorded. +type Recorded struct { + Step + RecordedAt time.Time `db:"recorded_at"` +} + +// Recent returns an organisation's latest runs, newest first. +func (s *Store) Recent(ctx context.Context, orgID string, limit int) ([]Summary, error) { + var out []Summary + if err := s.db.SelectContext(ctx, &out, ` + SELECT id, workflow, state, attempts, error, created_at, finished_at FROM runs.runs + WHERE org_id = $1 ORDER BY created_at DESC LIMIT $2`, orgID, limit); err != nil { + return nil, fmt.Errorf("list runs: %w", err) + } + return out, nil +} + +// Detail returns one of an organisation's runs; ok is false when it has none +// with that id. +func (s *Store) Detail(ctx context.Context, orgID string, id uuid.UUID) (Detail, bool, error) { + var d Detail + err := s.db.GetContext(ctx, &d, ` + SELECT id, workflow, state, attempts, error, created_at, finished_at, input, result + FROM runs.runs WHERE org_id = $1 AND id = $2`, orgID, id) + if errors.Is(err, sql.ErrNoRows) { + return Detail{}, false, nil + } + if err != nil { + return Detail{}, false, fmt.Errorf("read run: %w", err) + } + return d, true, nil +} + +// RecordedSteps returns a run's steps in order, with when each was recorded. +func (s *Store) RecordedSteps(ctx context.Context, id uuid.UUID) ([]Recorded, error) { + var out []Recorded + if err := s.db.SelectContext(ctx, &out, ` + SELECT run_id, seq, name, outcome, output, error, recorded_at FROM runs.steps + WHERE run_id = $1 ORDER BY seq`, id); err != nil { + return nil, fmt.Errorf("load steps: %w", err) + } + return out, nil +} + // whyNotWritten tells a lost lease from a step that already exists. func (s *Store) whyNotWritten(ctx context.Context, id, token uuid.UUID) error { var holds bool diff --git a/modules/runs/investigate.go b/modules/runs/investigate.go index 90cd17078..88b6d1a8a 100644 --- a/modules/runs/investigate.go +++ b/modules/runs/investigate.go @@ -9,11 +9,13 @@ import ( "regexp" "time" + "github.com/google/uuid" "github.com/samcharles93/ai-sdk/agentloop" "github.com/samcharles93/ai-sdk/core" "github.com/samcharles93/archie-core/internal/platform/prompts" "github.com/samcharles93/archie-core/modules/connectors" + "github.com/samcharles93/archie-core/modules/deliveries" "github.com/samcharles93/archie-core/modules/governance" ) @@ -29,6 +31,11 @@ type Toolbox interface { Get(name string) (*connectors.Connector, bool) } +// Notifier tells people what a run found. +type Notifier interface { + Notify(ctx context.Context, n deliveries.Notification) error +} + // investigateBudget bounds one investigation. A token cap set by the // organisation replaces it when settings grow one. var investigateBudget = agentloop.Budget{MaxSteps: 20, MaxTokens: 200_000, WallClock: 10 * time.Minute} @@ -37,7 +44,7 @@ var investigateBudget = agentloop.Budget{MaxSteps: 20, MaxTokens: 200_000, WallC // started the run and report its findings. The agent model and the tools are // pinned in the run's first steps, so a resumed run asks the same model with // the same tools even if settings or connectors changed meanwhile. -func Investigate(models AgentModels, box Toolbox) Workflow { +func Investigate(models AgentModels, box Toolbox, notify Notifier) Workflow { return func(rc *Context, input jsontext.Value) (jsontext.Value, error) { model, err := rc.Step("agent-model", func(ctx context.Context, _ string) (governance.Model, error) { return models.AgentModel(ctx) @@ -68,6 +75,11 @@ func Investigate(models AgentModels, box Toolbox) Workflow { if err != nil { return nil, err } + if _, err := rc.Step("notify", func(ctx context.Context, key string) (bool, error) { + return true, notify.Notify(ctx, findings(rc.RunID(), key, res)) + }); err != nil { + return nil, err + } out, err := json.Marshal(res) if err != nil { return nil, fmt.Errorf("encode findings: %w", err) @@ -79,6 +91,16 @@ func Investigate(models AgentModels, box Toolbox) Workflow { } } +// findings is the notification an investigation ends with, finished or not. +func findings(runID uuid.UUID, key string, res AgentResult) deliveries.Notification { + n := deliveries.Notification{RunID: runID, Key: key, Title: "Investigation finished", Body: res.Answer} + if !res.Completed { + n.Title = "Investigation stopped" + n.Body = fmt.Sprintf("The investigation stopped before it finished (%s). %s", res.StopReason, res.Detail) + } + return n +} + // offered keeps what an agent may call before judgement exists: lookups, // which change nothing, and read-only actions. func offered(all []connectors.Declaration) []connectors.Declaration { diff --git a/modules/runs/trail.go b/modules/runs/trail.go new file mode 100644 index 000000000..c0f864125 --- /dev/null +++ b/modules/runs/trail.go @@ -0,0 +1,197 @@ +package runs + +import ( + "context" + "encoding/json/jsontext" + json "encoding/json/v2" + "net/http" + "strconv" + "strings" + "time" + + "github.com/google/uuid" + "github.com/samcharles93/ai-sdk/agentloop" + "github.com/samcharles93/ai-sdk/chat" + + "github.com/samcharles93/archie-core/internal/platform/httpjson" + "github.com/samcharles93/archie-core/modules/runs/internal/store" +) + +// Origin is the event and trigger that started a run. +type Origin struct { + EventID uuid.UUID `json:"event_id"` + Source string `json:"source"` + Type string `json:"type"` + Fields jsontext.Value `json:"fields"` + ReceivedAt time.Time `json:"received_at"` + Trigger string `json:"trigger"` + Filter jsontext.Value `json:"filter"` +} + +// Origins finds the event and trigger that started a run. A run started any +// other way has none. +type Origins interface { + Origin(ctx context.Context, runID uuid.UUID) (Origin, bool, error) +} + +// RunView is a run as the API shows it. +type RunView struct { + ID uuid.UUID `json:"id"` + Workflow string `json:"workflow"` + State string `json:"state"` + Attempts int `json:"attempts"` + Error string `json:"error,omitzero"` + CreatedAt time.Time `json:"created_at"` + FinishedAt *time.Time `json:"finished_at,omitzero"` + Result jsontext.Value `json:"result,omitzero"` +} + +// Trail is a run's decision trail: what started it and every step it took, +// in order. +type Trail struct { + Run RunView `json:"run"` + Origin *Origin `json:"origin,omitzero"` + Entries []TrailEntry `json:"entries"` +} + +// TrailEntry is one recorded step. Kind is "model" or "compaction" for an +// agent's model call, "tool" for its tool call, and "step" for any other +// workflow step. +type TrailEntry struct { + Seq int `json:"seq"` + At time.Time `json:"at"` + Kind string `json:"kind"` + Name string `json:"name,omitzero"` + Text string `json:"text,omitzero"` + Reasoning string `json:"reasoning,omitzero"` + ToolCalls []ToolCallView `json:"tool_calls,omitzero"` + Usage *chat.Usage `json:"usage,omitzero"` + Input string `json:"input,omitzero"` + Output string `json:"output,omitzero"` + Value jsontext.Value `json:"value,omitzero"` + Error string `json:"error,omitzero"` + Unknown bool `json:"unknown,omitzero"` +} + +// ToolCallView is a tool call a model asked for. +type ToolCallView struct { + Name string `json:"name"` + Input string `json:"input"` +} + +// Routes adds the run API for orgID to mux behind guard. +func (e *Engine) Routes(mux *http.ServeMux, guard func(http.Handler) http.Handler, orgID string, origins Origins) { + api := &runAPI{db: e.db, orgID: orgID, origins: origins} + mux.Handle("GET /api/runs", guard(http.HandlerFunc(api.recent))) + mux.Handle("GET /api/runs/{id}", guard(http.HandlerFunc(api.trail))) +} + +type runAPI struct { + db *store.Store + orgID string + origins Origins +} + +func (a *runAPI) recent(w http.ResponseWriter, r *http.Request) { + limit := 50 + if n, err := strconv.Atoi(r.URL.Query().Get("limit")); err == nil && n > 0 && n <= 200 { + limit = n + } + runs, err := a.db.Recent(r.Context(), a.orgID, limit) + if err != nil { + httpjson.Error(w, http.StatusInternalServerError, "couldn't list runs") + return + } + views := make([]RunView, 0, len(runs)) + for _, s := range runs { + views = append(views, view(s, nil)) + } + httpjson.Write(w, http.StatusOK, views) +} + +func (a *runAPI) trail(w http.ResponseWriter, r *http.Request) { + id, err := uuid.Parse(r.PathValue("id")) + if err != nil { + httpjson.Error(w, http.StatusBadRequest, "a run id is a UUID") + return + } + d, ok, err := a.db.Detail(r.Context(), a.orgID, id) + switch { + case err != nil: + httpjson.Error(w, http.StatusInternalServerError, "couldn't read the run") + return + case !ok: + httpjson.Error(w, http.StatusNotFound, "no such run") + return + } + steps, err := a.db.RecordedSteps(r.Context(), id) + if err != nil { + httpjson.Error(w, http.StatusInternalServerError, "couldn't read the run's steps") + return + } + t := Trail{Run: view(d.Summary, d.Result), Entries: make([]TrailEntry, 0, len(steps))} + if o, ok, err := a.origins.Origin(r.Context(), id); err != nil { + httpjson.Error(w, http.StatusInternalServerError, "couldn't read what started the run") + return + } else if ok { + t.Origin = &o + } + for _, s := range steps { + t.Entries = append(t.Entries, entry(s)) + } + httpjson.Write(w, http.StatusOK, t) +} + +func view(s store.Summary, result jsontext.Value) RunView { + v := RunView{ + ID: s.ID, Workflow: s.Workflow, State: s.State, Attempts: s.Attempts, + Error: s.Error.String, CreatedAt: s.CreatedAt, Result: result, + } + if s.FinishedAt.Valid { + v.FinishedAt = &s.FinishedAt.Time + } + return v +} + +// entry turns a recorded step into a trail entry. An agent's journal steps +// are unpacked into the model and tool calls they record. +func entry(s store.Recorded) TrailEntry { + e := TrailEntry{Seq: s.Seq, At: s.RecordedAt, Kind: "step", Name: s.Name, Error: s.Error.String} + if s.Outcome == store.OutcomeUnknown { + e.Unknown = true + } + if !strings.HasPrefix(s.Name, "journal:agent:") { + e.Value = s.Output + return e + } + var je agentloop.Entry + if err := json.Unmarshal(s.Output, &je); err != nil { + e.Value = s.Output + return e + } + switch je.Kind { + case agentloop.EntryTool: + e.Kind, e.Name = "tool", je.ToolName + e.Input, e.Output, e.Error, e.Unknown = je.Input, je.Output, je.Error, je.Unknown + case agentloop.EntryModel, agentloop.EntryCompact: + e.Kind, e.Name = "model", "" + if je.Kind == agentloop.EntryCompact { + e.Kind = "compaction" + } + usage := je.Usage + e.Usage = &usage + if je.Message != nil { + e.Text = je.Message.Content + for _, p := range je.Message.Parts { + if rp, ok := p.(chat.ReasoningPart); ok { + e.Reasoning += rp.Text + } + } + for _, c := range je.Message.ToolCalls { + e.ToolCalls = append(e.ToolCalls, ToolCallView{Name: c.Name, Input: c.Arguments}) + } + } + e.Error = je.Error + } + return e +} diff --git a/ui/archie.html b/ui/archie.html new file mode 100644 index 000000000..4b0dc8e44 --- /dev/null +++ b/ui/archie.html @@ -0,0 +1,44 @@ + + + + + + + Archie + + + +
+ + + diff --git a/ui/src/archie/App.vue b/ui/src/archie/App.vue new file mode 100644 index 000000000..f7ec33542 --- /dev/null +++ b/ui/src/archie/App.vue @@ -0,0 +1,52 @@ + + + diff --git a/ui/src/archie/ComposerView.vue b/ui/src/archie/ComposerView.vue new file mode 100644 index 000000000..216c0b28f --- /dev/null +++ b/ui/src/archie/ComposerView.vue @@ -0,0 +1,90 @@ + + + diff --git a/ui/src/archie/RunView.vue b/ui/src/archie/RunView.vue new file mode 100644 index 000000000..6827c79c0 --- /dev/null +++ b/ui/src/archie/RunView.vue @@ -0,0 +1,144 @@ + + + diff --git a/ui/src/archie/RunsView.vue b/ui/src/archie/RunsView.vue new file mode 100644 index 000000000..3ab95056e --- /dev/null +++ b/ui/src/archie/RunsView.vue @@ -0,0 +1,73 @@ + + + diff --git a/ui/src/archie/api.ts b/ui/src/archie/api.ts new file mode 100644 index 000000000..5a2581843 --- /dev/null +++ b/ui/src/archie/api.ts @@ -0,0 +1,113 @@ +// The single binary's HTTP API. Until identities exist, every route sits +// behind the bootstrap admin token, held for this browser session only. +const TOKEN_KEY = "archie.adminToken"; + +export class Unauthorized extends Error {} + +export const token = (): string => sessionStorage.getItem(TOKEN_KEY) ?? ""; +export const setToken = (value: string) => sessionStorage.setItem(TOKEN_KEY, value); +export const clearToken = () => sessionStorage.removeItem(TOKEN_KEY); + +async function request(path: string, signal?: AbortSignal): Promise { + const res = await fetch(path, { headers: { Authorization: `Bearer ${token()}` }, signal }); + if (res.status === 401) throw new Unauthorized("The admin token was refused."); + if (!res.ok) { + const body = (await res.json().catch(() => ({}))) as { error?: string }; + throw new Error(body.error ?? `${res.status} ${res.statusText}`); + } + return res; +} + +async function get(path: string, signal?: AbortSignal): Promise { + return (await request(path, signal)).json() as Promise; +} + +export interface Message { + seq: number; + id: string; + kind: "notification"; + run_id?: string; + title: string; + body: string; + created_at: string; +} + +export interface Usage { + prompt_tokens: number; + completion_tokens: number; + total_tokens: number; + cached_tokens?: number; +} + +export interface Run { + id: string; + workflow: string; + state: "queued" | "running" | "waiting" | "succeeded" | "failed" | "cancelled"; + attempts: number; + error?: string; + created_at: string; + finished_at?: string; + result?: { answer?: string; stop_reason?: string; usage?: Usage; steps?: number; tool_calls?: number }; +} + +export interface Origin { + event_id: string; + source: string; + type: string; + fields: Record; + received_at: string; + trigger: string; + filter: Record; +} + +export interface TrailEntry { + seq: number; + at: string; + kind: "model" | "compaction" | "tool" | "step"; + name?: string; + text?: string; + reasoning?: string; + tool_calls?: { name: string; input: string }[]; + usage?: Usage; + input?: string; + output?: string; + value?: unknown; + error?: string; + unknown?: boolean; +} + +export interface Trail { + run: Run; + origin?: Origin; + entries: TrailEntry[]; +} + +export const latestMessages = (signal?: AbortSignal) => get("/api/composer/messages", signal); +export const messagesAfter = (seq: number, signal?: AbortSignal) => + get(`/api/composer/messages?after=${seq}`, signal); +export const listRuns = (signal?: AbortSignal) => get("/api/runs", signal); +export const runTrail = (id: string, signal?: AbortSignal) => get(`/api/runs/${encodeURIComponent(id)}`, signal); + +/** + * Yields each new composer message's seq as the server announces it. Returns + * when the server ends the stream (a subscriber that fell behind is cut off), + * so the caller reconnects and catches up from its cursor. + */ +export async function* composerStream(signal: AbortSignal): AsyncGenerator { + const res = await request("/api/composer/stream", signal); + if (!res.body) return; + const reader = res.body.pipeThrough(new TextDecoderStream()).getReader(); + let buffered = ""; + for (;;) { + const { value, done } = await reader.read(); + if (done) return; + buffered += value; + let end: number; + while ((end = buffered.indexOf("\n\n")) >= 0) { + const frame = buffered.slice(0, end); + buffered = buffered.slice(end + 2); + const data = frame.split("\n").find((line) => line.startsWith("data: ")); + if (data) yield (JSON.parse(data.slice(6)) as { seq: number }).seq; + } + } +} diff --git a/ui/src/archie/main.ts b/ui/src/archie/main.ts new file mode 100644 index 000000000..fa2633071 --- /dev/null +++ b/ui/src/archie/main.ts @@ -0,0 +1,13 @@ +import { createPinia } from "pinia"; +import { createApp } from "vue"; + +import { useAppearanceStore } from "@/stores/appearance"; +import App from "./App.vue"; +import router from "./router"; +import "@/style.css"; + +const app = createApp(App); +const pinia = createPinia(); +app.use(pinia).use(router); +useAppearanceStore(pinia).initialize(); +app.mount("#app"); diff --git a/ui/src/archie/router.ts b/ui/src/archie/router.ts new file mode 100644 index 000000000..4eb4fe846 --- /dev/null +++ b/ui/src/archie/router.ts @@ -0,0 +1,11 @@ +import { createRouter, createWebHistory } from "vue-router"; + +export default createRouter({ + history: createWebHistory(), + routes: [ + { path: "/", redirect: "/composer" }, + { path: "/composer", name: "composer", component: () => import("./ComposerView.vue") }, + { path: "/runs", name: "runs", component: () => import("./RunsView.vue") }, + { path: "/runs/:id", name: "run", component: () => import("./RunView.vue"), props: true }, + ], +}); diff --git a/ui/src/archie/state.ts b/ui/src/archie/state.ts new file mode 100644 index 000000000..dbc782f03 --- /dev/null +++ b/ui/src/archie/state.ts @@ -0,0 +1,18 @@ +import type { Run } from "./api"; + +/** The StatusDot tone for a run's state. */ +export function runTone(state: Run["state"]): "ok" | "warn" | "danger" | "info" | "idle" { + switch (state) { + case "succeeded": + return "ok"; + case "failed": + return "danger"; + case "running": + case "queued": + return "info"; + case "waiting": + return "warn"; + default: + return "idle"; + } +} diff --git a/ui/vite.config.ts b/ui/vite.config.ts index 0b2a713d6..d51d76621 100644 --- a/ui/vite.config.ts +++ b/ui/vite.config.ts @@ -14,6 +14,11 @@ export default defineConfig({ build: { outDir: "dist", emptyOutDir: true, + rollupOptions: { + // index.html is the old services' dashboard; archie.html is the single + // binary's, which calls only the new API. + input: { main: "index.html", archie: "archie.html" }, + }, }, server: { // Proxies the API to a locally running archie-ui (the process that serves