Files
archie/modules/runs/investigate.go
T

473 lines
17 KiB
Go

package runs
import (
"context"
"encoding/json/jsontext"
json "encoding/json/v2"
"errors"
"fmt"
"regexp"
"slices"
"strings"
"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/approvals"
"github.com/samcharles93/archie-core/modules/connectors"
"github.com/samcharles93/archie-core/modules/deliveries"
"github.com/samcharles93/archie-core/modules/governance"
"github.com/samcharles93/archie-core/modules/judgement"
)
// Settings is where a workflow finds what the organisation decided: the agent
// model it runs, and how long an approval request waits for an answer.
type Settings interface {
AgentModel(ctx context.Context) (governance.Model, error)
ApprovalDeadline(ctx context.Context) (time.Duration, error)
}
// Toolbox is where a workflow finds the connector lookups and actions and the
// MCP server tools it may offer an agent, and the tools that run them.
type Toolbox interface {
Declarations() []connectors.Declaration
Tool(name string) (connectors.Tool, bool)
}
// Judge decides whether an agent's action runs, and runs only what it
// decided.
type Judge interface {
Assess(ctx context.Context, req judgement.Request) (judgement.Decision, error)
Execute(ctx context.Context, d judgement.Decision, input jsontext.Value, key string) (string, error)
ExecuteApproved(ctx context.Context, d judgement.Decision, a judgement.Approval, input jsontext.Value, key string) (string, error)
ForRun(ctx context.Context, runID uuid.UUID) ([]judgement.Decision, error)
}
// Approver asks people to allow an action judgement held, and settles a request
// whose deadline passed.
type Approver interface {
Ask(ctx context.Context, runID uuid.UUID, key string, d judgement.Decision, deadline time.Time) (approvals.Request, error)
Expire(ctx context.Context, id uuid.UUID) error
}
// 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}
// 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. An action
// the agent proposes is judged as it calls it; one judgement holds is put to a
// person, and the run waits for the answer before running it.
func Investigate(settings Settings, box Toolbox, judge Judge, ask Approver, 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 settings.AgentModel(ctx)
})
if err != nil {
return nil, err
}
// Pinned here, like the model: a run that waits keeps the deadline it
// started with, whatever the setting becomes meanwhile. A step's value
// is encoded, so it travels as the duration's own text.
deadlineText, err := rc.Step("approval-deadline", func(ctx context.Context, _ string) (string, error) {
d, err := settings.ApprovalDeadline(ctx)
return d.String(), err
})
if err != nil {
return nil, err
}
deadline, err := time.ParseDuration(deadlineText)
if err != nil {
return nil, fmt.Errorf("approval deadline %q: %w", deadlineText, err)
}
decls, err := rc.Step("agent-tools", func(context.Context, string) ([]connectors.Declaration, error) {
return 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, judge, rc.RunID(), decls),
Budget: investigateBudget,
})
if err != nil {
return nil, err
}
if res, err = followThrough(rc, judge, decls, input, res, AgentRequest{
Provider: provider, Model: model.Model, ModelInfo: info,
Tools: toolSet(box, judge, rc.RunID(), decls),
}); err != nil {
return nil, err
}
outcomes, err := settleProposals(rc, judge, ask, deadline)
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, outcomes))
}); 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
}
}
// followThroughBudget bounds the turn that has the agent call what it only
// described.
var followThroughBudget = agentloop.Budget{MaxSteps: 8, MaxTokens: 60_000, WallClock: 5 * time.Minute}
// followThrough gives the agent one more turn when its findings name an action
// it never called: a small model often writes the call out instead of making
// it, and an action that was only described can't be judged or approved.
func followThrough(rc *Context, judge Judge, decls []connectors.Declaration, input jsontext.Value, res AgentResult, req AgentRequest) (AgentResult, error) {
if !res.Completed {
return res, nil
}
made, err := rc.Step("decisions-made", func(ctx context.Context, _ string) ([]string, error) {
decisions, err := judge.ForRun(ctx, rc.RunID())
names := make([]string, 0, len(decisions))
for _, d := range decisions {
names = append(names, toolName(d.Action.Connector, d.Action.Name))
}
return names, err
})
if err != nil {
return res, err
}
missed := uncalled(res.Answer, decls, made)
if len(missed) == 0 {
return res, nil
}
prompt, err := json.Marshal(map[string]any{"event": input, "findings": res.Answer, "described_but_not_called": missed})
if err != nil {
return res, err
}
req.Name, req.System, req.Prompt, req.Budget = "follow-through", prompts.Investigate()+"\n\n"+prompts.FollowThrough(), string(prompt), followThroughBudget
again, err := rc.Agent(req)
if err != nil || !again.Completed {
// The first findings stand when the extra turn doesn't finish.
return res, err
}
return again, nil
}
// uncalled lists the actions an answer names that no decision in the run
// records.
func uncalled(answer string, decls []connectors.Declaration, made []string) []string {
var out []string
for _, d := range decls {
name := toolName(d.Connector, d.Name)
if d.Kind == connectors.KindAction && strings.Contains(answer, name) && !slices.Contains(made, name) {
out = append(out, name)
}
}
return out
}
func toolName(connector, name string) string {
return unsafeToolChars.ReplaceAllString(connector+"_"+name, "_")
}
// approvalOutcome is what became of one action the agent proposed.
type approvalOutcome struct {
Action string `json:"action"`
Target string `json:"target"`
RequestID uuid.UUID `json:"request_id"`
State string `json:"state"`
By string `json:"by,omitzero"`
Result string `json:"result,omitzero"`
Error string `json:"error,omitzero"`
// Unknown is an action that was started but can't be confirmed: it may
// have taken effect, and it is never started again.
Unknown bool `json:"unknown,omitzero"`
}
// settleProposals puts every action judgement held to a person, one at a time,
// and runs the ones they allow. Each ask, wait and run is its own step, so a
// resumed run picks up where it waited. A proposal nobody answers in time is
// settled as expired and nothing runs.
func settleProposals(rc *Context, judge Judge, ask Approver, deadline time.Duration) ([]approvalOutcome, error) {
held, err := rc.Step("proposals", func(ctx context.Context, _ string) ([]judgement.Decision, error) {
decisions, err := judge.ForRun(ctx, rc.RunID())
if err != nil {
return nil, err
}
return heldByJudgement(decisions), nil
})
if err != nil {
return nil, err
}
out := make([]approvalOutcome, 0, len(held))
for _, d := range held {
outcome, err := settleOne(rc, judge, ask, d, deadline)
if err != nil {
return nil, err
}
out = append(out, outcome)
}
return out, nil
}
func settleOne(rc *Context, judge Judge, ask Approver, d judgement.Decision, deadline time.Duration) (approvalOutcome, error) {
out := approvalOutcome{Action: d.Action.Connector + " " + d.Action.Name, Target: d.Action.Target.Kind + ":" + d.Action.Target.ID}
request, err := rc.Step("ask:"+d.Key, func(ctx context.Context, _ string) (approvals.Request, error) {
return ask.Ask(ctx, rc.RunID(), waitKey(d.Key), d, time.Now().Add(deadline))
})
if err != nil {
return out, err
}
out.RequestID, out.State = request.ID, request.State
if request.State != approvals.StatePending {
return out, nil
}
answer, expired, err := waitForAnswer(rc, ask, d.Key, request, deadline)
if err != nil {
return out, err
}
if expired {
out.State = approvals.StateExpired
return out, nil
}
if !answer.Approved {
out.State, out.By = approvals.StateDenied, answer.By
return out, nil
}
out.By = answer.By
// The action's own failure is part of what the answer led to, and its step
// has recorded it, so the investigation still reports.
run, runErr := runApproved(rc, judge, d, answer)
out.State, out.Result, out.Error = approvals.StateApproved, run, errText(runErr)
out.Unknown = errors.Is(runErr, ErrOutcomeUnknown)
return out, nil
}
// unknownOutcome records a connector's unconfirmed action as a step whose
// outcome is unknown, so a resumed run reports it and never runs it again.
func unknownOutcome(err error) error {
if errors.Is(err, connectors.ErrOutcomeUnknown) {
return fmt.Errorf("%w: %w", ErrOutcomeUnknown, err)
}
return err
}
// errText is a failed action's reason, or nothing when it ran.
func errText(err error) string {
if err == nil {
return ""
}
return err.Error()
}
// waitForAnswer waits for the person's answer. When the deadline passes with
// none, the request is settled as expired and the caller runs nothing.
func waitForAnswer(rc *Context, ask Approver, key string, request approvals.Request, deadline time.Duration) (approvals.Answer, bool, error) {
payload, err := rc.Wait(waitKey(key), deadline)
if errors.Is(err, ErrWaitTimedOut) {
if _, eerr := rc.Step("expire:"+key, func(ctx context.Context, _ string) (bool, error) {
return true, ask.Expire(ctx, request.ID)
}); eerr != nil {
return approvals.Answer{}, true, eerr
}
return approvals.Answer{}, true, nil
}
if err != nil {
return approvals.Answer{}, false, err
}
var answer approvals.Answer
if err := json.Unmarshal(payload, &answer); err != nil {
return approvals.Answer{}, false, fmt.Errorf("decode approval answer: %w", err)
}
return answer, false, nil
}
// runApproved judges the action again and runs it, once. An approval covers
// the action the person was shown, so a judgement that came back worse than
// it was cannot be run on that approval.
func runApproved(rc *Context, judge Judge, d judgement.Decision, answer approvals.Answer) (string, error) {
fresh, err := rc.Step("judge-again:"+d.Key, func(ctx context.Context, key string) (judgement.Decision, error) {
return judge.Assess(ctx, judgement.Request{
RunID: rc.RunID(), Key: key, Connector: d.Action.Connector, Action: d.Action.Name, Input: d.Action.Input,
})
})
if err != nil {
return "", err
}
return rc.Step("run:"+d.Key, func(ctx context.Context, key string) (string, error) {
switch {
case fresh.Level == judgement.Never:
return "", fmt.Errorf("refused after approval: %s", fresh.Reason)
case fresh.Level.Runs():
out, err := judge.Execute(ctx, fresh, d.Action.Input, key)
return out, unknownOutcome(err)
case fresh.Level > d.Level:
return "", fmt.Errorf("judgement got worse after approval: now %s", fresh.Level)
}
out, err := judge.ExecuteApproved(ctx, d, answer.Approval(d), d.Action.Input, key)
return out, unknownOutcome(err)
})
}
// heldByJudgement is the actions an agent proposed that need a person before
// they run, once each: an agent that asks for the same action twice is asked
// about it once.
func heldByJudgement(decisions []judgement.Decision) []judgement.Decision {
seen := make(map[string]bool, len(decisions))
out := make([]judgement.Decision, 0, len(decisions))
for _, d := range decisions {
if d.Level < judgement.ProposeAndWait || d.Level == judgement.Never || seen[d.Action.Digest] {
continue
}
seen[d.Action.Digest] = true
out = append(out, d)
}
return out
}
// waitKey is the run key an approval answer wakes.
func waitKey(key string) string { return "approval:" + key }
// findings is the notification an investigation ends with, finished or not.
func findings(runID uuid.UUID, key string, res AgentResult, outcomes []approvalOutcome) 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)
}
// The record says plainly when nothing was proposed, whatever the findings
// then claim.
n.Body += "\n\n" + outcomeLines(outcomes)
return n
}
// outcomeLines says what became of each action the investigation proposed, and
// that none was when that is the case.
func outcomeLines(outcomes []approvalOutcome) string {
if len(outcomes) == 0 {
return "Actions: none proposed."
}
lines := make([]string, 0, len(outcomes))
for _, o := range outcomes {
line := fmt.Sprintf("- %s on %s: %s", o.Action, o.Target, o.State)
switch {
case o.Unknown:
line += ", it was started but its outcome is unknown: " + o.Error
case o.Error != "":
line += ", it did not run: " + o.Error
case o.Result != "":
line += ", it ran: " + o.Result
case o.State == approvals.StateApproved:
line += ", it ran"
}
if o.By != "" {
line += " (" + o.By + ")"
}
lines = append(lines, line)
}
return "Actions:\n" + strings.Join(lines, "\n")
}
// 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 or MCP server by name when the model asks, so one that has
// since stopped fails that call rather than the run.
func toolSet(box Toolbox, judge Judge, runID uuid.UUID, decls []connectors.Declaration) core.ToolSet {
set := core.ToolSet{}
for _, d := range decls {
name := toolName(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, judge, runID, d, jsontext.Value(input))
},
}
}
return set
}
func call(ctx context.Context, box Toolbox, judge Judge, runID uuid.UUID, d connectors.Declaration, input jsontext.Value) (string, error) {
tool, ok := box.Tool(d.Connector)
if !ok {
return "", fmt.Errorf("%q isn't running", d.Connector)
}
if d.Kind == connectors.KindLookup {
out, found, err := tool.Lookup(ctx, d.Name, input)
switch {
case err != nil:
return "", err
case !found:
return "not found", nil
}
return out, nil
}
// An action is judged first and runs only as decided. One judgement holds
// is proposed to a person when the investigation ends, so it comes back to
// the agent as something waiting rather than a failure.
key := core.IdempotencyKey(ctx)
decision, err := judge.Assess(ctx, judgement.Request{RunID: runID, Key: key, Connector: d.Connector, Action: d.Name, Input: input})
if err != nil {
return "", err
}
out, err := judge.Execute(ctx, decision, input, key)
if errors.Is(err, judgement.ErrHeld) {
return fmt.Sprintf("held at %s for a person's approval: %s. It is asked when your investigation ends, so don't propose it again.", decision.Level, findingsOf(decision)), nil
}
if errors.Is(err, connectors.ErrOutcomeUnknown) {
return "", fmt.Errorf("%w: %w", core.ErrOutcomeUnknown, err)
}
if err != nil {
return "", err
}
return out, nil
}
// findingsOf lists what held a decision back, for the agent.
func findingsOf(d judgement.Decision) string {
var parts []string
for _, v := range d.Verdicts {
if v.Advisory || v.Ceiling != d.Level {
continue
}
for _, f := range v.Findings {
parts = append(parts, v.Guard+": "+f.Text)
}
if v.Failed != "" {
parts = append(parts, v.Guard+" couldn't judge: "+v.Failed)
}
}
if len(parts) == 0 {
return "no guard allowed it to run unattended"
}
return strings.Join(parts, "; ")
}