feat(runs): the in-process agent loop, checkpointed as run steps, and the investigate workflow (#1977, #1889)

The agent model is an organisation setting in the new governance module.
Every model and tool call is a journal step, so a killed run resumes without
repeating either. Agents are offered connector lookups and read-only actions
only, until judgement exists.
This commit is contained in:
sam committed 2026-11-15 21:49:53 +11:00
1 parent 68d81fbbd0
commit 02df83ccb7
16 files changed
+795 -23

No files matched your search

+90
View File
@@ -0,0 +1,90 @@
package runs
import (
"context"
"github.com/samcharles93/ai-sdk/agentloop"
"github.com/samcharles93/ai-sdk/chat"
"github.com/samcharles93/ai-sdk/core"
"github.com/samcharles93/ai-sdk/middleware"
)
// AgentRequest is one agent loop inside a workflow.
type AgentRequest struct {
// Name keys the loop's journal and its idempotency keys; it must be
// unique within the workflow.
Name string
Provider chat.Provider
Model string
ModelInfo chat.ModelInfo
System string
Prompt string
Tools core.ToolSet
Budget agentloop.Budget
}
// AgentResult is how an agent loop ended.
type AgentResult struct {
Completed bool `json:"completed"`
StopReason string `json:"stop_reason"`
Detail string `json:"detail,omitempty"`
Answer string `json:"answer,omitempty"`
Steps int `json:"steps"`
ToolCalls int `json:"tool_calls"`
Usage chat.Usage `json:"usage"`
}
// Agent runs a tool-using agent loop whose every model call and tool call is
// a step of this run. After a crash the loop resumes from its recorded calls:
// no model call is paid for twice and no tool runs twice. Budgets count the
// calls recorded in earlier attempts.
func (rc *Context) Agent(req AgentRequest) (AgentResult, error) {
journal := rc.Journal[agentloop.Entry]("agent:" + req.Name)
res, err := agentloop.RunLoop(rc.ctx, agentloop.LoopConfig{
Provider: retryModel(req.Provider),
Model: req.Model,
ModelInfo: req.ModelInfo,
System: req.System,
Prompt: req.Prompt,
Tools: req.Tools,
Budget: req.Budget,
Journal: loopJournal{journal},
RunID: rc.run.ID.String() + ":" + req.Name,
})
out := AgentResult{
Completed: res.Status == agentloop.StatusCompleted,
StopReason: res.StopReason,
Detail: res.Detail,
Steps: len(res.Steps),
ToolCalls: len(res.ToolCalls),
Usage: res.Usage,
}
if out.Completed && len(res.Steps) > 0 {
out.Answer = res.Steps[len(res.Steps)-1].Text
}
if err != nil {
return out, err
}
// A lost lease or a shutdown ends the loop as cancelled; the run isn't
// finished, it resumes elsewhere.
if err := rc.ctx.Err(); err != nil {
return out, err
}
return out, nil
}
// retryModel retries a transient model failure at the same journal position.
// Only a final failure ends the loop, and it records nothing, so a resumed run
// asks again.
func retryModel(p chat.Provider) chat.Provider {
return middleware.RetryChat(middleware.RetryConfig{MaxAttempts: 4}, middleware.ExponentialBackoff{}, middleware.DefaultRetryableError)(p)
}
// loopJournal is the run journal in the shape the agent loop consults.
type loopJournal struct {
*Journal[agentloop.Entry]
}
func (j loopJournal) Record(ctx context.Context, e agentloop.Entry) error {
return j.Journal.Record(ctx, e.Position, e)
}
+148
View File
@@ -0,0 +1,148 @@
package runs
import (
"context"
"encoding/json/jsontext"
json "encoding/json/v2"
"errors"
"log/slog"
"strings"
"sync"
"testing"
"github.com/google/uuid"
"github.com/samcharles93/ai-sdk/chat"
"github.com/samcharles93/ai-sdk/core"
"github.com/samcharles93/archie-core/modules/runs/internal/store"
)
// scriptedModel answers by turn: a tool call first, then findings once the
// tool's result is in the history.
type scriptedModel struct {
mu sync.Mutex
calls int
}
func (m *scriptedModel) Name() string { return "scripted" }
func (m *scriptedModel) Chat(_ context.Context, req chat.Request) (chat.Response, error) {
m.mu.Lock()
m.calls++
m.mu.Unlock()
last := req.Messages[len(req.Messages)-1]
if last.Role == chat.RoleTool {
return chat.Response{
Role: chat.RoleAssistant, Content: "disk is full: " + last.Content, FinishReason: "stop",
Parts: chat.Parts{chat.ReasoningPart{Text: "the tool said why"}, chat.TextPart{Text: "disk is full: " + last.Content}},
Usage: chat.Usage{PromptTokens: 20, CompletionTokens: 5, TotalTokens: 25},
}, nil
}
return chat.Response{
Role: chat.RoleAssistant, FinishReason: "tool_calls",
Parts: chat.Parts{chat.ReasoningPart{Text: "look at the disk"}},
ToolCalls: []chat.ToolCall{{ID: "call-1", Name: "disk_usage", Arguments: `{"path":"/tmp"}`}},
Usage: chat.Usage{PromptTokens: 10, CompletionTokens: 3, TotalTokens: 13},
}, nil
}
func (m *scriptedModel) ChatStream(context.Context, chat.Request) (chat.Stream, error) {
return nil, errors.New("not streamed")
}
// TestAgentResumesFromItsRecordedCalls guards the agent loop's checkpoint
// contract (2.2, 2.3): a worker that stops after any recorded call, killed or
// shut down mid-tool, resumes the loop from the run's steps, replays what was
// recorded without calling the model or running the tool again, and ends with
// the same findings. A step encoding that changes a recorded call shows up as
// a replay that diverges from its journal.
func TestAgentResumesFromItsRecordedCalls(t *testing.T) {
// The uninterrupted run records a step before the loop (seq 0), the
// loop's model, tool and model calls (1 to 3), and a step after it (4).
type stop struct {
name string
// killAt makes writes fail as a lost lease from that many steps on.
killAt *int
// shutdownInTool ends the run's context while the tool runs.
shutdownInTool bool
// replayedModel and replayedTool are the calls the resume replays.
replayedModel, replayedTool int
}
at := func(n int) *int { return &n }
tests := []stop{
{name: "killed before the loop", killAt: at(0)},
{name: "killed before the first model call is recorded", killAt: at(1)},
{name: "killed before the tool is recorded", killAt: at(2), replayedModel: 1},
{name: "killed before the second model call is recorded", killAt: at(3), replayedModel: 1, replayedTool: 1},
{name: "killed before the last step", killAt: at(4), replayedModel: 2, replayedTool: 1},
{name: "killed before finishing", killAt: at(5), replayedModel: 2, replayedTool: 1},
{name: "shut down while the tool runs", shutdownInTool: true, replayedModel: 1, replayedTool: 1},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx, shutdown := context.WithCancel(t.Context())
defer shutdown()
duringTool := func() {}
if tt.shutdownInTool {
duringTool = shutdown
}
first := &fakeWork{rejectFrom: tt.killAt}
execute(ctx, t, first, &scriptedModel{}, new(int), duringTool)
resumed := &fakeWork{steps: first.steps}
model, toolRuns := &scriptedModel{}, new(int)
execute(t.Context(), t, resumed, model, toolRuns, func() {})
if len(resumed.finished) != 1 || resumed.finished[0] != store.StateSucceeded {
t.Fatalf("resumed run finished %v, want succeeded", resumed.finished)
}
var res AgentResult
if err := json.Unmarshal(resumed.results[0], &res); err != nil {
t.Fatal(err)
}
if res.Answer != "disk is full: 93%" || res.Usage.TotalTokens != 38 {
t.Fatalf("resumed findings = %+v", res)
}
if want := 1 - tt.replayedTool; *toolRuns != want {
t.Fatalf("tool ran %d times on resume, want %d", *toolRuns, want)
}
if want := 2 - tt.replayedModel; model.calls != want {
t.Fatalf("model called %d times on resume, want %d", model.calls, want)
}
})
}
}
// execute runs the probe workflow once on work. duringTool runs inside the
// tool call.
func execute(ctx context.Context, t *testing.T, work *fakeWork, model chat.Provider, toolRuns *int, duringTool func()) {
t.Helper()
engine := newEngine(nil, work, slog.New(slog.DiscardHandler), Options{})
engine.Register("agent", func(rc *Context, _ jsontext.Value) (jsontext.Value, error) {
if _, err := rc.Step("before", func(context.Context, string) (bool, error) { return true, nil }); err != nil {
return nil, err
}
res, err := rc.Agent(AgentRequest{
Name: "probe", Provider: model, Model: "m", Prompt: "why is the disk full?",
Tools: core.ToolSet{"disk_usage": {
Name: "disk_usage", Parameters: []byte(`{"type":"object"}`),
Execute: func(ctx context.Context, input string) (string, error) {
if !strings.Contains(core.IdempotencyKey(ctx), ":probe:") {
return "", errors.New("no idempotency key")
}
*toolRuns++
duringTool()
return "93%", nil
},
}},
})
if err != nil {
return nil, err
}
return rc.Step("after", func(context.Context, string) (jsontext.Value, error) { return json.Marshal(res) })
})
run := store.Run{ID: runID, OrgID: "org", Workflow: "agent", Input: jsontext.Value(`null`)}
engine.execute(ctx, run, uuid.New())
}
var runID = uuid.MustParse("6b1f6c2e-8d5a-4c43-9f0e-1d2a3b4c5d6e")
+11 -6
View File
@@ -65,11 +65,11 @@ func (rc *Context) Step[T any](name string, fn func(ctx context.Context, key str
if saved, ok := rc.saved[seq]; ok {
return replay[T](saved, name)
}
if err := rc.checkCancel(); err != nil {
if err := rc.checkCancel(rc.ctx); err != nil {
return zero, err
}
out, err := fn(rc.ctx, rc.run.ID.String()+":"+strconv.Itoa(seq))
step, recErr := rc.record(seq, name, out, err)
step, recErr := rc.record(rc.ctx, seq, name, out, err)
if errors.Is(recErr, store.ErrStepExists) {
// Another holder recorded this step first; its result is the one that
// counts.
@@ -122,14 +122,18 @@ func (rc *Context) Wait(key string, timeout time.Duration) (jsontext.Value, erro
})
}
// Context is the run's context: it ends when the run's lease is lost or the
// binary shuts down.
func (rc *Context) Context() context.Context { return rc.ctx }
func (rc *Context) advance() int {
seq := rc.next
rc.next++
return seq
}
func (rc *Context) checkCancel() error {
cancelled, err := rc.work.CancelRequested(rc.ctx, rc.run.ID)
func (rc *Context) checkCancel(ctx context.Context) error {
cancelled, err := rc.work.CancelRequested(ctx, rc.run.ID)
if err != nil {
return err
}
@@ -141,7 +145,7 @@ func (rc *Context) checkCancel() error {
// record saves a step's outcome. A suspension, a lost lease or a cancelled
// context is not an outcome: nothing is recorded and the error passes through.
func (rc *Context) record(seq int, name string, out any, stepErr error) (store.Step, error) {
func (rc *Context) record(ctx context.Context, seq int, name string, out any, stepErr error) (store.Step, error) {
if errors.Is(stepErr, errSuspended) || errors.Is(stepErr, store.ErrLeaseLost) || errors.Is(stepErr, context.Canceled) {
return store.Step{}, stepErr
}
@@ -160,9 +164,10 @@ func (rc *Context) record(seq int, name string, out any, stepErr error) (store.S
}
step.Output = raw
}
if err := rc.work.RecordStep(rc.ctx, rc.token, step); err != nil {
if err := rc.work.RecordStep(ctx, rc.token, step); err != nil {
return store.Step{}, err
}
rc.saved[seq] = step
return step, nil
}
+141
View File
@@ -0,0 +1,141 @@
package runs
import (
"context"
"encoding/json/jsontext"
json "encoding/json/v2"
"errors"
"fmt"
"regexp"
"time"
"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/governance"
)
// AgentModels is where a workflow finds the organisation's agent model.
type AgentModels interface {
AgentModel(ctx context.Context) (governance.Model, error)
}
// Toolbox is where a workflow finds the connector lookups and actions it may
// offer an agent, and the connectors that run them.
type Toolbox interface {
Declarations() []connectors.Declaration
Get(name string) (*connectors.Connector, bool)
}
// 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}
// Investigate is the workflow that has an agent look into the event that
// 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 {
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)
})
if err != nil {
return nil, err
}
decls, err := rc.Step("agent-tools", func(context.Context, string) ([]connectors.Declaration, error) {
return offered(box.Declarations()), nil
})
if err != nil {
return nil, err
}
provider, info, err := model.Provider(rc.Context())
if err != nil {
return nil, err
}
res, err := rc.Agent(AgentRequest{
Name: "investigate",
Provider: provider,
Model: model.Model,
ModelInfo: info,
System: prompts.Investigate(),
Prompt: string(input),
Tools: toolSet(box, decls),
Budget: investigateBudget,
})
if err != nil {
return nil, err
}
out, err := json.Marshal(res)
if err != nil {
return nil, fmt.Errorf("encode findings: %w", err)
}
if !res.Completed {
return out, fmt.Errorf("investigation stopped: %s", res.StopReason)
}
return out, nil
}
}
// 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 {
var out []connectors.Declaration
for _, d := range all {
if d.ReadOnly {
out = append(out, d)
}
}
return out
}
// unsafeToolChars are those a model API refuses in a tool name.
var unsafeToolChars = regexp.MustCompile(`[^a-zA-Z0-9_-]`)
// toolSet turns pinned declarations into the agent's tools. Each tool calls
// its connector by name when the model asks, so a connector that has since
// stopped fails that call rather than the run.
func toolSet(box Toolbox, decls []connectors.Declaration) core.ToolSet {
set := core.ToolSet{}
for _, d := range decls {
name := unsafeToolChars.ReplaceAllString(d.Connector+"_"+d.Name, "_")
set[name] = &core.Tool{
Name: name,
Description: d.Description,
Parameters: []byte(d.Schema),
Execute: func(ctx context.Context, input string) (string, error) {
return call(ctx, box, d, jsontext.Value(input))
},
}
}
return set
}
func call(ctx context.Context, box Toolbox, d connectors.Declaration, input jsontext.Value) (string, error) {
conn, ok := box.Get(d.Connector)
if !ok {
return "", fmt.Errorf("connector %q isn't running", d.Connector)
}
if d.Kind == connectors.KindLookup {
out, found, err := conn.Lookup[jsontext.Value](ctx, d.Name, input)
switch {
case err != nil:
return "", err
case !found:
return "not found", nil
}
return string(out), nil
}
out, err := conn.Invoke[jsontext.Value](ctx, connectors.Invocation{
Action: d.Name, Input: input, IdempotencyKey: core.IdempotencyKey(ctx),
})
if errors.Is(err, connectors.ErrOutcomeUnknown) {
return "", fmt.Errorf("%w: %w", core.ErrOutcomeUnknown, err)
}
if err != nil {
return "", err
}
return string(out), nil
}
+51
View File
@@ -0,0 +1,51 @@
package runs
import "context"
// Journal records a sequence of entries, such as an agent loop's model and
// tool calls, as steps of the run. Entry n is the step at the journal's base
// plus n, so a replay finds every entry where it was written and the workflow's
// later steps follow the last one.
type Journal[E any] struct {
rc *Context
name string
base int
}
// Journal starts a journal at the run's next step. name must be unique within
// the workflow.
func (rc *Context) Journal[E any](name string) *Journal[E] {
return &Journal[E]{rc: rc, name: "journal:" + name, base: rc.next}
}
// Lookup returns the entry recorded at pos, or nil when there is none. A
// position with no entry is where live work starts, so a requested
// cancellation stops the run there, as it does before a step.
func (j *Journal[E]) Lookup(ctx context.Context, pos int64) (*E, error) {
seq := j.base + int(pos)
saved, ok := j.rc.saved[seq]
if !ok {
return nil, j.rc.checkCancel(ctx)
}
entry, err := replay[E](saved, j.name)
if err != nil {
return nil, err
}
j.rc.reach(seq)
return &entry, nil
}
// Record saves entry at pos, fenced by the run's lease like any step.
func (j *Journal[E]) Record(ctx context.Context, pos int64, entry E) error {
seq := j.base + int(pos)
if _, err := j.rc.record(ctx, seq, j.name, entry, nil); err != nil {
return err
}
j.rc.reach(seq)
return nil
}
// reach moves the run's next step past seq.
func (rc *Context) reach(seq int) {
rc.next = max(rc.next, seq+1)
}
+12 -5
View File
@@ -23,9 +23,12 @@ type fakeWork struct {
// recordedElsewhere is a step another lease holder already recorded; it
// becomes visible once this worker tries to write the same position.
recordedElsewhere *store.Step
steps []store.Step
finished []string
results []jsontext.Value
// rejectFrom, when set, makes every write from that many recorded steps
// on fail as a lost lease: the worker was killed there.
rejectFrom *int
steps []store.Step
finished []string
results []jsontext.Value
}
func (f *fakeWork) Claim(context.Context, string, uuid.UUID, time.Duration) (store.Run, bool, error) {
@@ -42,10 +45,14 @@ func (f *fakeWork) Steps(context.Context, uuid.UUID) ([]store.Step, error) {
return append([]store.Step(nil), f.steps...), nil
}
func (f *fakeWork) RecordStep(_ context.Context, _ uuid.UUID, step store.Step) error {
func (f *fakeWork) RecordStep(ctx context.Context, _ uuid.UUID, step store.Step) error {
f.mu.Lock()
defer f.mu.Unlock()
if f.leaseLost {
// A database write fails on a cancelled context.
if err := ctx.Err(); err != nil {
return err
}
if f.leaseLost || (f.rejectFrom != nil && len(f.steps) >= *f.rejectFrom) {
return store.ErrLeaseLost
}
if f.recordedElsewhere != nil && f.recordedElsewhere.Seq == step.Seq {