diff --git a/cli/internal/acp/load.go b/cli/internal/acp/load.go index 6d40379ec..b0e1bc671 100644 --- a/cli/internal/acp/load.go +++ b/cli/internal/acp/load.go @@ -122,7 +122,7 @@ func (s *session) load(message request) (failure error) { if s.bufferFailure != nil { return s.bufferFailure } - s.adapter.respond(message.ID, map[string]any{}, nil) + s.adapter.respond(message.ID, map[string]any{"configOptions": modelOptions(s.models)}, nil) return s.drainBufferedLocked() } diff --git a/cli/internal/acp/models.go b/cli/internal/acp/models.go new file mode 100644 index 000000000..8a688e0f7 --- /dev/null +++ b/cli/internal/acp/models.go @@ -0,0 +1,71 @@ +package acp + +import ( + "errors" + "slices" + + "albedo/cli/internal/app" + "albedo/cli/internal/daemon" +) + +func modelOptions(models app.ACPModels) []map[string]any { + configuration := []map[string]any{} + if len(models.Available) == 0 { + return configuration + } + options := make([]map[string]string, 0, len(models.Available)) + for _, model := range models.Available { + options = append(options, map[string]string{"value": model, "name": model}) + } + return append(configuration, map[string]any{"id": "model", "name": "Model", "category": "model", "type": "select", "currentValue": models.Current, "options": options}) +} + +func (a *adapter) setConfigOption(message request) { + var params struct { + SessionID string `json:"sessionId"` + ConfigID string `json:"configId"` + Value string `json:"value"` + } + if decodeParams(message.Params, ¶ms) != nil || params.ConfigID != "model" || params.Value == "" { + a.respond(message.ID, nil, problem(-32602, "invalid_params", "Choose an available model")) + return + } + a.mu.Lock() + current := a.sessions[params.SessionID] + a.mu.Unlock() + if current == nil { + a.respond(message.ID, nil, problem(-32002, "session_not_found", "Session is not attached")) + return + } + current.mu.Lock() + if current.uncertain || current.ctx.Err() != nil { + current.mu.Unlock() + a.respond(message.ID, nil, problem(-32603, "observation_uncertain", "Resume the session before changing its model")) + return + } + if current.buffering || current.active != nil || current.turn != "" || len(current.inherited) > 0 { + current.mu.Unlock() + a.respond(message.ID, nil, problem(-32602, "busy", "Wait for the current turn before changing its model")) + return + } + if !slices.Contains(current.models.Available, params.Value) { + current.mu.Unlock() + a.respond(message.ID, nil, problem(-32602, "invalid_params", "Choose an available model")) + return + } + current.configuring = true + current.mu.Unlock() + models, err := a.backend.SetModel(current.ctx, current.id, params.Value) + current.mu.Lock() + defer current.mu.Unlock() + current.configuring = false + if err != nil { + if api, ok := errors.AsType[*daemon.APIError](err); !ok || api.StatusCode >= 500 { + current.lose("observation_uncertain", "Model selection may have changed; resume the session") + } + a.respond(message.ID, nil, err) + return + } + current.models = models + a.respond(message.ID, map[string]any{"configOptions": modelOptions(models)}, nil) +} diff --git a/cli/internal/acp/schema_test.go b/cli/internal/acp/schema_test.go index 0e9888e54..75b74a6c2 100644 --- a/cli/internal/acp/schema_test.go +++ b/cli/internal/acp/schema_test.go @@ -4,6 +4,7 @@ package acp import ( + "albedo/cli/internal/app" "albedo/cli/internal/daemon" "encoding/json" "github.com/google/jsonschema-go/jsonschema" @@ -22,6 +23,7 @@ func TestPinnedSchema(t *testing.T) { } s, backend := testSession(t) + s.models = app.ACPModels{Current: "fixture/model", Available: []string{"fixture/model", "other/model"}} s.adapter.respond(json.RawMessage("1"), initialize("test"), nil) for _, event := range []daemon.StreamEvent{ {Type: daemon.EventUser, Source: "chat", EntryID: "user", Text: "question"}, diff --git a/cli/internal/acp/server.go b/cli/internal/acp/server.go index 3da78bdc9..db4a90ac9 100644 --- a/cli/internal/acp/server.go +++ b/cli/internal/acp/server.go @@ -19,6 +19,9 @@ import ( ) type Backend interface { + Models(context.Context, string) (app.ACPModels, error) + CurrentModel(context.Context, string) (string, error) + SetModel(context.Context, string, string) (app.ACPModels, error) List(context.Context, *string, *string) (protocol.SessionPage, error) History(context.Context, string, int64, int64) ([]daemon.StreamEvent, int64, error) Cancel(context.Context, string, string) (protocol.InputCancellation, error) @@ -143,7 +146,7 @@ func Run(ctx context.Context, input io.Reader, output, diagnostics io.Writer, ve adapter.respond(message.ID, nil, problem(-32602, "invalid_params", "No authentication methods are available")) case "session/list": adapter.workers.Go(func() { adapter.list(message) }) - case "session/new", "session/resume", "session/load": + case "session/new", "session/resume", "session/load", "session/set_config_option": adapter.workers.Go(adapter.setupRequest(message)) case "session/prompt": adapter.prompt(message) @@ -227,7 +230,12 @@ func (a *adapter) setup(message request) { a.respond(message.ID, nil, err) return } - var err error + // Provider discovery can be slow; do it before acquiring or pausing a lease. + models, err := a.backend.Models(a.ctx, params.SessionID) + if err != nil { + a.respond(message.ID, nil, err) + return + } var attachment protocol.ACPAttachment var prior *session if message.Method == "session/new" { @@ -245,9 +253,25 @@ func (a *adapter) setup(message request) { a.respond(message.ID, nil, err) return } + models.Current, err = a.backend.CurrentModel(a.ctx, attachment.SessionID) + if err != nil { + if prior != nil { + prior.resumeObservation() + } else { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + _ = a.backend.Release(ctx, attachment.SessionID) + } + a.respond(message.ID, nil, err) + return + } + if !slices.Contains(models.Available, models.Current) { + models.Available = append(models.Available, models.Current) + } a.stopPrior(attachment.SessionID) a.mu.Lock() current := newSession(a, attachment) + current.models = models if message.Method == "session/load" { current.pauseObservation() for id := range current.boundaries { @@ -270,7 +294,7 @@ func (a *adapter) setup(message request) { } return } - result := map[string]any{} + result := map[string]any{"configOptions": modelOptions(models)} if message.Method == "session/new" { result["sessionId"] = attachment.SessionID } @@ -360,7 +384,11 @@ func (a *adapter) setupRequest(message request) func() { close(done) a.mu.Unlock() }() - a.setup(message) + if message.Method == "session/set_config_option" { + a.setConfigOption(message) + } else { + a.setup(message) + } } } diff --git a/cli/internal/acp/session.go b/cli/internal/acp/session.go index f92290832..746121ada 100644 --- a/cli/internal/acp/session.go +++ b/cli/internal/acp/session.go @@ -14,6 +14,7 @@ import ( "time" "unicode/utf8" + "albedo/cli/internal/app" "albedo/cli/internal/daemon" "albedo/cli/internal/daemon/protocol" ) @@ -73,6 +74,7 @@ type session struct { stop context.CancelFunc durable map[string]bool active *pendingPrompt + models app.ACPModels id string turn string cursor protocol.Cursor diff --git a/cli/internal/acp/setup_test.go b/cli/internal/acp/setup_test.go index ed1200c1b..c657d4592 100644 --- a/cli/internal/acp/setup_test.go +++ b/cli/internal/acp/setup_test.go @@ -11,6 +11,7 @@ import ( "testing" "time" + "albedo/cli/internal/app" "albedo/cli/internal/daemon" "albedo/cli/internal/daemon/protocol" ) @@ -23,6 +24,14 @@ type setupBackend struct { calls chan string } +func (b *setupBackend) Models(context.Context, string) (app.ACPModels, error) { + return app.ACPModels{Current: "fixture/model", Available: []string{"fixture/model"}}, nil +} + +func (b *setupBackend) CurrentModel(context.Context, string) (string, error) { + return "fixture/model", nil +} + func (b *setupBackend) Observer(id string, cursor protocol.Cursor) *daemon.ChatClient { client := daemon.NewChatClient(b.conn, id) client.SeedCursor(cursor) @@ -145,6 +154,10 @@ type refusedResumeBackend struct { prior *session } +func (b refusedResumeBackend) Models(context.Context, string) (app.ACPModels, error) { + return app.ACPModels{}, nil +} + func (b refusedResumeBackend) Resume(context.Context, string, string, []protocol.ACPMCPServer) (protocol.ACPAttachment, error) { b.prior.mu.Lock() defer b.prior.mu.Unlock() diff --git a/cli/internal/app/acp.go b/cli/internal/app/acp.go index 64caf8d66..43e235b3a 100644 --- a/cli/internal/app/acp.go +++ b/cli/internal/app/acp.go @@ -5,6 +5,7 @@ import ( "albedo/cli/internal/daemon/protocol" "context" "encoding/json" + "slices" ) // ACPConnection owns HTTP workflows; the protocol controller owns observation policy. @@ -18,6 +19,58 @@ type ACPModels struct { Available []string } +func (a *ACPConnection) Models(ctx context.Context, id string) (ACPModels, error) { + profiles, err := daemon.ProviderProfiles(ctx, a.connection) + if err != nil { + return ACPModels{}, err + } + provider := profiles.Active + model := profiles.Providers[provider].Model + models := ACPModels{Current: provider + "/" + model} + if id != "" { + models.Current, err = a.CurrentModel(ctx, id) + if err != nil { + return ACPModels{}, err + } + } + for _, catalog := range configuredModels(ctx, a.connection, profiles) { + for _, model := range catalog.models { + models.Available = append(models.Available, catalog.provider+"/"+model) + } + } + if !slices.Contains(models.Available, models.Current) { + models.Available = append(models.Available, models.Current) + } + return models, nil +} + +func (a *ACPConnection) CurrentModel(ctx context.Context, id string) (string, error) { + session, err := daemon.GetSession(ctx, a.connection, id) + return session.Provider + "/" + session.Model, err +} + +func (a *ACPConnection) SetModel(ctx context.Context, id, value string) (ACPModels, error) { + profiles, err := daemon.ProviderProfiles(ctx, a.connection) + if err != nil { + return ACPModels{}, err + } + provider, model, err := daemon.ResolveSessionModel(profiles, value) + if err != nil { + return ACPModels{}, &daemon.APIError{StatusCode: 400, Code: "model_unavailable", Message: err.Error()} + } + if provider+"/"+model != value { + return ACPModels{}, &daemon.APIError{StatusCode: 400, Code: "model_unavailable", Message: "The selected provider is no longer configured; resume to refresh models"} + } + configuration, err := daemon.GetSessionConfiguration(ctx, a.connection, id) + if err != nil { + return ACPModels{}, err + } + if err := daemon.SelectACPModel(ctx, a.connection, id, a.token, daemon.ModelSelectionRequest{Provider: provider, Model: model, ETag: configuration.ETag}); err != nil { + return ACPModels{}, err + } + return a.Models(ctx, id) +} + func (s *Service) ConnectACP(ctx context.Context, token string) (*ACPConnection, error) { conn, err := s.Connect(ctx) if err != nil { diff --git a/cli/internal/daemon/acp.go b/cli/internal/daemon/acp.go index f26dac703..2e062f6cd 100644 --- a/cli/internal/daemon/acp.go +++ b/cli/internal/daemon/acp.go @@ -69,6 +69,15 @@ func ReleaseACP(ctx context.Context, conn *Connection, id, token string) error { }}, []int{204}, func(_ []byte, _ int) error { return nil }) } +func SelectACPModel(ctx context.Context, conn *Connection, id, token string, selection ModelSelectionRequest) error { + headers, err := observedHeaders(selection.ETag) + if err != nil { + return err + } + headers.Set("Albedo-Attachment-Token", token) + _, err = patchSessionWithHeaders(ctx, conn, id, headers, map[string]any{"model": selection.Model, "provider_profile": selection.Provider}) + return err +} func (c *ChatClient) SeedCursor(cursor protocol.Cursor) { c.mu.Lock() defer c.mu.Unlock() diff --git a/robot-docs/acp.md b/robot-docs/acp.md index 9fc3d6656..7712b4e6d 100644 --- a/robot-docs/acp.md +++ b/robot-docs/acp.md @@ -6,7 +6,7 @@ The adapter supports local daemons and workspaces. It connects lazily, never prompts or restarts an incompatible daemon, and requires `capabilities.acp_attachment >= 3`. Provider credentials come from normal albedo configuration. Missing setup returns `provider_missing` with instructions to run `albedo login` in a terminal. -`initialize` answers without contacting the daemon. Supported methods are `session/new`, `session/list`, `session/load`, `session/resume`, `session/prompt`, and `session/cancel`. Output uses `session/update`. Prompts accept text and resource links. Images, embedded resources, editor filesystem and terminal callbacks, and HTTP MCP servers are unsupported. File tools use saved disk contents. +`initialize` answers without contacting the daemon. Supported methods are `session/new`, `session/list`, `session/load`, `session/resume`, `session/set_config_option`, `session/prompt`, and `session/cancel`. Output uses `session/update`. Prompts accept text and resource links. Images, embedded resources, editor filesystem and terminal callbacks, and HTTP MCP servers are unsupported. File tools use saved disk contents. Stdout contains newline-delimited JSON-RPC only; diagnostics use stderr. Reading, observation, and writing run independently. The writer bounds pending output to 4 MiB. Overflow or write failure disconnects the adapter without cancelling daemon work. @@ -22,6 +22,10 @@ A stream gap or incompatible durable replacement fails observation and requires ## Models and history +New, loaded, and resumed sessions return a `configOptions` model selector with `profile/model` choices from configured providers. Provider defaults remain available when a catalogue cannot be read. The current model remains visible even if no longer listed. + +`session/set_config_option` accepts `configId: "model"` and an advertised value. Switching requires an idle session, affects only that session, and rechecks attachment ownership inside the daemon actor. Resume refreshes choices and the current selection. + `session/list` discovers ACP sessions without acquiring ownership. It supports an exact `cwd` filter and opaque pagination. Load and resume require full session IDs, matching workspaces, and the intended MCP configuration. Competing writers cannot attach. Load replays durable user messages, replies, thoughts, and tools in order, then delivers buffered live activity. It excludes internal provider records and system input. Replay failure returns an error and releases the attachment. Resume delivers future activity without replay. Resuming running work permits cancellation but blocks new prompts until it ends. diff --git a/test/e2e/acp_test.py b/test/e2e/acp_test.py index dd38eda30..6f7c76c42 100644 --- a/test/e2e/acp_test.py +++ b/test/e2e/acp_test.py @@ -493,6 +493,119 @@ class AcpCreationTests(AcpSessionCase): self.assertEqual(self.session_ids(), before) +@exclusive +class AcpModelTests(AcpSessionCase): + """The editor's choice reaches the provider without changing global defaults.""" + + def setUp(self): + def prepare(app): + app.provider.catalog = { + "data": [{"id": "fixture-model"}, {"id": "other-model"}] + } + app.providers = { + name: { + "extension": "openai", + "baseUrl": app.provider.url, + "apiKey": "fixture-key", + "model": "fixture-model", + "protocol": "chat_completions", + } + for name in ("first", "second") + } + + self.albedo_options = {"prepare": prepare} + super().setUp() + + def test_model_choices_switch_only_the_session_and_survive_reattachment(self): + client = self.connect() + self.initialize(client) + created = self.result( + client.request( + "session/new", {"cwd": str(self.workspace), "mcpServers": []} + ) + ) + session = created["sessionId"] + selector = created["configOptions"][0] + self.assertEqual(selector["currentValue"], "first/fixture-model") + self.assertIn("second/other-model", {m["value"] for m in selector["options"]}) + selection = { + "sessionId": session, + "configId": "model", + "value": "second/other-model", + } + self.assertError( + client.request( + "session/set_config_option", {**selection, "value": "missing/model"} + ), + -32602, + ) + with self.app.api(f"/sessions/{session}?view=configuration") as response: + etag = response.headers["ETag"] + for token in (None, "A" * 43): + headers = {"If-Match": etag, "Content-Type": "application/merge-patch+json"} + if token: + headers["Albedo-Attachment-Token"] = token + with self.assertRaises(urllib.error.HTTPError) as refused: + self.app.api( + f"/sessions/{session}?view=configuration", + {"model": "other-model"}, + method="PATCH", + headers=headers, + ) + self.assertEqual(refused.exception.code, 409) + changed = self.result(client.request("session/set_config_option", selection)) + self.assertEqual( + changed["configOptions"][0]["currentValue"], selection["value"] + ) + self.assertEqual( + self.stop_reason( + self.prompt(client, session, text_block("use the selected model")) + ), + "end_turn", + ) + self.assertEqual(self.provider.requests[-1]["model"], "other-model") + self.assertEqual(self.snapshot(session)["provider_profile"], "second") + untouched = self.new_session(client) + self.assertEqual(self.snapshot(untouched)["model"], "fixture-model") + for method in ("session/resume", "session/load"): + loaded = self.result( + client.request( + method, + { + "sessionId": session, + "cwd": str(self.workspace), + "mcpServers": [], + }, + ) + ) + self.assertEqual( + loaded["configOptions"][0]["currentValue"], selection["value"] + ) + + def test_model_switch_is_refused_while_a_turn_runs(self): + client = self.connect() + self.initialize(client) + session = self.new_session(client) + gate, prompt = self.start_gated_prompt(client, session, "finished") + self.assertError( + client.request( + "session/set_config_option", + { + "sessionId": session, + "configId": "model", + "value": "second/other-model", + }, + ), + -32602, + "busy", + ) + self.release(gate) + self.assertEqual( + self.stop_reason(client.response(prompt, timeout=60)), "end_turn" + ) + self.assertEqual(self.snapshot(session)["model"], "fixture-model") + + @exclusive class AcpNoProviderTests(AcpSessionCase): """A home with no default provider answers auth_required and stays usable."""