Files
archie/modules/governance/governance.go
T
sam 0238f247e5 feat(approvals): a held action is asked of a person, and the run waits for the answer (archie #1985, #1999)
An action judgement holds at propose and wait is no longer a dead end. The
new approvals module owns the request: it binds to the decision and the
action's digest, so an answer covers the action the person was shown and
nothing else, and it settles once. The answer wakes the run, which judges the
action again and runs it only as the approval allows: a refusal still refuses,
an altered input runs nothing, and a judgement that came back worse runs
nothing on that approval.

The composer carries the request as a message with the request id and its
deadline, and its answer is a message too, so the trail shows what was asked
and what was answered. A request nobody answers inside its deadline is settled
as expired and nothing runs.

How long a request waits is an organisation setting, edited in the dashboard
and stored in milliseconds, because a Postgres interval scans as text. A run
pins the deadline it started with, like its model.

An agent that proposes the same action twice is asked about it once, and the
notification says when the investigation proposed nothing at all.
2026-11-16 02:21:06 +11:00

239 lines
8.1 KiB
Go

// Package governance owns an organisation's settings. So far that is the
// agent model: the provider class, base URL and model every agent loop uses.
// Nothing an event or a tool result says can change where a model request
// goes, because the client is built only from these settings.
package governance
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"net/url"
"time"
"github.com/jmoiron/sqlx"
"github.com/samcharles93/ai-sdk/chat"
"github.com/samcharles93/ai-sdk/runtime"
"github.com/samcharles93/archie-core/internal/platform/httpjson"
"github.com/samcharles93/archie-core/modules/governance/internal/store"
)
// ErrNoAgentModel means the organisation hasn't chosen its agent model. There
// is no built-in default.
var ErrNoAgentModel = errors.New("no agent model is set for the organisation")
const roleAgent = "agent"
// DefaultApprovalDeadline is how long an approval request waits for an answer
// when the organisation hasn't said.
const DefaultApprovalDeadline = 24 * time.Hour
// The bounds on an approval deadline. Below a minute nobody could answer; past
// a month the request outlives the incident it was raised for.
const (
minApprovalDeadline = time.Minute
maxApprovalDeadline = 30 * 24 * time.Hour
)
// Settings is what the organisation decides about how Archie acts.
type Settings struct {
// ApprovalDeadline is how long an approval request waits for an answer
// before the run gives up on it.
ApprovalDeadline time.Duration
}
// settingsRequest is the settings as the API shows and sets them. A duration
// travels as a Go duration string ("24h"), the same form every other duration
// in the config takes.
type settingsRequest struct {
ApprovalDeadline string `json:"approval_deadline"`
}
// Model is the model chosen for a role.
type Model struct {
Class string `json:"class"`
BaseURL string `json:"base_url"`
Model string `json:"model"`
}
// Provider builds the chat client for m. Only keyless providers work until
// secret engines can supply a provider key.
func (m Model) Provider(ctx context.Context) (chat.Provider, chat.ModelInfo, error) {
rt := runtime.NewRuntime(runtime.Config{Providers: map[string]runtime.ProviderConfig{
roleAgent: {ID: roleAgent, Class: m.Class, BaseURL: m.BaseURL, Auth: runtime.AuthConfig{Type: runtime.AuthTypeNone}},
}})
ref := roleAgent + "/" + m.Model
provider, _, err := rt.ChatProvider(ctx, ref)
if err != nil {
return nil, chat.ModelInfo{}, fmt.Errorf("agent model %s: %w", ref, err)
}
info, err := rt.ChatModelInfo(ref)
if err != nil {
return nil, chat.ModelInfo{}, fmt.Errorf("agent model %s: %w", ref, err)
}
return provider, info, nil
}
// Module serves one organisation's settings.
type Module struct {
orgID string
store *store.Store
log *slog.Logger
}
// NewModule returns the governance module for orgID. The ai-sdk provider
// classes must already be registered.
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string) *Module {
return &Module{orgID: orgID, store: store.New(db), log: log}
}
// AgentModel returns the organisation's agent model.
func (m *Module) AgentModel(ctx context.Context) (Model, error) {
role, ok, err := m.store.ModelRole(ctx, m.orgID, roleAgent)
if err != nil {
return Model{}, err
}
if !ok {
return Model{}, ErrNoAgentModel
}
return Model{Class: role.Class, BaseURL: role.BaseURL, Model: role.Model}, nil
}
// Settings returns the organisation's settings, with a default for every one it
// hasn't set.
func (m *Module) Settings(ctx context.Context) (Settings, error) {
row, ok, err := m.store.Settings(ctx, m.orgID)
if err != nil {
return Settings{}, err
}
if !ok {
return Settings{ApprovalDeadline: DefaultApprovalDeadline}, nil
}
return Settings{ApprovalDeadline: time.Duration(row.ApprovalDeadlineMS) * time.Millisecond}, nil
}
// ApprovalDeadline is how long an approval request waits for an answer.
func (m *Module) ApprovalDeadline(ctx context.Context) (time.Duration, error) {
set, err := m.Settings(ctx)
if err != nil {
return 0, err
}
return set.ApprovalDeadline, nil
}
// Routes adds the settings API to mux behind guard.
func (m *Module) Routes(mux *http.ServeMux, guard func(http.Handler) http.Handler) {
mux.Handle("GET /api/settings/agent-model", guard(http.HandlerFunc(m.getAgentModel)))
mux.Handle("PUT /api/settings/agent-model", guard(http.HandlerFunc(m.putAgentModel)))
mux.Handle("GET /api/settings", guard(http.HandlerFunc(m.getSettings)))
mux.Handle("PUT /api/settings", guard(http.HandlerFunc(m.putSettings)))
}
func (m *Module) getSettings(w http.ResponseWriter, r *http.Request) {
set, err := m.Settings(r.Context())
if err != nil {
m.log.ErrorContext(r.Context(), "read settings", "error", err)
httpjson.Error(w, http.StatusInternalServerError, "couldn't read the settings")
return
}
httpjson.Write(w, http.StatusOK, settingsRequest{ApprovalDeadline: set.ApprovalDeadline.String()})
}
func (m *Module) putSettings(w http.ResponseWriter, r *http.Request) {
var req settingsRequest
if err := httpjson.Read(r, &req); err != nil {
httpjson.Error(w, http.StatusBadRequest, err.Error())
return
}
deadline, err := time.ParseDuration(req.ApprovalDeadline)
if err != nil {
httpjson.Error(w, http.StatusBadRequest, "approval deadline is a duration, such as 24h")
return
}
set := Settings{ApprovalDeadline: deadline}
if err := set.validate(); err != nil {
httpjson.Error(w, http.StatusBadRequest, err.Error())
return
}
if err := m.store.PutSettings(r.Context(), store.Settings{
OrgID: m.orgID, ApprovalDeadlineMS: set.ApprovalDeadline.Milliseconds(),
}); err != nil {
m.log.ErrorContext(r.Context(), "put settings", "error", err)
httpjson.Error(w, http.StatusInternalServerError, "couldn't save the settings")
return
}
httpjson.Write(w, http.StatusOK, settingsRequest{ApprovalDeadline: set.ApprovalDeadline.String()})
}
// validate keeps a deadline inside the range an answer can be given in.
func (s Settings) validate() error {
if s.ApprovalDeadline < minApprovalDeadline || s.ApprovalDeadline > maxApprovalDeadline {
return fmt.Errorf("approval deadline must be between %s and %s", minApprovalDeadline, maxApprovalDeadline)
}
return nil
}
func (m *Module) getAgentModel(w http.ResponseWriter, r *http.Request) {
model, err := m.AgentModel(r.Context())
switch {
case errors.Is(err, ErrNoAgentModel):
httpjson.Error(w, http.StatusNotFound, err.Error())
case err != nil:
m.log.ErrorContext(r.Context(), "read agent model", "error", err)
httpjson.Error(w, http.StatusInternalServerError, "couldn't read the agent model")
default:
httpjson.Write(w, http.StatusOK, model)
}
}
// putAgentModel sets the agent model. An empty base URL takes the class's
// published default, and the stored value is always explicit.
func (m *Module) putAgentModel(w http.ResponseWriter, r *http.Request) {
var req Model
if err := httpjson.Read(r, &req); err != nil {
httpjson.Error(w, http.StatusBadRequest, err.Error())
return
}
model, err := settle(req)
if err != nil {
httpjson.Error(w, http.StatusBadRequest, err.Error())
return
}
if _, _, err := model.Provider(r.Context()); err != nil {
httpjson.Error(w, http.StatusBadRequest, err.Error())
return
}
if err := m.store.PutModelRole(r.Context(), store.ModelRole{
OrgID: m.orgID, Role: roleAgent, Class: model.Class, BaseURL: model.BaseURL, Model: model.Model,
}); err != nil {
m.log.ErrorContext(r.Context(), "put agent model", "error", err)
httpjson.Error(w, http.StatusInternalServerError, "couldn't save the agent model")
return
}
httpjson.Write(w, http.StatusOK, model)
}
func settle(req Model) (Model, error) {
if _, ok := runtime.GetClass(req.Class); !ok {
return Model{}, fmt.Errorf("unknown provider class %q", req.Class)
}
if req.Model == "" {
return Model{}, errors.New("a model is required")
}
if req.BaseURL == "" {
base, ok := runtime.DefaultBaseURL(req.Class)
if !ok {
return Model{}, fmt.Errorf("provider class %q has no default base URL; give one", req.Class)
}
req.BaseURL = base
}
u, err := url.Parse(req.BaseURL)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return Model{}, fmt.Errorf("base URL %q must be an http or https URL", req.BaseURL)
}
return req, nil
}