From 51a1cf51281e15d94b6e7e20d9c1921317c4e0ec Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sun, 22 Nov 2026 15:41:40 +1100 Subject: [PATCH] feat(governance): model aliases resolve through providers with a policy (#2063) --- api/openapi.yaml | 737 +++++++++++++++++- .../00055_governance_model_providers.sql | 59 ++ modules/chat/api.go | 2 +- modules/chat/chat.go | 2 +- modules/chat/turn.go | 4 +- modules/governance/accounts_api.go | 5 +- modules/governance/governance.go | 75 +- modules/governance/internal/store/store.go | 180 ++++- modules/governance/models_api.go | 287 +++++++ modules/governance/models_api_test.go | 31 + modules/runs/agent_test.go | 2 +- modules/runs/interpreter.go | 4 +- modules/runs/investigate_test.go | 2 +- modules/runs/runs.go | 2 +- modules/runs/steps_test.go | 2 +- 15 files changed, 1321 insertions(+), 73 deletions(-) create mode 100644 internal/platform/pg/migrations/00055_governance_model_providers.sql create mode 100644 modules/governance/models_api.go create mode 100644 modules/governance/models_api_test.go diff --git a/api/openapi.yaml b/api/openapi.yaml index 072bd261d..9ac88b97d 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -141,6 +141,32 @@ components: required: - capture type: object + CatalogueGrants: + additionalProperties: false + properties: + credentials: + items: + type: string + type: + - array + - "null" + egress: + items: + type: string + type: + - array + - "null" + env: + items: + type: string + type: + - array + - "null" + required: + - egress + - env + - credentials + type: object ChangePasswordInputBody: additionalProperties: false properties: @@ -437,6 +463,64 @@ components: - description - schema type: object + ConnectorsCatalogueEntry: + additionalProperties: false + properties: + contract: + type: string + description: + type: string + digest: + type: string + display_name: + type: string + grants: + $ref: "#/components/schemas/CatalogueGrants" + group: + enum: + - platform + - integration + - agent + type: string + installed: + type: boolean + installed_version: + type: string + name: + type: string + update_available: + type: boolean + version: + type: string + required: + - name + - display_name + - description + - contract + - group + - version + - digest + - grants + - installed + - update_available + type: object + ConnectorsCatalogueSource: + additionalProperties: false + properties: + location: + description: An https URL or an absolute path to the catalogue; its signature is beside it with .sig added + type: string + newest: + format: date-time + readOnly: true + type: string + public_key: + description: The base64 Ed25519 public key the catalogue is signed with + type: string + required: + - location + - public_key + type: object ConnectorsCredentialKind: additionalProperties: false properties: @@ -548,12 +632,16 @@ components: ConnectorsExtensionView: additionalProperties: false properties: + accepted: + $ref: "#/components/schemas/CatalogueGrants" args: items: type: string type: - array - "null" + can_rollback: + type: boolean capabilities: $ref: "#/components/schemas/ConnectorsCapabilities" contract: @@ -562,8 +650,14 @@ components: additionalProperties: type: string type: object + declared: + $ref: "#/components/schemas/CatalogueGrants" + description: + type: string digest: type: string + display_name: + type: string effects: $ref: "#/components/schemas/ConnectorsServerEffects" egress: @@ -572,6 +666,8 @@ components: type: - array - "null" + enabled: + type: boolean env: items: type: string @@ -586,10 +682,14 @@ components: - integration - agent type: string + managed: + type: boolean name: type: string path: type: string + pending: + $ref: "#/components/schemas/ConnectorsPendingView" settings: additionalProperties: type: string @@ -603,6 +703,8 @@ components: state: type: string tools: {} + update_policy: + type: string url: type: string version: @@ -618,6 +720,9 @@ components: - settings - settings_schema - credentials + - enabled + - managed + - can_rollback type: object ConnectorsField: additionalProperties: false @@ -630,6 +735,32 @@ components: type: string writeOnly: true type: object + ConnectorsGrantsRequest: + additionalProperties: false + properties: + credentials: + additionalProperties: + type: string + type: object + egress: + description: Every host the extension may reach; empty leaves it unconfined, which only an extension that declares no hosts may be given + items: + type: string + type: + - array + - "null" + env: + description: Host environment variables the extension may see + items: + type: string + type: + - array + - "null" + settings: + additionalProperties: + type: string + type: object + type: object ConnectorsHealth: additionalProperties: false properties: @@ -652,6 +783,26 @@ components: - contract - healthy type: object + ConnectorsLifecycle: + additionalProperties: false + properties: + digest: + type: string + enabled: + type: boolean + name: + type: string + pending: + type: boolean + version: + type: string + required: + - name + - version + - digest + - pending + - enabled + type: object ConnectorsMcpRequest: additionalProperties: false properties: @@ -711,6 +862,20 @@ components: - name - state type: object + ConnectorsPendingView: + additionalProperties: false + properties: + added: + $ref: "#/components/schemas/CatalogueGrants" + digest: + type: string + version: + type: string + required: + - version + - digest + - added + type: object ConnectorsPrivilegedEffects: additionalProperties: false properties: @@ -761,6 +926,16 @@ components: - key - label type: object + ConnectorsSourceView: + additionalProperties: false + properties: + configured: + type: boolean + source: + $ref: "#/components/schemas/ConnectorsCatalogueSource" + required: + - configured + type: object ConnectorsTarget: additionalProperties: false properties: @@ -1565,6 +1740,33 @@ components: type: string type: object type: object + ExtensionEnabledInputBody: + additionalProperties: false + properties: + enabled: + type: boolean + required: + - enabled + type: object + ExtensionPolicyInputBody: + additionalProperties: false + properties: + policy: + enum: + - manual + - auto + type: string + required: + - policy + type: object + ExtensionSettingsInputBody: + additionalProperties: false + properties: + settings: + additionalProperties: + type: string + type: object + type: object GovernanceAuthStatusBody: additionalProperties: false properties: @@ -1846,16 +2048,22 @@ components: additionalProperties: false properties: api_key_credential: + readOnly: true type: string base_url: + readOnly: true type: string class: + readOnly: true type: string model: + description: The model's name on the provider + type: string + provider: + description: The provider the model is called on type: string required: - - class - - base_url + - provider - model type: object GovernanceModelAnswer: @@ -1869,6 +2077,54 @@ components: - model - answer type: object + GovernanceModelClass: + additionalProperties: false + properties: + class: + type: string + default_base_url: + type: string + required: + - class + type: object + GovernanceModelPolicy: + additionalProperties: false + properties: + chat_aliases: + description: Aliases chat may use; null lets it use any + items: + type: string + type: + - array + - "null" + workflow_aliases: + description: Aliases workflows may name; null lets them use any + items: + type: string + type: + - array + - "null" + required: + - workflow_aliases + - chat_aliases + type: object + GovernanceModelProvider: + additionalProperties: false + properties: + api_key_credential: + type: string + base_url: + type: string + class: + description: A provider class from the model classes catalogue + type: string + name: + description: Lowercase letters, digits, dots, underscores or hyphens + type: string + required: + - name + - class + type: object GovernanceOrgBody: additionalProperties: false properties: @@ -5509,6 +5765,343 @@ paths: summary: List the kinds of extension and the group each belongs to tags: - Connectors + /api/extensions: + get: + operationId: list-extensions + responses: + "200": + content: + application/json: + schema: + items: + $ref: "#/components/schemas/ConnectorsExtensionView" + type: + - array + - "null" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: List every accepted package, whatever its contract + tags: + - Extensions + /api/extensions/catalogue: + get: + operationId: list-catalogue + responses: + "200": + content: + application/json: + schema: + items: + $ref: "#/components/schemas/ConnectorsCatalogueEntry" + type: + - array + - "null" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: List the extensions the signed catalogue offers + tags: + - Extension catalogue + /api/extensions/catalogue-source: + get: + operationId: get-catalogue-source + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ConnectorsSourceView" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Get where the extension catalogue is read from + tags: + - Extension catalogue + put: + operationId: put-catalogue-source + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/ConnectorsCatalogueSource" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ConnectorsSourceView" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Set where the extension catalogue is read from and the key that signs it + tags: + - Extension catalogue + /api/extensions/catalogue/{name}/install: + post: + operationId: install-extension + parameters: + - in: path + name: name + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ConnectorsLifecycle" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Fetch an extension at the digest the catalogue pins and install it, not yet accepted + tags: + - Extension catalogue + /api/extensions/{name}: + delete: + operationId: remove-extension + parameters: + - in: path + name: name + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ConnectorsPackageState" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Remove an accepted package + tags: + - Extensions + /api/extensions/{name}/accept: + post: + operationId: accept-extension-grants + parameters: + - in: path + name: name + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/ConnectorsGrantsRequest" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ConnectorsLifecycle" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Accept the grants an installed extension may use, and its settings + tags: + - Extension catalogue + /api/extensions/{name}/approve-update: + post: + operationId: approve-extension-update + parameters: + - in: path + name: name + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ConnectorsLifecycle" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Apply the pending update and accept the grants it declares + tags: + - Extension catalogue + /api/extensions/{name}/enabled: + put: + operationId: put-extension-enabled + parameters: + - in: path + name: name + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/ExtensionEnabledInputBody" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ConnectorsLifecycle" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Start or stop an accepted extension + tags: + - Extension catalogue + /api/extensions/{name}/rollback: + post: + operationId: rollback-extension + parameters: + - in: path + name: name + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ConnectorsLifecycle" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Restore the previous version with the grants accepted for it + tags: + - Extension catalogue + /api/extensions/{name}/settings: + put: + operationId: put-extension-settings + parameters: + - in: path + name: name + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/ExtensionSettingsInputBody" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ConnectorsLifecycle" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Save an installed extension's settings and restart it + tags: + - Extension catalogue + /api/extensions/{name}/update: + post: + operationId: update-extension + parameters: + - in: path + name: name + required: true + schema: + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ConnectorsLifecycle" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Move an extension to the digest the catalogue now pins + tags: + - Extension catalogue + /api/extensions/{name}/update-policy: + put: + operationId: put-extension-update-policy + parameters: + - in: path + name: name + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/ExtensionPolicyInputBody" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ConnectorsLifecycle" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Set whether an extension follows the catalogue on its own + tags: + - Extension catalogue /api/groups: get: operationId: list-groups @@ -7138,6 +7731,146 @@ paths: summary: Change the organisation's standing instructions tags: - Governance + /api/settings/model-classes: + get: + operationId: list-model-classes + responses: + "200": + content: + application/json: + schema: + items: + $ref: "#/components/schemas/GovernanceModelClass" + type: + - array + - "null" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: List the provider classes the runtime can build + tags: + - Governance + /api/settings/model-policy: + get: + operationId: get-model-policy + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GovernanceModelPolicy" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Get which aliases workflows and chat may use + tags: + - Governance + put: + operationId: put-model-policy + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/GovernanceModelPolicy" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GovernanceModelPolicy" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Set which aliases workflows and chat may use + tags: + - Governance + /api/settings/model-providers: + get: + operationId: list-model-providers + responses: + "200": + content: + application/json: + schema: + additionalProperties: + $ref: "#/components/schemas/GovernanceModelProvider" + type: object + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: List model providers + tags: + - Governance + /api/settings/model-providers/{name}: + delete: + operationId: delete-model-provider + parameters: + - in: path + name: name + required: true + schema: + type: string + responses: + "204": + description: No Content + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Delete a model provider no alias uses + tags: + - Governance + put: + operationId: put-model-provider + parameters: + - description: Lowercase letters, digits, dots, underscores or hyphens + in: path + name: name + required: true + schema: + description: Lowercase letters, digits, dots, underscores or hyphens + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/GovernanceModelProvider" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GovernanceModelProvider" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Save a model provider + tags: + - Governance /api/sources: get: operationId: list-sources diff --git a/internal/platform/pg/migrations/00055_governance_model_providers.sql b/internal/platform/pg/migrations/00055_governance_model_providers.sql new file mode 100644 index 000000000..1f644aa98 --- /dev/null +++ b/internal/platform/pg/migrations/00055_governance_model_providers.sql @@ -0,0 +1,59 @@ +-- +goose Up +-- A provider is an endpoint models are called on: its class, base URL and the +-- credential whose token authenticates it. An alias names a provider and a +-- model on it, so one provider serves every alias that uses it. +CREATE TABLE governance.model_providers ( + org_id text NOT NULL, + name text NOT NULL CHECK (name ~ '^[a-z0-9][a-z0-9_.-]{0,62}$'), + class text NOT NULL, + base_url text NOT NULL, + api_key_credential text NOT NULL DEFAULT '', + updated_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (org_id, name) +); + +ALTER TABLE governance.model_roles ADD COLUMN provider text; + +-- Each distinct endpoint an alias already used becomes a provider named for +-- its class, with a number after the first. +INSERT INTO governance.model_providers (org_id, name, class, base_url, api_key_credential) +SELECT org_id, CASE WHEN n = 1 THEN class ELSE class || '-' || n END, class, base_url, api_key_credential +FROM ( + SELECT org_id, class, base_url, api_key_credential, + row_number() OVER (PARTITION BY org_id, class ORDER BY base_url, api_key_credential) AS n + FROM (SELECT DISTINCT org_id, class, base_url, api_key_credential FROM governance.model_roles) d +) numbered; + +UPDATE governance.model_roles r SET provider = p.name +FROM governance.model_providers p +WHERE p.org_id = r.org_id AND p.class = r.class AND p.base_url = r.base_url + AND p.api_key_credential = r.api_key_credential; + +ALTER TABLE governance.model_roles + ALTER COLUMN provider SET NOT NULL, + ADD FOREIGN KEY (org_id, provider) REFERENCES governance.model_providers (org_id, name), + DROP COLUMN class, + DROP COLUMN base_url, + DROP COLUMN api_key_credential; + +-- Which aliases a workflow and chat may use. Null lets either use any alias. +CREATE TABLE governance.model_policy ( + org_id text PRIMARY KEY, + workflow_aliases jsonb, + chat_aliases jsonb, + updated_at timestamptz NOT NULL DEFAULT now() +); + +-- +goose Down +DROP TABLE governance.model_policy; +ALTER TABLE governance.model_roles + ADD COLUMN class text, + ADD COLUMN base_url text, + ADD COLUMN api_key_credential text NOT NULL DEFAULT ''; +UPDATE governance.model_roles r SET class = p.class, base_url = p.base_url, api_key_credential = p.api_key_credential +FROM governance.model_providers p WHERE p.org_id = r.org_id AND p.name = r.provider; +ALTER TABLE governance.model_roles + ALTER COLUMN class SET NOT NULL, + ALTER COLUMN base_url SET NOT NULL, + DROP COLUMN provider; +DROP TABLE governance.model_providers; diff --git a/modules/chat/api.go b/modules/chat/api.go index d8207fa3e..5ca622aec 100644 --- a/modules/chat/api.go +++ b/modules/chat/api.go @@ -105,7 +105,7 @@ func (m *Module) listSessions(ctx context.Context, _ *struct{}) (*httpapi.Reply[ out.Sessions = append(out.Sessions, sessionOf(r)) } if d, ok := m.uses(); ok { - if model, err := d.Settings.AgentModelForAlias(ctx, ""); err != nil { + if model, err := d.Settings.ChatModelForAlias(ctx, ""); err != nil { out.ModelError = err.Error() } else { out.ActiveModel = model.Model diff --git a/modules/chat/chat.go b/modules/chat/chat.go index 5365d64e6..8d93d6988 100644 --- a/modules/chat/chat.go +++ b/modules/chat/chat.go @@ -29,7 +29,7 @@ import ( // Settings provides the agent model and the escalation path approvals follow. type Settings interface { - AgentModelForAlias(ctx context.Context, alias string) (governance.Model, error) + ChatModelForAlias(ctx context.Context, alias string) (governance.Model, error) // Instructions are the organisation's standing instructions for agents. Instructions(ctx context.Context) (string, error) AgentProvider(ctx context.Context, model governance.Model) (chat.Provider, chat.ModelInfo, error) diff --git a/modules/chat/turn.go b/modules/chat/turn.go index 5ad8de915..707a8f699 100644 --- a/modules/chat/turn.go +++ b/modules/chat/turn.go @@ -177,7 +177,7 @@ func (m *Module) generate(ctx context.Context, t store.Turn) (string, string, er if err != nil { return "", "", err } - model, err := d.Settings.AgentModelForAlias(ctx, "") + model, err := d.Settings.ChatModelForAlias(ctx, "") if err != nil { return "", "", fmt.Errorf("no agent model is configured: %w", err) } @@ -372,7 +372,7 @@ func (m *Module) title(ctx context.Context, t store.Turn, reply string) { } ctx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() - model, err := d.Settings.AgentModelForAlias(ctx, "") + model, err := d.Settings.ChatModelForAlias(ctx, "") if err != nil { return } diff --git a/modules/governance/accounts_api.go b/modules/governance/accounts_api.go index 6c842510c..daabd097a 100644 --- a/modules/governance/accounts_api.go +++ b/modules/governance/accounts_api.go @@ -607,14 +607,15 @@ func (m *Module) capabilities(ctx context.Context, _ *struct{}) (*httpapi.Reply[ p, signedIn := PrincipalFromContext(ctx) sections := map[string]bool{"chat": signedIn, "memory": signedIn} for _, name := range []string{ - "settings", "events", "workflows", "runs", "credentials", "extensions", "secret_engines", "models", "controls", "memory_admin", + "settings", "events", "workflows", "runs", "credentials", "secret_engines", "controls", "memory_admin", "home", "system_status", "org_config", "captures", "mappings", "bindings", + "extension_catalogue", "model_aliases", } { sections[name] = p.InstanceAdmin() } for _, name := range []string{ "tasks", "work_requests", "logs", "skills", "curators", "channels", - "workflow_editor", "extension_catalogue", "model_aliases", + "workflow_editor", "task_execution", "organisations", "tools", "plugins", "container_runtime", "agent_profiles", "org_agents", "org_audit", "org_usage", "org_work_intake", } { diff --git a/modules/governance/governance.go b/modules/governance/governance.go index b95a0f27b..98021ebf2 100644 --- a/modules/governance/governance.go +++ b/modules/governance/governance.go @@ -14,7 +14,6 @@ import ( "net/http" "net/url" "regexp" - "strings" "sync/atomic" "time" @@ -39,6 +38,10 @@ const ( var agentAliasPattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,62}$`) +// providerName is the shape of a provider name; it is stored as an identifier +// beside the alias that names it. +var providerName = regexp.MustCompile(`^[a-z0-9][a-z0-9_.-]{0,62}$`) + // ValidateAgentModelAlias accepts an empty alias for the default model. func ValidateAgentModelAlias(alias string) error { if alias != "" && !agentAliasPattern.MatchString(alias) { @@ -201,12 +204,15 @@ func stepsOf(req []stepRequest) ([]Step, error) { // Model is the model chosen for a role. type Model struct { - Class string `json:"class"` - BaseURL string `json:"base_url"` - Model string `json:"model"` - // APIKeyCredential names the credential whose token authenticates the - // provider. The dashboard shows the name, never the token. - APIKeyCredential string `json:"api_key_credential,omitempty"` + // Provider is the endpoint the model is called on, and Model is its name + // there. + Provider string `json:"provider" doc:"The provider the model is called on"` + Model string `json:"model" doc:"The model's name on the provider"` + // Class, BaseURL and APIKeyCredential are read from the provider. The + // dashboard shows the credential's name, never its token. + Class string `json:"class,omitempty" readOnly:"true"` + BaseURL string `json:"base_url,omitempty" readOnly:"true"` + APIKeyCredential string `json:"api_key_credential,omitempty" readOnly:"true"` } // Credentials resolves a credential's token by name. It is the connectors @@ -305,7 +311,10 @@ func (m *Module) AgentModelForAlias(ctx context.Context, alias string) (Model, e } return Model{}, ErrNoAgentModel } - return Model{Class: role.Class, BaseURL: role.BaseURL, Model: role.Model, APIKeyCredential: role.APIKeyCredential}, nil + return Model{ + Provider: role.Provider, Model: role.Model, + Class: role.Class, BaseURL: role.BaseURL, APIKeyCredential: role.APIKeyCredential, + }, nil } // Settings returns the organisation's settings, with a default for every one it @@ -425,6 +434,7 @@ func (m *Module) Register(api huma.API) { OperationID: "test-agent-model", Method: http.MethodPost, Path: "/api/settings/agent-model/test", Summary: "Ask a model one question before saving it", Tags: tags, }, m.testAgentModel) + m.registerModels(api) m.registerInstructions(api) } @@ -567,11 +577,10 @@ func (m *Module) listAgentModels(ctx context.Context, _ *struct{}) (*httpapi.Rep } out := make(map[string]Model, len(rows)) for _, row := range rows { - alias := strings.TrimPrefix(row.Role, agentAliasPrefix) - if row.Role == roleAgent { - alias = "default" + out[aliasOf(row.Role)] = Model{ + Provider: row.Provider, Model: row.Model, + Class: row.Class, BaseURL: row.BaseURL, APIKeyCredential: row.APIKeyCredential, } - out[alias] = Model{Class: row.Class, BaseURL: row.BaseURL, Model: row.Model, APIKeyCredential: row.APIKeyCredential} } return httpapi.OK(out), nil } @@ -601,22 +610,17 @@ type agentModelInput struct { Body Model } -// putAgentModel stores the resolved base URL so saved settings are explicit. +// putAgentModel stores the provider and model an alias names. func (m *Module) putAgentModel(ctx context.Context, in *agentModelInput) (*httpapi.Reply[Model], error) { if err := ValidateAgentModelAlias(in.Alias); err != nil { return nil, huma.NewError(http.StatusBadRequest, err.Error()) } - req := in.Body - model, err := settle(req) + model, err := m.modelOf(ctx, in.Body) if err != nil { return nil, huma.NewError(http.StatusBadRequest, err.Error()) } - if _, _, err := m.provider(ctx, model); err != nil { - return nil, huma.NewError(http.StatusBadRequest, err.Error()) - } if err := m.store.PutModelRole(ctx, store.ModelRole{ - OrgID: m.orgID, Role: agentModelRole(in.Alias), Class: model.Class, BaseURL: model.BaseURL, Model: model.Model, - APIKeyCredential: model.APIKeyCredential, + OrgID: m.orgID, Role: agentModelRole(in.Alias), Provider: model.Provider, Model: model.Model, }); err != nil { m.log.ErrorContext(ctx, "put agent model", "error", err) return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the agent model") @@ -652,14 +656,13 @@ const testTimeout = 60 * time.Second // testAgentModel asks the model one question and reports its answer, so the // operator knows the endpoint, model and key work before saving them. func (m *Module) testAgentModel(ctx context.Context, in *struct{ Body Model }) (*httpapi.Reply[modelAnswer], error) { - req := in.Body - model, err := settle(req) + model, err := m.modelOf(ctx, in.Body) if err != nil { return nil, huma.NewError(http.StatusBadRequest, err.Error()) } provider, _, err := m.provider(ctx, model) if err != nil { - return nil, huma.NewError(http.StatusBadRequest, err.Error()) + return nil, huma.NewError(http.StatusInternalServerError, err.Error()) } ctx, cancel := context.WithTimeout(ctx, testTimeout) defer cancel() @@ -674,23 +677,25 @@ func (m *Module) testAgentModel(ctx context.Context, in *struct{ Body Model }) ( return httpapi.OK(modelAnswer{Model: model.Model, Answer: resp.Content}), nil } -func settle(req Model) (Model, error) { - if _, ok := runtime.GetClass(req.Class); !ok { - return Model{}, fmt.Errorf("unknown provider class %q", req.Class) +// endpoint checks a provider's class and endpoint and returns it with the +// class's default base URL filled in. +func endpoint(name, class, baseURL, credential string) (store.Provider, error) { + if !providerName.MatchString(name) { + return store.Provider{}, errors.New("a provider name is lowercase letters, digits, dots, underscores or hyphens") } - if req.Model == "" { - return Model{}, errors.New("a model is required") + if _, ok := runtime.GetClass(class); !ok { + return store.Provider{}, fmt.Errorf("unknown provider class %q", class) } - if req.BaseURL == "" { - base, ok := runtime.DefaultBaseURL(req.Class) + if baseURL == "" { + base, ok := runtime.DefaultBaseURL(class) if !ok { - return Model{}, fmt.Errorf("provider class %q has no default base URL; give one", req.Class) + return store.Provider{}, fmt.Errorf("provider class %q has no default base URL; give one", class) } - req.BaseURL = base + baseURL = base } - u, err := url.Parse(req.BaseURL) + u, err := url.Parse(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 store.Provider{}, fmt.Errorf("base URL %q must be an http or https URL", baseURL) } - return req, nil + return store.Provider{Name: name, Class: class, BaseURL: baseURL, APIKeyCredential: credential}, nil } diff --git a/modules/governance/internal/store/store.go b/modules/governance/internal/store/store.go index 92329e7ea..8ac042920 100644 --- a/modules/governance/internal/store/store.go +++ b/modules/governance/internal/store/store.go @@ -11,15 +11,35 @@ import ( "github.com/jmoiron/sqlx" ) -// ModelRole is the model an organisation chose for one role. +// ModelRole is the model an organisation chose for one role: a provider and a +// model name on it. type ModelRole struct { - OrgID string `db:"org_id"` - Role string `db:"role"` - Class string `db:"class"` - BaseURL string `db:"base_url"` - Model string `db:"model"` + OrgID string `db:"org_id"` + Role string `db:"role"` + Provider string `db:"provider"` + Model string `db:"model"` +} + +// ResolvedRole is a role with the endpoint its provider names. +type ResolvedRole struct { + OrgID string `db:"org_id"` + Role string `db:"role"` + Provider string `db:"provider"` + Model string `db:"model"` + Class string `db:"class"` + BaseURL string `db:"base_url"` // APIKeyCredential names the credential whose token authenticates the - // model provider, or empty when it needs no key. + // provider, or empty when it needs no key. + APIKeyCredential string `db:"api_key_credential"` +} + +// Provider is an endpoint models are called on: a provider class, base URL and +// the credential whose token authenticates it. +type Provider struct { + OrgID string `db:"org_id"` + Name string `db:"name"` + Class string `db:"class"` + BaseURL string `db:"base_url"` APIKeyCredential string `db:"api_key_credential"` } @@ -31,28 +51,96 @@ type Store struct { // New returns a store on db. func New(db *sqlx.DB) *Store { return &Store{db: db} } -// ModelRole returns the organisation's model for role; ok is false when none -// was chosen. -func (s *Store) ModelRole(ctx context.Context, orgID, role string) (ModelRole, bool, error) { - var out ModelRole +// Providers lists the organisation's providers in name order. +func (s *Store) Providers(ctx context.Context, orgID string) ([]Provider, error) { + var out []Provider + if err := s.db.SelectContext(ctx, &out, ` + SELECT org_id, name, class, base_url, api_key_credential + FROM governance.model_providers WHERE org_id = $1 ORDER BY name`, orgID); err != nil { + return nil, fmt.Errorf("list model providers: %w", err) + } + return out, nil +} + +// Provider returns the named provider; ok is false when none exists. +func (s *Store) Provider(ctx context.Context, orgID, name string) (Provider, bool, error) { + var out Provider err := s.db.GetContext(ctx, &out, ` - SELECT org_id, role, class, base_url, model, api_key_credential FROM governance.model_roles - WHERE org_id = $1 AND role = $2`, orgID, role) + SELECT org_id, name, class, base_url, api_key_credential + FROM governance.model_providers WHERE org_id = $1 AND name = $2`, orgID, name) if errors.Is(err, sql.ErrNoRows) { - return ModelRole{}, false, nil + return Provider{}, false, nil } if err != nil { - return ModelRole{}, false, fmt.Errorf("read model role %q: %w", role, err) + return Provider{}, false, fmt.Errorf("read model provider %q: %w", name, err) } return out, true, nil } -func (s *Store) AgentModelRoles(ctx context.Context, orgID string) ([]ModelRole, error) { - var out []ModelRole +// PutProvider records a provider. +func (s *Store) PutProvider(ctx context.Context, p Provider) error { + if _, err := s.db.NamedExecContext(ctx, ` + INSERT INTO governance.model_providers (org_id, name, class, base_url, api_key_credential) + VALUES (:org_id, :name, :class, :base_url, :api_key_credential) + ON CONFLICT (org_id, name) DO UPDATE + SET class = EXCLUDED.class, base_url = EXCLUDED.base_url, + api_key_credential = EXCLUDED.api_key_credential, updated_at = now()`, p); err != nil { + return fmt.Errorf("put model provider %q: %w", p.Name, err) + } + return nil +} + +// DeleteProvider removes a provider and reports whether one existed. +func (s *Store) DeleteProvider(ctx context.Context, orgID, name string) (bool, error) { + res, err := s.db.ExecContext(ctx, `DELETE FROM governance.model_providers WHERE org_id = $1 AND name = $2`, orgID, name) + if err != nil { + return false, fmt.Errorf("delete model provider %q: %w", name, err) + } + n, err := res.RowsAffected() + if err != nil { + return false, fmt.Errorf("delete model provider %q: %w", name, err) + } + return n > 0, nil +} + +// AliasesUsingProvider names the roles that call models through provider. +func (s *Store) AliasesUsingProvider(ctx context.Context, orgID, provider string) ([]string, error) { + var roles []string + if err := s.db.SelectContext(ctx, &roles, ` + SELECT role FROM governance.model_roles WHERE org_id = $1 AND provider = $2 ORDER BY role`, orgID, provider); err != nil { + return nil, fmt.Errorf("read model roles for provider %q: %w", provider, err) + } + return roles, nil +} + +// ModelRole returns the organisation's model for role with its provider's +// endpoint; ok is false when none was chosen. +func (s *Store) ModelRole(ctx context.Context, orgID, role string) (ResolvedRole, bool, error) { + var out ResolvedRole + err := s.db.GetContext(ctx, &out, ` + SELECT r.org_id, r.role, r.provider, r.model, p.class, p.base_url, p.api_key_credential + FROM governance.model_roles r + JOIN governance.model_providers p ON p.org_id = r.org_id AND p.name = r.provider + WHERE r.org_id = $1 AND r.role = $2`, orgID, role) + if errors.Is(err, sql.ErrNoRows) { + return ResolvedRole{}, false, nil + } + if err != nil { + return ResolvedRole{}, false, fmt.Errorf("read model role %q: %w", role, err) + } + return out, true, nil +} + +// AgentModelRoles lists the organisation's agent roles with their providers' +// endpoints, in role order. +func (s *Store) AgentModelRoles(ctx context.Context, orgID string) ([]ResolvedRole, error) { + var out []ResolvedRole if err := s.db.SelectContext(ctx, &out, ` - SELECT org_id, role, class, base_url, model, api_key_credential - FROM governance.model_roles - WHERE org_id = $1 AND (role = 'agent' OR role LIKE 'agent:%')`, orgID); err != nil { + SELECT r.org_id, r.role, r.provider, r.model, p.class, p.base_url, p.api_key_credential + FROM governance.model_roles r + JOIN governance.model_providers p ON p.org_id = r.org_id AND p.name = r.provider + WHERE r.org_id = $1 AND (r.role = 'agent' OR r.role LIKE 'agent:%') + ORDER BY r.role`, orgID); err != nil { return nil, fmt.Errorf("list agent models: %w", err) } return out, nil @@ -61,16 +149,60 @@ func (s *Store) AgentModelRoles(ctx context.Context, orgID string) ([]ModelRole, // PutModelRole records the organisation's model for a role. func (s *Store) PutModelRole(ctx context.Context, m ModelRole) error { if _, err := s.db.NamedExecContext(ctx, ` - INSERT INTO governance.model_roles (org_id, role, class, base_url, model, api_key_credential) - VALUES (:org_id, :role, :class, :base_url, :model, :api_key_credential) + INSERT INTO governance.model_roles (org_id, role, provider, model) + VALUES (:org_id, :role, :provider, :model) ON CONFLICT (org_id, role) DO UPDATE - SET class = EXCLUDED.class, base_url = EXCLUDED.base_url, model = EXCLUDED.model, - api_key_credential = EXCLUDED.api_key_credential, updated_at = now()`, m); err != nil { + SET provider = EXCLUDED.provider, model = EXCLUDED.model, updated_at = now()`, m); err != nil { return fmt.Errorf("put model role %q: %w", m.Role, err) } return nil } +// ModelPolicy is which aliases workflows and chat may name. A nil list lets +// any alias through. +type ModelPolicy struct { + OrgID string `db:"org_id"` + // WorkflowAliases and ChatAliases are JSON arrays, or nil for no limit. + WorkflowAliases []byte `db:"workflow_aliases"` + ChatAliases []byte `db:"chat_aliases"` +} + +// Policy returns the organisation's model policy; ok is false when none was +// saved, which lets every alias through. +func (s *Store) Policy(ctx context.Context, orgID string) (ModelPolicy, bool, error) { + var out ModelPolicy + err := s.db.GetContext(ctx, &out, ` + SELECT org_id, workflow_aliases, chat_aliases FROM governance.model_policy WHERE org_id = $1`, orgID) + if errors.Is(err, sql.ErrNoRows) { + return ModelPolicy{}, false, nil + } + if err != nil { + return ModelPolicy{}, false, fmt.Errorf("read model policy: %w", err) + } + return out, true, nil +} + +// PutPolicy records the organisation's model policy. A nil list is stored as +// SQL NULL, which lifts the limit. +func (s *Store) PutPolicy(ctx context.Context, p ModelPolicy) error { + var workflow, chat any + if p.WorkflowAliases != nil { + workflow = string(p.WorkflowAliases) + } + if p.ChatAliases != nil { + chat = string(p.ChatAliases) + } + if _, err := s.db.ExecContext(ctx, ` + INSERT INTO governance.model_policy (org_id, workflow_aliases, chat_aliases) + VALUES ($1, $2::jsonb, $3::jsonb) + ON CONFLICT (org_id) DO UPDATE + SET workflow_aliases = EXCLUDED.workflow_aliases, chat_aliases = EXCLUDED.chat_aliases, updated_at = now()`, + p.OrgID, workflow, chat); err != nil { + return fmt.Errorf("put model policy: %w", err) + } + return nil +} + // DeleteModelRole removes the organisation's model for role and reports // whether one existed. func (s *Store) DeleteModelRole(ctx context.Context, orgID, role string) (bool, error) { diff --git a/modules/governance/models_api.go b/modules/governance/models_api.go new file mode 100644 index 000000000..b1c2accd3 --- /dev/null +++ b/modules/governance/models_api.go @@ -0,0 +1,287 @@ +package governance + +import ( + "context" + json "encoding/json/v2" + "errors" + "fmt" + "net/http" + "slices" + "strings" + + "github.com/danielgtaylor/huma/v2" + "github.com/samcharles93/ai-sdk/runtime" + + "github.com/samcharles93/archie-core/internal/platform/httpapi" + "github.com/samcharles93/archie-core/modules/governance/internal/store" +) + +// ErrModelNotAllowed means the organisation's model policy doesn't allow the +// alias where it was named. +var ErrModelNotAllowed = errors.New("the organisation's model policy doesn't allow this alias") + +// ModelProvider is an endpoint models are called on. +type ModelProvider struct { + Name string `json:"name" doc:"Lowercase letters, digits, dots, underscores or hyphens"` + Class string `json:"class" doc:"A provider class from the model classes catalogue"` + // BaseURL is the endpoint; empty uses the class's default. + BaseURL string `json:"base_url,omitempty"` + // APIKeyCredential names the credential whose token authenticates the + // provider. Only the name is ever returned. + APIKeyCredential string `json:"api_key_credential,omitempty"` +} + +// ModelClass is one provider class the runtime can build. +type ModelClass struct { + Class string `json:"class"` + // DefaultBaseURL is where the class calls when a provider gives none. + DefaultBaseURL string `json:"default_base_url,omitempty"` +} + +// ModelPolicy is which aliases workflows and chat may name. A nil list lets +// any alias through. +type ModelPolicy struct { + WorkflowAliases []string `json:"workflow_aliases" doc:"Aliases workflows may name; null lets them use any"` + ChatAliases []string `json:"chat_aliases" doc:"Aliases chat may use; null lets it use any"` +} + +// modelOf returns the model a request names with its provider's endpoint. +func (m *Module) modelOf(ctx context.Context, req Model) (Model, error) { + if req.Provider == "" { + return Model{}, errors.New("a provider is required") + } + if req.Model == "" { + return Model{}, errors.New("a model is required") + } + p, ok, err := m.store.Provider(ctx, m.orgID, req.Provider) + if err != nil { + return Model{}, err + } + if !ok { + return Model{}, fmt.Errorf("no provider named %q", req.Provider) + } + return Model{ + Provider: p.Name, Model: req.Model, + Class: p.Class, BaseURL: p.BaseURL, APIKeyCredential: p.APIKeyCredential, + }, nil +} + +// ModelPolicy returns the organisation's model policy. +func (m *Module) ModelPolicy(ctx context.Context) (ModelPolicy, error) { + row, ok, err := m.store.Policy(ctx, m.orgID) + if err != nil { + return ModelPolicy{}, err + } + if !ok { + return ModelPolicy{}, nil + } + workflow, err := aliasesOf(row.WorkflowAliases) + if err != nil { + return ModelPolicy{}, err + } + chat, err := aliasesOf(row.ChatAliases) + if err != nil { + return ModelPolicy{}, err + } + return ModelPolicy{WorkflowAliases: workflow, ChatAliases: chat}, nil +} + +// WorkflowModelForAlias resolves a model a workflow named, refusing one the +// organisation's policy doesn't allow. +func (m *Module) WorkflowModelForAlias(ctx context.Context, alias string) (Model, error) { + policy, err := m.ModelPolicy(ctx) + if err != nil { + return Model{}, err + } + if err := allowedAlias(policy.WorkflowAliases, alias); err != nil { + return Model{}, err + } + return m.AgentModelForAlias(ctx, alias) +} + +// ChatModelForAlias resolves the model chat may use, refusing one the +// organisation's policy doesn't allow. +func (m *Module) ChatModelForAlias(ctx context.Context, alias string) (Model, error) { + policy, err := m.ModelPolicy(ctx) + if err != nil { + return Model{}, err + } + if err := allowedAlias(policy.ChatAliases, alias); err != nil { + return Model{}, err + } + return m.AgentModelForAlias(ctx, alias) +} + +func allowedAlias(allowed []string, alias string) error { + if allowed == nil { + return nil + } + name := alias + if name == "" { + name = "default" + } + if !slices.Contains(allowed, name) { + return fmt.Errorf("model alias %q: %w", name, ErrModelNotAllowed) + } + return nil +} + +func aliasesOf(raw []byte) ([]string, error) { + if raw == nil { + return nil, nil + } + var out []string + if err := json.Unmarshal(raw, &out); err != nil { + return nil, fmt.Errorf("model policy: %w", err) + } + return out, nil +} + +func marshalAliases(aliases []string) ([]byte, error) { + if aliases == nil { + return nil, nil + } + return json.Marshal(aliases) +} + +func (m *Module) listModelProviders(ctx context.Context, _ *struct{}) (*httpapi.Reply[map[string]ModelProvider], error) { + rows, err := m.store.Providers(ctx, m.orgID) + if err != nil { + m.log.ErrorContext(ctx, "list model providers", "error", err) + return nil, huma.NewError(http.StatusInternalServerError, "couldn't list model providers") + } + out := make(map[string]ModelProvider, len(rows)) + for _, p := range rows { + out[p.Name] = ModelProvider{Name: p.Name, Class: p.Class, BaseURL: p.BaseURL, APIKeyCredential: p.APIKeyCredential} + } + return httpapi.OK(out), nil +} + +func (m *Module) putModelProvider(ctx context.Context, in *struct { + Name string `path:"name" doc:"Lowercase letters, digits, dots, underscores or hyphens"` + Body ModelProvider +}, +) (*httpapi.Reply[ModelProvider], error) { + p, err := endpoint(in.Name, in.Body.Class, in.Body.BaseURL, in.Body.APIKeyCredential) + if err != nil { + return nil, huma.NewError(http.StatusBadRequest, err.Error()) + } + p.OrgID = m.orgID + if err := m.store.PutProvider(ctx, p); err != nil { + m.log.ErrorContext(ctx, "put model provider", "error", err) + return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the model provider") + } + return httpapi.OK(ModelProvider{ + Name: p.Name, Class: p.Class, BaseURL: p.BaseURL, APIKeyCredential: p.APIKeyCredential, + }), nil +} + +func (m *Module) deleteModelProvider(ctx context.Context, in *struct { + Name string `path:"name"` +}, +) (*struct{}, error) { + users, err := m.store.AliasesUsingProvider(ctx, m.orgID, in.Name) + if err != nil { + m.log.ErrorContext(ctx, "read the aliases that use a provider", "provider", in.Name, "error", err) + return nil, huma.NewError(http.StatusInternalServerError, "couldn't check the aliases that use "+in.Name) + } + if len(users) > 0 { + aliases := make([]string, 0, len(users)) + for _, role := range users { + aliases = append(aliases, aliasOf(role)) + } + return nil, huma.NewError(http.StatusConflict, + fmt.Sprintf("provider %s is used by aliases: %s", in.Name, strings.Join(aliases, ", "))) + } + found, err := m.store.DeleteProvider(ctx, m.orgID, in.Name) + if err != nil { + m.log.ErrorContext(ctx, "delete model provider", "provider", in.Name, "error", err) + return nil, huma.NewError(http.StatusInternalServerError, "couldn't delete "+in.Name) + } + if !found { + return nil, huma.NewError(http.StatusNotFound, "no provider named "+in.Name) + } + return nil, nil +} + +func listModelClasses(context.Context, *struct{}) (*httpapi.Reply[[]ModelClass], error) { + names := slices.Clone(runtime.ClassNames()) + slices.Sort(names) + names = slices.Compact(names) + out := make([]ModelClass, 0, len(names)) + for _, name := range names { + base, _ := runtime.DefaultBaseURL(name) + out = append(out, ModelClass{Class: name, DefaultBaseURL: base}) + } + return httpapi.OK(out), nil +} + +func (m *Module) getModelPolicy(ctx context.Context, _ *struct{}) (*httpapi.Reply[ModelPolicy], error) { + policy, err := m.ModelPolicy(ctx) + if err != nil { + m.log.ErrorContext(ctx, "read the model policy", "error", err) + return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the model policy") + } + return httpapi.OK(policy), nil +} + +func (m *Module) putModelPolicy(ctx context.Context, in *struct{ Body ModelPolicy }) (*httpapi.Reply[ModelPolicy], error) { + for _, aliases := range [][]string{in.Body.WorkflowAliases, in.Body.ChatAliases} { + for _, alias := range aliases { + if err := ValidateAgentModelAlias(alias); err != nil { + return nil, huma.NewError(http.StatusBadRequest, err.Error()) + } + } + } + workflow, err := marshalAliases(in.Body.WorkflowAliases) + if err != nil { + return nil, huma.NewError(http.StatusBadRequest, err.Error()) + } + chat, err := marshalAliases(in.Body.ChatAliases) + if err != nil { + return nil, huma.NewError(http.StatusBadRequest, err.Error()) + } + if err := m.store.PutPolicy(ctx, store.ModelPolicy{ + OrgID: m.orgID, WorkflowAliases: workflow, ChatAliases: chat, + }); err != nil { + m.log.ErrorContext(ctx, "put the model policy", "error", err) + return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the model policy") + } + return httpapi.OK(in.Body), nil +} + +// aliasOf returns the dashboard's name for a stored role. +func aliasOf(role string) string { + if role == roleAgent { + return "default" + } + return strings.TrimPrefix(role, agentAliasPrefix) +} + +func (m *Module) registerModels(api huma.API) { + tags := []string{"Governance"} + httpapi.Register(api, httpapi.AdminAuthorized(ActionRead, KindSettings), huma.Operation{ + OperationID: "list-model-providers", Method: http.MethodGet, Path: "/api/settings/model-providers", + Summary: "List model providers", Tags: tags, + }, m.listModelProviders) + httpapi.Register(api, httpapi.AdminAuthorized(ActionUpdate, KindSettings), huma.Operation{ + OperationID: "put-model-provider", Method: http.MethodPut, Path: "/api/settings/model-providers/{name}", + Summary: "Save a model provider", Tags: tags, + }, m.putModelProvider) + httpapi.Register(api, httpapi.AdminAuthorized(ActionUpdate, KindSettings), huma.Operation{ + OperationID: "delete-model-provider", Method: http.MethodDelete, Path: "/api/settings/model-providers/{name}", + Summary: "Delete a model provider no alias uses", Tags: tags, DefaultStatus: http.StatusNoContent, + }, m.deleteModelProvider) + httpapi.Register(api, httpapi.AdminAuthorized(ActionRead, KindSettings), huma.Operation{ + OperationID: "list-model-classes", Method: http.MethodGet, Path: "/api/settings/model-classes", + Summary: "List the provider classes the runtime can build", Tags: tags, + }, listModelClasses) + httpapi.Register(api, httpapi.AdminAuthorized(ActionRead, KindSettings), huma.Operation{ + OperationID: "get-model-policy", Method: http.MethodGet, Path: "/api/settings/model-policy", + Summary: "Get which aliases workflows and chat may use", Tags: tags, + }, m.getModelPolicy) + httpapi.Register(api, httpapi.AdminAuthorized(ActionUpdate, KindSettings), huma.Operation{ + OperationID: "put-model-policy", Method: http.MethodPut, Path: "/api/settings/model-policy", + Summary: "Set which aliases workflows and chat may use", Tags: tags, + }, m.putModelPolicy) +} diff --git a/modules/governance/models_api_test.go b/modules/governance/models_api_test.go new file mode 100644 index 000000000..f565c42eb --- /dev/null +++ b/modules/governance/models_api_test.go @@ -0,0 +1,31 @@ +package governance + +import ( + "errors" + "testing" +) + +// TestModelPolicyAllowsEveryAliasOnlyWhenUnset guards the model policy +// boundary: no policy lets every alias through, while a policy that names no +// alias allows none. +func TestModelPolicyAllowsEveryAliasOnlyWhenUnset(t *testing.T) { + cases := []struct { + name string + allowed []string + alias string + wantErr error + }{ + {"no policy allows the default", nil, "", nil}, + {"no policy allows a named alias", nil, "fast", nil}, + {"a policy naming nothing allows no alias", []string{}, "", ErrModelNotAllowed}, + {"a policy allows what it names", []string{"default", "fast"}, "fast", nil}, + {"a policy refuses the alias it leaves out", []string{"fast"}, "", ErrModelNotAllowed}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if err := allowedAlias(c.allowed, c.alias); !errors.Is(err, c.wantErr) { + t.Fatalf("allowedAlias(%v, %q) error = %v, want %v", c.allowed, c.alias, err, c.wantErr) + } + }) + } +} diff --git a/modules/runs/agent_test.go b/modules/runs/agent_test.go index 1355dd85f..31f2f1831 100644 --- a/modules/runs/agent_test.go +++ b/modules/runs/agent_test.go @@ -42,7 +42,7 @@ type modelSettings struct { name string } -func (s modelSettings) AgentModelForAlias(_ context.Context, alias string) (governance.Model, error) { +func (s modelSettings) WorkflowModelForAlias(_ context.Context, alias string) (governance.Model, error) { if alias != "fast" { return governance.Model{}, governance.ErrNoAgentModel } diff --git a/modules/runs/interpreter.go b/modules/runs/interpreter.go index 17d85ee84..ed6b8ab96 100644 --- a/modules/runs/interpreter.go +++ b/modules/runs/interpreter.go @@ -30,7 +30,7 @@ import ( // Settings provides the organisation's model configuration and escalation policy. type Settings interface { - AgentModelForAlias(ctx context.Context, alias string) (governance.Model, error) + WorkflowModelForAlias(ctx context.Context, alias string) (governance.Model, error) // Instructions are the organisation's standing instructions for agents. Instructions(ctx context.Context) (string, error) // AgentProvider builds the chat client for a model, resolving the @@ -324,7 +324,7 @@ func (d Deps) pin(rc *Context, p *progress, aliases []string, withMemory bool) e step += ":" + alias } model, err := rc.Step(step, func(ctx context.Context, _ string) (governance.Model, error) { - return d.Settings.AgentModelForAlias(ctx, alias) + return d.Settings.WorkflowModelForAlias(ctx, alias) }) if err != nil { return err diff --git a/modules/runs/investigate_test.go b/modules/runs/investigate_test.go index ff2b5499e..c46837c24 100644 --- a/modules/runs/investigate_test.go +++ b/modules/runs/investigate_test.go @@ -86,7 +86,7 @@ type investigateSettings struct { model chat.Provider } -func (s investigateSettings) AgentModelForAlias(context.Context, string) (governance.Model, error) { +func (s investigateSettings) WorkflowModelForAlias(context.Context, string) (governance.Model, error) { return governance.Model{Model: "test"}, nil } diff --git a/modules/runs/runs.go b/modules/runs/runs.go index f12d89dde..b483a6896 100644 --- a/modules/runs/runs.go +++ b/modules/runs/runs.go @@ -169,7 +169,7 @@ func (e *Engine) validateDocument(ctx context.Context, body string) (Document, e if err != nil { return Document{}, err } - if _, err := deps.Settings.AgentModelForAlias(ctx, s.Model); err != nil { + if _, err := deps.Settings.WorkflowModelForAlias(ctx, s.Model); err != nil { if !errors.Is(err, governance.ErrNoAgentModel) { return Document{}, err } diff --git a/modules/runs/steps_test.go b/modules/runs/steps_test.go index 6da81ab19..f108b7e63 100644 --- a/modules/runs/steps_test.go +++ b/modules/runs/steps_test.go @@ -88,7 +88,7 @@ func (a *askCounter) Discard(context.Context, uuid.UUID, string) error { return // onePersonPath sends every request to one person. type onePersonPath struct{} -func (onePersonPath) AgentModelForAlias(context.Context, string) (governance.Model, error) { +func (onePersonPath) WorkflowModelForAlias(context.Context, string) (governance.Model, error) { return governance.Model{}, errors.New("no agent in these workflows") }