package archied import ( "context" "crypto/rand" "encoding/hex" "errors" "fmt" "log/slog" "maps" "regexp" "slices" "strings" "sync" "time" v1 "github.com/ai-openshell/sdk-go/openshell/v1" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/daemon" "github.com/samcharles93/archie-core/internal/infrastructure/egress" "github.com/samcharles93/archie-core/internal/infrastructure/openshell" "github.com/samcharles93/archie-core/internal/secret" ) const ( // providerDeleteAttempts and providerDeleteWait bound how long Close waits // for the gateway to detach a provider from a sandbox it is still deleting. providerDeleteAttempts = 5 providerDeleteWait = 2 * time.Second providerCloseTimeout = time.Minute ) var nonNameChars = regexp.MustCompile(`[^a-z0-9]+`) // gatewayProviders is the part of the OpenShell client model egress needs. type gatewayProviders interface { Providers() v1.ProviderInterface } // keyResolver resolves the org's bound credential for a service on behalf of // the run a credential names. type keyResolver interface { Resolve(ctx context.Context, credential, service string) (string, error) } // openShellModelEgress opens task sandboxes' model sessions on the OpenShell // gateway. Each keyed provider's real key is registered as a gateway provider // owned by the task; the gateway puts a placeholder in the sandbox and // substitutes the key on requests to the provider's host, so the key never // enters the sandbox. type openShellModelEgress struct { client gatewayProviders workspace string instance string secrets *secret.Registry bindings keyResolver log *slog.Logger mu sync.Mutex owned map[string][]string // run credential -> gateway provider names } func newOpenShellModelEgress(client gatewayProviders, workspace, instance string, secrets *secret.Registry, bindings keyResolver, log *slog.Logger) *openShellModelEgress { if workspace == "" { workspace = "default" } return &openShellModelEgress{client: client, workspace: workspace, instance: instance, secrets: secrets, bindings: bindings, log: log, owned: map[string][]string{}} } func (m *openShellModelEgress) Open(ctx context.Context, token, org string, providers map[string]config.Provider, _ []string) (daemon.ModelSession, error) { var session daemon.ModelSession for _, name := range slices.Sorted(maps.Keys(providers)) { p := providers[name] mp, err := m.openProvider(ctx, token, org, name, p.KeyEnv(name), p) if err != nil { m.Close(ctx, token) return daemon.ModelSession{}, err } session.Providers = append(session.Providers, mp) } return session, nil } func (m *openShellModelEgress) openProvider(ctx context.Context, token, org, name, keyEnv string, p config.Provider) (daemon.ModelProvider, error) { host, port, err := providerEndpoint(p) if err != nil { return daemon.ModelProvider{}, fmt.Errorf("provider %q: %w", name, err) } if keyEnv == "" { // Nothing for the gateway to hold: the sandbox only needs the host. return daemon.ModelProvider{Host: host, Port: port}, nil } key, err := m.key(ctx, token, org, name, p) if err != nil { return daemon.ModelProvider{}, err } profile, err := m.ensureProfile(ctx, keyEnv, p.Class) if err != nil { return daemon.ModelProvider{}, fmt.Errorf("provider %q: %w", name, err) } gateway, err := m.providerName() if err != nil { return daemon.ModelProvider{}, err } // Recorded before the create so a call that fails after the gateway // accepted it is still deleted. m.own(token, gateway) if _, err := m.client.Providers().Create(ctx, m.workspace, &v1.Provider{ Name: gateway, Type: profile, Labels: map[string]string{openshell.InstanceLabel: m.instance}, Spec: v1.ProviderSpec{Credentials: map[string]string{keyEnv: key}}, }); err != nil { return daemon.ModelProvider{}, fmt.Errorf("provider %q: create gateway provider: %w", name, err) } return daemon.ModelProvider{Gateway: gateway, Host: host, Port: port}, nil } // key is the real key for provider name: its api_key_ref, or the org's // credential binding for a provider that only declares an env var. func (m *openShellModelEgress) key(ctx context.Context, token, org, name string, p config.Provider) (string, error) { if p.APIKey != (config.SecretRef{}) { return resolveKeyRef(m.secrets, name, p) } key, err := m.bindings.Resolve(ctx, token, name) if err != nil { return "", fmt.Errorf("provider %q has no usable credential binding named %q in org %s: %w", name, name, org, err) } if key = strings.TrimSpace(key); key == "" { return "", fmt.Errorf("provider %q: credential binding resolved empty", name) } return key, nil } // keyHeaders are the request headers providers that do not take a bearer // token read their key from, by class. The gateway only substitutes a // credential where its profile says it is placed. var keyHeaders = map[string]string{ "anthropic": "x-api-key", "gemini": "x-goog-api-key", "gemini-interactions": "x-goog-api-key", } // ensureProfile makes sure a profile declaring keyEnv as its one credential, // placed where class's providers read it, exists, and returns its id. // Profiles are shared and stay. func (m *openShellModelEgress) ensureProfile(ctx context.Context, keyEnv, class string) (string, error) { credential := v1.ProfileCredential{Name: "api_key", EnvVars: []string{keyEnv}, Required: true, Secret: true} id := "archie-" + strings.ReplaceAll(strings.ToLower(keyEnv), "_", "-") if header, ok := keyHeaders[class]; ok { credential.AuthStyle, credential.HeaderName = "header", header id += "-" + header } profiles := m.client.Providers().Profiles() if _, err := profiles.Get(ctx, "", id); err == nil { return id, nil } else if !v1.IsNotFound(err) { return "", fmt.Errorf("look up gateway profile %s: %w", id, err) } res, err := profiles.Import(ctx, "", []v1.ProfileImportItem{{ Source: "archie", Profile: v1.ProviderProfile{ ID: id, DisplayName: keyEnv, Category: v1.ProfileCategoryInference, InferenceCapable: true, Credentials: []v1.ProfileCredential{credential}, }, }}) if err == nil && res.Imported { return id, nil } // Another task may have imported it first. if _, getErr := profiles.Get(ctx, "", id); getErr == nil { return id, nil } if err != nil { return "", fmt.Errorf("import gateway profile %s: %w", id, err) } return "", fmt.Errorf("import gateway profile %s: rejected: %+v", id, res.Diagnostics) } // providerName is a unique gateway provider name. It carries neither the run // credential nor the key. func (m *openShellModelEgress) providerName() (string, error) { var b [6]byte if _, err := rand.Read(b[:]); err != nil { return "", fmt.Errorf("name gateway provider: %w", err) } instance := strings.Trim(nonNameChars.ReplaceAllString(strings.ToLower(m.instance), "-"), "-") if instance == "" { instance = "archie" } return "archie-" + instance + "-" + hex.EncodeToString(b[:]), nil } func (m *openShellModelEgress) own(token, gateway string) { m.mu.Lock() defer m.mu.Unlock() m.owned[token] = append(m.owned[token], gateway) } // Close deletes every gateway provider Open created for token. It outlives // ctx's cancellation: a cancelled task must still lose its keys. func (m *openShellModelEgress) Close(ctx context.Context, token string) { m.mu.Lock() names := m.owned[token] delete(m.owned, token) m.mu.Unlock() if len(names) == 0 { return } ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), providerCloseTimeout) defer cancel() for _, name := range names { if err := m.deleteProvider(ctx, name); err != nil { m.log.ErrorContext(ctx, "openshell: gateway provider not deleted", "provider", name, "err", err) } } } // Sweep deletes the gateway providers a previous daemon of this instance left // holding keys. It runs at boot, before any task opens a session. func (m *openShellModelEgress) Sweep(ctx context.Context) error { all, err := m.client.Providers().ListAll(ctx, m.workspace) if err != nil { return fmt.Errorf("list gateway providers: %w", err) } var errs []error for _, p := range all { if p.Labels[openshell.InstanceLabel] != m.instance { continue } m.log.InfoContext(ctx, "removing orphaned gateway provider", "provider", p.Name) if err := m.deleteProvider(ctx, p.Name); err != nil { errs = append(errs, fmt.Errorf("remove gateway provider %s: %w", p.Name, err)) } } return errors.Join(errs...) } // deleteProvider retries while the gateway still has the provider attached to // a sandbox it is deleting. func (m *openShellModelEgress) deleteProvider(ctx context.Context, name string) error { var err error for attempt := range providerDeleteAttempts { if attempt > 0 { select { case <-ctx.Done(): return ctx.Err() case <-time.After(providerDeleteWait): } } _, err = m.client.Providers().Delete(ctx, m.workspace, name, v1.DeleteOptions{AllowMissing: true}) if err == nil || !v1.IsConflict(err) { return err } } return err } // providerEndpoint is the host and port p's requests go to. func providerEndpoint(p config.Provider) (string, int, error) { return egress.ProviderEndpoint(p.Class, p.BaseURL) }