Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8534: fix Devin model discovery with API key authentication (#9859)
Multica Eved52e48f8c737
diff --git a/apps/docs/content/docs/providers.mdx b/apps/docs/content/docs/providers.mdxindex 400edc27da..0aa55c2cc0 100644--- a/apps/docs/content/docs/providers.mdx+++ b/apps/docs/content/docs/providers.mdx@@ -62,9 +62,9 @@ When you create an agent, the model list comes from the corresponding runtime. SIf you do not pick a model, Multica uses the tool's own default. If the list is empty, confirm the runtime is online and the tool is signed in, then refresh the model list.-Devin's catalog can include models unavailable to your account. Choose a canonical model ID, an unambiguous session model name or catalog family slug/alias (such as `opus`), or leave the model empty for the CLI default. Multica confirms the actual session model before sending the prompt; a fallback to another family is rejected. Ambiguous names, arbitrary partial names, or unavailable variants require a canonical ID rather than a guessed match. Usage is attributed to the reported model, not the launch flag. Adaptive usage stays under the reported Adaptive routing ID, not an inferred underlying model.+Devin's picker lists the model choices advertised by its ACP session. Choose a canonical model ID, an unambiguous session model name or catalog family slug/alias (such as `opus`), or leave the model empty for the CLI default. Family aliases that require `devin models list` can still require a saved CLI login; if alias resolution fails, select a model ID from the picker. Multica confirms the actual session model before sending the prompt; a fallback to another family is rejected. Ambiguous names, arbitrary partial names, or unavailable variants require a canonical ID rather than a guessed match. Usage is attributed to the reported model, not the launch flag. Adaptive usage stays under the reported Adaptive routing ID, not an inferred underlying model.-Devin reads `WINDSURF_API_KEY` when set, otherwise the login saved by `devin auth login`; unknown ACP auth methods do not block that stored login. Multica preserves Devin's configured session mode rather than raising permissions. If it defaults to `plan`, switch to an editing mode in Devin before dispatching work that must change files.+Devin reads `WINDSURF_API_KEY` when set, otherwise the login saved by `devin auth login`; unknown ACP auth methods do not block that stored login. Model discovery uses the daemon user's credentials: a key set only in an agent's custom environment is unavailable to the runtime model picker. An empty session model list prompts you to check those credentials and your team's model allowlist. Multica preserves Devin's configured session mode rather than raising permissions. If it defaults to `plan`, switch to an editing mode in Devin before dispatching work that must change files.QwenPaw, MiniMax Code, and ZeroClaw are exceptions: they do not accept a model chosen from Multica, so the picker is inert and shows "Managed by runtime". Choose the model in the tool's own configuration instead. An empty model list for these tools is expected and does not mean the runtime is offline.diff --git a/server/pkg/agent/devin.go b/server/pkg/agent/devin.goindex 27ea5b00e1..319e7f2bda 100644--- a/server/pkg/agent/devin.go+++ b/server/pkg/agent/devin.go@@ -6,6 +6,7 @@ import ("errors""fmt""io"+ "os""os/exec""path/filepath""strings"@@ -431,109 +432,68 @@ func selectDevinAuthMethod(methods []string, haveWindsurfKey bool) string {return ""}-// discoverDevinModels runs `devin models list --format json`.-// Unknown/empty output degrades to an empty catalog (manual entry).func discoverDevinModels(ctx context.Context, runtimeCmd Command) ([]Model, error) {- if runtimeCmd.Path == "" {- runtimeCmd.Path = "devin"+ models, err := discoverACPModels(ctx, runtimeCmd, acpDiscoveryProvider{+ defaultBin: "devin",+ clientName: "multica-model-discovery",+ tmpdirPrefix: "multica-devin-discovery-",+ timeout: 15 * time.Second,+ strictErrors: true,+ parseModels: parseDevinSessionModels,+ selectAuthMethod: func(initResult json.RawMessage, childEnv []string) (string, error) {+ return selectDevinAuthMethod(extractACPAuthMethods(initResult), envHasNonEmpty(childEnv, "WINDSURF_API_KEY")), nil+ },+ })+ if err != nil {+ var rpcErr *acpRPCError+ if errors.As(err, &rpcErr) {+ detail := devinDiagnostic(rpcErr.Message, os.Environ())+ if data := devinDiagnostic(rpcErr.Data, os.Environ()); data != "" {+ detail += "; " + data+ }+ return nil, fmt.Errorf("devin model discovery %s failed (code=%d): %s", rpcErr.Method, rpcErr.Code, detail)+ }+ return nil, fmt.Errorf("devin model discovery: %s", devinDiagnostic(err.Error(), os.Environ()))}- if _, err := exec.LookPath(runtimeCmd.Path); err != nil {- return []Model{}, nil+ if len(models) == 0 {+ return nil, fmt.Errorf("Devin returned no model choices: set WINDSURF_API_KEY in the daemon environment or run devin auth login as the daemon user, and check your team's model allowlist")}- stdout, err := devinModelsOutput(ctx, runtimeCmd, nil, "")- if err != nil {- return nil, err+ return models, nil+}++// Redact before taking a bounded tail so truncation cannot split a credential+// away from the field name that identifies it to the shared sanitizer.+func devinDiagnostic(value string, env []string) string {+ for _, entry := range env {+ key, secret, ok := strings.Cut(entry, "=")+ if ok && strings.EqualFold(key, "WINDSURF_API_KEY") && secret != "" {+ value = strings.ReplaceAll(value, secret, "[REDACTED]")+ }}- return parseDevinModels(stdout)+ value = strings.TrimSpace(sanitizeAgentDiagnostic(value))+ if len(value) > agentStderrTailBytes {+ value = "…" + strings.ToValidUTF8(value[len(value)-agentStderrTailBytes:], "")+ }+ return value}func devinModelsOutput(ctx context.Context, runtimeCmd Command, env []string, cwd string) ([]byte, error) {runCtx, cancel := context.WithTimeout(ctx, 15*time.Second)defer cancel()cmd := runtimeCmd.exec(runCtx, "models", "list", "--format", "json")+ if env == nil {+ env = os.Environ()+ }cmd.Env, cmd.Dir = env, cwdhideAgentWindow(cmd)stdout, err := outputOwned(cmd, runtimeCmd.logger)if err != nil {- return nil, fmt.Errorf("devin model discovery: %w", err)- }- return stdout, nil-}--func parseDevinModels(data []byte) ([]Model, error) {- type entry struct {- ID string `json:"id"`- Name string `json:"name"`- Label string `json:"label"`- Provider string `json:"provider"`- Model string `json:"model"`- ModelUID string `json:"model_uid"`- }- var families struct {- Families []struct {- Slug string `json:"slug"`- Variants []entry `json:"variants"`- } `json:"families"`- }- if err := json.Unmarshal(data, &families); err == nil && len(families.Families) > 0 {- out := make([]Model, 0, 64)- seen := map[string]bool{}- for _, fam := range families.Families {- provider := strings.TrimSpace(fam.Slug)- for _, e := range fam.Variants {- id := strings.TrimSpace(e.ModelUID)- if id == "" {- id = strings.TrimSpace(e.ID)- }- if id == "" || seen[id] {- continue- }- seen[id] = true- label := strings.TrimSpace(e.Label)- if label == "" {- label = strings.TrimSpace(e.Name)- }- if label == "" {- label = id- }- out = append(out, Model{ID: id, Label: label, Provider: provider})- }- }- if len(out) > 0 {- return out, nil+ detail := devinDiagnostic(err.Error(), env)+ var exitErr *exec.ExitError+ if errors.As(err, &exitErr) {+ detail = withAgentStderr(detail, "devin", devinDiagnostic(string(exitErr.Stderr), env))}+ return nil, fmt.Errorf("devin model aliases: %s", detail)}- var models []entry- var wrapper struct {- Models []entry `json:"models"`- }- if err := json.Unmarshal(data, &wrapper); err == nil && len(wrapper.Models) > 0 {- models = wrapper.Models- } else if err := json.Unmarshal(data, &models); err != nil {- return []Model{}, nil- }- out := make([]Model, 0, len(models))- seen := map[string]bool{}- for _, e := range models {- id := strings.TrimSpace(e.ID)- if id == "" {- id = strings.TrimSpace(e.ModelUID)- }- if id == "" {- id = strings.TrimSpace(e.Model)- }- if id == "" || seen[id] {- continue- }- seen[id] = true- label := strings.TrimSpace(e.Name)- if label == "" {- label = strings.TrimSpace(e.Label)- }- if label == "" {- label = id- }- out = append(out, Model{ID: id, Label: label, Provider: strings.TrimSpace(e.Provider)})- }- return out, nil+ return stdout, nil}diff --git a/server/pkg/agent/devin_contract_test.go b/server/pkg/agent/devin_contract_test.goindex 7b198afc1a..e97d22f755 100644--- a/server/pkg/agent/devin_contract_test.go+++ b/server/pkg/agent/devin_contract_test.go@@ -17,6 +17,11 @@ import (// Replays the reported Devin CLI v3000.10.21 wire contract without account access.const fakeDevinContractScript = `#!/bin/shif [ "$1" = models ]; then+ if [ -n "$DEVIN_REQUESTS_FILE" ]; then printf '%s\n' 'models list' >> "$DEVIN_REQUESTS_FILE"; fi+ if [ -n "$DEVIN_TEST_CATALOG_ERROR" ]; then+ printf '%s\n' "$DEVIN_TEST_CATALOG_ERROR" >&2+ exit 1+ fiprintf '%s\n' "${DEVIN_TEST_CATALOG:-null}"exit 0fi@@ -25,6 +30,10 @@ while IFS= read -r line; doid=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')method=$(printf '%s' "$line" | sed -n 's/.*"method":"\([^"]*\)".*/\1/p')if [ "$method" = "$DEVIN_TEST_FAIL_RPC" ]; then+ if [ -n "$DEVIN_TEST_RPC_ERROR" ]; then+ printf '{"jsonrpc":"2.0","id":%s,"error":%s}\n' "$id" "$DEVIN_TEST_RPC_ERROR"+ exit 0+ fiprintf '{"jsonrpc":"2.0","id":%s,"error":{"code":%s,"message":"%s"}}\n' "$id" "${DEVIN_TEST_ERROR_CODE:--32016}" "${DEVIN_TEST_ERROR_MESSAGE:-Session not found}"if [ "$DEVIN_TEST_IGNORE_EOF" != 1 ]; then exit 0; ficontinue@@ -37,6 +46,10 @@ while IFS= read -r line; doprintf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id";;session/new|session/load|session/set_config_option)+ if [ "$method" = session/new ] && [ -n "$DEVIN_TEST_SESSION_RESULT" ]; then+ printf '{"jsonrpc":"2.0","id":%s,"result":%s}\n' "$id" "$DEVIN_TEST_SESSION_RESULT"+ continue+ fimodel=${DEVIN_TEST_INITIAL_MODEL:-default-model}if [ "$method" = session/set_config_option ] && [ "$DEVIN_TEST_APPLY_MODEL" = 1 ]; then model=selected-model; fiprintf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"devin-session","configOptions":[{"id":"model","category":"model","name":"Model","type":"select","currentValue":"%s","options":[{"value":"default-model","name":"Default"},{"value":"selected-model","name":"Selected"}]}]}}\n' "$id" "$model"@@ -133,13 +146,18 @@ func runDevinContract(t *testing.T, opts ExecOptions, env map[string]string) (Reif runtime.GOOS == "windows" {t.Skip("POSIX fake CLI; native Windows lifecycle is covered by the shared process ownership tests")}+ fakePath := filepath.Join(t.TempDir(), "devin")+ writeTestExecutable(t, fakePath, []byte(fakeDevinContractScript))+ return runDevinContractAt(t, fakePath, opts, env)+}++func runDevinContractAt(t *testing.T, fakePath string, opts ExecOptions, env map[string]string) (Result, []Message, string) {+ t.Helper()if env == nil {env = make(map[string]string)}requestsFile := filepath.Join(t.TempDir(), "requests.jsonl")env["DEVIN_REQUESTS_FILE"] = requestsFile- fakePath := filepath.Join(t.TempDir(), "devin")- writeTestExecutable(t, fakePath, []byte(fakeDevinContractScript))backend, err := New("devin", Config{ExecutablePath: fakePath, Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), Env: env})if err != nil {t.Fatal(err)diff --git a/server/pkg/agent/devin_discovery_test.go b/server/pkg/agent/devin_discovery_test.gonew file mode 100644index 0000000000..7624ffe9f1--- /dev/null+++ b/server/pkg/agent/devin_discovery_test.go@@ -0,0 +1,190 @@+package agent++import (+ "context"+ "encoding/json"+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "testing"+ "time"+ "unicode/utf8"+)++func devinDiscoveryFixture(t *testing.T, env map[string]string) (Command, string) {+ t.Helper()+ if runtime.GOOS == "windows" {+ t.Skip("POSIX fake CLI")+ }+ dir := t.TempDir()+ path := filepath.Join(dir, "devin")+ writeTestExecutable(t, path, []byte(fakeDevinContractScript))+ requests := filepath.Join(dir, "requests.jsonl")+ t.Setenv("DEVIN_REQUESTS_FILE", requests)+ t.Setenv("WINDSURF_API_KEY", "")+ t.Setenv("DEVIN_TEST_AUTH_METHODS", `[{"id":"windsurf-api-key"}]`)+ for key, value := range env {+ t.Setenv(key, value)+ }+ return Command{Path: path}, requests+}++func readDevinRequests(t *testing.T, path string) string {+ t.Helper()+ raw, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ return string(raw)+}++func TestDiscoverDevinModelsUsesSessionCredentials(t *testing.T) {+ for _, tc := range []struct {+ name, key, methods string+ auth bool+ }{+ {"API key", "fixture-key", `[{"id":"windsurf-api-key"}]`, true},+ {"stored login", "", `[{"id":"windsurf-api-key"}]`, false},+ {"unadvertised key method", "fixture-key", `[]`, false},+ {"unknown method", "fixture-key", `[{"id":"future-auth"}]`, false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ cmd, requestsFile := devinDiscoveryFixture(t, map[string]string{+ "WINDSURF_API_KEY": tc.key, "DEVIN_TEST_AUTH_METHODS": tc.methods,+ "DEVIN_TEST_CATALOG_ERROR": "Not logged in. Run devin auth login to authenticate.",+ })+ models, err := discoverDevinModels(context.Background(), cmd)+ if err != nil || len(models) != 2 || models[0].ID != "default-model" || !models[0].Default || models[1].ID != "selected-model" {+ t.Fatalf("models=%+v err=%v", models, err)+ }+ requests := readDevinRequests(t, requestsFile)+ initAt := strings.Index(requests, `"method":"initialize"`)+ authAt := strings.Index(requests, `"method":"authenticate"`)+ sessionAt := strings.Index(requests, `"method":"session/new"`)+ if initAt < 0 || sessionAt <= initAt || (authAt >= 0) != tc.auth || (tc.auth && !(initAt < authAt && authAt < sessionAt)) {+ t.Fatalf("wrong discovery handshake: %s", requests)+ }+ if tc.auth && (!strings.Contains(requests, `"headless":true`) || !strings.Contains(requests, `"methodId":"windsurf-api-key"`)) {+ t.Fatalf("missing headless key authentication: %s", requests)+ }+ if strings.Contains(requests, "fixture-key") || strings.Contains(requests, "models list") || strings.Contains(requests, `"method":"session/prompt"`) {+ t.Fatalf("discovery sent credentials, queried aliases, or prompted: %s", requests)+ }+ })+ }+}++func TestDiscoverDevinModelsRejectsEmptyAndUnrecognizedCatalogs(t *testing.T) {+ for _, tc := range []struct {+ name, result, want string+ }{+ {"no credentials", `{"configOptions":[{"id":"model","options":[]}]}`, "WINDSURF_API_KEY"},+ {"missing options", `{"configOptions":[{"id":"model"}]}`, "WINDSURF_API_KEY"},+ {"null options", `{"configOptions":[{"id":"model","options":null}]}`, "WINDSURF_API_KEY"},+ {"empty overrides legacy", `{"configOptions":[{"id":"model","options":[]}],"models":{"availableModels":[{"modelId":"forbidden"}]}}`, "model allowlist"},+ {"missing options overrides legacy", `{"configOptions":[{"id":"model"}],"models":{"availableModels":[{"modelId":"forbidden"}]}}`, "model allowlist"},+ {"legacy only", `{"models":{"availableModels":[{"modelId":"legacy"}]}}`, "unrecognized Devin model catalog"},+ {"missing model", `{"configOptions":[{"id":"mode","options":[]}]}`, "unrecognized Devin model catalog"},+ {"missing model id", `{"configOptions":[{"category":"model","options":[]}]}`, "unrecognized Devin model catalog"},+ {"malformed model", `{"configOptions":[{"id":"model","options":"bad"}]}`, "unrecognized Devin model catalog"},+ {"malformed choice", `{"configOptions":[{"id":"model","options":[{}]}]}`, "unrecognized Devin model catalog"},+ {"malformed response", `[]`, "unrecognized Devin model catalog"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ cmd, requestsFile := devinDiscoveryFixture(t, map[string]string{"DEVIN_TEST_SESSION_RESULT": tc.result})+ models, err := discoverDevinModels(context.Background(), cmd)+ if err == nil || len(models) != 0 || !strings.Contains(err.Error(), tc.want) {+ t.Fatalf("models=%+v err=%v, want %q", models, err, tc.want)+ }+ if strings.Contains(tc.want, "unrecognized") && strings.Contains(err.Error(), "WINDSURF_API_KEY") {+ t.Fatalf("malformed catalog was misreported as an authentication problem: %v", err)+ }+ if strings.Contains(readDevinRequests(t, requestsFile), `"method":"session/prompt"`) {+ t.Fatal("failed discovery sent a prompt")+ }+ })+ }+}++func TestDiscoverDevinModelsUsesGroupedSessionChoicesOverLegacy(t *testing.T) {+ cmd, _ := devinDiscoveryFixture(t, map[string]string{+ "DEVIN_TEST_SESSION_RESULT": `{"configOptions":[{"id":"unrelated","currentValue":true},{"id":"model","currentValue":"b","options":[{"value":"a","name":"Model A"},{"group":"recommended","options":[{"value":"b","name":"Model B"},{"group":"nested","options":[{"value":"c"},{"value":"b"}]}]}]}],"models":{"availableModels":[{"modelId":"forbidden"}]}}`,+ })+ models, err := discoverDevinModels(context.Background(), cmd)+ if err != nil || len(models) != 3 || models[0].ID != "a" || models[1].ID != "b" || models[1].Label != "Model B" || !models[1].Default || models[2].ID != "c" || models[2].Label != "c" {+ t.Fatalf("models=%+v err=%v", models, err)+ }+}++func TestDiscoverDevinModelsReportsSafeRPCFailures(t *testing.T) {+ for _, stage := range []string{"initialize", "authenticate", "session/new"} {+ t.Run(stage, func(t *testing.T) {+ wireError, err := json.Marshal(map[string]any{+ "code": -32000, "message": "invalid api key: opaque-fixture-key",+ "data": map[string]string{"token": "private-token", "detail": strings.Repeat("界", 3000) + " opaque-fixture-key"},+ })+ if err != nil {+ t.Fatal(err)+ }+ cmd, requestsFile := devinDiscoveryFixture(t, map[string]string{+ "WINDSURF_API_KEY": "opaque-fixture-key", "DEVIN_TEST_FAIL_RPC": stage, "DEVIN_TEST_RPC_ERROR": string(wireError),+ })+ _, err = discoverDevinModels(context.Background(), cmd)+ if err == nil || !strings.Contains(err.Error(), stage) || !strings.Contains(err.Error(), "invalid api key") {+ t.Fatalf("lost failure stage or reason: %v", err)+ }+ message := err.Error()+ if strings.Contains(message, "opaque-fixture-key") || strings.Contains(message, "private-token") || len(message) > 4500 || !utf8.ValidString(message) {+ t.Fatalf("unsafe or unbounded diagnostic (%d bytes)", len(message))+ }+ requests := readDevinRequests(t, requestsFile)+ if strings.Contains(requests, `"method":"session/prompt"`) || (stage != "session/new" && strings.Contains(requests, `"method":"session/new"`)) {+ t.Fatalf("discovery continued after failure: %s", requests)+ }+ })+ }+}++func TestDevinDiscoveredModelExecutesWithoutAliasCatalog(t *testing.T) {+ cmd, requestsFile := devinDiscoveryFixture(t, map[string]string{+ "WINDSURF_API_KEY": "fixture-key", "DEVIN_TEST_APPLY_MODEL": "1",+ "DEVIN_TEST_CATALOG_ERROR": "Not logged in. Run devin auth login to authenticate.",+ })+ catalog, err := ListModels(context.Background(), "devin", cmd)+ if err != nil || len(catalog.Models) != 2 {+ t.Fatalf("catalog=%+v err=%v", catalog, err)+ }+ result, _, requests := runDevinContractAt(t, cmd.Path, ExecOptions{Model: catalog.Models[1].ID}, map[string]string{})+ if result.Status != "completed" || result.Usage["selected-model"].InputTokens != 7 || !strings.Contains(requests, `"value":"selected-model"`) {+ t.Fatalf("discovered non-default model did not execute: %+v requests=%s", result, requests)+ }+ if strings.Contains(requests, "models list") || strings.Contains(readDevinRequests(t, requestsFile), "models list") {+ t.Fatal("canonical session ID required alias discovery")+ }+}++func TestDevinAliasFailureIncludesSafeStderr(t *testing.T) {+ key := "opaque-fixture-key"+ result, _, requests := runDevinContract(t, ExecOptions{Model: "opus"}, map[string]string{+ "WINDSURF_API_KEY": key,+ "DEVIN_TEST_CATALOG_ERROR": "Authorization: Bearer private-bearer\n" + strings.Repeat("界", 3000) + "\nNot logged in. Run devin auth login; credential " + key,+ })+ if result.Status != "failed" || !strings.Contains(result.Error, "Not logged in") || !strings.Contains(result.Error, "model picker") || !strings.Contains(requests, "models list") || strings.Contains(requests, `"method":"session/prompt"`) {+ t.Fatalf("alias failure lost its remedy: %+v requests=%s", result, requests)+ }+ if strings.Contains(result.Error, key) || strings.Contains(result.Error, "private-bearer") || len(result.Error) > 2500 || !utf8.ValidString(result.Error) {+ t.Fatalf("unsafe alias diagnostic (%d bytes)", len(result.Error))+ }+}++func TestDiscoverDevinModelsHonorsCancellation(t *testing.T) {+ cmd, _ := devinDiscoveryFixture(t, nil)+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ start := time.Now()+ _, err := discoverDevinModels(ctx, cmd)+ if err == nil || time.Since(start) > 3*time.Second {+ t.Fatalf("cancellation was not honored: %v", err)+ }+}diff --git a/server/pkg/agent/devin_model.go b/server/pkg/agent/devin_model.goindex ba4065c36e..aa10947dfd 100644--- a/server/pkg/agent/devin_model.go+++ b/server/pkg/agent/devin_model.go@@ -22,19 +22,73 @@ type devinModelOption struct {}func devinSessionModel(raw json.RawMessage) devinModelOption {+ if option, err := devinSessionModelOption(raw); err == nil {+ return option+ }+ // Older CLI builds expose the same selected-model fact in models.+ return devinModelOption{CurrentValue: extractACPCurrentModelID(raw)}+}++func devinSessionModelOption(raw json.RawMessage) (devinModelOption, error) {var response struct {ConfigOptions []json.RawMessage `json:"configOptions"`}- if json.Unmarshal(raw, &response) == nil {- for _, rawOption := range response.ConfigOptions {- var option devinModelOption- if json.Unmarshal(rawOption, &option) == nil && (option.Category == "model" || option.ID == "model") {- return option+ if json.Unmarshal(raw, &response) != nil {+ return devinModelOption{}, fmt.Errorf("unrecognized Devin model catalog: malformed configOptions")+ }+ for _, rawOption := range response.ConfigOptions {+ var header struct {+ ID string `json:"id"`+ Category string `json:"category"`+ }+ if json.Unmarshal(rawOption, &header) != nil {+ continue+ }+ if header.Category != "model" && header.ID != "model" {+ continue+ }+ var option devinModelOption+ if json.Unmarshal(rawOption, &option) != nil {+ return devinModelOption{}, fmt.Errorf("unrecognized Devin model catalog: malformed model option")+ }+ return option, nil+ }+ return devinModelOption{}, fmt.Errorf("unrecognized Devin model catalog: missing model config option")+}++func parseDevinSessionModels(raw json.RawMessage) ([]Model, error) {+ option, err := devinSessionModelOption(raw)+ if err != nil {+ return nil, err+ }+ if option.ID == "" {+ return nil, fmt.Errorf("unrecognized Devin model catalog: missing model option id")+ }+ models := make([]Model, 0, len(option.Options))+ seen := make(map[string]bool)+ var collect func([]devinModelChoice) error+ collect = func(choices []devinModelChoice) error {+ for _, choice := range choices {+ if choice.Options != nil {+ if err := collect(choice.Options); err != nil {+ return err+ }+ continue+ }+ if strings.TrimSpace(choice.Value) == "" {+ return fmt.Errorf("unrecognized Devin model catalog: model choice has no value")+ }+ if !seen[choice.Value] {+ seen[choice.Value] = true+ models = append(models, acpModelEntry(choice.Value, choice.Name, option.CurrentValue))}}+ return nil}- // Older CLI builds expose the same selected-model fact in models.- return devinModelOption{CurrentValue: extractACPCurrentModelID(raw)}+ if err := collect(option.Options); err != nil {+ return nil, err+ }+ return models, nil}func devinModelAvailable(choices []devinModelChoice, value string) bool {@@ -134,7 +188,7 @@ func confirmDevinModel(ctx context.Context, request acpRequestFn, sessionID, reqif len(values) == 0 && catalog != nil {data, err := catalog(ctx)if err != nil {- return "", fmt.Errorf("resolve Devin model %q: %w; choose a canonical model ID", requested, err)+ return "", fmt.Errorf("resolve Devin model %q: %w; choose a model ID from the model picker", requested, err)}values, err = devinCatalogModelValues(data, requested)if err != nil {diff --git a/server/pkg/agent/devin_test.go b/server/pkg/agent/devin_test.goindex b7d917ec7d..6c15d5a23a 100644--- a/server/pkg/agent/devin_test.go+++ b/server/pkg/agent/devin_test.go@@ -217,22 +217,3 @@ func TestSelectDevinAuthMethod(t *testing.T) {}}}--func TestParseDevinModels(t *testing.T) {- t.Parallel()- got, err := parseDevinModels([]byte(`{"models":[{"id":"kimi-k2.5","name":"Kimi K2.5"}]}`))- if err != nil {- t.Fatal(err)- }- if len(got) != 1 || got[0].ID != "kimi-k2.5" || got[0].Label != "Kimi K2.5" {- t.Fatalf("got %+v", got)- }- got, err = parseDevinModels([]byte(`[{"id":"opus","label":"Opus"}]`))- if err != nil || len(got) != 1 || got[0].Label != "Opus" {- t.Fatalf("array form: %+v err %v", got, err)- }- got, err = parseDevinModels([]byte(`{"families":[{"slug":"kimi-k3","variants":[{"model_uid":"kimi-k3-high","label":"Kimi K3 High"}]}]}`))- if err != nil || len(got) != 1 || got[0].ID != "kimi-k3-high" || got[0].Provider != "kimi-k3" {- t.Fatalf("families form: %+v err %v", got, err)- }-}diff --git a/server/pkg/agent/models.go b/server/pkg/agent/models.goindex c023b14e8f..2311b9e549 100644--- a/server/pkg/agent/models.go+++ b/server/pkg/agent/models.go@@ -2026,9 +2026,12 @@ type acpDiscoveryProvider struct {// server mode. Defaults to []string{"acp"} when nil/empty.acpArgs []string// selectAuthMethod inspects the initialize response and child environment- // after initialize succeeds. A non-nil selector must return one advertised- // method id; its error aborts discovery before any session operation.+ // after initialize succeeds. An empty method id skips authentication; an+ // error aborts discovery before any session operation.selectAuthMethod func(json.RawMessage, []string) (string, error)+ // parseModels overrides the shared catalog parser for providers whose+ // execution contract gives a different session field precedence.+ parseModels func(json.RawMessage) ([]Model, error)// strictErrors surfaces stage-specific handshake errors to the caller.// Legacy discovery providers keep their empty-list behavior; Grok enables// this so it can log the actual fallback reason.@@ -2223,11 +2226,13 @@ func discoverACPModels(ctx context.Context, runtimeCmd Command, p acpDiscoveryPrif err != nil {return fail("auth method selection", err)}- if _, err := requestACP("authenticate", map[string]any{- "methodId": methodID,- "_meta": map[string]any{"headless": true},- }); err != nil {- return fail(fmt.Sprintf("authenticate (%s)", methodID), err)+ if methodID != "" {+ if _, err := requestACP("authenticate", map[string]any{+ "methodId": methodID,+ "_meta": map[string]any{"headless": true},+ }); err != nil {+ return fail(fmt.Sprintf("authenticate (%s)", methodID), err)+ }}}@@ -2238,7 +2243,15 @@ func discoverACPModels(ctx context.Context, runtimeCmd Command, p acpDiscoveryPrif err != nil {return fail("session/new", err)}- models := parseACPSessionNewModels(sessionResult)+ var models []Model+ if p.parseModels != nil {+ models, err = p.parseModels(sessionResult)+ if err != nil {+ return fail("session/new model parsing", err)+ }+ } else {+ models = parseACPSessionNewModels(sessionResult)+ }if len(models) == 0 {// session/new succeeded but carried no catalog we recognise. This// is what upstream schema drift looks like from here (MUL-5239: