285 lines
9.6 KiB
Go
285 lines
9.6 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
|
|
|
|
// DefaultRaiseAfter is how many approvals in a row earn a proposal to raise an
|
|
// action class when the organisation hasn't said.
|
|
const DefaultRaiseAfter = 3
|
|
|
|
// maxRaiseAfter bounds the count: past it a class could never earn a raise.
|
|
const maxRaiseAfter = 100
|
|
|
|
// 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
|
|
// RaiseAfter is how many approvals in a row, since an action class was last
|
|
// tightened, earn a proposal to raise it one level.
|
|
RaiseAfter int
|
|
// Frozen holds every action that changes something at propose and wait,
|
|
// without changing any class's level.
|
|
Frozen bool
|
|
}
|
|
|
|
// 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"`
|
|
RaiseAfter int `json:"raise_after"`
|
|
Frozen bool `json:"frozen"`
|
|
}
|
|
|
|
func (s Settings) request() settingsRequest {
|
|
return settingsRequest{ApprovalDeadline: s.ApprovalDeadline.String(), RaiseAfter: s.RaiseAfter, Frozen: s.Frozen}
|
|
}
|
|
|
|
// 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, RaiseAfter: DefaultRaiseAfter}, nil
|
|
}
|
|
return Settings{
|
|
ApprovalDeadline: time.Duration(row.ApprovalDeadlineMS) * time.Millisecond,
|
|
RaiseAfter: row.RaiseAfter, Frozen: row.Frozen,
|
|
}, nil
|
|
}
|
|
|
|
// RaiseAfter is how many approvals in a row earn a proposal to raise an action
|
|
// class.
|
|
func (m *Module) RaiseAfter(ctx context.Context) (int, error) {
|
|
set, err := m.Settings(ctx)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return set.RaiseAfter, nil
|
|
}
|
|
|
|
// Frozen reports whether the organisation has frozen its actions.
|
|
func (m *Module) Frozen(ctx context.Context) (bool, error) {
|
|
set, err := m.Settings(ctx)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
return set.Frozen, 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, set.request())
|
|
}
|
|
|
|
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, RaiseAfter: req.RaiseAfter, Frozen: req.Frozen}
|
|
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(),
|
|
RaiseAfter: set.RaiseAfter, Frozen: set.Frozen,
|
|
}); 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, set.request())
|
|
}
|
|
|
|
// validate keeps a deadline inside the range an answer can be given in, and
|
|
// the count of approvals a raise needs inside the range a class can earn.
|
|
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)
|
|
}
|
|
if s.RaiseAfter < 1 || s.RaiseAfter > maxRaiseAfter {
|
|
return fmt.Errorf("raise after must be between 1 and %d approvals", maxRaiseAfter)
|
|
}
|
|
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
|
|
}
|