package app import ( "context" "encoding/json" "fmt" "maps" "slices" "strings" "albedo/cli/internal/config" "albedo/cli/internal/daemon" "albedo/cli/internal/daemon/protocol" ) const EffortInherit = "inherit" type ACPConnection struct { connection *daemon.Connection token string } type ACPSettings struct { Models []string Model string Efforts map[string][]string Effort string Windows map[string][]int Window *int Strategies []string Strategy string // Notes are provider catalogues that could not be read. They are carried // rather than swallowed so a caller can say why models are missing. Notes []string } // EffortLevels are the reasoning levels the session's model accepts. func (a ACPSettings) EffortLevels() []string { return levelsFor(a.Model, a.Efforts) } // WindowLevels are the context windows the session's model offers. func (a ACPSettings) WindowLevels() []int { return levelsFor(a.Model, a.Windows) } // levelsFor reads the catalogue row for one model. A session saved under a // provider profile that was since renamed or removed names no row; a model id // that exactly one profile carries still finds its row, so a rename cannot // empty a selector. A model two profiles carry stays ambiguous, because the // levels would belong to an account the session does not use. func levelsFor[T any](model string, catalogue map[string][]T) []T { if levels := catalogue[model]; len(levels) > 0 { return levels } _, id, split := strings.Cut(model, "/") if !split || id == "" { return nil } var found []T for key, levels := range catalogue { if len(levels) == 0 { continue } if _, candidate, ok := strings.Cut(key, "/"); !ok || candidate != id { continue } if found != nil { return nil } found = levels } return found } func (a *ACPConnection) Catalog(ctx context.Context) (ACPSettings, error) { return a.catalog(ctx) } func (a *ACPConnection) Settings(ctx context.Context, session string) (ACPSettings, error) { settings, err := a.catalog(ctx) if err != nil { return ACPSettings{}, err } return a.Refresh(ctx, session, settings) } // Refresh fills one session's selection and its own account's catalogue into a // catalogue read before the session existed. func (a *ACPConnection) Refresh(ctx context.Context, session string, settings ACPSettings) (ACPSettings, error) { info, err := daemon.GetSession(ctx, a.connection, session) if err != nil { return ACPSettings{}, err } settings.Model = info.Provider + "/" + info.Model if !slices.Contains(settings.Models, settings.Model) { settings.Models = append(settings.Models, settings.Model) } a.scopeModel(ctx, session, info.Provider, info.Model, &settings) a.readSelection(ctx, session, &settings) return settings, nil } // catalog reads every configured provider once: the selection list, the levels // each model accepts, and the windows each offers. A provider whose catalogue // cannot be read still contributes its default model and a Note, so a // transient failure never looks like a provider whose models have no levels. func (a *ACPConnection) catalog(ctx context.Context) (ACPSettings, error) { profiles, err := daemon.ProviderProfiles(ctx, a.connection) if err != nil { return ACPSettings{}, err } settings := ACPSettings{Efforts: map[string][]string{}, Windows: map[string][]int{}} for _, provider := range catalogOrder(profiles) { profile := profiles.Providers[provider] if profile.Model != "" { settings.Models = appendUnique(settings.Models, provider+"/"+profile.Model) } models, readErr := daemon.ListProfileModels(ctx, a.connection, profile) if readErr != nil { settings.Notes = append(settings.Notes, fmt.Sprintf("provider %s: %v", provider, readErr)) } for _, model := range models { id := provider + "/" + model.ID settings.Models = appendUnique(settings.Models, id) if len(model.Efforts) > 0 { settings.Efforts[id] = model.Efforts } if windows := windowsOf(model); len(windows) > 0 { settings.Windows[id] = windows } } } return settings, nil } // appendUnique adds a model id unless it is already listed. func appendUnique(models []string, id string) []string { if slices.Contains(models, id) { return models } return append(models, id) } // catalogOrder lists providers with the active one first, as the model picker // does, so a session's own provider is offered first. func catalogOrder(profiles config.Profiles) []string { names := slices.Sorted(maps.Keys(profiles.Providers)) if i := slices.Index(names, profiles.Active); i > 0 { names = append([]string{profiles.Active}, slices.Delete(names, i, i+1)...) } return names } func (a *ACPConnection) scopeModel(ctx context.Context, session, provider, model string, settings *ACPSettings) { models, err := daemon.ListSessionProfileModels(ctx, a.connection, session, provider) if err != nil { return } for _, candidate := range models { if candidate.ID == model { *settings = scopedTo(*settings, candidate) return } } } // scopedTo takes the levels and windows this session's own account reports; a // profile catalogue can omit levels only that account knows. func scopedTo(settings ACPSettings, model daemon.Model) ACPSettings { if len(model.Efforts) > 0 { settings.Efforts[settings.Model] = model.Efforts } if windows := windowsOf(model); len(windows) > 0 { settings.Windows[settings.Model] = windows } return settings } func (a *ACPConnection) readSelection(ctx context.Context, session string, settings *ACPSettings) { if configuration, err := daemon.GetSessionConfiguration(ctx, a.connection, session); err == nil { if effort := configuration.Value.Effort; effort != nil && *effort != "" { settings.Effort = *effort } if window := configuration.Value.ContextWindow; window != nil { tokens := int(*window) settings.Window = &tokens } } if state, err := daemon.CompactionStrategies(ctx, a.connection, session); err == nil { settings.Strategies = state.Strategies settings.Strategy = state.Current } } // windowsOf offers a fixed ladder up to the model's usable window. func windowsOf(model daemon.Model) []int { ladder := []int{50_000, 100_000, 250_000, 500_000, 750_000, 1_000_000} ceiling := model.Context if model.Raised && model.MaxContext > ceiling { ceiling = model.MaxContext } if model.CompactAt > 0 && (ceiling <= 0 || model.CompactAt < ceiling) { ceiling = model.CompactAt } windows := []int{} for _, tokens := range ladder { if ceiling > 0 && tokens > ceiling { break } windows = append(windows, tokens) } return windows } func (a *ACPConnection) SetModel(ctx context.Context, session, value string) error { profiles, err := daemon.ProviderProfiles(ctx, a.connection) if err != nil { return err } provider, model, err := daemon.ResolveSessionModel(profiles, value) if err != nil { return &daemon.APIError{StatusCode: 400, Code: "model_unavailable", Message: err.Error()} } if provider+"/"+model != value { return &daemon.APIError{StatusCode: 400, Code: "model_unavailable", Message: "The selected provider is no longer configured; resume to refresh models"} } return switchModel(ctx, a.connection, session, modelChoice{provider, model}, a.token) } func (a *ACPConnection) SetEffort(ctx context.Context, session, value string) error { _, err := daemon.PatchSessionEffort(ctx, a.connection, session, value, a.token) return err } // SetContextWindow saves the session's own window, or restores the model's // when tokens is nil: the ACP choice of Automatic clears the override. func (a *ACPConnection) SetContextWindow(ctx context.Context, session string, tokens *int) error { _, err := daemon.PatchSessionContextWindow(ctx, a.connection, session, tokens, a.token) return err } func (a *ACPConnection) SetCompactionStrategy(ctx context.Context, session string, strategy *string) error { _, err := daemon.PatchSessionCompactionStrategy(ctx, a.connection, session, strategy, a.token) return err } func (s *Service) ConnectACP(ctx context.Context, token string) (*ACPConnection, error) { conn, err := s.Connect(ctx) if err != nil { return nil, err } info, err := daemon.ProbeServer(ctx, conn) if err != nil { return nil, err } if info.Capabilities["acp_attachment"] < 3 { return nil, &daemon.APIError{Code: "daemon_incompatible", Message: "Run `albedo daemon --restart` in a terminal to enable ACP."} } return &ACPConnection{connection: conn, token: token}, nil } func (a *ACPConnection) New(ctx context.Context, cwd string, servers []protocol.ACPMCPServer) (protocol.ACPAttachment, error) { profiles, err := daemon.ProviderProfiles(ctx, a.connection) if err != nil { return protocol.ACPAttachment{}, err } _, configured := profiles.Providers[profiles.Active] if profiles.Active == "" || !configured { return protocol.ACPAttachment{}, &daemon.APIError{Code: "provider_missing", Message: "Run `albedo login` in a terminal, then try again."} } id, err := daemon.CreateACPSession(ctx, a.connection, a.token, protocol.ACPSessionRequest{Kind: "acp", Workspace: cwd, MCPServers: servers}) if err != nil { return protocol.ACPAttachment{}, err } return a.Resume(ctx, id, cwd, servers) } func (a *ACPConnection) Resume(ctx context.Context, id, cwd string, servers []protocol.ACPMCPServer) (protocol.ACPAttachment, error) { return daemon.AttachACP(ctx, a.connection, id, a.token, protocol.ACPAttachRequest{Workspace: cwd, MCPServers: servers}) } func (a *ACPConnection) Prepare(id string, blocks []json.RawMessage) (*daemon.OperationHandle, error) { return daemon.NewACPInput(id, a.token, blocks) } func (a *ACPConnection) Submit(ctx context.Context, handle *daemon.OperationHandle) error { _, err := daemon.SubmitOperation(ctx, a.connection, handle) return err } func (a *ACPConnection) Renew(ctx context.Context, id string) error { return daemon.RenewACP(ctx, a.connection, id, a.token) } func (a *ACPConnection) Release(ctx context.Context, id string) error { return daemon.ReleaseACP(ctx, a.connection, id, a.token) } func (a *ACPConnection) Observer(id string, cursor protocol.Cursor) *daemon.ChatClient { client := daemon.NewChatClient(a.connection, id) client.SeedCursor(cursor) return client } func (a *ACPConnection) Cancel(ctx context.Context, session, id string) (protocol.InputCancellation, error) { return daemon.NewChatClient(a.connection, session).CancelInput(ctx, id, a.token) } func (a *ACPConnection) Compact(ctx context.Context, id string) (daemon.CompactionResult, error) { return daemon.CompactSessionWithToken(ctx, a.connection, id, "", a.token) } func (a *ACPConnection) Delete(ctx context.Context, id string) error { configuration, err := daemon.GetSessionConfiguration(ctx, a.connection, id) if err != nil { return err } result, err := daemon.DeleteSession(ctx, a.connection, id, false, daemon.SessionCondition{ETag: configuration.ETag}) if err != nil { return err } if !result.OK { return &daemon.APIError{StatusCode: 409, Code: "session_delete_incomplete", Message: result.Message} } return nil } func (a *ACPConnection) List(ctx context.Context, cwd, cursor *string) (protocol.SessionPage, error) { return daemon.ListACPSessions(ctx, a.connection, cwd, cursor) } func (a *ACPConnection) History(ctx context.Context, id string, cursor daemon.ACPHistoryCursor, cutoff int64) ([]daemon.StreamEvent, daemon.ACPHistoryCursor, error) { return daemon.ACPHistory(ctx, a.connection, id, cursor, cutoff) }