Files
archie/modules/chat/actions.go
T
samandCopilot cbfcd43018 feat(chat): add the chat module to the archie binary (#2018)
Conversations are the chat module's own tables. A turn is stored before it
is acknowledged, runs after the turns before it in its session, and records
everything it streams, so a reader replays it from a cursor. The agent uses
the configured agent model, the same connector tools as a run and the
dashboard's own reads; every action is judged, and one judgement holds is
put to people through approvals and run once when approved. A restart fails
the turns it interrupted visibly and never restarts a started action.

Conversation memory is a set of notes in the memory module. The chat
prompts are copied from internal/prompts (chat-system.tmpl, soul.md,
session-title.md) into internal/platform/prompts while the gateway still
reads them; the tool parameter redaction is copied from
internal/domain/messaging/tool_parameters.go.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-19 19:40:44 +11:00

217 lines
7.2 KiB
Go

package chat
import (
"context"
"encoding/json"
"encoding/json/jsontext"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/internal/platform/hub"
"github.com/samcharles93/archie-core/modules/approvals"
"github.com/samcharles93/archie-core/modules/chat/internal/store"
"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"
)
// Action states.
const (
actionWaiting = "waiting"
actionApproved = "approved"
actionRunning = "running"
actionSucceeded = "succeeded"
actionFailed = "failed"
actionUnknown = "unknown"
actionDenied = "denied"
actionExpired = "expired"
)
// Signal takes the answer to an approval a chat turn asked for. It reports
// false when id is not a chat turn, so the caller passes the answer on to the
// run waiting on it. The answer is stored before anything runs; the work loop
// runs an approved action once.
func (m *Module) Signal(ctx context.Context, id uuid.UUID, key string, payload jsontext.Value) (bool, error) {
ours, err := m.store.IsTurn(ctx, id)
if err != nil || !ours {
return false, err
}
var answer approvals.Answer
if err := json.Unmarshal(payload, &answer); err != nil {
return true, fmt.Errorf("decode approval answer: %w", err)
}
state := actionDenied
if answer.Approved {
state = actionApproved
}
answered, err := m.store.Answer(ctx, id, key, state, payload)
if err != nil || !answered {
return true, err
}
if !answer.Approved {
m.record(ctx, id, kindAction, ActionDone{RequestID: answer.RequestID, State: actionDenied})
m.hub.Publish(hub.Note{Topic: sessionTopic})
}
m.poke()
return true, nil
}
// settleActions escalates or expires actions nobody answered in time and runs
// the approved ones. An action found running was started by a process that
// stopped: it may have taken effect, so it is never started again.
func (m *Module) settleActions(ctx context.Context) {
d, ok := m.uses()
if !ok {
return
}
open, err := m.store.Open(ctx)
if err != nil {
if ctx.Err() == nil {
m.log.ErrorContext(ctx, "list held chat actions", "error", err)
}
return
}
for _, a := range open {
var err error
switch a.State {
case actionWaiting:
if time.Now().After(a.StepDue) {
err = m.escalate(ctx, d, a)
}
case actionApproved:
err = m.runApproved(ctx, d, a)
case actionRunning:
err = m.settled(ctx, d, a, actionRunning, actionUnknown,
"It was started before Archie restarted and its outcome is unknown; it may have taken effect and won't run again.")
}
if err != nil {
m.log.ErrorContext(ctx, "settle chat action", "action", a.ID, "request", a.RequestID, "error", err)
}
}
}
// escalate passes an unanswered action to the next step of its path, or
// expires it after the last.
func (m *Module) escalate(ctx context.Context, d Deps, a store.Action) error {
var path []governance.PathStep
if err := json.Unmarshal(a.Path, &path); err != nil {
return fmt.Errorf("decode escalation path: %w", err)
}
next := a.Step + 1
if next < len(path) {
if err := d.Approver.Escalate(ctx, a.RequestID, next, path[next]); err != nil {
return err
}
return m.store.Escalated(ctx, a.ID, next, time.Now().Add(path[next].Deadline()))
}
if err := d.Approver.Expire(ctx, a.RequestID); err != nil {
return err
}
return m.settled(ctx, d, a, actionWaiting, actionExpired, "Nobody answered before the last deadline, so it didn't run.")
}
// runApproved judges an approved action again and runs it once. An approval
// for an action that has since changed or become stricter is discarded, and
// the operator asks again.
func (m *Module) runApproved(ctx context.Context, d Deps, a store.Action) error {
var (
held judgement.Decision
answer approvals.Answer
)
if err := json.Unmarshal(a.Decision, &held); err != nil {
return fmt.Errorf("decode decision: %w", err)
}
if err := json.Unmarshal(a.Answer, &answer); err != nil {
return fmt.Errorf("decode answer: %w", err)
}
fresh, err := d.Judge.Assess(ctx, judgement.Request{
RunID: a.TurnID, Key: held.Key + ":again", Connector: held.Action.Connector, Action: held.Action.Name,
Input: held.Action.Input, Workflow: principal,
})
if err != nil {
// Nothing runs that wasn't judged again; the operator asks again.
return m.settled(ctx, d, a, actionApproved, actionFailed, "It couldn't be judged again before running: "+err.Error())
}
if why := invalidated(held, fresh); why != "" {
if err := d.Approver.Discard(ctx, a.RequestID, why); err != nil {
return err
}
return m.settled(ctx, d, a, actionApproved, actionFailed, "The approval no longer holds: "+why+". Ask Archie again.")
}
started, err := m.store.Move(ctx, a.ID, actionApproved, actionRunning, "")
if err != nil || !started {
return err
}
var out string
if fresh.Level.Runs() {
out, err = d.Judge.Execute(ctx, fresh, fresh.Action.Input, a.Key)
} else {
if err := d.Approver.Accept(ctx, a.RequestID); err != nil {
return err
}
out, err = d.Judge.ExecuteApproved(ctx, held, answer.Approval(held), held.Action.Input, a.Key)
}
switch {
case errors.Is(err, connectors.ErrOutcomeUnknown):
return m.settled(ctx, d, a, actionRunning, actionUnknown, "It was started and its outcome is unknown; it may have taken effect: "+err.Error())
case err != nil:
return m.settled(ctx, d, a, actionRunning, actionFailed, err.Error())
}
return m.settled(ctx, d, a, actionRunning, actionSucceeded, out)
}
// invalidated says why an approval no longer covers the action as judged now,
// or nothing when it still does.
func invalidated(approved, fresh judgement.Decision) string {
switch {
case fresh.Level == judgement.Never:
return "it is now refused: " + fresh.Reason
case fresh.Level.Runs():
return ""
case fresh.Action.Target != approved.Action.Target:
return "its target changed since it was approved"
case fresh.Action.Effect != approved.Action.Effect:
return "its effect changed since it was approved"
case fresh.Level > approved.Level:
return "judgement is stricter than when it was approved: now " + fresh.Level.String()
}
return ""
}
// settled records what became of an action, shows it in its conversation and
// tells the people notifications go to. The notification names no run: a
// chat turn isn't one.
func (m *Module) settled(ctx context.Context, d Deps, a store.Action, from, to, result string) error {
moved, err := m.store.Move(ctx, a.ID, from, to, result)
if err != nil || !moved {
return err
}
done := ActionDone{RequestID: a.RequestID, State: to, Result: truncateRunes(result, outputMaxRunes)}
m.record(ctx, a.TurnID, kindAction, done)
m.hub.Publish(hub.Note{Topic: sessionTopic})
var held judgement.Decision
_ = json.Unmarshal(a.Decision, &held)
return d.Notifier.Notify(ctx, deliveries.Notification{
Key: "chat:" + a.ID.String() + ":" + to,
Title: actionTitle(to) + ": " + held.Action.Connector + " " + held.Action.Name,
Body: result,
})
}
func actionTitle(state string) string {
switch state {
case actionSucceeded:
return "Approved action ran"
case actionExpired:
return "Approval timed out"
case actionUnknown:
return "An action's outcome is unknown"
default:
return "Approved action didn't run"
}
}