Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6471: fix(daemon): let pi and opencode reach custom providers (#7312)
Bohan Jiang20ceaccc432e
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 60b20168c1..fc05ce29c2 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -6140,6 +6140,171 @@ func skillRefFromBundle(bundle SkillData) SkillRefData {}}+// taskModelSelection is what a task actually launches with: the model+// selector plus the capability overrides that survived validation.+type taskModelSelection struct {+ Model string+ ThinkingLevel string+ ServiceTier string+}++// resolveTaskModelSelection settles the model selector and its capability+// overrides against the runtime's own model catalog, reading that catalog at+// most once per task — and not at all when nothing needs it.+//+// The single read is the point. Discovery is a CLI subprocess with a 15-30s+// ceiling, and cachedDiscovery deliberately does not memoize a result that+// came back empty or as a fallback (#3729, MUL-5549) so a transient failure+// can retry immediately. A logged-out or timing-out runtime therefore pays+// that ceiling in full on every read, and a task that read the catalog once to+// qualify its model and again to validate thinking_level would pay it twice+// before the agent even starts (MUL-6471 review).+//+// Who asks for the catalog:+// - opencode and its DevEco fork cannot execute an unqualified selector, so+// a pinned model has to be resolved against the catalog before launch.+// - thinking_level / service_tier are catalog-owned and keyed on the+// catalog's own model id, so they need it whenever they are set.+//+// A pi task with no capability override asks for neither: pi's own resolver+// accepts the persisted id in every shape it can take, so the daemon has+// nothing to add and skips discovery entirely. Same for claude, codex, and any+// task that pins no model.+//+// Qualification runs first because both checks below match on the catalog's+// canonical id: an unqualified id silently fails every lookup and drops a+// perfectly valid level (GH #7300).+func resolveTaskModelSelection(+ ctx context.Context,+ provider string,+ runtimeCmd agent.Command,+ sel taskModelSelection,+ taskLog *slog.Logger,+) taskModelSelection {+ capabilityChecksPending := sel.ThinkingLevel != "" || sel.ServiceTier != ""++ read := false+ var (+ catalog agent.Catalog+ catalogErr error+ )+ loadCatalog := func() (agent.Catalog, error) {+ if !read {+ read = true+ catalog, catalogErr = listModels(ctx, provider, runtimeCmd)+ }+ return catalog, catalogErr+ }++ sel.Model = qualifyTaskModel(provider, sel.Model, capabilityChecksPending, loadCatalog, taskLog)++ // service_tier is catalog-owned and currently Codex-only. As with+ // thinking_level, stale or incompatible persisted values degrade to the+ // runtime default instead of failing the task. Catalog lookup errors pass+ // through so a transient discovery failure does not silently disable a+ // previously valid user choice.+ if sel.ServiceTier != "" {+ ok, err := agent.ValidateServiceTierWith(loadCatalog, provider, sel.Model, sel.ServiceTier)+ if err != nil {+ taskLog.Warn("service_tier: catalog lookup failed; passing through",+ "provider", provider,+ "model", sel.Model,+ "service_tier", sel.ServiceTier,+ "error", err,+ )+ } else if !ok {+ taskLog.Warn("service_tier: not valid for this (provider, model); skipping injection",+ "provider", provider,+ "model", sel.Model,+ "service_tier", sel.ServiceTier,+ )+ sel.ServiceTier = ""+ }+ }+ // Per-model guard: the server validates the literal token against the+ // provider's enum, but per-model gaps (Claude's `xhigh` on a non-Opus+ // model, Codex's per-model `supported_reasoning_levels`) only resolve+ // here, against the daemon's local CLI catalog. Invalid combinations+ // log a warning and drop the level rather than failing the task, so a+ // stale persisted value never blocks execution. An empty model is+ // resolved by ValidateThinkingLevelWith to the provider's default model so+ // default-model tasks aren't misjudged — except for codex, whose empty+ // model follows config.toml (any model) and so fails closed, dropping the+ // level here without a catalog read at all. Discovery errors fail open for+ // resolved models: if we can't list models, we keep the persisted level+ // and let the CLI object.+ if sel.ThinkingLevel != "" {+ ok, err := agent.ValidateThinkingLevelWith(loadCatalog, provider, sel.Model, sel.ThinkingLevel)+ if err != nil {+ taskLog.Warn("thinking_level: catalog lookup failed; passing through",+ "provider", provider,+ "model", sel.Model,+ "thinking_level", sel.ThinkingLevel,+ "error", err,+ )+ } else if !ok {+ taskLog.Warn("thinking_level: not valid for this (provider, model); skipping injection",+ "provider", provider,+ "model", sel.Model,+ "thinking_level", sel.ThinkingLevel,+ )+ sel.ThinkingLevel = ""+ }+ }++ return sel+}++// qualifyTaskModel promotes a persisted model id to the canonical+// `<provider>/<id>` selector its runtime catalog advertises, and returns the+// model to actually launch with.+//+// agent.model holds whatever was persisted, and for gateway-style providers a+// bare model id is itself slash-shaped (`claude/claude-opus-5` under provider+// `multica-anthropic`), so the delimiter cannot tell a missing provider from a+// present one — only the catalog knows (GH #7300).+//+// It reads the catalog for two distinct reasons, and neither is "because we+// can": either the runtime refuses to launch without a qualified selector, or+// a capability check is about to read the catalog anyway and will match+// nothing unless the id is canonical first. When neither holds, the persisted+// value goes to the CLI untouched and no subprocess is spawned.+func qualifyTaskModel(+ provider, model string,+ capabilityChecksPending bool,+ loadCatalog func() (agent.Catalog, error),+ taskLog *slog.Logger,+) string {+ if model == "" {+ return model+ }+ if !agent.ModelSelectorMustBeProviderQualified(provider) && !capabilityChecksPending {+ return model+ }+ catalog, err := loadCatalog()+ if err != nil {+ // Same fail-open posture as the capability checks: an unreachable+ // catalog must not stop a task whose model may well be exactly what+ // the CLI expects.+ taskLog.Warn("model: catalog lookup failed; using the configured model as-is",+ "provider", provider,+ "model", model,+ "error", err,+ )+ return model+ }+ qualified, rewritten := agent.QualifyModelID(catalog, model)+ if !rewritten {+ return model+ }+ taskLog.Info("model: qualified against the runtime catalog",+ "provider", provider,+ "configured_model", model,+ "model", qualified,+ )+ return qualified+}+func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot int, taskLog *slog.Logger) (taskResult TaskResult, returnErr error) {// A claim carries the task-row agent id both at the top level and inside// the expanded agent configuration. The top-level id is authoritative@@ -6973,10 +7138,32 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot ireturn TaskResult{}, fmt.Errorf("create agent backend: %w", err)}+ // Two-tier model resolution: an explicit agent.model wins,+ // then the daemon-wide MULTICA_<PROVIDER>_MODEL env var. If+ // both are empty we deliberately pass "" through — each+ // backend omits `--model` from the CLI invocation, so the+ // provider picks its own default (Claude Code's shipped+ // default, codex app-server's account-scoped default, etc.).+ // Baking a Go-side "recommended default" here is how the+ // cursor regression happened — static guesses drift from+ // whatever the upstream CLI actually accepts.+ //+ // Resolved before the start log rather than at first use: logging+ // entry.Model there reported the env-var tier alone, so every task whose+ // model came from agent.model — the common case — announced itself with an+ // empty model and looked like the selection had been dropped (GH #7300).+ model := ""+ if task.Agent != nil && task.Agent.Model != "" {+ model = task.Agent.Model+ }+ if model == "" {+ model = entry.Model+ }+taskLog.Info("starting agent","provider", provider,"workdir", env.WorkDir,- "model", entry.Model,+ "model", model,"reused", reused,)if task.PriorSessionID != "" {@@ -7002,80 +7189,16 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// has no overlay to protect and keeps its flags untouched.customArgs = hermesOverlayCustomArgs}- // Two-tier model resolution: an explicit agent.model wins,- // then the daemon-wide MULTICA_<PROVIDER>_MODEL env var. If- // both are empty we deliberately pass "" through — each- // backend omits `--model` from the CLI invocation, so the- // provider picks its own default (Claude Code's shipped- // default, codex app-server's account-scoped default, etc.).- // Baking a Go-side "recommended default" here is how the- // cursor regression happened — static guesses drift from- // whatever the upstream CLI actually accepts.- model := ""- if task.Agent != nil && task.Agent.Model != "" {- model = task.Agent.Model- }- if model == "" {- model = entry.Model- }thinkingLevel := ""serviceTier := ""if task.Agent != nil {thinkingLevel = task.Agent.ThinkingLevelserviceTier = task.Agent.ServiceTier}- // service_tier is catalog-owned and currently Codex-only. As with- // thinking_level, stale or incompatible persisted values degrade to the- // runtime default instead of failing the task. Catalog lookup errors pass- // through so a transient discovery failure does not silently disable a- // previously valid user choice.- if serviceTier != "" {- ok, err := agent.ValidateServiceTier(ctx, provider, agent.NewCommand(entry.Path, profileFixedArgs), model, serviceTier)- if err != nil {- taskLog.Warn("service_tier: catalog lookup failed; passing through",- "provider", provider,- "model", model,- "service_tier", serviceTier,- "error", err,- )- } else if !ok {- taskLog.Warn("service_tier: not valid for this (provider, model); skipping injection",- "provider", provider,- "model", model,- "service_tier", serviceTier,- )- serviceTier = ""- }- }- // Per-model guard: the server validates the literal token against the- // provider's enum, but per-model gaps (Claude's `xhigh` on a non-Opus- // model, Codex's per-model `supported_reasoning_levels`) only resolve- // here, against the daemon's local CLI catalog. Invalid combinations- // log a warning and drop the level rather than failing the task, so a- // stale persisted value never blocks execution. An empty model is- // resolved by ValidateThinkingLevel to the provider's default model so- // default-model tasks aren't misjudged — except for codex, whose empty- // model follows config.toml (any model) and so fails closed, dropping the- // level here. Discovery errors fail open for resolved models: if we can't- // list models, we keep the persisted level and let the CLI object.- if thinkingLevel != "" {- ok, err := agent.ValidateThinkingLevel(ctx, provider, agent.NewCommand(entry.Path, profileFixedArgs), model, thinkingLevel)- if err != nil {- taskLog.Warn("thinking_level: catalog lookup failed; passing through",- "provider", provider,- "model", model,- "thinking_level", thinkingLevel,- "error", err,- )- } else if !ok {- taskLog.Warn("thinking_level: not valid for this (provider, model); skipping injection",- "provider", provider,- "model", model,- "thinking_level", thinkingLevel,- )- thinkingLevel = ""- }- }+ selection := resolveTaskModelSelection(ctx, provider, agent.NewCommand(entry.Path, profileFixedArgs),+ taskModelSelection{Model: model, ThinkingLevel: thinkingLevel, ServiceTier: serviceTier}, taskLog)+ model, thinkingLevel, serviceTier = selection.Model, selection.ThinkingLevel, selection.ServiceTier+var idleWatchdogTimeout time.Durationif provider == "opencode" {idleWatchdogTimeout = d.cfg.OpenCodeIdleWatchdogdiff --git a/server/internal/daemon/model_qualify_test.go b/server/internal/daemon/model_qualify_test.gonew file mode 100644index 0000000000..940a175971--- /dev/null+++ b/server/internal/daemon/model_qualify_test.go@@ -0,0 +1,216 @@+package daemon++import (+ "context"+ "io"+ "log/slog"+ "sync"+ "testing"++ "github.com/multica-ai/multica/server/pkg/agent"+)++// stubModelDiscovery replaces the daemon's listModels indirection with a+// counting fake, so a test can assert BOTH what a task resolved to and how+// many discovery rounds it took to get there. The count is the contract:+// discovery is a CLI subprocess with a 15-30s ceiling that cachedDiscovery+// does not memoize when it returns empty or fallback, so "once" and "never"+// are behaviours worth pinning, not implementation detail.+func stubModelDiscovery(t *testing.T, catalogs map[string]agent.Catalog) func() int {+ t.Helper()+ var mu sync.Mutex+ calls := 0++ orig := listModels+ listModels = func(_ context.Context, provider string, _ agent.Command) (agent.Catalog, error) {+ mu.Lock()+ calls+++ mu.Unlock()+ return catalogs[provider], nil+ }+ t.Cleanup(func() { listModels = orig })++ return func() int {+ mu.Lock()+ defer mu.Unlock()+ return calls+ }+}++func quietTaskLog() *slog.Logger {+ return slog.New(slog.NewTextHandler(io.Discard, nil))+}++// thinkingCatalogs mirrors the shapes the reporter's gateway config produces:+// a slash-shaped model id under a custom provider, advertising a reasoning+// catalog. codex carries a service tier so the codex-specific paths are real.+func thinkingCatalogs() map[string]agent.Catalog {+ gatewayOpus := agent.Model{+ ID: "multica-anthropic/claude/claude-opus-5",+ Provider: "multica-anthropic",+ Thinking: &agent.ModelThinking{SupportedLevels: []agent.ThinkingLevel{+ {Value: "high", Label: "High"},+ }},+ }+ return map[string]agent.Catalog{+ "pi": {Models: []agent.Model{gatewayOpus}},+ "opencode": {Models: []agent.Model{gatewayOpus}},+ "omp": {Models: []agent.Model{gatewayOpus}},+ "claude": {Models: []agent.Model{{+ ID: "claude-opus-5",+ Provider: "anthropic",+ Thinking: &agent.ModelThinking{SupportedLevels: []agent.ThinkingLevel{+ {Value: "high", Label: "High"},+ }},+ }}},+ "codex": {Models: []agent.Model{{+ ID: "gpt-5.6-sol",+ Provider: "openai",+ ServiceTiers: []agent.ModelServiceTier{{ID: "priority", Name: "Priority"}},+ Thinking: &agent.ModelThinking{SupportedLevels: []agent.ThinkingLevel{+ {Value: "high", Label: "High"},+ }},+ }}},+ }+}++// TestResolveTaskModelSelectionReadsTheCatalogAtMostOnce is the production+// path the previous round left unguarded (MUL-6471 review): a task that both+// qualifies its model and validates a capability override must not pay for+// discovery twice. It also pins the other half — the tasks that must not+// reach discovery at all.+func TestResolveTaskModelSelectionReadsTheCatalogAtMostOnce(t *testing.T) {+ tests := []struct {+ name string+ provider string+ in taskModelSelection+ want taskModelSelection+ wantReads int+ }{+ {+ // The reporter's exact configuration. One read serves both the+ // selector promotion and the thinking-level check; before the fix+ // the id never matched the catalog, so the level was dropped.+ name: "pi qualifies and validates on a single read",+ provider: "pi",+ in: taskModelSelection{Model: "claude/claude-opus-5", ThinkingLevel: "high"},+ want: taskModelSelection{Model: "multica-anthropic/claude/claude-opus-5", ThinkingLevel: "high"},+ wantReads: 1,+ },+ {+ name: "opencode qualifies and validates on a single read",+ provider: "opencode",+ in: taskModelSelection{Model: "claude/claude-opus-5", ThinkingLevel: "high"},+ want: taskModelSelection{Model: "multica-anthropic/claude/claude-opus-5", ThinkingLevel: "high"},+ wantReads: 1,+ },+ {+ // pi launches an unqualified id correctly on its own, so with no+ // capability override there is nothing to look up.+ name: "pi without a capability override never reads the catalog",+ provider: "pi",+ in: taskModelSelection{Model: "claude/claude-opus-5"},+ want: taskModelSelection{Model: "claude/claude-opus-5"},+ wantReads: 0,+ },+ {+ name: "omp inherits pi's launch contract",+ provider: "omp",+ in: taskModelSelection{Model: "claude/claude-opus-5"},+ want: taskModelSelection{Model: "claude/claude-opus-5"},+ wantReads: 0,+ },+ {+ // opencode cannot launch an unqualified selector, so it reads even+ // with no capability override — the one case that must pay.+ name: "opencode reads even without a capability override",+ provider: "opencode",+ in: taskModelSelection{Model: "claude/claude-opus-5"},+ want: taskModelSelection{Model: "multica-anthropic/claude/claude-opus-5"},+ wantReads: 1,+ },+ {+ name: "claude with no override never reads the catalog",+ provider: "claude",+ in: taskModelSelection{Model: "claude-opus-5"},+ want: taskModelSelection{Model: "claude-opus-5"},+ wantReads: 0,+ },+ {+ name: "claude with a thinking level reads exactly once",+ provider: "claude",+ in: taskModelSelection{Model: "claude-opus-5", ThinkingLevel: "high"},+ want: taskModelSelection{Model: "claude-opus-5", ThinkingLevel: "high"},+ wantReads: 1,+ },+ {+ // codex validates both overrides; they share the one read.+ name: "codex validates thinking and service tier on a single read",+ provider: "codex",+ in: taskModelSelection{Model: "gpt-5.6-sol", ThinkingLevel: "high", ServiceTier: "priority"},+ want: taskModelSelection{Model: "gpt-5.6-sol", ThinkingLevel: "high", ServiceTier: "priority"},+ wantReads: 1,+ },+ {+ // codex with no explicit model fails both checks closed, and does+ // so without a catalog read — the guard predates this change and+ // must survive it.+ name: "codex without a model fails closed without reading",+ provider: "codex",+ in: taskModelSelection{ThinkingLevel: "high", ServiceTier: "priority"},+ want: taskModelSelection{},+ wantReads: 0,+ },+ {+ name: "no pinned model and no overrides reads nothing",+ provider: "opencode",+ in: taskModelSelection{},+ want: taskModelSelection{},+ wantReads: 0,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ reads := stubModelDiscovery(t, thinkingCatalogs())++ got := resolveTaskModelSelection(context.Background(), tt.provider, agent.Command{}, tt.in, quietTaskLog())+ if got != tt.want {+ t.Errorf("resolveTaskModelSelection(%s, %+v) = %+v, want %+v", tt.provider, tt.in, got, tt.want)+ }+ if reads() != tt.wantReads {+ t.Errorf("catalog reads = %d, want %d", reads(), tt.wantReads)+ }+ })+ }+}++// A runtime that cannot answer must not block the task: the persisted model+// may well be exactly what its CLI expects, and a stale-looking capability+// override is kept rather than silently dropped on a transient failure. The+// failed read is still only attempted once.+func TestResolveTaskModelSelectionFailsOpenOnDiscoveryError(t *testing.T) {+ var mu sync.Mutex+ calls := 0++ orig := listModels+ listModels = func(_ context.Context, _ string, _ agent.Command) (agent.Catalog, error) {+ mu.Lock()+ calls+++ mu.Unlock()+ return agent.Catalog{}, context.DeadlineExceeded+ }+ t.Cleanup(func() { listModels = orig })++ in := taskModelSelection{Model: "claude/claude-opus-5", ThinkingLevel: "high"}+ got := resolveTaskModelSelection(context.Background(), "opencode", agent.Command{}, in, quietTaskLog())+ if got != in {+ t.Errorf("resolveTaskModelSelection on discovery error = %+v, want %+v unchanged", got, in)+ }++ mu.Lock()+ defer mu.Unlock()+ if calls != 1 {+ t.Errorf("catalog reads = %d, want 1 — a failed read must not be retried within the task", calls)+ }+}diff --git a/server/pkg/agent/models.go b/server/pkg/agent/models.goindex e009816a9e..fbd0ec2893 100644--- a/server/pkg/agent/models.go+++ b/server/pkg/agent/models.go@@ -267,6 +267,90 @@ func ListModels(ctx context.Context, providerType string, runtimeCmd Command) (C}}+// ModelSelectorMustBeProviderQualified reports whether a runtime's CLI+// refuses a model id that does not carry its `<provider>/` prefix.+//+// This is an execution contract, not a statement about catalog shape. It+// decides one thing: whether the daemon has to read the runtime catalog before+// launching a task that pins a model. That read costs a CLI subprocess with a+// 15-30s ceiling which cachedDiscovery deliberately does not memoize when it+// comes back empty or as a fallback (#3729, MUL-5549), so a logged-out runtime+// pays the ceiling on every read — worth spending only where the launch+// genuinely fails without it (MUL-6471 review).+//+// opencode's `run --model` and the DevEco fork of it resolve strictly through+// `provider/model` and reject anything else — verified against opencode+// 1.18.14, which answers a bare id with `UnknownError` before any provider+// call. pi is deliberately absent: its resolver accepts a canonical selector,+// a bare id, AND an id containing a slash (see buildPiArgs), so a pi task+// launches correctly without the daemon qualifying anything first.+//+// Built-in runtime identities resolve through their protocol family, so a fork+// inherits the contract from its descriptor entry rather than a name here.+func ModelSelectorMustBeProviderQualified(providerType string) bool {+ if desc, ok := BuiltinRuntimeByID(providerType); ok {+ providerType = desc.ProtocolFamily+ }+ switch providerType {+ case "opencode", "deveco":+ return true+ default:+ return false+ }+}++// QualifyModelID resolves a persisted model string to the canonical ID the+// runtime's own catalog advertises, and reports whether it rewrote anything.+// catalog is the runtime's discovered catalog; callers already holding one+// (the daemon reads it for the thinking-level and service-tier checks) pay+// nothing extra.+//+// Runtimes that namespace their catalog (opencode's `provider/model`, pi's+// `provider/id` selector) want the qualified form, but `agent.model` holds+// whatever was persisted — and for gateway-style providers the bare model id+// is itself slash-shaped (`claude/claude-opus-5` under provider+// `multica-anthropic`). The slash is therefore not a provider boundary and+// cannot be guessed at: the catalog is the only thing that knows which+// provider owns an id. Callers get the qualified id when exactly one provider+// claims the value, and the input untouched otherwise.+//+// Untouched is the deliberate answer for every uncertain case — the catalog is+// a static fallback rather than the runtime's real list, the value already+// matches a catalog ID, or two providers expose the same bare id. Manual model+// entry is supported everywhere, so a value this function cannot confidently+// place must still reach the CLI verbatim; the CLI's own resolver is a better+// judge than a guess here would be.+func QualifyModelID(catalog Catalog, model string) (string, bool) {+ model = strings.TrimSpace(model)+ // A fallback catalog is a static stand-in, not what the runtime actually+ // supports (see Catalog.Fallback) — qualifying against it would rewrite a+ // working id into one the CLI never advertised.+ if model == "" || catalog.Fallback {+ return model, false+ }+ for _, m := range catalog.Models {+ if m.ID == model {+ return model, false+ }+ }+ qualified := ""+ for _, m := range catalog.Models {+ if m.Provider == "" || m.ID != m.Provider+"/"+model {+ continue+ }+ if qualified != "" && qualified != m.ID {+ // Two providers expose this same bare id. Picking one would be a+ // coin flip that silently routes the task to the wrong gateway.+ return model, false+ }+ qualified = m.ID+ }+ if qualified == "" {+ return model, false+ }+ return qualified, true+}+// ModelSelectionSupported reports whether setting `agent.model` has// any effect for the given provider. Every built-in provider now honours// `opts.Model` end-to-end — Hermes routes it through the ACP@@ -1223,11 +1307,10 @@ func discoverOmpModels(ctx context.Context, runtimeCmd Command) ([]Model, error)// {"models":[{"provider":"anthropic","id":"claude-sonnet-5","selector":"anthropic/claude-sonnet-5","name":"Claude Sonnet 5",...}]}//// The persistable Model.ID is the selector (provider/id), matching the-// convention parsePiModels uses: buildPiArgs splits Model.ID on "/" and-// emits --provider + --model. Using the bare id would drop --provider and-// let omp's internal provider priority ranking pick a different backend-// for the same model id. Provider is kept for UI grouping. The dedup key-// is the selector when present, falling back to provider/id.+// convention parsePiModels uses: buildPiArgs hands Model.ID to --model whole.+// Using the bare id would let omp's internal provider priority ranking pick a+// different backend for the same model id. Provider is kept for UI grouping.+// The dedup key is the selector when present, falling back to provider/id.func parseOmpModels(data []byte) ([]Model, error) {var wrapper struct {Models []struct {@@ -1249,9 +1332,9 @@ func parseOmpModels(data []byte) ([]Model, error) {}provider := strings.TrimSpace(e.Provider)// Model.ID is the qualified selector (provider/id) so buildPiArgs- // emits both --provider and --model. When selector is absent, fall- // back to provider/id; when provider is also absent, the bare id is- // the only form available.+ // forwards a selector omp can resolve unambiguously. When selector is+ // absent, fall back to provider/id; when provider is also absent, the+ // bare id is the only form available.selector := strings.TrimSpace(e.Selector)if selector == "" {if provider != "" {diff --git a/server/pkg/agent/models_test.go b/server/pkg/agent/models_test.goindex f0a78b3859..389853418d 100644--- a/server/pkg/agent/models_test.go+++ b/server/pkg/agent/models_test.go@@ -1907,3 +1907,198 @@ func TestDiscoveryCacheKeyIsolatesByExecutable(t *testing.T) {t.Errorf("expected 2 underlying calls (one per executable), got %d", calls)}}++// TestQualifyModelID covers GH #7300: a persisted model id that+// omits its provider must be promoted to the catalog's canonical selector,+// but only when exactly one provider claims it. opencode rejects an+// unqualified id outright, and every capability lookup keyed on the model id+// misses until the two agree.+func TestQualifyModelID(t *testing.T) {+ t.Parallel()++ gateway := []Model{+ {ID: "multica-anthropic/claude/claude-opus-5", Provider: "multica-anthropic"},+ {ID: "multica-anthropic/claude/claude-sonnet-5", Provider: "multica-anthropic"},+ {ID: "multica-codex/codex/gpt-5.6-sol", Provider: "multica-codex"},+ }++ tests := []struct {+ name string+ catalog Catalog+ model string+ want string+ wantRewritten bool+ }{+ {+ name: "slash-shaped id gains its provider",+ catalog: Catalog{Models: gateway},+ model: "claude/claude-opus-5",+ want: "multica-anthropic/claude/claude-opus-5",+ wantRewritten: true,+ },+ {+ name: "already canonical is left alone",+ catalog: Catalog{Models: gateway},+ model: "multica-anthropic/claude/claude-opus-5",+ want: "multica-anthropic/claude/claude-opus-5",+ },+ {+ name: "an exact catalog id wins over a qualifiable one",+ // Both a bare `shared-id` model and a `vendor/shared-id` model+ // exist. The exact match is what the user picked; promoting it to+ // the other provider's entry would silently reroute the task.+ catalog: Catalog{Models: []Model{+ {ID: "shared-id", Provider: ""},+ {ID: "vendor/shared-id", Provider: "vendor"},+ }},+ model: "shared-id",+ want: "shared-id",+ },+ {+ name: "ambiguous across providers stays untouched",+ catalog: Catalog{Models: []Model{+ {ID: "gateway-a/claude/claude-opus-5", Provider: "gateway-a"},+ {ID: "gateway-b/claude/claude-opus-5", Provider: "gateway-b"},+ }},+ model: "claude/claude-opus-5",+ want: "claude/claude-opus-5",+ },+ {+ name: "unknown model is passed through for the CLI to judge",+ catalog: Catalog{Models: gateway},+ model: "something-nobody-advertises",+ want: "something-nobody-advertises",+ },+ {+ name: "empty catalog cannot qualify anything",+ catalog: Catalog{},+ model: "claude/claude-opus-5",+ want: "claude/claude-opus-5",+ },+ {+ // A static stand-in is not what the runtime actually supports, so+ // promoting against it would invent an id the CLI never advertised.+ name: "a fallback catalog is never authoritative",+ catalog: Catalog{Models: gateway, Fallback: true},+ model: "claude/claude-opus-5",+ want: "claude/claude-opus-5",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ t.Parallel()+ got, rewritten := QualifyModelID(tt.catalog, tt.model)+ if got != tt.want || rewritten != tt.wantRewritten {+ t.Errorf("QualifyModelID(%q) = (%q, %v), want (%q, %v)",+ tt.model, got, rewritten, tt.want, tt.wantRewritten)+ }+ })+ }+}++// A blank model means "let the runtime pick its own default" — there is+// nothing to qualify, and the runtime resolves its own selection.+func TestQualifyModelIDIgnoresBlankModel(t *testing.T) {+ t.Parallel()+ catalog := Catalog{Models: []Model{{ID: "vendor/only-model", Provider: "vendor"}}}+ got, rewritten := QualifyModelID(catalog, " ")+ if got != "" || rewritten {+ t.Errorf("QualifyModelID(blank) = (%q, %v), want (\"\", false)", got, rewritten)+ }+}++// TestSlashShapedPiModelKeepsItsThinkingCatalog walks the chain that GH #7300+// reported as a dropped thinking_level: pi's RPC catalog carries a+// gateway-style model whose own id contains a slash, the agent persisted that+// bare id, and every capability lookup keyed on it missed. Qualifying the id+// first is what puts the persisted value back on the catalog entry that+// actually advertises the levels.+func TestSlashShapedPiModelKeepsItsThinkingCatalog(t *testing.T) {+ t.Parallel()++ // Verbatim shape of a real `get_available_models` RPC response for the+ // reporter's models.json.+ raw := []piRPCModel{+ {ID: "claude/claude-opus-5", Name: "Claude Opus 5", Provider: "multica-anthropic", Reasoning: true},+ {ID: "claude/claude-sonnet-5", Name: "Claude Sonnet 5", Provider: "multica-anthropic", Reasoning: true},+ }+ models := piModelsFromRPC(raw, piRPCState{})++ qualified, rewritten := QualifyModelID(Catalog{Models: models}, "claude/claude-opus-5")+ if !rewritten || qualified != "multica-anthropic/claude/claude-opus-5" {+ t.Fatalf("qualified = (%q, %v), want (%q, true)",+ qualified, rewritten, "multica-anthropic/claude/claude-opus-5")+ }++ var thinking *ModelThinking+ for _, m := range models {+ if m.ID == qualified {+ thinking = m.Thinking+ }+ }+ if thinking == nil {+ t.Fatalf("qualified model %q advertises no thinking catalog", qualified)+ }+ if !piThinkingSupports(thinking, "high") {+ t.Errorf("thinking catalog for %q missing \"high\": %+v", qualified, thinking.SupportedLevels)+ }+}++// TestModelSelectorMustBeProviderQualifiedIsAnExecutionContract pins what the+// predicate actually claims: whether a runtime's CLI refuses a model id that+// carries no provider prefix. It is deliberately NOT a statement about catalog+// shape — several runtimes (pi, omp, deveco) emit provider-prefixed ids, but+// only the ones whose CLI *rejects* the unprefixed form justify spending a+// discovery subprocess before launch.+//+// The pi entries are the load-bearing ones: buildPiArgs and its tests prove pi+// resolves a canonical selector, a bare id, and an id containing a slash all+// on its own, so a pi task must launch without the daemon reading any catalog.+func TestModelSelectorMustBeProviderQualifiedIsAnExecutionContract(t *testing.T) {+ t.Parallel()++ tests := []struct {+ provider string+ want bool+ why string+ }{+ {"opencode", true, "run --model resolves strictly through provider/model"},+ {"deveco", true, "opencode fork with the same --model contract"},+ {"pi", false, "pi's own resolver accepts bare and slash-shaped ids"},+ {"omp", false, "pi-family fork, inherits pi's resolver"},+ {"claude", false, "bare model ids, no provider segment to miss"},+ {"codex", false, "bare model ids"},+ {"copilot", false, "bare model ids under a display-name provider"},+ {"dsh", false, "resolves its own provider-prefixed ids"},+ {"", false, "unknown provider must not spend discovery"},+ }++ for _, tt := range tests {+ t.Run(tt.provider, func(t *testing.T) {+ t.Parallel()+ if got := ModelSelectorMustBeProviderQualified(tt.provider); got != tt.want {+ t.Errorf("ModelSelectorMustBeProviderQualified(%q) = %v, want %v (%s)",+ tt.provider, got, tt.want, tt.why)+ }+ })+ }+}++// omp is a built-in runtime identity rather than a protocol family, so the+// predicate must resolve it through its descriptor. This is what keeps "add a+// fork" a descriptor entry instead of a change here.+func TestModelSelectorContractFollowsProtocolFamily(t *testing.T) {+ t.Parallel()++ desc, ok := BuiltinRuntimeByID("omp")+ if !ok {+ t.Fatal("omp is no longer a built-in runtime identity; this test needs a new subject")+ }+ if desc.ProtocolFamily != "pi" {+ t.Fatalf("omp protocol family = %q, want pi", desc.ProtocolFamily)+ }+ if ModelSelectorMustBeProviderQualified("omp") != ModelSelectorMustBeProviderQualified(desc.ProtocolFamily) {+ t.Error("omp does not inherit its selector contract from the pi protocol family")+ }+}diff --git a/server/pkg/agent/omp_test.go b/server/pkg/agent/omp_test.goindex 37fd944c45..b289968c67 100644--- a/server/pkg/agent/omp_test.go+++ b/server/pkg/agent/omp_test.go@@ -226,7 +226,7 @@ func TestOmpExecuteCompletesFromEventStream(t *testing.T) {// an object wrapper {"models":[...]} where each entry has separate `provider`,// `id`, `selector` (provider/id), and `name` fields. The persistable Model.ID// is the selector (provider/id), matching the convention parsePiModels uses-// so buildPiArgs emits both --provider and --model.+// so buildPiArgs can hand the whole selector to --model.func TestParseOmpModels(t *testing.T) {sample := `{"models":[` +`{"provider":"anthropic","id":"claude-sonnet-5","selector":"anthropic/claude-sonnet-5","name":"Claude Sonnet 5","contextWindow":200000,"maxTokens":64000,"reasoning":true},` +@@ -315,8 +315,9 @@ func TestOmpModelsJSONShape(t *testing.T) {// TestOmpSelectorSurvivesToBuildPiArgs is the regression test the review// asked for: a real `omp models --json` fixture → parseOmpModels →-// buildPiArgs should emit both --provider and --model, not just --model.-// This pins the contract that Model.ID is the selector (provider/id).+// buildPiArgs should hand the selector to --model whole. This pins the+// contract that Model.ID is the selector (provider/id) and that the selector+// reaches the CLI intact — the pi-family resolver takes it from there.func TestOmpSelectorSurvivesToBuildPiArgs(t *testing.T) {raw := `{"models":[{"provider":"anthropic","id":"claude-sonnet-5","selector":"anthropic/claude-sonnet-5","name":"Claude Sonnet 5"}]}`models, err := parseOmpModels([]byte(raw))@@ -326,15 +327,17 @@ func TestOmpSelectorSurvivesToBuildPiArgs(t *testing.T) {if len(models) != 1 {t.Fatalf("expected 1 model, got %d", len(models))}- // The model ID is "anthropic/claude-sonnet-5" (the selector).- // buildPiArgs should split it into --provider anthropic --model claude-sonnet-5.+ // The model ID is "anthropic/claude-sonnet-5" (the selector), and that is+ // exactly what --model receives. Splitting it into --provider anthropic+ // --model claude-sonnet-5 resolves identically for a real provider prefix+ // but breaks slash-shaped model ids, so the split is gone (GH #7300).args := buildPiArgs("/tmp/session.jsonl", ExecOptions{Model: models[0].ID}, slog.Default())joined := strings.Join(args, " ")- if !strings.Contains(joined, "--provider anthropic") {- t.Errorf("args missing --provider anthropic: %s", joined)+ if !strings.Contains(joined, "--model anthropic/claude-sonnet-5") {+ t.Errorf("args missing --model anthropic/claude-sonnet-5: %s", joined)}- if !strings.Contains(joined, "--model claude-sonnet-5") {- t.Errorf("args missing --model claude-sonnet-5: %s", joined)+ if strings.Contains(joined, "--provider") {+ t.Errorf("args should not synthesize --provider: %s", joined)}}diff --git a/server/pkg/agent/pi.go b/server/pkg/agent/pi.goindex cda446bea6..5f2f64c855 100644--- a/server/pkg/agent/pi.go+++ b/server/pkg/agent/pi.go@@ -619,8 +619,7 @@ var piCustomArgModes = map[string]blockedArgMode{// -p non-interactive mode (prompt arrives on stdin)// --mode json emit one JSON event per line on stdout// --session <path> session log file (created upfront, reused on resume)-// --provider <name> provider, when Model is "provider/id"-// --model <id> model identifier+// --model <selector> model selector, passed through verbatim// --thinking <level> per-agent reasoning level override//// The prompt is deliberately absent from argv. Pi reads a non-TTY stdin in@@ -634,14 +633,18 @@ func buildPiArgs(sessionPath string, opts ExecOptions, logger *slog.Logger) []stif sessionPath != "" {args = append(args, "--session", sessionPath)}- if opts.Model != "" {- provider, model := splitPiModel(opts.Model)- if provider != "" {- args = append(args, "--provider", provider)- }- if model != "" {- args = append(args, "--model", model)- }+ // The selector goes to --model whole, and --provider is never synthesized.+ // Pi's own resolver already accepts every shape we hold: a canonical+ // `provider/id`, a bare id, and — crucially — an id that itself contains a+ // slash, which is the normal case for gateway-style providers whose model+ // ids look like `claude/claude-opus-5`. Splitting on the first slash to+ // fill --provider turns that id into a provider name Pi has never heard of,+ // and an unknown --provider is a hard error ("Unknown provider ...") rather+ // than something Pi can recover from — whereas --model alone falls back to+ // matching the full string as a raw model id. Passing less is strictly more+ // capable here (GH #7300).+ if model := strings.TrimSpace(opts.Model); model != "" {+ args = append(args, "--model", model)}if opts.ThinkingLevel != "" {args = append(args, "--thinking", opts.ThinkingLevel)@@ -718,16 +721,6 @@ func filterPiCustomArgs(args []string, logger *slog.Logger) []string {return filtered}-// splitPiModel parses a "provider/model" string into its parts. Plain-// "model" strings pass through as (provider="", model="model").-func splitPiModel(s string) (provider, model string) {- s = strings.TrimSpace(s)- if i := strings.Index(s, "/"); i >= 0 {- return strings.TrimSpace(s[:i]), strings.TrimSpace(s[i+1:])- }- return "", s-}-// ── Session path ──// piSessionDir returns the directory where Pi session JSONL files live.diff --git a/server/pkg/agent/pi_stdin_unix_test.go b/server/pkg/agent/pi_stdin_unix_test.goindex 7a15173da2..f117938ac4 100644--- a/server/pkg/agent/pi_stdin_unix_test.go+++ b/server/pkg/agent/pi_stdin_unix_test.go@@ -92,7 +92,7 @@ func TestPiExecuteSendsBuilderPromptOnStdinNotArgv(t *testing.T) {}}joined := strings.Join(argv, " ")- for _, want := range []string{"-p", "--mode json", "--session", "--provider cpa", "--model grok-4.5-high"} {+ for _, want := range []string{"-p", "--mode json", "--session", "--model cpa/grok-4.5-high"} {if !strings.Contains(joined, want) {t.Errorf("expected %q in argv, got %v", want, argv)}diff --git a/server/pkg/agent/pi_stdin_windows_test.go b/server/pkg/agent/pi_stdin_windows_test.goindex a007ab8ab7..aefc493da1 100644--- a/server/pkg/agent/pi_stdin_windows_test.go+++ b/server/pkg/agent/pi_stdin_windows_test.go@@ -234,7 +234,7 @@ func assertPiPromptSurvivesShim(t *testing.T) {}}gotArgv := string(argvRaw)- for _, want := range []string{"-p", "--mode", "json", "--session", "--provider", "cpa", "--model", "grok-4.5-high"} {+ for _, want := range []string{"-p", "--mode", "json", "--session", "--model", "cpa/grok-4.5-high"} {if !strings.Contains(gotArgv, want) {t.Errorf("expected %q to reach native child; argv=%q", want, gotArgv)}diff --git a/server/pkg/agent/pi_test.go b/server/pkg/agent/pi_test.goindex 82fc6931be..7f5fd75813 100644--- a/server/pkg/agent/pi_test.go+++ b/server/pkg/agent/pi_test.go@@ -29,7 +29,7 @@ func TestBuildPiArgsBasicFlags(t *testing.T) {}, slog.Default())joined := strings.Join(args, " ")- for _, want := range []string{"-p", "--mode json", "--session /tmp/s.jsonl", "--provider anthropic", "--model claude-sonnet-4-20250514", "--thinking high"} {+ for _, want := range []string{"-p", "--mode json", "--session /tmp/s.jsonl", "--model anthropic/claude-sonnet-4-20250514", "--thinking high"} {if !strings.Contains(joined, want) {t.Errorf("expected %q in args, got: %v", want, args)}@@ -458,3 +458,55 @@ func TestFlushPiTextBufferKeepsUnmatchedToolPrefixes(t *testing.T) {}}}++// TestBuildPiArgsKeepsSlashShapedModelIDIntact is the GH #7300 regression.+// A gateway-style provider registers model ids that themselves contain a+// slash (`claude/claude-opus-5` under provider `multica-anthropic`). Splitting+// on that slash to fill --provider produced `--provider claude --model+// claude-opus-5`, and pi answers an unknown --provider with a hard+// `Unknown provider "claude"` before it ever looks at --model. The whole+// selector must reach --model instead, where pi's resolver matches it as a+// raw model id.+func TestBuildPiArgsKeepsSlashShapedModelIDIntact(t *testing.T) {+ args := buildPiArgs("/tmp/s.jsonl", ExecOptions{Model: "claude/claude-opus-5"}, slog.Default())++ joined := strings.Join(args, " ")+ if !strings.Contains(joined, "--model claude/claude-opus-5") {+ t.Errorf("model id was not passed through intact: %v", args)+ }+ for _, arg := range args {+ if arg == "--provider" {+ t.Errorf("buildPiArgs synthesized --provider from a model id: %v", args)+ }+ }+}++// A fully-qualified selector is passed through the same way: pi infers the+// provider from the prefix itself, so the daemon never has to take it apart.+func TestBuildPiArgsPassesQualifiedSelectorWhole(t *testing.T) {+ args := buildPiArgs("/tmp/s.jsonl", ExecOptions{Model: "multica-anthropic/claude/claude-opus-5"}, slog.Default())++ joined := strings.Join(args, " ")+ if !strings.Contains(joined, "--model multica-anthropic/claude/claude-opus-5") {+ t.Errorf("qualified selector was not passed through intact: %v", args)+ }+ if strings.Contains(joined, "--provider") {+ t.Errorf("buildPiArgs synthesized --provider: %v", args)+ }+}++// A bare model id stays bare, and an empty model still omits --model entirely+// so pi resolves its own default.+func TestBuildPiArgsBareAndEmptyModels(t *testing.T) {+ bare := buildPiArgs("", ExecOptions{Model: " claude-opus-5 "}, slog.Default())+ if joined := strings.Join(bare, " "); !strings.Contains(joined, "--model claude-opus-5") {+ t.Errorf("bare model not forwarded (or not trimmed): %v", bare)+ }++ empty := buildPiArgs("", ExecOptions{Model: " "}, slog.Default())+ for _, arg := range empty {+ if arg == "--model" {+ t.Errorf("blank model should omit --model so pi picks its default: %v", empty)+ }+ }+}diff --git a/server/pkg/agent/thinking.go b/server/pkg/agent/thinking.goindex 815e14b309..b097c0f008 100644--- a/server/pkg/agent/thinking.go+++ b/server/pkg/agent/thinking.go@@ -589,6 +589,12 @@ func parseACPCodebuddyEffort(raw json.RawMessage) (levels []string, defaultLevel// ── Shared validation ────────────────────────────────────────────────+// catalogLoader adapts the ambient ListModels call into the lazy loader the+// Validate*With functions take, so the ctx-based entry points stay one line.+func catalogLoader(ctx context.Context, providerType string, cmd Command) func() (Catalog, error) {+ return func() (Catalog, error) { return ListModels(ctx, providerType, cmd) }+}+// ValidateThinkingLevel reports whether `value` is in the supported// catalog for the given (provider, model) pair. Empty value is always// valid — it means "use the runtime default".@@ -620,17 +626,32 @@ func parseACPCodebuddyEffort(raw json.RawMessage) (levels []string, defaultLevel// daemon's pre-execution guard and the server's UpdateAgent gate can// share the same source of truth.func ValidateThinkingLevel(ctx context.Context, providerType string, cmd Command, model, value string) (bool, error) {+ return ValidateThinkingLevelWith(catalogLoader(ctx, providerType, cmd), providerType, model, value)+}++// ValidateThinkingLevelWith is ValidateThinkingLevel over a caller-supplied+// catalog loader. loadCatalog is invoked at most once, and only when the answer+// genuinely depends on the catalog — the guards below settle their cases+// without it.+//+// The daemon passes a loader memoized for the whole task so model+// qualification and both capability checks share one discovery round. That+// matters because discovery is a CLI subprocess with a 15-30s ceiling and+// cachedDiscovery deliberately does not memoize an empty or fallback result+// (#3729, MUL-5549), so each read costs the ceiling again on a logged-out or+// timing-out runtime (MUL-6471 review).+func ValidateThinkingLevelWith(loadCatalog func() (Catalog, error), providerType, model, value string) (bool, error) {if value == "" {return true, nil}- // Codex empty-model fail-closed (see doc comment). Checked before- // ListModels so the outcome is deterministic even when discovery would+ // Codex empty-model fail-closed (see doc comment). Checked before the+ // catalog load so the outcome is deterministic even when discovery would// error — an errored lookup makes the daemon pass the level through, which// is exactly what we must NOT do for an unresolved codex model.if model == "" && providerType == "codex" {return false, nil}- catalog, err := ListModels(ctx, providerType, cmd)+ catalog, err := loadCatalog()if err != nil {return false, err}@@ -676,13 +697,19 @@ func ValidateThinkingLevel(ctx context.Context, providerType string, cmd Command// means "inherit runtime configuration". An empty Codex model fails closed:// its effective model comes from config.toml and may not support the tier.func ValidateServiceTier(ctx context.Context, providerType string, cmd Command, model, value string) (bool, error) {+ return ValidateServiceTierWith(catalogLoader(ctx, providerType, cmd), providerType, model, value)+}++// ValidateServiceTierWith is ValidateServiceTier over a caller-supplied+// catalog loader. See ValidateThinkingLevelWith for why the daemon needs one.+func ValidateServiceTierWith(loadCatalog func() (Catalog, error), providerType, model, value string) (bool, error) {if value == "" {return true, nil}if providerType != "codex" || model == "" {return false, nil}- catalog, err := ListModels(ctx, providerType, cmd)+ catalog, err := loadCatalog()if err != nil {return false, err}