feat(runs,deliveries): the decision trail, the composer channel, and the dashboard that shows them (#1996, #1984)

GET /api/runs/{id} assembles a run's trail from rows already kept: the event
and trigger that started it, each workflow step, and each model and tool call
from the agent's journal. Investigations end by notifying their findings on
the composer, whose messages are read from a cursor with a live stream that
only says when to read. The binary serves its own SPA entry, archie.html,
calling only the new API. The investigate prompt now treats the event as a
claim to check against what it measures.
This commit is contained in:
sam committed 2026-11-15 23:36:42 +11:00
1 parent 93c9eb51f3
commit 66220e1752
22 files changed
+1276 -3

No files matched your search

+12 -2
View File
@@ -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 {
+61
View File
@@ -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)
}
}
}
@@ -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;
+4
View File
@@ -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.
+44
View File
@@ -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)
})
}
+159
View File
@@ -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()
}
}
@@ -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
}
+12
View File
@@ -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,
+30
View File
@@ -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
}
+62
View File
@@ -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
+23 -1
View File
@@ -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 {
+197
View File
@@ -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
}
+44
View File
@@ -0,0 +1,44 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Archie</title>
<script>
// Set before the first paint so a reload does not flash the wrong
// palette or layout. Kept in sync with the appearance Pinia store;
// blocked site data falls back to the OS theme, comfortable spacing and
// the system motion preference.
(function () {
var theme = "dark";
try {
theme = matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light";
} catch (e) {
/* dark stands */
}
try {
var storedTheme = localStorage.getItem("archie.theme");
if (storedTheme === "light" || storedTheme === "dark") {
theme = storedTheme;
}
if (localStorage.getItem("archie.density") === "compact") {
document.documentElement.dataset.density = "compact";
}
if (localStorage.getItem("archie.motion") === "reduced") {
document.documentElement.dataset.motion = "reduced";
}
} catch (e) {
/* default stands */
}
document.documentElement.dataset.theme = theme;
})();
</script>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/archie/main.ts"></script>
</body>
</html>
+52
View File
@@ -0,0 +1,52 @@
<script setup lang="ts">
import { ref } from "vue";
import { RouterLink, RouterView } from "vue-router";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Section } from "@/components/ui/section";
import { clearToken, setToken, token } from "./api";
/**
* The shell: the admin token gate, then the composer and runs. The token is
* the bootstrap credential until identities exist.
*/
const signedIn = ref(token() !== "");
const draft = ref("");
function signIn() {
if (!draft.value.trim()) return;
setToken(draft.value.trim());
draft.value = "";
signedIn.value = true;
}
function signOut() {
clearToken();
signedIn.value = false;
}
</script>
<template>
<div class="mx-auto flex min-h-dvh max-w-4xl flex-col gap-4 p-4">
<header class="flex items-center gap-4">
<span class="text-title font-semibold">Archie</span>
<nav v-if="signedIn" class="flex flex-1 items-center gap-3 text-label">
<RouterLink to="/composer" active-class="text-foreground" class="text-muted-foreground">Composer</RouterLink>
<RouterLink to="/runs" active-class="text-foreground" class="text-muted-foreground">Runs</RouterLink>
<Button variant="ghost" size="xs" class="ml-auto" @click="signOut">Sign out</Button>
</nav>
</header>
<form v-if="!signedIn" class="max-w-md" @submit.prevent="signIn">
<Section title="Admin token">
<div class="flex gap-2">
<Input v-model="draft" type="password" autocomplete="off" aria-label="Admin token" />
<Button type="submit">Sign in</Button>
</div>
</Section>
</form>
<RouterView v-else v-slot="{ Component }">
<component :is="Component" @unauthorized="signOut" />
</RouterView>
</div>
</template>
+90
View File
@@ -0,0 +1,90 @@
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from "vue";
import { RouterLink } from "vue-router";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { ReadError } from "@/components/ui/read-error";
import { Section } from "@/components/ui/section";
import { Spinner } from "@/components/ui/spinner";
import { Timestamp } from "@/components/ui/timestamp";
import { composerStream, latestMessages, messagesAfter, type Message, Unauthorized } from "./api";
/**
* The composer: what Archie tells you, newest last. Messages are read from a
* cursor; the stream only says when there is more to read.
*/
const emit = defineEmits<{ unauthorized: [] }>();
const messages = ref<Message[]>([]);
const loading = ref(true);
const error = ref("");
const controller = new AbortController();
const cursor = () => messages.value.at(-1)?.seq ?? 0;
async function load() {
loading.value = true;
error.value = "";
try {
messages.value = await latestMessages(controller.signal);
} catch (err) {
fail(err);
} finally {
loading.value = false;
}
}
async function catchUp() {
const more = await messagesAfter(cursor(), controller.signal);
messages.value.push(...more);
}
async function follow() {
let backoff = 1000;
while (!controller.signal.aborted) {
try {
for await (const seq of composerStream(controller.signal)) {
backoff = 1000;
if (seq > cursor()) await catchUp();
}
await catchUp();
} catch (err) {
if (controller.signal.aborted) return;
if (err instanceof Unauthorized) return fail(err);
}
await new Promise((resolve) => setTimeout(resolve, backoff));
backoff = Math.min(backoff * 2, 30000);
}
}
function fail(err: unknown) {
if (controller.signal.aborted) return;
if (err instanceof Unauthorized) emit("unauthorized");
error.value = err instanceof Error ? err.message : String(err);
}
onMounted(async () => {
await load();
void follow();
});
onBeforeUnmount(() => controller.abort());
</script>
<template>
<div>
<Spinner v-if="loading" />
<ReadError v-else-if="error" :message="error" retry-label="Retry" @retry="load" />
<Empty v-else-if="messages.length === 0">
<EmptyHeader><EmptyTitle>Nothing yet</EmptyTitle></EmptyHeader>
</Empty>
<Section v-for="m in messages" v-else :key="m.id" :title="m.title">
<template #action>
<span class="flex items-center gap-2 text-caption text-muted-foreground">
<RouterLink v-if="m.run_id" :to="{ name: 'run', params: { id: m.run_id } }" class="underline">Run</RouterLink>
<Timestamp :at="m.created_at" />
</span>
</template>
<p class="whitespace-pre-wrap text-label">{{ m.body }}</p>
</Section>
</div>
</template>
+144
View File
@@ -0,0 +1,144 @@
<script setup lang="ts">
import { Bot, Footprints, Wrench } from "@lucide/vue";
import { computed, onBeforeUnmount, ref, watch } from "vue";
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block";
import { MetadataList } from "@/components/ui/metadata-list";
import { ReadError } from "@/components/ui/read-error";
import { Section } from "@/components/ui/section";
import { Spinner } from "@/components/ui/spinner";
import { StatusDot } from "@/components/ui/status-dot";
import { Timestamp } from "@/components/ui/timestamp";
import {
Trace,
TraceCollapsible,
TraceCollapsibleContent,
TraceCollapsibleTrigger,
TraceIcon,
TraceLine,
TraceTitle,
} from "@/components/ui/trace";
import { runTrail, type Trail, type TrailEntry, Unauthorized } from "./api";
import { runTone } from "./state";
/** A run's decision trail: what started it, every step in order, and how it ended. */
const props = defineProps<{ id: string }>();
const emit = defineEmits<{ unauthorized: [] }>();
const trail = ref<Trail>();
const loading = ref(true);
const error = ref("");
let controller = new AbortController();
async function load() {
controller.abort();
controller = new AbortController();
const signal = controller.signal;
loading.value = true;
error.value = "";
try {
const got = await runTrail(props.id, signal);
if (!signal.aborted) trail.value = got;
} catch (err) {
if (signal.aborted) return;
if (err instanceof Unauthorized) emit("unauthorized");
error.value = err instanceof Error ? err.message : String(err);
} finally {
if (!signal.aborted) loading.value = false;
}
}
watch(() => props.id, load, { immediate: true });
onBeforeUnmount(() => controller.abort());
const originRows = computed(() => {
const o = trail.value?.origin;
if (!o) return [];
return [
{ label: "Source", value: o.source },
{ label: "Event", value: o.type },
{ label: "Trigger", value: o.trigger },
];
});
const usage = computed(() => trail.value?.run.result?.usage);
function title(e: TrailEntry): string {
switch (e.kind) {
case "model":
return e.tool_calls?.length ? `Model asked for ${e.tool_calls.map((c) => c.name).join(", ")}` : "Model answered";
case "compaction":
return "History compacted";
case "tool":
return e.unknown ? `${e.name}: outcome unknown` : e.error ? `${e.name} failed` : (e.name ?? "Tool");
default:
return e.name ?? "Step";
}
}
const json = (v: unknown) => JSON.stringify(v, null, 2);
</script>
<template>
<div>
<Spinner v-if="loading && !trail" />
<ReadError v-else-if="error" :message="error" retry-label="Retry" @retry="load" />
<template v-else-if="trail">
<Section :title="trail.run.workflow">
<template #action>
<span class="flex items-center gap-2 text-caption">
<StatusDot :tone="runTone(trail.run.state)" :live="trail.run.state === 'running'" />{{ trail.run.state }}
<Timestamp :at="trail.run.created_at" />
</span>
</template>
<p v-if="trail.run.result?.answer" class="whitespace-pre-wrap text-label">{{ trail.run.result.answer }}</p>
<p v-if="trail.run.error" class="text-label text-destructive">{{ trail.run.error }}</p>
<p v-if="usage" class="mt-2 text-caption text-muted-foreground">
{{ usage.total_tokens.toLocaleString() }} tokens, {{ trail.run.result?.tool_calls ?? 0 }} tool calls
</p>
</Section>
<Section v-if="trail.origin" title="Started by">
<MetadataList :rows="originRows" />
<CodeBlock size="sm" class="mt-2">
<CodeBlockContent wrap class="max-h-64">{{ json(trail.origin.fields) }}</CodeBlockContent>
</CodeBlock>
</Section>
<Section title="Steps">
<Trace>
<TraceCollapsible v-for="e in trail.entries" :key="e.seq" :default-open="Boolean(e.error || e.unknown)">
<TraceCollapsibleTrigger>
<TraceLine :status="e.error || e.unknown ? 'error' : undefined">
<TraceIcon>
<Bot v-if="e.kind === 'model' || e.kind === 'compaction'" />
<Wrench v-else-if="e.kind === 'tool'" />
<Footprints v-else />
</TraceIcon>
<TraceTitle class="truncate">{{ title(e) }}</TraceTitle>
<span v-if="e.usage" class="text-caption tabular-nums">{{ e.usage.total_tokens.toLocaleString() }} tokens</span>
</TraceLine>
</TraceCollapsibleTrigger>
<TraceCollapsibleContent>
<div class="flex flex-col gap-2 text-label">
<p v-if="e.reasoning" class="whitespace-pre-wrap text-muted-foreground">{{ e.reasoning }}</p>
<p v-if="e.text" class="whitespace-pre-wrap">{{ e.text }}</p>
<CodeBlock v-for="(c, i) in e.tool_calls" :key="i" size="sm">
<CodeBlockContent wrap>{{ c.name }} {{ c.input }}</CodeBlockContent>
</CodeBlock>
<CodeBlock v-if="e.input" size="sm">
<CodeBlockContent wrap>{{ e.input }}</CodeBlockContent>
</CodeBlock>
<CodeBlock v-if="e.output" size="sm">
<CodeBlockContent wrap class="max-h-64">{{ e.output }}</CodeBlockContent>
</CodeBlock>
<CodeBlock v-if="e.kind === 'step' && e.value !== undefined" size="sm">
<CodeBlockContent wrap class="max-h-64">{{ json(e.value) }}</CodeBlockContent>
</CodeBlock>
<p v-if="e.error" class="text-destructive">{{ e.error }}</p>
</div>
</TraceCollapsibleContent>
</TraceCollapsible>
</Trace>
</Section>
</template>
</div>
</template>
+73
View File
@@ -0,0 +1,73 @@
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { ReadError } from "@/components/ui/read-error";
import { Spinner } from "@/components/ui/spinner";
import { StatusDot } from "@/components/ui/status-dot";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Timestamp } from "@/components/ui/timestamp";
import { listRuns, type Run, Unauthorized } from "./api";
import { runTone } from "./state";
const emit = defineEmits<{ unauthorized: [] }>();
const router = useRouter();
const runs = ref<Run[]>([]);
const loading = ref(true);
const error = ref("");
const controller = new AbortController();
async function load() {
loading.value = true;
error.value = "";
try {
runs.value = await listRuns(controller.signal);
} catch (err) {
if (controller.signal.aborted) return;
if (err instanceof Unauthorized) emit("unauthorized");
error.value = err instanceof Error ? err.message : String(err);
} finally {
loading.value = false;
}
}
onMounted(load);
onBeforeUnmount(() => controller.abort());
</script>
<template>
<div>
<Spinner v-if="loading" />
<ReadError v-else-if="error" :message="error" retry-label="Retry" @retry="load" />
<Empty v-else-if="runs.length === 0">
<EmptyHeader><EmptyTitle>No runs yet</EmptyTitle></EmptyHeader>
</Empty>
<Table v-else>
<TableHeader>
<TableRow>
<TableHead>Workflow</TableHead>
<TableHead>State</TableHead>
<TableHead>Started</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow
v-for="r in runs"
:key="r.id"
class="cursor-pointer"
tabindex="0"
@click="router.push({ name: 'run', params: { id: r.id } })"
@keydown.enter="router.push({ name: 'run', params: { id: r.id } })"
>
<TableCell>{{ r.workflow }}</TableCell>
<TableCell>
<span class="flex items-center gap-2"><StatusDot :tone="runTone(r.state)" :live="r.state === 'running'" />{{ r.state }}</span>
</TableCell>
<TableCell><Timestamp :at="r.created_at" /></TableCell>
</TableRow>
</TableBody>
</Table>
</div>
</template>
+113
View File
@@ -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<Response> {
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<T>(path: string, signal?: AbortSignal): Promise<T> {
return (await request(path, signal)).json() as Promise<T>;
}
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<string, unknown>;
received_at: string;
trigger: string;
filter: Record<string, string>;
}
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<Message[]>("/api/composer/messages", signal);
export const messagesAfter = (seq: number, signal?: AbortSignal) =>
get<Message[]>(`/api/composer/messages?after=${seq}`, signal);
export const listRuns = (signal?: AbortSignal) => get<Run[]>("/api/runs", signal);
export const runTrail = (id: string, signal?: AbortSignal) => get<Trail>(`/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<number> {
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;
}
}
}
+13
View File
@@ -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");
+11
View File
@@ -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 },
],
});
+18
View File
@@ -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";
}
}
+5
View File
@@ -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