package webui import ( "context" "encoding/json" "fmt" "maps" "net/http" "slices" "strings" "github.com/samcharles93/archie-core/internal/config" controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1" "github.com/samcharles93/archie-core/internal/domain/identity" "github.com/samcharles93/archie-core/internal/domain/org" ) // SetupStep is one item in the dashboard's getting-started checklist. Path is // the page that owns the configuration the step is about, so an operator can // follow the step to where it is fixed rather than guess a settings page. type SetupStep struct { Title string `json:"title"` Detail string `json:"detail,omitempty"` Done bool `json:"done"` Path string `json:"path,omitempty"` } // ModelReader reads the model aliases the calling principal's org may use. type ModelReader interface { CallerModels(ctx context.Context) (org string, aliases map[string]string, err error) } // The control-plane resources the effective-model read layers: the org's own // providers and the credential bindings that carry their keys. Spelled here // rather than imported so the dashboard package stays a leaf. const ( providerSettingsKind = "provider-settings" credentialBindingsKind = "credential-bindings" //nolint:gosec // G101: a resource kind, not a credential. ) // providerDoc is the part of one provider-settings entry the read needs: where // the provider's key comes from. type providerDoc struct { Class string `json:"class"` APIKeyEnv string `json:"api_key_env,omitempty"` APIKeyRef config.SecretRef `json:"api_key_ref"` } // credentialBindingDoc is the part of one credential-bindings entry the read // needs: the org secret the service's key resolves through. type credentialBindingDoc struct { Service string `json:"service"` Secret config.SecretRef `json:"secret"` } // effectiveModel is one model alias the caller's org may use, with the state // of the provider credential it runs on. An alias whose provider's credential // is missing or does not resolve cannot run a task, so the Model setup step // stays open and names it. type effectiveModel struct { Alias string Model string Provider string // Credential reports that the provider's credential is present and // resolves; Detail names what is missing when it does not. Credential bool Detail string } // handleSetup reports which setup steps are still missing in the caller's // organisation, from live state. Optional capabilities (a chat channel, a // repository) are set up where they are used, not listed here. func (s *Server) handleSetup(w http.ResponseWriter, r *http.Request) { steps := []SetupStep{} if s.Store == nil { writeJSON(w, map[string]any{"steps": steps}) return } if done, ok := s.hasActiveAgent(r); ok { steps = append(steps, SetupStep{Title: "Agent identity", Done: done, Path: "/org/agents"}) } if count, err := s.Store.StatusCounts(r.Context()); err == nil { total := 0 for _, n := range count { total += n } steps = append(steps, SetupStep{Title: "First task", Done: total > 0, Path: "/tasks"}) } if s.Models != nil { // Shown only while the org has no runnable model, so a working setup // carries no extra step: an alias whose provider credential does not // resolve is no more runnable than no alias at all. if models, err := s.callerEffectiveModels(r.Context()); err == nil { if step, open := modelSetupStep(models); open { steps = append(steps, step) } } } writeJSON(w, map[string]any{"steps": steps}) } // modelSetupStep is the Model checklist step for the caller's effective // models. The step stays open until every alias's provider credential // resolves; its detail names the credential that does not. func modelSetupStep(models []effectiveModel) (SetupStep, bool) { if len(models) == 0 { return SetupStep{Title: "Model", Path: "/org/models", Detail: "no model alias configured"}, true } for _, model := range models { if !model.Credential { return SetupStep{Title: "Model", Path: "/org/models", Detail: model.Detail}, true } } return SetupStep{}, false } // callerEffectiveModels reads the caller's effective models: the aliases the // org may use, each with the validity of the provider credential it runs on. // The credential surfaces are optional; without them the read reports the // aliases alone with every credential taken as valid. func (s *Server) callerEffectiveModels(ctx context.Context) ([]effectiveModel, error) { _, aliases, err := s.Models.CallerModels(ctx) if err != nil { return nil, err } models := make([]effectiveModel, 0, len(aliases)) for _, alias := range slices.Sorted(maps.Keys(aliases)) { provider, _, _ := strings.Cut(aliases[alias], "/") models = append(models, effectiveModel{Alias: alias, Model: aliases[alias], Provider: provider, Credential: true}) } if s.ControlPlane == nil || s.CheckSecret == nil || len(models) == 0 { return models, nil } var providers map[string]providerDoc if err := s.queryResourceValue(ctx, providerSettingsKind, &providers); err != nil { return nil, err } if providers == nil { providers = map[string]providerDoc{} } var bindings []credentialBindingDoc if err := s.queryResourceValue(ctx, credentialBindingsKind, &bindings); err != nil { return nil, err } for i := range models { models[i].Credential, models[i].Detail = s.providerCredential(ctx, models[i].Provider, providers, bindings) } return models, nil } // queryResourceValue decodes one control-plane resource of the caller's org // into into; an absent resource leaves into untouched. func (s *Server) queryResourceValue(ctx context.Context, kind string, into any) error { response, err := s.ControlPlane.Query(ctx, &controlpb.QueryRequest{Kind: kind}) if err != nil { return err } if response.Resource == nil || len(response.Resource.ValueJson) == 0 { return nil } return json.Unmarshal(response.Resource.ValueJson, into) } // providerCredential reports whether provider's credential is present and // resolves, and names what is missing when it does not. The key comes from // the provider's own api_key_ref, or from the org's credential binding named // after the provider, or from its api_key_env. A provider // that is not the org's own and has no binding is an instance provider: its // credential is the instance admin's, not this org's to configure. func (s *Server) providerCredential(ctx context.Context, provider string, providers map[string]providerDoc, bindings []credentialBindingDoc) (bool, string) { doc, own := providers[provider] if own && doc.APIKeyRef != (config.SecretRef{}) { return s.secretCredential(ctx, provider, doc.APIKeyRef) } for _, binding := range bindings { if binding.Service != provider { continue } if binding.Secret != (config.SecretRef{}) { return s.secretCredential(ctx, provider, binding.Secret) } return false, fmt.Sprintf("credential binding %q names no secret", provider) } if own { if doc.APIKeyEnv != "" { return s.secretCredential(ctx, provider, config.SecretRef{Engine: "env", Key: doc.APIKeyEnv}) } return false, fmt.Sprintf("provider %q declares no credential: set its api_key_ref or add a credential binding named %q", provider, provider) } return true, "" } // secretCredential reports whether ref resolves through the gateway's secret // engines, naming the reference when it does not. func (s *Server) secretCredential(ctx context.Context, provider string, ref config.SecretRef) (bool, string) { resolved, err := s.CheckSecret(ctx, ref) if err == nil && resolved { return true, "" } return false, fmt.Sprintf("provider %q credential %s:%s does not resolve", provider, ref.Engine, ref.Key) } // hasActiveAgent reports whether the caller's org has an active bot or // service account assigned; ok is false when that cannot be read. func (s *Server) hasActiveAgent(r *http.Request) (done, ok bool) { reader, isReader := s.Orgs.(org.AgentAssignments) if !isReader || s.Identities == nil { return false, false } assignments, err := reader.ListOrgAgents(r.Context(), policyOrg(r)) if err != nil { return false, false } for _, assignment := range assignments { value, err := s.Identities.Get(r.Context(), assignment.IdentityID) if err == nil && value.Kind.Agent() && value.Lifecycle == identity.LifecycleActive { return true, true } } return false, true }