Files
archie/modules/runs/trail.go
T
sam 66220e1752 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.
2026-11-15 23:36:42 +11:00

198 lines
5.9 KiB
Go

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
}