Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6260 fix(daemon): treat custom runtime fixed_args as the argv prefix (#7052)
Bohan Jiang3b0842368422
diff --git a/apps/docs/content/docs/daemon-runtimes.mdx b/apps/docs/content/docs/daemon-runtimes.mdxindex 776d613ede..865dd28619 100644--- a/apps/docs/content/docs/daemon-runtimes.mdx+++ b/apps/docs/content/docs/daemon-runtimes.mdx@@ -98,6 +98,23 @@ The profile is shared across the workspace. Each connected computer looks up theThe command field takes an executable and arguments, not a shell script. Plain arguments, quotes, and backslash escapes work; pipes, redirects, `&&`, `;`, backticks, and environment variable expansion do not. When you need those behaviors, put them in a wrapper script and use that script as the command.+### How your arguments are ordered++Everything you type in the command field stays directly after the executable, ahead of the arguments Multica adds:++```text+<your command> <your fixed arguments> <Multica's protocol arguments> <the agent's custom arguments>+```++This is what makes a subcommand-style wrapper work. If your command is `ccms start q36`, the tool sees `start q36` first and can select its subcommand before Multica's `-p` and the rest arrive — which is the only order such a wrapper accepts.++Your arguments used to be appended last instead. Most flag-style commands parse the same either way, but not all of them do — a command that distinguishes global flags from subcommand flags can care where a flag sits. If you already have a profile with fixed arguments, re-run one task on it after upgrading to confirm it still starts.++Two more consequences worth knowing:++- **Multica's own values win a conflict.** If your fixed arguments set a flag Multica also sets, Multica's value comes later and takes effect. Most importantly, a model chosen on the agent overrides a `--model` pinned in the profile. To pin a model for everyone, leave the agents' model field empty.+- **Protocol-critical flags are ignored.** `-p`, `--output-format`, `--input-format`, `--permission-mode`, and the equivalents for other families are dropped from your fixed arguments, because overriding them would break the daemon's connection to the tool. Subcommands and other positional arguments always pass through.+If a Desktop-launched daemon cannot find a command your terminal can run, set an absolute path for the current computer:```bashdiff --git a/apps/docs/content/docs/daemon-runtimes.zh.mdx b/apps/docs/content/docs/daemon-runtimes.zh.mdxindex eddc28b6e4..87271d07b8 100644--- a/apps/docs/content/docs/daemon-runtimes.zh.mdx+++ b/apps/docs/content/docs/daemon-runtimes.zh.mdx@@ -98,6 +98,23 @@ multica daemon start这里填写的是可执行文件和参数,不是 shell 脚本。可以使用普通参数、引号和反斜杠转义,但不能使用管道、重定向、`&&`、`;`、反引号或环境变量展开。需要这些行为时,把它们放进 wrapper script,再把该脚本作为命令填写。+### 参数的排列顺序++命令字段里填写的内容会紧跟在可执行文件之后,排在 Multica 追加的参数之前:++```text+<你的命令> <你的固定参数> <Multica 的协议参数> <Agent 的自定义参数>+```++带子命令的 wrapper 正是依靠这个顺序才能工作。如果命令是 `ccms start q36`,工具会先看到 `start q36`,在 Multica 的 `-p` 等参数到达之前完成子命令选择——这类 wrapper 只接受这一种顺序。++此前这里填写的参数是追加在最后的。多数 flag 形式的命令在两种位置下解析结果相同,但并非全部——如果某个命令区分全局 flag 和子命令 flag,它就会在意 flag 的位置。如果你已经配置了带固定参数的 profile,升级后请跑一个任务确认它仍能正常启动。++另有两点需要注意:++- **冲突时以 Multica 的值为准。** 如果固定参数设置了 Multica 也会设置的 flag,Multica 的值排在后面并最终生效。最典型的是:在 Agent 上选择的模型会覆盖 profile 里固定的 `--model`。若要为所有人固定模型,请把 Agent 的模型字段留空。+- **协议关键 flag 会被忽略。** `-p`、`--output-format`、`--input-format`、`--permission-mode` 以及其他协议族的对应 flag 会从固定参数中被剔除,因为覆盖它们会切断 daemon 与工具之间的通信。子命令和其他位置参数始终原样传递。+如果 Desktop 启动的守护进程找不到终端里能够执行的命令,可以为当前电脑设置绝对路径:```bashdiff --git a/server/internal/daemon/agent_path_selfheal_test.go b/server/internal/daemon/agent_path_selfheal_test.goindex 60ed3857be..84ca26e125 100644--- a/server/internal/daemon/agent_path_selfheal_test.go+++ b/server/internal/daemon/agent_path_selfheal_test.go@@ -8,6 +8,8 @@ import ("runtime""strings""testing"++ "github.com/multica-ai/multica/server/pkg/agent")// newSelfHealTestDaemon builds a Daemon with just the state resolveAgentEntry@@ -28,7 +30,8 @@ func newSelfHealTestDaemon() *Daemon {func stubDetectVersionFromPath(t *testing.T) {t.Helper()orig := detectAgentVersion- detectAgentVersion = func(_ context.Context, path string) (string, error) {+ detectAgentVersion = func(_ context.Context, runtimeCmd agent.Command) (string, error) {+ path := runtimeCmd.Pathreturn filepath.Base(filepath.Dir(filepath.Dir(path))), nil}t.Cleanup(func() { detectAgentVersion = orig })diff --git a/server/internal/daemon/agent_version_refresh_test.go b/server/internal/daemon/agent_version_refresh_test.goindex 86a0479a56..464c2a9d95 100644--- a/server/internal/daemon/agent_version_refresh_test.go+++ b/server/internal/daemon/agent_version_refresh_test.go@@ -549,11 +549,12 @@ func TestRefreshAgentVersions_BlankProbeDoesNotWipeAnUnflooredProvidersVersion(t// gate has no floor, so the blank sails through to the payload builder.origDetect := detectAgentVersiont.Cleanup(func() { detectAgentVersion = origDetect })- detectAgentVersion = func(ctx context.Context, path string) (string, error) {+ detectAgentVersion = func(ctx context.Context, runtimeCmd agent.Command) (string, error) {+ path := runtimeCmd.Pathif strings.Contains(path, "claude") {return "", nil}- return origDetect(ctx, path)+ return origDetect(ctx, runtimeCmd)}// codex upgrades, which re-registers the whole built-in set — claude ridesdiff --git a/server/internal/daemon/config_windows_test.go b/server/internal/daemon/config_windows_test.goindex e44c0cff33..de8aee3797 100644--- a/server/internal/daemon/config_windows_test.go+++ b/server/internal/daemon/config_windows_test.go@@ -118,7 +118,8 @@ func TestResolveAgentExecutablePathKeepsPATHJunctionEntryPoint(t *testing.T) {func TestResolveAgentEntryFollowsRetargetedInstallerJunction(t *testing.T) {originalDetect := detectAgentVersion- detectAgentVersion = func(_ context.Context, path string) (string, error) {+ detectAgentVersion = func(_ context.Context, runtimeCmd agent.Command) (string, error) {+ path := runtimeCmd.Pathreturn filepath.Base(filepath.Dir(filepath.Dir(path))), nil}t.Cleanup(func() { detectAgentVersion = originalDetect })@@ -168,13 +169,13 @@ func TestResolveAgentEntryFollowsRetargetedInstallerJunction(t *testing.T) {func TestResolveAgentEntryForLaunchRejectsUnverifiedInitialJunctionTarget(t *testing.T) {tests := []struct {name string- detect func(context.Context, string) (string, error)+ detect func(context.Context, agent.Command) (string, error)check func(error) boolwantError string}{{name: "version detection failure",- detect: func(context.Context, string) (string, error) {+ detect: func(context.Context, agent.Command) (string, error) {return "", errors.New("version probe failed")},check: func(err error) bool { return strings.Contains(err.Error(), "version probe failed") },@@ -182,7 +183,7 @@ func TestResolveAgentEntryForLaunchRejectsUnverifiedInitialJunctionTarget(t *tes},{name: "below minimum version",- detect: func(context.Context, string) (string, error) {+ detect: func(context.Context, agent.Command) (string, error) {return "0.9.0", nil},check: func(err error) bool {@@ -240,7 +241,8 @@ func TestResolveAgentEntryDoesNotSharePreRetargetSingleflightResult(t *testing.TreleaseV1Probe := make(chan struct{})v2ProbeStarted := make(chan struct{}, 1)originalDetect := detectAgentVersion- detectAgentVersion = func(_ context.Context, path string) (string, error) {+ detectAgentVersion = func(_ context.Context, runtimeCmd agent.Command) (string, error) {+ path := runtimeCmd.Pathswitch {case sameFile(path, v1):select {@@ -337,7 +339,8 @@ func TestResolveAgentEntryForLaunchFailsWhenJunctionKeepsRetargeting(t *testing.stableExecutable := filepath.Join(visibleBin, "codex.exe")originalDetect := detectAgentVersion- detectAgentVersion = func(_ context.Context, path string) (string, error) {+ detectAgentVersion = func(_ context.Context, runtimeCmd agent.Command) (string, error) {+ path := runtimeCmd.Pathif sameFile(path, v1) {retarget(v2)return "0.144.1", nil@@ -364,7 +367,7 @@ func TestResolveAgentEntryForLaunchFailsWhenJunctionKeepsRetargeting(t *testing.func TestResolveAgentEntryCanonicalizesRediscoveredJunction(t *testing.T) {originalDetect := detectAgentVersion- detectAgentVersion = func(_ context.Context, path string) (string, error) {+ detectAgentVersion = func(_ context.Context, runtimeCmd agent.Command) (string, error) {return "0.144.3", nil}t.Cleanup(func() { detectAgentVersion = originalDetect })@@ -391,7 +394,7 @@ func TestResolveAgentEntryForLaunchRejectsRediscoveredJunctionWhenFinalPathResoloriginalDetect := detectAgentVersiondetectCalled := false- detectAgentVersion = func(context.Context, string) (string, error) {+ detectAgentVersion = func(context.Context, agent.Command) (string, error) {detectCalled = truereturn "0.144.3", nil}diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 62d4043ff7..53c94e7c07 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -1067,7 +1067,7 @@ func (d *Daemon) adoptAgentPath(ctx context.Context, provider, command, newPath,// older or broken install must not be launched under the daemon's stale// version policy, and must not slip past the minimum-version gate that the// registration path applies (MUL-4486 review).- version, err := detectAgentVersion(ctx, newPath)+ version, err := detectAgentVersion(ctx, agent.Command{Path: newPath})if err != nil {d.logger.Warn("re-resolved agent executable failed version detection; keeping pinned path","provider", provider, "command", command, "new_path", newPath, "error", err)@@ -2298,7 +2298,7 @@ func (d *Daemon) probeBuiltinRuntime(ctx context.Context, name string, entry Age"name", name, "version", heal.rejected.Detected, "error", heal.rejected.Error())return heal.rejected.Detected, heal.rejected.Error(), builtinProbeBelowMinimum}- version, err := detectAgentVersion(ctx, resolved.Path)+ version, err := detectAgentVersion(ctx, agent.Command{Path: resolved.Path})if err != nil {lastErr = errif time.Since(startedAt) >= runtimeVersionProbeRetryWindow {@@ -2792,8 +2792,14 @@ func (d *Daemon) appendProfileRuntimes(ctx context.Context, workspaceID string,}resolved = r}- // Best-effort version detection; an empty version is acceptable.- version, verErr := detectAgentVersion(ctx, resolved)+ // Best-effort version detection; an empty version is acceptable. The+ // probe carries the profile's fixed_args so a wrapper reports the+ // version of the CLI it execs rather than its own: `ccms start q36+ // --version` is Claude Code's version, `ccms --version` is the+ // wrapper's, and only the former means anything to the min-version+ // gate (GH #7046).+ version, verErr := detectAgentVersion(ctx, agent.NewCommand(resolved,+ agent.FilterLaunchPrefix(profile.ProtocolFamily, profile.FixedArgs, d.logger)))if verErr != nil {d.logger.Debug("custom runtime profile: version probe failed (registering with empty version)","workspace_id", workspaceID, "profile_id", profile.ID, "path", resolved, "error", verErr)@@ -4043,10 +4049,16 @@ func (d *Daemon) handleModelList(ctx context.Context, rt Runtime, requestID stri// path is also never re-resolved: like runTask, we don't second-guess a// path the profile pinned.var execPath string+ // fixedArgs mirrors the launch prefix runTask would use. Discovery has to+ // enumerate the CLI the profile actually runs, so a subcommand wrapper is+ // probed as `ccms start q36 models`, not `ccms models` (GH #7046).+ var fixedArgs []stringif customSpec, isCustom := d.customProfileLaunchForRuntime(rt.ID); isCustom {execPath = customSpec.path+ fixedArgs = agent.FilterLaunchPrefix(rt.Provider, customSpec.fixedArgs, d.logger)d.logger.Info("model list uses custom runtime profile command",- "runtime_id", rt.ID, "provider", rt.Provider, "command_path", execPath)+ "runtime_id", rt.ID, "provider", rt.Provider, "command_path", execPath,+ "fixed_args", len(fixedArgs))} else if entry, ok := d.agents()[rt.Provider]; ok {// Built-in provider: self-heal a pinned executable path an in-place// upgrade deleted (MUL-4486).@@ -4060,7 +4072,7 @@ func (d *Daemon) handleModelList(ctx context.Context, rt Runtime, requestID strireturn}- catalog, err := listModels(ctx, rt.Provider, execPath)+ catalog, err := listModels(ctx, rt.Provider, agent.NewCommand(execPath, fixedArgs))if err != nil {d.reportModelListResult(ctx, rt, requestID, map[string]any{"status": "failed",@@ -6131,7 +6143,11 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iusesCustomProfileCommand = trueentry.Path = customSpec.pathresolvedVersion = customSpec.version- profileFixedArgs = customSpec.fixedArgs+ // Filter here rather than relying on agent.New doing it, so that the+ // launch and the catalog lookups below agree on one prefix. They share+ // a discovery memo keyed on the command, and two spellings of the same+ // runtime would key two entries.+ profileFixedArgs = agent.FilterLaunchPrefix(provider, customSpec.fixedArgs, d.logger)ok = trued.logger.Info("task uses custom runtime profile command","task_id", task.ID, "runtime_id", task.RuntimeID,@@ -6327,6 +6343,10 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// instead of silently downgrading a user's isolation opt-in (MUL-4957).var codexSandboxArgs []stringif provider == "codex" {+ // profileFixedArgs still belongs in this reconstruction even though it+ // no longer travels via ExtraArgs: it is a launch prefix now, so it is+ // still on codex's argv, and a `-c windows.sandbox=...` written there+ // must still be visible to the sandbox decision.extraArgs := append(append([]string{}, profileFixedArgs...), defaultArgsForProvider(d.cfg, provider)...)codexSandboxArgs = agent.NormalizeCodexLaunchArgs(extraArgs, agentCustomArgs, effectiveMcpConfig, d.logger)}@@ -6347,7 +6367,15 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot ivar hermesMemoryStore stringvar hermesSessionStore stringif provider == "hermes" {- sel := agent.ParseHermesProfileArgs(agentCustomArgs)+ // Resolve from the argv hermes will actually parse — launch prefix,+ // `acp`, then the filtered custom args — which agent.HermesLaunchArgv+ // assembles the same way the backend does. A custom runtime profile's+ // fixed_args are the launch prefix now, so they are scanned before+ // custom_args, and the backend's own `acp` token sits between them and+ // participates in the scan. Approximating that argv reads a different+ // profile than the process does, and the overlay ends up seeded from+ // the wrong home (GH #7046).+ sel := agent.ParseHermesProfileArgs(agent.HermesLaunchArgv(profileFixedArgs, agentCustomArgs, d.logger))res := execenv.ResolveHermesProfile(agentEnvOverrides["HERMES_HOME"], sel.Name, sel.Found, sel.Inline)if res.Err != nil {return TaskResult{}, fmt.Errorf("resolve hermes profile: %w", res.Err)@@ -6810,6 +6838,21 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iif err := configureCodexTaskShellEnvironment(provider, env.CodexHome, os.Environ(), agentEnv, agentCustomEnv, d.logger); err != nil {return TaskResult{}, err}+ // The overlay is authoritative once built, so nothing on the command line+ // may re-point HERMES_HOME out of it. Both argv regions are stripped+ // together, against the same assembled argv the resolver read: a selection+ // can straddle them (a prefix ending in a bare `-p` captures the backend's+ // `acp`), which per-region stripping cannot see.+ var hermesOverlayCustomArgs []string+ hermesOverlayActive := provider == "hermes" && env != nil && env.HermesHome != ""+ if hermesOverlayActive {+ var rawCustomArgs []string+ if task.Agent != nil {+ rawCustomArgs = task.Agent.CustomArgs+ }+ profileFixedArgs, hermesOverlayCustomArgs = agent.StripHermesProfileSelectors(+ profileFixedArgs, rawCustomArgs, d.logger)+ }// Resolve the backend through the unified runtime resolver: built-in// runtime identities (e.g. "omp") dispatch through NewRuntime, protocol// families go through New. This is the single production boundary — the@@ -6817,6 +6860,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// factories stay meaning exactly one thing each.backend, err := agent.ResolveBackend(provider, agent.Config{ExecutablePath: entry.Path,+ LaunchPrefix: profileFixedArgs,CLIVersion: resolvedVersion,Env: agentEnv,Logger: d.logger,@@ -6843,17 +6887,21 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot itaskStart := time.Now()var customArgs []string+ // profileFixedArgs deliberately does NOT go here. It travels as+ // agent.Config.LaunchPrefix instead, because ExtraArgs is honoured by only+ // six of the twenty-one backends and lands *after* the protocol flags in+ // the ones that do — so a wrapper's subcommand was either dropped on the+ // floor or spliced in behind `-p` (GH #7046).extraArgs := defaultArgsForProvider(d.cfg, provider)- if len(profileFixedArgs) > 0 {- extraArgs = append(append([]string{}, profileFixedArgs...), extraArgs...)- }var mcpConfig json.RawMessageif task.Agent != nil {customArgs = task.Agent.CustomArgsmcpConfig = effectiveMcpConfig}- if provider == "hermes" {- customArgs = hermesLaunchArgs(customArgs, env != nil && env.HermesHome != "")+ if hermesOverlayActive {+ // Stripped above, alongside the launch prefix. A skill-less hermes task+ // 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@@ -6883,7 +6931,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// through so a transient discovery failure does not silently disable a// previously valid user choice.if serviceTier != "" {- ok, err := agent.ValidateServiceTier(ctx, provider, entry.Path, model, 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,@@ -6912,7 +6960,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// 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, entry.Path, model, 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,@@ -8345,22 +8393,6 @@ func sanitizeAgentEnv(customEnv map[string]string) map[string]string {return out}-// hermesLaunchArgs decides the final Hermes custom_args: with the per-task-// overlay active, the -p/--profile flags are stripped (the overlay was seeded-// from that profile's home and exports its own HERMES_HOME, so the flag must not-// re-resolve the profile past it); with no overlay, the flags pass through so a-// skill-less task's profile behavior is unchanged.-func hermesLaunchArgs(customArgs []string, overlayActive bool) []string {- if !overlayActive {- return customArgs- }- // Strip exactly the occurrence the resolver acted on. This re-parses with the- // same authoritative parser used to resolve the source home, so parsing and- // stripping never diverge.- sel := agent.ParseHermesProfileArgs(customArgs)- return agent.StripHermesProfileArgs(customArgs, sel)-}-// hermesProviderUnconfiguredHint is appended verbatim to a "no LLM provider// configured" failure. It is a CONSTANT, and that is a correctness property,// not a style choice — see annotateHermesProviderUnconfigured.diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.goindex 3debf3a708..8c2affff87 100644--- a/server/internal/daemon/daemon_test.go+++ b/server/internal/daemon/daemon_test.go@@ -5186,9 +5186,9 @@ func TestHermesLaunchArgsAndEnvByScenario(t *testing.T) {customArgs := []string{"-p", "research", "--yolo"}customEnv := map[string]string{"HERMES_HOME": "/home/u/.hermes"}- // No overlay (skill-less): profile flag passes through, and the user's- // HERMES_HOME passes through — behavior unchanged.- noOverlayArgs := hermesLaunchArgs(customArgs, false)+ // No overlay (skill-less): runTask never strips, so the profile flag passes+ // through, and the user's HERMES_HOME passes through — behavior unchanged.+ noOverlayArgs := customArgsif len(noOverlayArgs) != 3 || noOverlayArgs[0] != "-p" || noOverlayArgs[1] != "research" {t.Errorf("skill-less task must keep its profile flags, got %v", noOverlayArgs)}@@ -5199,7 +5199,7 @@ func TestHermesLaunchArgsAndEnvByScenario(t *testing.T) {}// Overlay active: profile flag is stripped, and HERMES_HOME is the overlay.- overlayArgs := hermesLaunchArgs(customArgs, true)+ _, overlayArgs := agent.StripHermesProfileSelectors(nil, customArgs, slog.Default())if len(overlayArgs) != 1 || overlayArgs[0] != "--yolo" {t.Errorf("overlay task must strip profile flags, got %v", overlayArgs)}@@ -5563,3 +5563,42 @@ func TestBuildPromptSquadLeaderMultiThreadCarvesOutNoAction(t *testing.T) {t.Fatalf("ordinary multi-thread prompt leaked the leader carve-out\n---\n%s", ordinary)}}++// TestHermesProfileChainCoversLaunchPrefix is the daemon half of GH #7046's+// Hermes regression. A custom runtime profile's fixed_args are no longer folded+// into custom_args — they become the launch prefix and reach hermes ahead of+// custom_args, with the backend's own `acp` token between the two.+//+// Both halves of the profile chain therefore have to run against the argv the+// backend really assembles. Resolving or stripping against a hand-built+// approximation reads a different profile than the process does, and the+// overlay gets seeded from the wrong home.+func TestHermesProfileChainCoversLaunchPrefix(t *testing.T) {+ t.Parallel()++ // A prefix ending in a value-taking flag: the `acp` token decides which+ // selection hermes sees, so it must be present when the daemon resolves.+ launchPrefix := []string{"--model"}+ customArgs := []string{"-p", "research", "--yolo"}++ sel := agent.ParseHermesProfileArgs(+ agent.HermesLaunchArgv(launchPrefix, customArgs, slog.Default()))+ if !sel.Found || sel.Name != "research" {+ t.Fatalf("effective profile = %+v, want the `research` hermes actually selects", sel)+ }++ // Overlay active: both regions are stripped together, and the launched argv+ // can no longer redirect HERMES_HOME out of the overlay.+ strippedPrefix, strippedCustom := agent.StripHermesProfileSelectors(+ launchPrefix, customArgs, slog.Default())+ if sel := agent.ParseHermesProfileArgs(+ agent.HermesLaunchArgv(strippedPrefix, strippedCustom, slog.Default())); sel.Found {+ t.Fatalf("the launched argv can still redirect HERMES_HOME: %+v", sel)+ }+ if strings.Join(strippedPrefix, "\x00") != "--model" {+ t.Errorf("prefix = %v, want the non-selector token kept", strippedPrefix)+ }+ if strings.Join(strippedCustom, "\x00") != "--yolo" {+ t.Errorf("custom = %v, want only the selector removed", strippedCustom)+ }+}diff --git a/server/internal/daemon/model_list_binary_test.go b/server/internal/daemon/model_list_binary_test.goindex 59220c2e8e..71646ba24a 100644--- a/server/internal/daemon/model_list_binary_test.go+++ b/server/internal/daemon/model_list_binary_test.go@@ -7,6 +7,7 @@ import ("net/http/httptest""os""path/filepath"+ "strings""sync""testing"@@ -15,13 +16,15 @@ import (// modelListFixture stands up a Daemon whose model-list report is captured and// whose agent.ListModels call is stubbed, so a test can assert exactly which-// executable path model discovery enumerated without shelling out to a CLI.+// command model discovery enumerated — path and launch prefix both — without+// shelling out to a CLI.type modelListFixture struct {daemon *Daemonmu sync.MutexlistedProvider stringlistedPath string+ listedPrefix []stringlistCalls intreport map[string]any}@@ -48,10 +51,11 @@ func newModelListFixture(t *testing.T) *modelListFixture {fx.daemon = dorig := listModels- listModels = func(_ context.Context, provider, execPath string) (agent.Catalog, error) {+ listModels = func(_ context.Context, provider string, runtimeCmd agent.Command) (agent.Catalog, error) {fx.mu.Lock()fx.listedProvider = provider- fx.listedPath = execPath+ fx.listedPath = runtimeCmd.Path+ fx.listedPrefix = append([]string(nil), runtimeCmd.Prefix...)fx.listCalls++fx.mu.Unlock()return agent.Catalog{Models: []agent.Model{{ID: "m-1", Label: "M 1"}}}, nil@@ -219,3 +223,60 @@ func TestHandleModelList_UnresolvedProfileFallsBackToBuiltin(t *testing.T) {t.Fatalf("report status = %v, want completed (report: %v)", got, report)}}++// TestHandleModelList_CustomProfileCarriesFixedArgs is the discovery half of+// GH #7046. #6488 aligned model discovery to the profile's own binary but+// carried only the path, so a wrapper whose CLI is reachable only through a+// subcommand was enumerated as `ccms models` — the wrapper's own catalog, or+// more often an error — instead of `ccms start q36 models`. The launch prefix+// has to travel with the path.+func TestHandleModelList_CustomProfileCarriesFixedArgs(t *testing.T) {+ fx := newModelListFixture(t)+ d := fx.daemon++ d.cfg.Agents = map[string]AgentEntry{}+ d.runtimeIndex["rt-custom"] = Runtime{ID: "rt-custom", Provider: "claude", ProfileID: "prof-1"}+ d.profileLaunchSpecs["prof-1"] = profileLaunchSpec{+ path: "/usr/local/bin/ccms",+ fixedArgs: []string{"start", "q36"},+ }++ d.handleModelList(context.Background(), d.runtimeIndex["rt-custom"], "req-1")++ fx.mu.Lock()+ path, prefix := fx.listedPath, append([]string(nil), fx.listedPrefix...)+ fx.mu.Unlock()++ if path != "/usr/local/bin/ccms" {+ t.Fatalf("discovery path = %q, want the profile's command path", path)+ }+ if strings.Join(prefix, "\x00") != "start\x00q36" {+ t.Fatalf("discovery launch prefix = %v, want the profile's fixed_args [start q36]", prefix)+ }+}++// TestHandleModelList_FixedArgsFilteredBeforeDiscovery: the prefix a probe runs+// with is the same one a task launches with, protocol-critical flags dropped.+// If the two disagreed, the picker would enumerate a CLI configured+// differently from the one that runs.+func TestHandleModelList_FixedArgsFilteredBeforeDiscovery(t *testing.T) {+ fx := newModelListFixture(t)+ d := fx.daemon++ d.cfg.Agents = map[string]AgentEntry{}+ d.runtimeIndex["rt-custom"] = Runtime{ID: "rt-custom", Provider: "claude", ProfileID: "prof-1"}+ d.profileLaunchSpecs["prof-1"] = profileLaunchSpec{+ path: "/usr/local/bin/ccms",+ fixedArgs: []string{"start", "q36", "--output-format", "text"},+ }++ d.handleModelList(context.Background(), d.runtimeIndex["rt-custom"], "req-1")++ fx.mu.Lock()+ prefix := append([]string(nil), fx.listedPrefix...)+ fx.mu.Unlock()++ if strings.Join(prefix, "\x00") != "start\x00q36" {+ t.Fatalf("discovery prefix = %v, want the protocol flag filtered out", prefix)+ }+}diff --git a/server/internal/daemon/runtime_gone_test.go b/server/internal/daemon/runtime_gone_test.goindex 842b1b2f1e..f44fcbed59 100644--- a/server/internal/daemon/runtime_gone_test.go+++ b/server/internal/daemon/runtime_gone_test.go@@ -13,6 +13,8 @@ import ("sync/atomic""testing""time"++ "github.com/multica-ai/multica/server/pkg/agent")// freshDaemon builds a Daemon with every map field the production New() seeds@@ -45,7 +47,7 @@ func stubAgentVersion(t *testing.T) func() {t.Helper()origDetect := detectAgentVersionorigCheck := checkAgentMinVersion- detectAgentVersion = func(_ context.Context, _ string) (string, error) {+ detectAgentVersion = func(_ context.Context, _ agent.Command) (string, error) {return "9.9.9", nil}checkAgentMinVersion = func(_, _ string) error { return nil }diff --git a/server/internal/daemon/runtime_not_executable_test.go b/server/internal/daemon/runtime_not_executable_test.goindex d9b9c0ca83..a2d1871440 100644--- a/server/internal/daemon/runtime_not_executable_test.go+++ b/server/internal/daemon/runtime_not_executable_test.go@@ -23,7 +23,8 @@ func stubNotExecutableProbe(t *testing.T, path string) {t.Helper()orig := detectAgentVersiont.Cleanup(func() { detectAgentVersion = orig })- detectAgentVersion = func(_ context.Context, p string) (string, error) {+ detectAgentVersion = func(_ context.Context, runtimeCmd agent.Command) (string, error) {+ p := runtimeCmd.Pathenoexec := &fs.PathError{Op: "fork/exec", Path: p, Err: syscall.ENOEXEC}return "", fmt.Errorf("detect version for %s: %w", p, agent.ExplainExecError(enoexec))}@@ -202,7 +203,8 @@ func TestDetectBuiltinRuntimes_HealthyProbeClearsPendingVerdict(t *testing.T) {broken := trueorig := detectAgentVersiont.Cleanup(func() { detectAgentVersion = orig })- detectAgentVersion = func(_ context.Context, p string) (string, error) {+ detectAgentVersion = func(_ context.Context, runtimeCmd agent.Command) (string, error) {+ p := runtimeCmd.Pathif broken {enoexec := &fs.PathError{Op: "fork/exec", Path: p, Err: syscall.ENOEXEC}return "", fmt.Errorf("detect version for %s: %w", p, agent.ExplainExecError(enoexec))diff --git a/server/internal/daemon/runtime_probe_batch_test.go b/server/internal/daemon/runtime_probe_batch_test.goindex b4dadfb586..558c4d167b 100644--- a/server/internal/daemon/runtime_probe_batch_test.go+++ b/server/internal/daemon/runtime_probe_batch_test.go@@ -315,7 +315,8 @@ func newBatchFixture(t *testing.T) *batchFixture {detectAgentVersion = origDetectcheckAgentMinVersion = origCheck})- detectAgentVersion = func(_ context.Context, path string) (string, error) {+ detectAgentVersion = func(_ context.Context, runtimeCmd agent.Command) (string, error) {+ path := runtimeCmd.Pathfx.mu.Lock()fx.probes[path]++attempt := fx.probes[path]@@ -759,7 +760,8 @@ func countingVersionProbe(t *testing.T, answer func(path string) (string, error)checkAgentMinVersion = origCheck})var probes atomic.Int32- detectAgentVersion = func(_ context.Context, path string) (string, error) {+ detectAgentVersion = func(_ context.Context, runtimeCmd agent.Command) (string, error) {+ path := runtimeCmd.Pathprobes.Add(1)return answer(path)}diff --git a/server/internal/daemon/runtime_probe_concurrency_test.go b/server/internal/daemon/runtime_probe_concurrency_test.goindex 67dbb93565..747d4866d6 100644--- a/server/internal/daemon/runtime_probe_concurrency_test.go+++ b/server/internal/daemon/runtime_probe_concurrency_test.go@@ -5,6 +5,8 @@ import ("sync/atomic""testing""time"++ "github.com/multica-ai/multica/server/pkg/agent")// TestDetectBuiltinRuntimes_ProbesRunConcurrently proves the registration@@ -22,7 +24,7 @@ func TestDetectBuiltinRuntimes_ProbesRunConcurrently(t *testing.T) {const probeBlock = 100 * time.Millisecondvar inFlight, maxInFlight int32- detectAgentVersion = func(_ context.Context, _ string) (string, error) {+ detectAgentVersion = func(_ context.Context, _ agent.Command) (string, error) {cur := atomic.AddInt32(&inFlight, 1)for {prev := atomic.LoadInt32(&maxInFlight)@@ -83,7 +85,8 @@ func TestDetectBuiltinRuntimes_SkipsFailedProbes(t *testing.T) {checkAgentMinVersion = origCheck})- detectAgentVersion = func(_ context.Context, path string) (string, error) {+ detectAgentVersion = func(_ context.Context, runtimeCmd agent.Command) (string, error) {+ path := runtimeCmd.Pathif path == "/broken" {return "", context.DeadlineExceeded}diff --git a/server/pkg/agent/acp_effort_unix_test.go b/server/pkg/agent/acp_effort_unix_test.goindex c5c4d461cc..4e388f7875 100644--- a/server/pkg/agent/acp_effort_unix_test.go+++ b/server/pkg/agent/acp_effort_unix_test.go@@ -78,7 +78,7 @@ func TestValidateThinkingLevelReasonix(t *testing.T) {{model: "", level: "high", want: true},{model: "no-such-model", level: "high", want: false},} {- got, err := ValidateThinkingLevel(context.Background(), "reasonix", fakePath, tc.model, tc.level)+ got, err := ValidateThinkingLevel(context.Background(), "reasonix", Command{Path: fakePath}, tc.model, tc.level)if err != nil {t.Fatalf("ValidateThinkingLevel(%q, %q): %v", tc.model, tc.level, err)}@@ -114,7 +114,7 @@ func TestReasonixPerModelEffortIsNotSharedAcrossModels(t *testing.T) {fakePath := filepath.Join(t.TempDir(), "reasonix")writeTestExecutable(t, fakePath, []byte(reasonixStubFor(reasonixThreeModelSessionResult)))- models, err := discoverReasonixModels(context.Background(), fakePath)+ models, err := discoverReasonixModels(context.Background(), Command{Path: fakePath})if err != nil {t.Fatalf("discoverReasonixModels: %v", err)}@@ -154,7 +154,7 @@ func TestReasonixPerModelEffortIsNotSharedAcrossModels(t *testing.T) {{model: "deepseek-v4-pro", level: "high", want: false},{model: "glm-4-air", level: "high", want: false},} {- got, err := ValidateThinkingLevel(context.Background(), "reasonix", fakePath, tc.model, tc.level)+ got, err := ValidateThinkingLevel(context.Background(), "reasonix", Command{Path: fakePath}, tc.model, tc.level)if err != nil {t.Fatalf("ValidateThinkingLevel(%q, %q): %v", tc.model, tc.level, err)}@@ -171,7 +171,7 @@ func TestDiscoverReasonixModelsAnnotatesEffort(t *testing.T) {fakePath := filepath.Join(t.TempDir(), "reasonix")writeTestExecutable(t, fakePath, []byte(reasonixStubFor(reasonixEffortSessionResult)))- models, err := discoverReasonixModels(context.Background(), fakePath)+ models, err := discoverReasonixModels(context.Background(), Command{Path: fakePath})if err != nil {t.Fatalf("discoverReasonixModels: %v", err)}diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex 15ec669d42..15c2d43c04 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -260,6 +260,16 @@ type Config struct {// vendor's binary; it defaults to false so an unset caller fails// closed onto standard behavior.BuiltinRuntime bool+ // LaunchPrefix is the argv prefix that belongs to ExecutablePath itself —+ // a custom runtime profile's fixed_args. It is spliced in directly after+ // the executable, ahead of every argument a backend builds, because a+ // wrapper's subcommand has to be consumed before the wrapped CLI's own+ // flags mean anything (`ccms start q36` then `-p …`, GH #7046).+ //+ // Unlike ExtraArgs this is not opt-in: New filters it once and the+ // Command boundary applies it to every process the package spawns, task+ // launches and CLI probes alike. Backends never read it directly.+ LaunchPrefix []string}// New creates a Backend for the given agent type.@@ -348,6 +358,12 @@ func New(agentType string, cfg Config) (Backend, error) {if cfg.Logger == nil {cfg.Logger = slog.Default()}+ // Filter the launch prefix here, at the one point that knows both the+ // prefix and the protocol family. Doing it per-backend would be the same+ // opt-in arrangement that let ExtraArgs rot: a family that forgot the call+ // would accept a fixed_args `--output-format text` and break its own+ // stream-json channel.+ cfg.LaunchPrefix = filterLaunchPrefix(cfg.LaunchPrefix, agentType, cfg.Logger)switch agentType {case "claude":@@ -396,8 +412,13 @@ func New(agentType string, cfg Config) (Backend, error) {}// DetectVersion runs the agent CLI with --version and returns the output.-func DetectVersion(ctx context.Context, executablePath string) (string, error) {- return detectCLIVersion(ctx, executablePath)+//+// cmd carries the runtime's launch prefix, so a custom profile is probed the+// way it is launched: `ccms start q36 --version` reports the version of the+// CLI the wrapper actually execs, where a bare `ccms --version` would report+// the wrapper's own and pin the runtime to the wrong compatibility policy.+func DetectVersion(ctx context.Context, cmd Command) (string, error) {+ return detectCLIVersion(ctx, cmd)}// launchHeaders maps each supported agent type to the user-visible skeletondiff --git a/server/pkg/agent/agent_test.go b/server/pkg/agent/agent_test.goindex f04ef4cb5b..8c53ffe4ab 100644--- a/server/pkg/agent/agent_test.go+++ b/server/pkg/agent/agent_test.go@@ -116,7 +116,7 @@ func TestNewDefaultsLogger(t *testing.T) {func TestDetectVersionFailsForMissingBinary(t *testing.T) {t.Parallel()- _, err := DetectVersion(context.Background(), "/nonexistent/binary")+ _, err := DetectVersion(context.Background(), Command{Path: "/nonexistent/binary"})if err == nil {t.Fatal("expected error for missing binary")}@@ -168,7 +168,7 @@ func TestDetectVersionTimesOutOnHang(t *testing.T) {done := make(chan error, 1)start := time.Now()go func() {- _, err := DetectVersion(context.Background(), script)+ _, err := DetectVersion(context.Background(), Command{Path: script})done <- err}()diff --git a/server/pkg/agent/antigravity.go b/server/pkg/agent/antigravity.goindex 13cf54f8f9..c11d97deeb 100644--- a/server/pkg/agent/antigravity.go+++ b/server/pkg/agent/antigravity.go@@ -60,7 +60,7 @@ func (b *antigravityBackend) Execute(ctx context.Context, prompt string, opts Ex// resolve the value itself rather than blocking the run on a discovery// hiccup (see antigravityModelError).if opts.Model != "" {- catalog, _ := ListModels(ctx, "antigravity", execPath)+ catalog, _ := ListModels(ctx, "antigravity", b.cfg.commandAt(execPath))if err := antigravityModelError(opts.Model, catalog.Models); err != nil {return nil, err}@@ -79,7 +79,7 @@ func (b *antigravityBackend) Execute(ctx context.Context, prompt string, opts Exargs := buildAntigravityArgs(prompt, logPath, timeout, opts, b.cfg.Logger)- cmd := exec.CommandContext(runCtx, execPath, args...)+ cmd := b.cfg.commandAt(execPath).exec(runCtx, args...)hideAgentWindow(cmd)b.cfg.Logger.Info("agent command", "exec", execPath, "args", args)cmd.WaitDelay = 10 * time.Seconddiff --git a/server/pkg/agent/builtin_runtimes.go b/server/pkg/agent/builtin_runtimes.goindex 7c10add68d..4e07a7d103 100644--- a/server/pkg/agent/builtin_runtimes.go+++ b/server/pkg/agent/builtin_runtimes.go@@ -70,10 +70,11 @@ type BuiltinRuntime struct {}// ModelDiscoveryFunc discovers available models for a runtime identity.-// It receives the context and the resolved executable path, and returns-// a model catalog. When the binary is missing or too old, it returns an-// empty slice (ListModels swallows the error and degrades to manual entry).-type ModelDiscoveryFunc func(ctx context.Context, executablePath string) ([]Model, error)+// It receives the context and the resolved command — executable plus the+// runtime's launch prefix — and returns a model catalog. When the binary is+// missing or too old, it returns an empty slice (ListModels swallows the+// error and degrades to manual entry).+type ModelDiscoveryFunc func(ctx context.Context, runtimeCmd Command) ([]Model, error)// BuiltinRuntimes is the registry of built-in runtime identities that are// NOT in SupportedTypes (they are protocol-family derivatives, not familiesdiff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.goindex 8cb31ac359..f296192b26 100644--- a/server/pkg/agent/claude.go+++ b/server/pkg/agent/claude.go@@ -72,7 +72,7 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt}}()- cmd := exec.CommandContext(runCtx, execPath, args...)+ cmd := b.cfg.commandAt(execPath).exec(runCtx, args...)hideAgentWindow(cmd)// Run claude in its own process group so cancellation can reach the whole// tree — the claude CLI plus the MCP servers and tool subprocesses it@@ -1106,11 +1106,11 @@ func cleanupMcpConfigTemp(path string) {// tests can shrink it without waiting out the real bound.var detectVersionTimeout = 10 * time.Second-func detectCLIVersion(ctx context.Context, execPath string) (string, error) {+func detectCLIVersion(ctx context.Context, runtimeCmd Command) (string, error) {ctx, cancel := context.WithTimeout(ctx, detectVersionTimeout)defer cancel()- cmd := exec.CommandContext(ctx, execPath, "--version")+ cmd := runtimeCmd.exec(ctx, "--version")hideAgentWindow(cmd)// exec.CommandContext only kills the direct child on timeout. A broken CLI// (node/bun shim) can leave grandchildren that inherited and still hold our@@ -1124,7 +1124,7 @@ func detectCLIVersion(ctx context.Context, execPath string) (string, error) {// provider through here, so an ENOEXEC diagnosis added at this point// reaches the reason the daemon reports for a skipped runtime// (MUL-6164).- return "", fmt.Errorf("detect version for %s: %w", execPath, ExplainExecError(err))+ return "", fmt.Errorf("detect version for %s: %w", runtimeCmd, ExplainExecError(err))}return extractVersionLine(string(data)), nil}diff --git a/server/pkg/agent/codebuddy.go b/server/pkg/agent/codebuddy.goindex a4224dc7ef..e1839d0dad 100644--- a/server/pkg/agent/codebuddy.go+++ b/server/pkg/agent/codebuddy.go@@ -135,7 +135,7 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Exec}}()- cmd := exec.CommandContext(runCtx, execPath, args...)+ cmd := b.cfg.commandAt(execPath).exec(runCtx, args...)hideAgentWindow(cmd)b.cfg.Logger.Info("agent command", "exec", execPath, "args", args)cmd.WaitDelay = 10 * time.Seconddiff --git a/server/pkg/agent/codebuddy_discovery_fallback_test.go b/server/pkg/agent/codebuddy_discovery_fallback_test.goindex d726927db7..7a293dd6b4 100644--- a/server/pkg/agent/codebuddy_discovery_fallback_test.go+++ b/server/pkg/agent/codebuddy_discovery_fallback_test.go@@ -85,7 +85,7 @@ func TestDiscoverCodebuddyModelsFromACP(t *testing.T) {resetCodebuddyDiscoveryCaches(t)path := writeCodebuddyACPStub(t, codebuddyACPSessionResult)- catalog, err := discoverCodebuddyModels(context.Background(), path)+ catalog, err := discoverCodebuddyModels(context.Background(), Command{Path: path})if err != nil {t.Fatalf("discoverCodebuddyModels: %v", err)}@@ -184,7 +184,7 @@ func TestDiscoverCodebuddyModelsACPEffort(t *testing.T) {resetCodebuddyDiscoveryCaches(t)path := writeCodebuddyACPStub(t, codebuddyACPSessionResult)- catalog, err := discoverCodebuddyModels(context.Background(), path)+ catalog, err := discoverCodebuddyModels(context.Background(), Command{Path: path})if err != nil {t.Fatalf("discoverCodebuddyModels: %v", err)}@@ -252,7 +252,7 @@ func TestDiscoverCodebuddyModelsFallsBackOnACPFailure(t *testing.T) {} {t.Run(tc.name, func(t *testing.T) {resetCodebuddyDiscoveryCaches(t)- catalog, err := discoverCodebuddyModels(context.Background(), tc.path(t))+ catalog, err := discoverCodebuddyModels(context.Background(), Command{Path: tc.path(t)})if err != nil {t.Fatalf("discoverCodebuddyModels: %v", err)}diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.goindex d6db518f26..6f91ac7860 100644--- a/server/pkg/agent/codex.go+++ b/server/pkg/agent/codex.go@@ -318,6 +318,21 @@ func NormalizeCodexLaunchArgs(extraArgs, customArgs []string, mcpConfig json.Raw// catalog-owned `priority` tier. Future service tiers must not accidentally// inherit Fast mode semantics.func enforceCodexFastMode(args []string, logger *slog.Logger) []string {+ return append(stripCodexFastModeConflicts(args, logger), "--enable", codexFastModeFeature)+}++// stripCodexFastModeConflicts removes the lower-priority overrides that would+// defeat an explicit priority tier, without appending the managed enable.+//+// Split out of enforceCodexFastMode because the enable belongs exactly once, on+// the final managed args, while the removal has to reach every argv region the+// user can write into — including a custom runtime profile's launch prefix.+// Prefix-first does not protect this setting: `--disable fast_mode` beats+// `--enable fast_mode` regardless of argv order, and a `-c+// features.fast_mode=false` beats config.toml from any position. Leaving the+// prefix unfiltered would let a profile override the tier the agent explicitly+// selected, inverting the precedence this package promises (GH #7046).+func stripCodexFastModeConflicts(args []string, logger *slog.Logger) []string {args = filterCodexConfigOverrides(args,codexManagedFastModeConfigKeyRe,@@ -352,7 +367,7 @@ func enforceCodexFastMode(args []string, logger *slog.Logger) []string {}filtered = append(filtered, arg)}- return append(filtered, "--enable", codexFastModeFeature)+ return filtered}// hasManagedCodexMcpConfig reports whether the agent's mcp_config field is@@ -968,15 +983,39 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Execreturn nil, fmt.Errorf("codex: mcp_config is set but CODEX_HOME env var is not configured; cannot apply managed MCP")}+ // A custom runtime profile's fixed_args reach codex as the launch prefix.+ // Being first does not protect the daemon's managed config from them: a+ // `-c key=value` override wins over the task-local config.toml from any+ // argv position, so the prefix needs the same two removals ExtraArgs and+ // CustomArgs get below.+ runtimeCmd := b.cfg.commandAt(execPath)if codexHome != "" {// The daemon owns shell_environment_policy in the task-local config.// Codex -c/--config overrides are last-wins, so remove user-provided// root or profile policy overrides before building the final argv.opts.ExtraArgs = filterCodexShellEnvConfigOverrides(opts.ExtraArgs, b.cfg.Logger)opts.CustomArgs = filterCodexShellEnvConfigOverrides(opts.CustomArgs, b.cfg.Logger)+ runtimeCmd = runtimeCmd.withFilteredPrefix(func(prefix []string) []string {+ return filterCodexShellEnvConfigOverrides(prefix, b.cfg.Logger)+ })+ }+ if hasManagedCodexMcpConfig(opts.McpConfig) {+ // Mirrors NormalizeCodexLaunchArgs, which applies this to ExtraArgs and+ // CustomArgs once an agent has a managed mcp_config.+ runtimeCmd = runtimeCmd.withFilteredPrefix(func(prefix []string) []string {+ return filterCodexCustomConfigOverrides(prefix, b.cfg.Logger)+ })+ }+ if opts.ServiceTier == codexFastServiceTier {+ // Mirrors enforceCodexFastMode, which buildCodexArgs applies to the+ // managed args. The enable itself is appended there, once; the prefix+ // only needs the conflicting disable/config overrides removed.+ runtimeCmd = runtimeCmd.withFilteredPrefix(func(prefix []string) []string {+ return stripCodexFastModeConflicts(prefix, b.cfg.Logger)+ })}codexArgs := buildCodexArgs(opts, b.cfg.Logger)- cmd := exec.CommandContext(runCtx, execPath, codexArgs...)+ cmd := runtimeCmd.exec(runCtx, codexArgs...)hideAgentWindow(cmd)// Run codex in its own process group so a cancel-on-stuck cleanup// reaches the whole tree — the codex Node wrapper plus the native@@ -1606,7 +1645,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec}stderrTail := sanitizeCodexDiagnostic(stderrBuf.Tail())if timeoutDiagnostic.Kind != codexTimeoutNone {- timeoutDiagnostic.CodexVersion = detectCodexVersionForDiagnostics(context.Background(), execPath, cmd.Env, b.cfg.Logger)+ timeoutDiagnostic.CodexVersion = detectCodexVersionForDiagnostics(context.Background(), b.cfg.commandAt(execPath), cmd.Env, b.cfg.Logger)finalError = buildCodexTimeoutDiagnosticError(timeoutDiagnostic, stderrTail)}@@ -2022,11 +2061,11 @@ func appendCodexKnownStderrHint(msg, stderrTail string) string {return msg}-func detectCodexVersionForDiagnostics(ctx context.Context, execPath string, env []string, logger *slog.Logger) string {+func detectCodexVersionForDiagnostics(ctx context.Context, runtimeCmd Command, env []string, logger *slog.Logger) string {versionCtx, cancel := context.WithTimeout(ctx, codexVersionDiagnosticTimeout)defer cancel()- cmd := exec.CommandContext(versionCtx, execPath, "--version")+ cmd := runtimeCmd.exec(versionCtx, "--version")cmd.Env = envdata, err := cmd.Output()if err != nil {diff --git a/server/pkg/agent/copilot.go b/server/pkg/agent/copilot.goindex a07c06489e..f9ee4036e1 100644--- a/server/pkg/agent/copilot.go+++ b/server/pkg/agent/copilot.go@@ -348,9 +348,7 @@ func (b *copilotBackend) Execute(ctx context.Context, prompt string, opts ExecOprunCtx, cancel := runContext(ctx, timeout)args := buildCopilotArgs(prompt, opts, b.cfg.Logger)- argv0, cmdArgs := chooseCopilotInvocation(execName, lookedUp, args, b.cfg.Logger)-- cmd := exec.CommandContext(runCtx, argv0, cmdArgs...)+ cmd, argv0, cmdArgs := b.cfg.commandAt(execName).execVia(runCtx, chooseCopilotInvocation, lookedUp, args, b.cfg.Logger)hideAgentWindow(cmd)b.cfg.Logger.Info("agent command", "exec", argv0, "args", cmdArgs)cmd.WaitDelay = 10 * time.Seconddiff --git a/server/pkg/agent/cursor.go b/server/pkg/agent/cursor.goindex b08c0e396a..e424e465dd 100644--- a/server/pkg/agent/cursor.go+++ b/server/pkg/agent/cursor.go@@ -36,9 +36,7 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOptrunCtx, cancel := runContext(ctx, timeout)args := buildCursorArgs(opts, b.cfg.Logger)- argv0, cmdArgs := chooseCursorInvocation(execName, lookedUp, args, b.cfg.Logger)-- cmd := exec.CommandContext(runCtx, argv0, cmdArgs...)+ cmd, argv0, cmdArgs := b.cfg.commandAt(execName).execVia(runCtx, chooseCursorInvocation, lookedUp, args, b.cfg.Logger)hideAgentWindow(cmd)b.cfg.Logger.Info("agent command", "exec", argv0, "args", cmdArgs)cmd.WaitDelay = 500 * time.Milliseconddiff --git a/server/pkg/agent/deveco.go b/server/pkg/agent/deveco.goindex 433b30d7da..79137f6bf3 100644--- a/server/pkg/agent/deveco.go+++ b/server/pkg/agent/deveco.go@@ -119,7 +119,7 @@ func (b *devecoBackend) Execute(ctx context.Context, prompt string, opts ExecOptargs = append(args, filterCustomArgs(opts.CustomArgs, devecoBlockedArgs, b.cfg.Logger)...)args = append(args, prompt)- cmd := exec.CommandContext(runCtx, execPath, args...)+ cmd := b.cfg.commandAt(execPath).exec(runCtx, args...)hideAgentWindow(cmd)// Run deveco in its own process group so cancellation can reach the whole// tree (deveco plus any tool subprocess it spawns), not just the directdiff --git a/server/pkg/agent/deveco_models.go b/server/pkg/agent/deveco_models.goindex 453029896b..888bc22688 100644--- a/server/pkg/agent/deveco_models.go+++ b/server/pkg/agent/deveco_models.go@@ -17,18 +17,18 @@ import (// the DevEco Code CLI and parses `provider/model` rows. Discovery failures// (binary missing, non-zero exit, unparseable output) silently yield an empty// list so model selection degrades to manual entry rather than blocking.-func discoverDevecoModels(ctx context.Context, executablePath string) ([]Model, error) {- if executablePath == "" {- executablePath = "deveco"+func discoverDevecoModels(ctx context.Context, runtimeCmd Command) ([]Model, error) {+ if runtimeCmd.Path == "" {+ runtimeCmd.Path = "deveco"}- if _, err := exec.LookPath(executablePath); err != nil {+ if _, err := exec.LookPath(runtimeCmd.Path); err != nil {return []Model{}, nil}// `deveco models` may sync its hosted catalog over the network on first// run; allow a generous timeout so the picker isn't empty on a cold start.runCtx, cancel := context.WithTimeout(ctx, 15*time.Second)defer cancel()- cmd := exec.CommandContext(runCtx, executablePath, "models")+ cmd := runtimeCmd.exec(runCtx, "models")hideAgentWindow(cmd)out, _ := cmd.Output()models := parseDevecoModels(string(out))diff --git a/server/pkg/agent/dsh.go b/server/pkg/agent/dsh.goindex 088ed91ddc..b7eb9dbeb4 100644--- a/server/pkg/agent/dsh.go+++ b/server/pkg/agent/dsh.go@@ -220,7 +220,7 @@ func (b *dshBackend) Execute(ctx context.Context, prompt string, opts ExecOptionrunCtx, cancel := runContext(ctx, opts.Timeout)args := dshLaunchArgs()- cmd := exec.CommandContext(runCtx, execPath, args...)+ cmd := b.cfg.commandAt(execPath).exec(runCtx, args...)hideAgentWindow(cmd)configureProcessGroup(cmd)cmd.Cancel = func() error { return nil }@@ -429,11 +429,11 @@ func handleDshFrame(frame dshFrame, requestID string, ch chan<- Message, state *}}-func discoverDshModels(ctx context.Context, executablePath string) ([]Model, error) {- if executablePath == "" {- executablePath = "dsh"+func discoverDshModels(ctx context.Context, runtimeCmd Command) ([]Model, error) {+ if runtimeCmd.Path == "" {+ runtimeCmd.Path = "dsh"}- cmd := exec.CommandContext(ctx, executablePath, "--profile", dshProfile, "--list-models")+ cmd := runtimeCmd.exec(ctx, "--profile", dshProfile, "--list-models")hideAgentWindow(cmd)cmd.WaitDelay = time.Secondstdout, err := cmd.StdoutPipe()diff --git a/server/pkg/agent/dsh_test.go b/server/pkg/agent/dsh_test.goindex 61b391ca70..4908206049 100644--- a/server/pkg/agent/dsh_test.go+++ b/server/pkg/agent/dsh_test.go@@ -142,7 +142,7 @@ func TestDiscoverDshModels(t *testing.T) {bin := writeDshFixture(t, `printf '%s\n' '{"v":1,"type":"models","models":[{"id":"deepseek-official/deepseek-v4-flash","label":"DeepSeek V4 Flash","provider":"DeepSeek","default":true,"thinking":{"supported_levels":[{"value":"high","label":"High"},{"value":"max","label":"Max"}],"default_level":"high"}}]}'`)- models, err := discoverDshModels(context.Background(), bin)+ models, err := discoverDshModels(context.Background(), Command{Path: bin})if err != nil {t.Fatal(err)}diff --git a/server/pkg/agent/grok.go b/server/pkg/agent/grok.goindex edf950c4c0..61eeea64de 100644--- a/server/pkg/agent/grok.go+++ b/server/pkg/agent/grok.go@@ -143,7 +143,7 @@ func (b *grokBackend) Execute(ctx context.Context, prompt string, opts ExecOptiogrokArgs = append(grokArgs, filterCustomArgs(opts.CustomArgs, grokBlockedArgs, b.cfg.Logger)...)grokArgs = append(grokArgs, "stdio")- cmd := exec.CommandContext(runCtx, execPath, grokArgs...)+ cmd := b.cfg.commandAt(execPath).exec(runCtx, grokArgs...)hideAgentWindow(cmd)b.cfg.Logger.Info("agent command", "exec", execPath, "args", grokArgs)if opts.Cwd != "" {diff --git a/server/pkg/agent/grok_test.go b/server/pkg/agent/grok_test.goindex 59104bab5e..93bff8d7a8 100644--- a/server/pkg/agent/grok_test.go+++ b/server/pkg/agent/grok_test.go@@ -746,7 +746,7 @@ func TestDiscoverGrokModelsWaitsForAdvertisedAuth(t *testing.T) {t.Setenv("GROK_AUTH_METHODS", "api")t.Setenv("XAI_API_KEY", "test-only-key")- catalog, err := discoverGrokModels(context.Background(), fakePath)+ catalog, err := discoverGrokModels(context.Background(), Command{Path: fakePath})if err != nil {t.Fatalf("discover grok models: %v", err)}@@ -792,7 +792,7 @@ func TestDiscoverGrokModelsStopsOnAuthFailures(t *testing.T) {t.Setenv("GROK_AUTH_FAIL", tc.authFail)t.Setenv("XAI_API_KEY", "")- catalog, err := discoverGrokModels(context.Background(), fakePath)+ catalog, err := discoverGrokModels(context.Background(), Command{Path: fakePath})if err != nil {t.Fatalf("discover grok models: %v", err)}@@ -851,7 +851,7 @@ func TestGrokValidateThinkingLevelUsesPerModelCatalog(t *testing.T) {{model: "grok-composer-2.5-fast", level: "low", want: false},{model: "future-grok", level: "high", want: false},} {- got, err := ValidateThinkingLevel(context.Background(), "grok", "/nonexistent/grok", tc.model, tc.level)+ got, err := ValidateThinkingLevel(context.Background(), "grok", Command{Path: "/nonexistent/grok"}, tc.model, tc.level)if err != nil {t.Fatalf("ValidateThinkingLevel(%q, %q): %v", tc.model, tc.level, err)}diff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.goindex 5828b4c72d..bad79a3875 100644--- a/server/pkg/agent/hermes.go+++ b/server/pkg/agent/hermes.go@@ -134,6 +134,97 @@ func hermesInsideMcpAdd(args []string, index int) bool {return false}+// hermesACPSubcommand is the subcommand the backend always launches with. It+// sits between the runtime's launch prefix and the agent's custom args, and it+// is an ordinary argv token to Hermes' own parser — which is why the daemon+// cannot reason about a profile selection without it.+const hermesACPSubcommand = "acp"++// hermesCLIArgsFrom assembles the argv the backend passes after the executable+// and its launch prefix, from custom args that are already filtered.+func hermesCLIArgsFrom(filteredCustomArgs []string) []string {+ args := make([]string, 0, 1+len(filteredCustomArgs))+ args = append(args, hermesACPSubcommand)+ return append(args, filteredCustomArgs...)+}++// hermesCLIArgs is what hermesBackend.Execute passes to the launch boundary.+func hermesCLIArgs(customArgs []string, logger *slog.Logger) []string {+ return hermesCLIArgsFrom(filterCustomArgs(customArgs, hermesBlockedArgs, logger))+}++// HermesLaunchArgv returns the exact argv Hermes will parse: the runtime's+// launch prefix, then `acp`, then the agent's custom args after the same+// blocked-flag filtering the backend applies.+//+// The daemon resolves the profile selection from this rather than from a+// hand-assembled approximation. Concatenating prefix and custom args alone+// silently disagrees with the real command line, because the `acp` token+// participates in Hermes' scan: with fixed_args `--model` and custom_args+// `-p research`, the approximation reads `-p` as `--model`'s value and finds+// no selection, while the real `--model acp -p research` skips `--model acp`+// and selects `research`. The overlay would then be seeded from the default+// home while the process runs under a different profile's config.+func HermesLaunchArgv(launchPrefix, customArgs []string, logger *slog.Logger) []string {+ return Command{Prefix: launchPrefix}.Argv(hermesCLIArgs(customArgs, logger)...)+}++// StripHermesProfileSelectors removes every profile selection from the argv+// Hermes will parse and hands each surviving token back to the region it came+// from — launch prefix or custom args.+//+// The daemon calls this only when it built the per-task overlay, where the+// overlay's HERMES_HOME is authoritative and nothing on the command line may+// re-point out of it.+//+// It works on the assembled argv rather than on each region separately for two+// reasons, both of which leave a live selector behind if ignored:+//+// - A selection can straddle the boundary. A launch prefix ending in a bare+// `-p` takes the backend's own `acp` token as its value, and neither region+// contains a complete selection to strip.+// - Removing one selection promotes the next. Hermes honours the first and+// ignores the rest, so a single pass can hand the job to a later+// occurrence — and with the prefix and custom args configured separately,+// two selections is ordinary configuration rather than a user mistake.+//+// Tokens Hermes itself discards — an invalid profile value, which makes+// ParseHermesProfileArgs report nothing found — are left alone: they redirect+// nothing. The `acp` token is never removed, because the backend re-adds it at+// launch; dropping the flag that captured it is what breaks the selection.+func StripHermesProfileSelectors(launchPrefix, customArgs []string, logger *slog.Logger) ([]string, []string) {+ prefix := append([]string(nil), launchPrefix...)+ custom := append([]string(nil), filterCustomArgs(customArgs, hermesBlockedArgs, logger)...)+ for {+ sel := ParseHermesProfileArgs(Command{Prefix: prefix}.Argv(hermesCLIArgsFrom(custom)...))+ if !sel.Found {+ return prefix, custom+ }+ acpIndex := len(prefix)+ removed := false+ // Walk back to front so earlier indices stay valid as tokens go.+ for i := sel.ArgFrom + sel.ArgLen - 1; i >= sel.ArgFrom; i-- {+ switch {+ case i < acpIndex:+ prefix = append(prefix[:i], prefix[i+1:]...)+ removed = true+ case i == acpIndex:+ // Backend-owned; re-added at launch.+ default:+ if j := i - acpIndex - 1; j < len(custom) {+ custom = append(custom[:j], custom[j+1:]...)+ removed = true+ }+ }+ }+ if !removed {+ // Defensive: a selection always contains a flag from one of the two+ // regions, so this cannot loop forever. Bail rather than spin.+ return prefix, custom+ }+ }+}+// StripHermesProfileArgs removes exactly the argv occurrence ParseHermesProfileArgs// selected. The daemon calls this only when it built the per-task overlay, so// Hermes uses the overlay's HERMES_HOME instead of re-resolving the profile —@@ -192,8 +283,10 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpttimeout := opts.TimeoutrunCtx, cancel := runContext(ctx, timeout)- hermesArgs := append([]string{"acp"}, filterCustomArgs(opts.CustomArgs, hermesBlockedArgs, b.cfg.Logger)...)- cmd := exec.CommandContext(runCtx, execPath, hermesArgs...)+ // Same assembly HermesLaunchArgv reproduces for the daemon, so the profile+ // the overlay is seeded from is the one this argv actually selects.+ hermesArgs := hermesCLIArgs(opts.CustomArgs, b.cfg.Logger)+ cmd := b.cfg.commandAt(execPath).exec(runCtx, hermesArgs...)hideAgentWindow(cmd)b.cfg.Logger.Info("agent command", "exec", execPath, "args", hermesArgs)agentsMDPresent := falsediff --git a/server/pkg/agent/kimi.go b/server/pkg/agent/kimi.goindex b4fb1d3a90..4a4d1f8e39 100644--- a/server/pkg/agent/kimi.go+++ b/server/pkg/agent/kimi.go@@ -65,7 +65,7 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio// a safe granting option the agent offered (see// selectACPApprovalOptionID) for each session/request_permission request.kimiArgs := append([]string{"acp"}, filterCustomArgs(opts.CustomArgs, kimiBlockedArgs, b.cfg.Logger)...)- cmd := exec.CommandContext(runCtx, execPath, kimiArgs...)+ cmd := b.cfg.commandAt(execPath).exec(runCtx, kimiArgs...)hideAgentWindow(cmd)b.cfg.Logger.Info("agent command", "exec", execPath, "args", kimiArgs)if opts.Cwd != "" {diff --git a/server/pkg/agent/kiro.go b/server/pkg/agent/kiro.goindex 07d3b99b8f..cbcff40364 100644--- a/server/pkg/agent/kiro.go+++ b/server/pkg/agent/kiro.go@@ -62,7 +62,7 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptiorunCtx, cancel := runContext(ctx, timeout)kiroArgs := append([]string{"acp", "--trust-all-tools"}, filterCustomArgs(opts.CustomArgs, kiroBlockedArgs, b.cfg.Logger)...)- cmd := exec.CommandContext(runCtx, execPath, kiroArgs...)+ cmd := b.cfg.commandAt(execPath).exec(runCtx, kiroArgs...)hideAgentWindow(cmd)b.cfg.Logger.Info("agent command", "exec", execPath, "args", kiroArgs)if opts.Cwd != "" {diff --git a/server/pkg/agent/launch.go b/server/pkg/agent/launch.gonew file mode 100644index 0000000000..fd8c39765d--- /dev/null+++ b/server/pkg/agent/launch.go@@ -0,0 +1,285 @@+package agent++import (+ "context"+ "log/slog"+ "os/exec"+ "strings"+)++// Command is the identity of a runtime CLI: the executable Multica spawns plus+// the argv prefix that belongs to the command itself rather than to any single+// invocation.+//+// A custom runtime profile (MUL-3284) is configured as `command_name` plus+// `fixed_args`, and for a wrapper like `ccms start q36` those two fixed_args+// tokens are part of *what the program is*, not options passed to it. The+// wrapper only reaches the real Claude binary after its `start` subcommand has+// been selected, so `-p` and the rest of the stream-json protocol flags are+// meaningless — and rejected outright by a Commander-style parser — until the+// prefix has been consumed (GH #7046).+//+// So the prefix goes directly after the executable and before everything a+// backend builds:+//+// <Path> <Prefix...> <protocol args...> <ExtraArgs...> <CustomArgs...>+//+// Subcommand-style prefixes work only in this position. Flag-style prefixes+// generally parse the same either way — `agent --model composer-2.5 -p …` and+// `agent -p … --model composer-2.5` are equivalent to most parsers — so+// prefix-first is the broader of the two orders, not a universally safe one: a+// CLI that separates global flags from subcommand flags can still care where a+// flag lands. That residual risk is why the position change is called out in+// the runtime docs rather than treated as invisible.+//+// The zero Command is a bare executable with no prefix, which is what every+// built-in runtime uses.+type Command struct {+ // Path is the executable to spawn — a PATH lookup name or an absolute path.+ Path string+ // Prefix is the argv prefix that belongs to the command, already filtered+ // by FilterLaunchPrefix. Never mutate a Command's Prefix in place; Argv+ // copies it precisely so a caller cannot alias it.+ Prefix []string+ // logger reports prefix/argument conflicts at the moment a process is+ // built. Optional: a zero Command logs nothing.+ logger *slog.Logger+}++// NewCommand builds a Command from a resolved executable path and a launch+// prefix. Callers inside this package normally go through Config.commandAt+// instead, which carries the prefix the daemon configured for the runtime.+//+// The prefix should already have been through FilterLaunchPrefix; pass a raw+// fixed_args list only where no protocol channel exists to protect, such as a+// one-shot `--version` probe.+func NewCommand(path string, prefix []string) Command {+ return Command{Path: path, Prefix: append([]string(nil), prefix...)}+}++// Argv returns the full argument vector for one invocation: the command's own+// prefix followed by args. The result never aliases either input, so callers+// may append to it freely.+func (c Command) Argv(args ...string) []string {+ argv := make([]string, 0, len(c.Prefix)+len(args))+ argv = append(argv, c.Prefix...)+ argv = append(argv, args...)+ return argv+}++// exec builds the *exec.Cmd that runs this command with args.+//+// This is the single place in the package where a runtime CLI process is+// constructed. Everything the daemon launches or probes — task execution,+// `--version` detection, model discovery — routes through here or through+// execVia, so a new backend cannot forget the launch prefix and silently+// reintroduce GH #7046. TestOnlyLaunchGoSpawnsRuntimeProcesses enforces it.+func (c Command) exec(ctx context.Context, args ...string) *exec.Cmd {+ warnLaunchPrefixOverlap(c.Prefix, args, c.logger)+ return exec.CommandContext(ctx, c.Path, c.Argv(args...)...)+}++// invocationChooser is the shape of the per-tool platform launch rewrites+// (chooseCursorInvocation, chooseCopilotInvocation, choosePiInvocation). On+// Windows they replace argv[0] with a PowerShell host or a bundled native+// binary and wrap the CLI's own argv; on other platforms they pass through.+type invocationChooser func(execName, lookedUp string, args []string, logger *slog.Logger) (string, []string)++// execVia builds the *exec.Cmd for a runtime CLI whose launch goes through a+// platform invocation chooser.+//+// The prefix is applied to the CLI's own argv *before* the chooser runs, never+// to the final argv[0]: on Windows the chooser may prepend its own tokens+// (`-NoProfile -ExecutionPolicy Bypass -File cursor-agent.ps1`) that must stay+// in front. `ccms start q36` has to land after the PowerShell preamble, on the+// wrapped CLI, not ahead of PowerShell's own flags.+func (c Command) execVia(ctx context.Context, choose invocationChooser, lookedUp string, args []string, logger *slog.Logger) (*exec.Cmd, string, []string) {+ warnLaunchPrefixOverlap(c.Prefix, args, logger)+ argv0, cmdArgs := choose(c.Path, lookedUp, c.Argv(args...), logger)+ return exec.CommandContext(ctx, argv0, cmdArgs...), argv0, cmdArgs+}++// withFilteredPrefix returns a copy of the command whose prefix has been+// through fn.+//+// Moving the prefix to the front makes it lose an ordinary last-wins flag+// conflict, which is the point. But a few settings are not decided by argv+// order at all: Codex's `-c key=value` beats the daemon-written config.toml+// from any position, so a `-c mcp_servers.…` in fixed_args shadows managed MCP+// whether it sits first or last. Those need the same removal that ExtraArgs+// and CustomArgs already get, and only the backend knows which they are.+func (c Command) withFilteredPrefix(fn func([]string) []string) Command {+ c.Prefix = fn(c.Prefix)+ return c+}++// cacheKey identifies the command for the model-discovery memo. The prefix is+// part of it because two profiles can share one binary and still enumerate+// different catalogs — `ccms start q36` and `ccms start opus` are the same+// executable with different models behind it, and keying on the path alone+// would serve the first one's catalog to the second (see discoveryCacheKey).+func (c Command) cacheKey() string {+ if len(c.Prefix) == 0 {+ return c.Path+ }+ return c.Path + "\x00" + strings.Join(c.Prefix, "\x00")+}++// String renders the command the way a user wrote it in the Runtimes UI, for+// logs and error messages.+func (c Command) String() string {+ if len(c.Prefix) == 0 {+ return c.Path+ }+ return c.Path + " " + strings.Join(c.Prefix, " ")+}++// commandAt pairs a resolved executable path with this runtime's launch+// prefix. Backends call it after their own PATH resolution and default-binary+// fallback, which is why the path is a parameter rather than read from+// Config.ExecutablePath.+func (c Config) commandAt(path string) Command {+ return Command{Path: path, Prefix: c.LaunchPrefix, logger: c.Logger}+}++// launchPrefixBlockedArgs maps a protocol family to the flags a launch prefix+// may not set. It exists so New can filter the prefix once, at the single+// point that knows the family, instead of asking each backend to remember.+//+// Only families that reject flags at all appear here; a family whose backend+// has no blocked-arg policy accepts any prefix.+var launchPrefixBlockedArgs = map[string]map[string]blockedArgMode{+ "antigravity": antigravityBlockedArgs,+ "claude": claudeBlockedArgs,+ "codebuddy": codebuddyBlockedArgs,+ "codex": codexBlockedArgs,+ "copilot": copilotBlockedArgs,+ "cursor": cursorBlockedArgs,+ "deveco": devecoBlockedArgs,+ "grok": grokBlockedArgs,+ "hermes": hermesBlockedArgs,+ "kimi": kimiBlockedArgs,+ "kiro": kiroBlockedArgs,+ "opencode": opencodeBlockedArgs,+ "openclaw": openclawBlockedArgs,+ "pi": piBlockedArgs,+ "qoder": qoderBlockedArgs,+ "qoderclicn": qoderBlockedArgs,+ "qwen": qwenBlockedArgs,+ "qwenpaw": qwenpawBlockedArgs,+ "reasonix": reasonixBlockedArgs,+ "traecli": traecliBlockedArgs,+}++// FilterLaunchPrefix is the exported form for callers outside this package —+// the daemon, which builds Commands for CLI probes that never reach New.+// Without it a `--version` probe and a task launch would disagree about what+// the runtime's prefix is.+func FilterLaunchPrefix(agentType string, prefix []string, logger *slog.Logger) []string {+ return filterLaunchPrefix(prefix, agentType, logger)+}++// filterLaunchPrefix drops protocol-critical flags from a launch prefix while+// letting positional tokens through.+//+// The two token kinds answer different questions. A positional token is the+// command's identity — `start`, `q36` — and the daemon has no opinion about+// it. A flag token competes with the protocol arguments the daemon owns, and+// the prefix position would let it win: putting `--output-format text` in+// fixed_args would break the daemon↔CLI stream-json channel exactly like+// putting it in custom_args, which is already refused.+//+// This deliberately does NOT delegate to filterCustomArgs, even though the two+// share blocklists. Those maps also carry positional tokens — Hermes and+// QwenPaw block `acp`, TRAE blocks `acp` and `serve`, Grok blocks `agent`,+// `stdio` and `serve` — because in custom_args a bare `acp` really is someone+// re-issuing the backend's own subcommand. In a launch prefix the same token+// is part of the command's identity: `hermes-wrapper acp tenant` names a+// program, and dropping `acp` from it would silently rewrite the command into+// one the operator never configured. Only a leading `-` makes a token eligible+// for the blocklist here.+//+// A blocked flag still consumes its separate value token, positional or not,+// so `--permission-mode ask` cannot leave a stray `ask` behind to be read as a+// subcommand.+func filterLaunchPrefix(prefix []string, agentType string, logger *slog.Logger) []string {+ if len(prefix) == 0 {+ return nil+ }+ blocked, ok := launchPrefixBlockedArgs[agentType]+ if !ok {+ return append([]string(nil), prefix...)+ }+ if logger == nil {+ logger = slog.Default()+ }+ filtered := make([]string, 0, len(prefix))+ for i := 0; i < len(prefix); i++ {+ arg := unshellQuoteArg(prefix[i])+ flag, isFlag := launchPrefixFlagName(arg)+ if !isFlag {+ // The command's own identity. Never filtered, even when it+ // collides with a backend subcommand name.+ filtered = append(filtered, arg)+ continue+ }+ mode, isBlocked := blocked[flag]+ if !isBlocked {+ filtered = append(filtered, arg)+ continue+ }+ logger.Warn("custom runtime fixed_args: blocked protocol-critical flag, skipping", "flag", flag)+ hasInlineValue := strings.Contains(arg, "=")+ if mode == blockedWithValue && !hasInlineValue {+ i+++ } else if mode == blockedOptionalValue && !hasInlineValue && i+1 < len(prefix) &&+ !strings.HasPrefix(unshellQuoteArg(prefix[i+1]), "-") {+ i+++ }+ }+ return filtered+}++// warnLaunchPrefixOverlap logs the flags a launch prefix shares with the+// arguments the daemon builds for this run.+//+// Overlap is not an error: the prefix comes first, so the daemon's own value+// is the later one and wins under the last-wins parsing every supported CLI+// uses. That is the intended precedence — an explicitly chosen per-agent model+// should beat a runtime-wide default — but before GH #7046 the prefix sat last+// and quietly won instead, so a runtime pinned to `--model composer-2.5` used+// to override the model the member picked in the UI. Anyone who was relying on+// that gets a line in the log naming the flag rather than a silent change.+func warnLaunchPrefixOverlap(prefix, args []string, logger *slog.Logger) {+ if len(prefix) == 0 || len(args) == 0 || logger == nil {+ return+ }+ later := make(map[string]bool, len(args))+ for _, a := range args {+ if flag, ok := launchPrefixFlagName(a); ok {+ later[flag] = true+ }+ }+ for _, p := range prefix {+ flag, ok := launchPrefixFlagName(p)+ if !ok || !later[flag] {+ continue+ }+ logger.Warn("custom runtime fixed_args set a flag the runtime also sets; the runtime's value wins",+ "flag", flag)+ }+}++// launchPrefixFlagName extracts the flag name from an argv token, reporting+// false for positional tokens. `--model=o3` and `--model o3` both yield+// "--model" so the two spellings compare equal.+func launchPrefixFlagName(arg string) (string, bool) {+ arg = unshellQuoteArg(arg)+ if !strings.HasPrefix(arg, "-") || arg == "-" || arg == "--" {+ return "", false+ }+ if idx := strings.Index(arg, "="); idx > 0 {+ return arg[:idx], true+ }+ return arg, true+}diff --git a/server/pkg/agent/launch_test.go b/server/pkg/agent/launch_test.gonew file mode 100644index 0000000000..a6362484bc--- /dev/null+++ b/server/pkg/agent/launch_test.go@@ -0,0 +1,548 @@+package agent++import (+ "bytes"+ "context"+ "go/ast"+ "go/parser"+ "go/token"+ "log/slog"+ "os"+ "path/filepath"+ "strings"+ "testing"+)++// prefixIndex reports where the first token of want starts inside argv, or -1.+func prefixIndex(argv, want []string) int {+ for i := 0; i+len(want) <= len(argv); i++ {+ if strings.Join(argv[i:i+len(want)], "\x00") == strings.Join(want, "\x00") {+ return i+ }+ }+ return -1+}++// TestLaunchPrefixPrecedesProtocolFlags is GH #7046 in one assertion. `ccms+// start q36` only reaches the real Claude binary after its `start` subcommand+// is selected, so a `-p` that arrives first is parsed by the wrapper, which+// rejects it outright ("unknown option '-p'"). The subcommand tokens have to+// come first.+func TestLaunchPrefixPrecedesProtocolFlags(t *testing.T) {+ t.Parallel()++ cfg := Config{ExecutablePath: "ccms", LaunchPrefix: []string{"start", "q36"}, Logger: slog.Default()}+ argv := cfg.commandAt("ccms").Argv(buildClaudeArgs(ExecOptions{}, slog.Default())...)++ subcommand := prefixIndex(argv, []string{"start", "q36"})+ if subcommand != 0 {+ t.Fatalf("fixed_args must be the argv prefix, found at %d: %v", subcommand, argv)+ }+ protocol := prefixIndex(argv, []string{"-p"})+ if protocol < 0 {+ t.Fatalf("protocol flags missing from argv: %v", argv)+ }+ if protocol < subcommand+2 {+ t.Fatalf("-p at %d must come after the `start q36` prefix: %v", protocol, argv)+ }+}++// TestLaunchPrefixPlacesFlagStyleWrappersFirst pins where a flag-style prefix+// lands. It asserts the argv Multica builds, not that any particular third-party+// parser accepts the new position — most treat the two orders as equivalent,+// but a CLI that separates global from subcommand flags may not, which is why+// the docs call the move out instead of promising it is invisible.+func TestLaunchPrefixPlacesFlagStyleWrappersFirst(t *testing.T) {+ t.Parallel()++ cfg := Config{ExecutablePath: "agent", LaunchPrefix: []string{"--model", "composer-2.5"}, Logger: slog.Default()}+ argv := cfg.commandAt("agent").Argv(buildClaudeArgs(ExecOptions{}, slog.Default())...)++ if idx := prefixIndex(argv, []string{"--model", "composer-2.5"}); idx != 0 {+ t.Fatalf("flag-style fixed_args must still lead the argv, found at %d: %v", idx, argv)+ }+}++// TestLaunchPrefixLosesToExplicitAgentModel pins the precedence flip this+// change makes deliberately. Before GH #7046 the prefix sat last and won every+// last-wins parse, so a runtime pinned to `--model composer-2.5` silently+// overrode the model the member picked in the UI. Prefix-first inverts that:+// the more specific per-agent choice is the later token and wins.+func TestLaunchPrefixLosesToExplicitAgentModel(t *testing.T) {+ t.Parallel()++ cfg := Config{ExecutablePath: "agent", LaunchPrefix: []string{"--model", "composer-2.5"}, Logger: slog.Default()}+ argv := cfg.commandAt("agent").Argv(buildClaudeArgs(ExecOptions{Model: "claude-opus-4-7"}, slog.Default())...)++ runtimeModel := prefixIndex(argv, []string{"--model", "composer-2.5"})+ agentModel := prefixIndex(argv, []string{"--model", "claude-opus-4-7"})+ if runtimeModel < 0 || agentModel < 0 {+ t.Fatalf("expected both --model occurrences: %v", argv)+ }+ if agentModel <= runtimeModel {+ t.Fatalf("the agent's explicit model must be the later --model (runtime at %d, agent at %d): %v",+ runtimeModel, agentModel, argv)+ }+}++// TestFilterLaunchPrefixKeepsSubcommandsDropsProtocolFlags covers the+// blocklist split: positional tokens are the command's identity and pass+// through, flag tokens compete with the daemon's own protocol arguments and do+// not. A blocked flag takes its value token with it.+func TestFilterLaunchPrefixKeepsSubcommandsDropsProtocolFlags(t *testing.T) {+ t.Parallel()++ got := filterLaunchPrefix(+ []string{"start", "q36", "-p", "--output-format", "text", "--model", "composer-2.5"},+ "claude", slog.Default())+ want := []string{"start", "q36", "--model", "composer-2.5"}++ if strings.Join(got, "\x00") != strings.Join(want, "\x00") {+ t.Fatalf("filterLaunchPrefix = %v, want %v", got, want)+ }+}++// TestNewFiltersLaunchPrefixOnce proves the filter runs at the single point+// that knows the protocol family, so no backend has to remember to call it.+func TestNewFiltersLaunchPrefixOnce(t *testing.T) {+ t.Parallel()++ backend, err := New("claude", Config{+ ExecutablePath: "ccms",+ LaunchPrefix: []string{"start", "q36", "--output-format", "text"},+ Logger: slog.Default(),+ })+ if err != nil {+ t.Fatalf("New(claude): %v", err)+ }+ got := backend.(*claudeBackend).cfg.LaunchPrefix+ want := []string{"start", "q36"}+ if strings.Join(got, "\x00") != strings.Join(want, "\x00") {+ t.Fatalf("New did not filter the launch prefix: got %v, want %v", got, want)+ }+}++// TestLaunchPrefixReachesACPFamilies is the regression guard for the half of+// the bug the report did not name: fixed_args used to ride on ExtraArgs, which+// the ACP backends never read, so on those families it was silently dropped+// rather than merely misordered. The prefix must land ahead of the hardcoded+// `acp` subcommand.+func TestLaunchPrefixReachesACPFamilies(t *testing.T) {+ t.Parallel()++ for _, family := range []string{"kimi", "hermes", "kiro", "reasonix", "qwenpaw"} {+ t.Run(family, func(t *testing.T) {+ t.Parallel()+ cfg := Config{LaunchPrefix: []string{"start", "q36"}, Logger: slog.Default()}+ argv := cfg.commandAt("wrapper").Argv("acp")+ if idx := prefixIndex(argv, []string{"start", "q36", "acp"}); idx != 0 {+ t.Fatalf("%s: prefix must precede the acp subcommand, got %v", family, argv)+ }+ })+ }+}++// TestDiscoveryCacheKeySeparatesLaunchPrefixes: one binary behind two+// different prefixes is two different catalogs.+func TestDiscoveryCacheKeySeparatesLaunchPrefixes(t *testing.T) {+ t.Parallel()++ q36 := discoveryCacheKey("claude", Command{Path: "/usr/local/bin/ccms", Prefix: []string{"start", "q36"}})+ opus := discoveryCacheKey("claude", Command{Path: "/usr/local/bin/ccms", Prefix: []string{"start", "opus"}})+ bare := discoveryCacheKey("claude", Command{Path: "/usr/local/bin/ccms"})++ if q36 == opus {+ t.Fatalf("two prefixes on one binary share a cache key: %q", q36)+ }+ if q36 == bare || opus == bare {+ t.Fatalf("a prefixed command must not share the bare binary's key: %q / %q / %q", q36, opus, bare)+ }+}++// TestCommandArgvNeverAliasesItsInputs: Argv results get appended to by+// callers, so a shared backing array would let one invocation's arguments+// leak into the next.+func TestCommandArgvNeverAliasesItsInputs(t *testing.T) {+ t.Parallel()++ prefix := []string{"start", "q36"}+ cmd := Command{Path: "ccms", Prefix: prefix}++ first := cmd.Argv("-p")+ first = append(first, "mutated")+ second := cmd.Argv("--version")++ if strings.Join(cmd.Prefix, "\x00") != "start\x00q36" {+ t.Fatalf("Argv mutated the command's prefix: %v", cmd.Prefix)+ }+ if prefixIndex(second, []string{"mutated"}) >= 0 {+ t.Fatalf("a later Argv saw an earlier call's append: %v", second)+ }+}++// TestOnlyLaunchGoSpawnsRuntimeProcesses is the structural half of this fix.+//+// Distributed opt-in is what let ExtraArgs rot: it was honoured by six of+// twenty-one backends, and MULTICA_QWENPAW_ARGS shipped plumbed-but-dropped+// because nothing failed when a backend forgot to read it. Re-establishing the+// same convention for the launch prefix would rot the same way, so the rule is+// mechanical instead: every runtime process in this package is constructed in+// launch.go, which is the one place that applies the prefix.+//+// A new backend that calls os/exec directly fails here rather than silently+// reintroducing GH #7046.+func TestOnlyLaunchGoSpawnsRuntimeProcesses(t *testing.T) {+ t.Parallel()++ entries, err := os.ReadDir(".")+ if err != nil {+ t.Fatalf("read package dir: %v", err)+ }++ fset := token.NewFileSet()+ var offenders []string+ for _, entry := range entries {+ name := entry.Name()+ if entry.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {+ continue+ }+ // launch.go owns the boundary. The platform invocation rewrites resolve+ // a PowerShell host with exec.LookPath but never spawn the runtime.+ if name == "launch.go" {+ continue+ }+ src, err := os.ReadFile(name)+ if err != nil {+ t.Fatalf("read %s: %v", name, err)+ }+ file, err := parser.ParseFile(fset, name, src, 0)+ if err != nil {+ t.Fatalf("parse %s: %v", name, err)+ }+ ast.Inspect(file, func(n ast.Node) bool {+ call, ok := n.(*ast.CallExpr)+ if !ok {+ return true+ }+ sel, ok := call.Fun.(*ast.SelectorExpr)+ if !ok {+ return true+ }+ pkg, ok := sel.X.(*ast.Ident)+ if !ok || pkg.Name != "exec" {+ return true+ }+ if sel.Sel.Name != "Command" && sel.Sel.Name != "CommandContext" {+ return true+ }+ offenders = append(offenders,+ fset.Position(call.Pos()).String()+": exec."+sel.Sel.Name)+ return true+ })+ }++ if len(offenders) > 0 {+ t.Fatalf("runtime processes must be built through Command.exec / Command.execVia in launch.go, "++ "otherwise a custom runtime's fixed_args are dropped (GH #7046). Offending sites:\n%s",+ strings.Join(offenders, "\n"))+ }+}++// TestClaudeBackendLaunchesWrapperSubcommandFirst is the end-to-end proof:+// a real subprocess, spawned through the real backend, records the argv it was+// handed. The fake wrapper stands in for `ccms` and never touches a+// user-installed CLI.+func TestClaudeBackendLaunchesWrapperSubcommandFirst(t *testing.T) {+ t.Parallel()++ dir := t.TempDir()+ argsFile := filepath.Join(dir, "argv")+ wrapper := filepath.Join(dir, "ccms")+ writeTestExecutable(t, wrapper, []byte("#!/bin/sh\n"++ "for arg in \"$@\"; do printf '%s\\n' \"$arg\" >> \""+argsFile+"\"; done\n"++ "exit 0\n"))++ backend, err := New("claude", Config{+ ExecutablePath: wrapper,+ LaunchPrefix: []string{"start", "q36"},+ Logger: slog.Default(),+ })+ if err != nil {+ t.Fatalf("New(claude): %v", err)+ }+ session, err := backend.Execute(context.Background(), "hello", ExecOptions{Cwd: dir})+ if err != nil {+ t.Fatalf("Execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()+ <-session.Result++ raw, err := os.ReadFile(argsFile)+ if err != nil {+ t.Fatalf("wrapper recorded no argv: %v", err)+ }+ argv := strings.Fields(string(bytes.TrimSpace(raw)))+ if idx := prefixIndex(argv, []string{"start", "q36"}); idx != 0 {+ t.Fatalf("wrapper was launched as %v; `start q36` must lead", argv)+ }+ if idx := prefixIndex(argv, []string{"-p"}); idx < 2 {+ t.Fatalf("-p reached the wrapper before its subcommand: %v", argv)+ }+}++// TestLaunchPrefixOutranksExtraArgs locks the full argv contract that replaced+// "fixed_args are prepended to ExtraArgs" (#4408). The old arrangement put the+// prefix inside ExtraArgs, which lands *after* the protocol flags — and which+// fifteen of the twenty-one backends never read at all. The prefix now has its+// own slot ahead of everything.+func TestLaunchPrefixOutranksExtraArgs(t *testing.T) {+ t.Parallel()++ cfg := Config{LaunchPrefix: []string{"start", "q36"}, Logger: slog.Default()}+ argv := cfg.commandAt("ccms").Argv(buildClaudeArgs(ExecOptions{+ ExtraArgs: []string{"--extra-arg"},+ CustomArgs: []string{"--custom-arg"},+ }, slog.Default())...)++ prefix := prefixIndex(argv, []string{"start", "q36"})+ protocol := prefixIndex(argv, []string{"-p"})+ extra := prefixIndex(argv, []string{"--extra-arg"})+ custom := prefixIndex(argv, []string{"--custom-arg"})++ if prefix != 0 {+ t.Fatalf("launch prefix must lead: %v", argv)+ }+ if !(prefix < protocol && protocol < extra && extra < custom) {+ t.Fatalf("want prefix < protocol < extra < custom, got %d/%d/%d/%d: %v",+ prefix, protocol, extra, custom, argv)+ }+}++// TestBuiltinRuntimeIdentitiesFilterLaunchPrefix: NewRuntime composes New, so+// a runtime identity (omp) inherits the same prefix policy as its family.+func TestBuiltinRuntimeIdentitiesFilterLaunchPrefix(t *testing.T) {+ t.Parallel()++ backend, err := ResolveBackend("omp", Config{+ ExecutablePath: "wrapper",+ LaunchPrefix: []string{"start", "q36", "-p"},+ Logger: slog.Default(),+ })+ if err != nil {+ t.Fatalf("ResolveBackend(omp): %v", err)+ }+ got := backend.(*piBackend).cfg.LaunchPrefix+ if strings.Join(got, "\x00") != "start\x00q36" {+ t.Fatalf("runtime identity did not inherit prefix filtering: %v", got)+ }+}++// TestCodexLaunchPrefixCannotShadowManagedConfig: prefix-first wins ordinary+// flag conflicts on purpose, but Codex `-c key=value` beats the daemon-written+// config.toml from any argv position. A fixed_args entry aimed at a managed+// namespace has to be removed, not merely outranked.+func TestCodexLaunchPrefixCannotShadowManagedConfig(t *testing.T) {+ t.Parallel()++ cmd := Command{Prefix: []string{+ "proxy", "run",+ "-c", "mcp_servers.evil.command=/bin/sh",+ "-c", "shell_environment_policy.inherit=all",+ "--model", "gpt-5",+ }}++ filtered := cmd.+ withFilteredPrefix(func(p []string) []string { return filterCodexShellEnvConfigOverrides(p, slog.Default()) }).+ withFilteredPrefix(func(p []string) []string { return filterCodexCustomConfigOverrides(p, slog.Default()) })++ want := []string{"proxy", "run", "--model", "gpt-5"}+ if strings.Join(filtered.Prefix, "\x00") != strings.Join(want, "\x00") {+ t.Fatalf("prefix = %v, want the managed-namespace overrides dropped and %v kept",+ filtered.Prefix, want)+ }+}++// TestFilterLaunchPrefixKeepsPositionalCollidingWithSubcommand is Elon's+// must-fix 2. The blocklists are shared with custom_args, and several carry+// positional tokens — hermes/qwenpaw block `acp`, traecli blocks `acp` and+// `serve`, grok blocks `agent`, `stdio` and `serve`. Those entries exist to+// stop someone re-issuing the backend's own subcommand through custom_args.+// A launch prefix is the opposite case: the token is the command's identity,+// and dropping it rewrites the operator's command into a different one.+func TestFilterLaunchPrefixKeepsPositionalCollidingWithSubcommand(t *testing.T) {+ t.Parallel()++ cases := []struct {+ family string+ prefix []string+ want []string+ }{+ {"hermes", []string{"acp", "tenant"}, []string{"acp", "tenant"}},+ {"qwenpaw", []string{"acp", "tenant"}, []string{"acp", "tenant"}},+ {"traecli", []string{"serve", "acp"}, []string{"serve", "acp"}},+ {"grok", []string{"agent", "stdio"}, []string{"agent", "stdio"}},+ {"grok", []string{"leader", "headless"}, []string{"leader", "headless"}},+ // Flags in the same prefix are still filtered; grok blocks -p.+ {"grok", []string{"agent", "-p", "stdio"}, []string{"agent", "stdio"}},+ }+ for _, tc := range cases {+ t.Run(tc.family+"/"+strings.Join(tc.prefix, "_"), func(t *testing.T) {+ t.Parallel()+ got := filterLaunchPrefix(tc.prefix, tc.family, slog.Default())+ if strings.Join(got, "\x00") != strings.Join(tc.want, "\x00") {+ t.Fatalf("filterLaunchPrefix(%v, %s) = %v, want %v", tc.prefix, tc.family, got, tc.want)+ }+ })+ }+}++// TestFilterLaunchPrefixConsumesBlockedFlagValue: dropping a blocked flag must+// take its value with it, or the leftover value token would be read as a+// subcommand — precisely the kind of token this filter otherwise preserves.+func TestFilterLaunchPrefixConsumesBlockedFlagValue(t *testing.T) {+ t.Parallel()++ got := filterLaunchPrefix(+ []string{"start", "--permission-mode", "ask", "q36", "--output-format=text"},+ "claude", slog.Default())+ want := []string{"start", "q36"}+ if strings.Join(got, "\x00") != strings.Join(want, "\x00") {+ t.Fatalf("filterLaunchPrefix = %v, want %v", got, want)+ }+}++// TestHermesLaunchArgvMatchesBackendAssembly is the root of the second-round+// Hermes finding: the daemon must resolve the profile from the argv the backend+// actually builds, not from a concatenation that leaves out `acp`.+//+// With fixed_args `--model` and custom_args `-p research`, the two disagree.+// `--model` is a value-taking flag, so the approximation `--model -p research`+// consumes `-p` as its value and finds no selection at all, while the real+// `--model acp -p research` skips `--model acp` and selects `research`. Seeding+// the overlay from the first answer while the process runs the second is a+// silent config mismatch.+func TestHermesLaunchArgvMatchesBackendAssembly(t *testing.T) {+ t.Parallel()++ prefix := []string{"--model"}+ custom := []string{"-p", "research"}++ argv := HermesLaunchArgv(prefix, custom, slog.Default())+ if want := []string{"--model", "acp", "-p", "research"}; strings.Join(argv, "\x00") != strings.Join(want, "\x00") {+ t.Fatalf("HermesLaunchArgv = %v, want %v", argv, want)+ }+ // It must equal what the backend hands the launch boundary.+ backend := Command{Prefix: prefix}.Argv(hermesCLIArgs(custom, slog.Default())...)+ if strings.Join(argv, "\x00") != strings.Join(backend, "\x00") {+ t.Fatalf("resolver argv %v diverges from backend argv %v", argv, backend)+ }+ sel := ParseHermesProfileArgs(argv)+ if !sel.Found || sel.Name != "research" {+ t.Fatalf("selection = %+v, want research — the profile the process really reads", sel)+ }+ // The approximation this replaced is what got it wrong.+ if naive := ParseHermesProfileArgs(append(append([]string{}, prefix...), custom...)); naive.Found {+ t.Fatalf("expected the prefix++custom approximation to disagree, got %+v", naive)+ }+}++// TestStripHermesProfileSelectorsSpansRegionBoundary: a launch prefix ending in+// a bare `-p` captures the backend's own `acp` token as its profile value.+// Neither region holds a complete selection, so stripping them separately+// leaves the selector live and the task walks out of the overlay.+func TestStripHermesProfileSelectorsSpansRegionBoundary(t *testing.T) {+ t.Parallel()++ prefix, custom := StripHermesProfileSelectors([]string{"-p"}, []string{"research", "--yolo"}, slog.Default())++ if sel := ParseHermesProfileArgs(Command{Prefix: prefix}.Argv(hermesCLIArgsFrom(custom)...)); sel.Found {+ t.Fatalf("launched argv still selects %q: prefix=%v custom=%v", sel.Name, prefix, custom)+ }+ if len(prefix) != 0 {+ t.Fatalf("the straddling `-p` must be removed from the prefix, got %v", prefix)+ }+ if strings.Join(custom, "\x00") != strings.Join([]string{"research", "--yolo"}, "\x00") {+ t.Fatalf("custom args must survive intact, got %v", custom)+ }+}++// TestStripHermesProfileSelectorsRemovesEveryOccurrence: hermes honours the+// first selection and ignores the rest, so removing one promotes the next.+// With prefix and custom args configured separately, several selections is+// ordinary configuration rather than a user mistake.+func TestStripHermesProfileSelectorsRemovesEveryOccurrence(t *testing.T) {+ t.Parallel()++ prefix, custom := StripHermesProfileSelectors(+ []string{"wrapper-sub", "-p", "research"},+ []string{"--profile=ops", "--model", "x", "-p", "third"},+ slog.Default())++ argv := Command{Prefix: prefix}.Argv(hermesCLIArgsFrom(custom)...)+ if sel := ParseHermesProfileArgs(argv); sel.Found {+ t.Fatalf("a selection survived: %+v in %v", sel, argv)+ }+ if strings.Join(prefix, "\x00") != "wrapper-sub" {+ t.Fatalf("prefix = %v, want the command identity kept and the selector gone", prefix)+ }+ if strings.Join(custom, "\x00") != strings.Join([]string{"--model", "x"}, "\x00") {+ t.Fatalf("custom = %v, want unrelated args kept", custom)+ }+}++// TestStripHermesProfileSelectorsLeavesInvalidSelectionAlone: a value hermes+// itself discards redirects nothing, so removing it would only mangle the+// user's argv.+func TestStripHermesProfileSelectorsLeavesInvalidSelectionAlone(t *testing.T) {+ t.Parallel()++ prefix, custom := StripHermesProfileSelectors(nil, []string{"-p", "NOT_A_PROFILE"}, slog.Default())+ if len(prefix) != 0 {+ t.Fatalf("prefix = %v, want empty", prefix)+ }+ if strings.Join(custom, "\x00") != strings.Join([]string{"-p", "NOT_A_PROFILE"}, "\x00") {+ t.Fatalf("custom = %v, want the discarded selection left untouched", custom)+ }+}++// TestCodexLaunchPrefixCannotOverrideExplicitFastMode is Elon's must-fix 3.+// `--disable fast_mode` beats `--enable fast_mode` regardless of argv order and+// `-c features.fast_mode=false` beats config.toml from any position, so being+// first does not make the prefix lose. Both spellings have to be removed.+func TestCodexLaunchPrefixCannotOverrideExplicitFastMode(t *testing.T) {+ t.Parallel()++ for _, prefix := range [][]string{+ {"proxy", "run", "--disable", "fast_mode"},+ {"proxy", "run", "--disable=fast_mode"},+ {"proxy", "run", "-c", "features.fast_mode=false"},+ } {+ t.Run(strings.Join(prefix, "_"), func(t *testing.T) {+ t.Parallel()+ got := stripCodexFastModeConflicts(prefix, slog.Default())+ want := []string{"proxy", "run"}+ if strings.Join(got, "\x00") != strings.Join(want, "\x00") {+ t.Fatalf("stripCodexFastModeConflicts(%v) = %v, want %v", prefix, got, want)+ }+ // The managed enable is appended once, by buildCodexArgs, not here.+ if prefixIndex(got, []string{"--enable"}) >= 0 {+ t.Fatalf("the strip helper must not append the managed enable: %v", got)+ }+ })+ }+}++// TestEnforceCodexFastModeStillAppendsEnableOnce guards the split: pulling the+// removal out of enforceCodexFastMode must not change what it produces.+func TestEnforceCodexFastModeStillAppendsEnableOnce(t *testing.T) {+ t.Parallel()++ got := enforceCodexFastMode([]string{"--disable", "fast_mode", "--model", "gpt-5"}, slog.Default())+ want := []string{"--model", "gpt-5", "--enable", "fast_mode"}+ if strings.Join(got, "\x00") != strings.Join(want, "\x00") {+ t.Fatalf("enforceCodexFastMode = %v, want %v", got, want)+ }+}diff --git a/server/pkg/agent/model_discovery_cache_key_test.go b/server/pkg/agent/model_discovery_cache_key_test.goindex 7b0a362093..f5a0a9cbf3 100644--- a/server/pkg/agent/model_discovery_cache_key_test.go+++ b/server/pkg/agent/model_discovery_cache_key_test.go@@ -6,11 +6,11 @@ import "testing"// keeps the bare provider key (what a built-in on PATH resolves to), and two// executables of the same protocol family never collapse onto one key.func TestDiscoveryCacheKeyScopesByExecutable(t *testing.T) {- if got, want := discoveryCacheKey("hermes", ""), "hermes"; got != want {+ if got, want := discoveryCacheKey("hermes", Command{}), "hermes"; got != want {t.Fatalf("discoveryCacheKey(hermes, \"\") = %q, want %q", got, want)}- builtin := discoveryCacheKey("hermes", "/usr/local/bin/hermes")- custom := discoveryCacheKey("hermes", "/usr/local/bin/jcode")+ builtin := discoveryCacheKey("hermes", Command{Path: "/usr/local/bin/hermes"})+ custom := discoveryCacheKey("hermes", Command{Path: "/usr/local/bin/jcode"})if builtin == custom {t.Fatalf("same key %q for two different executables", builtin)}@@ -27,8 +27,8 @@ func TestDiscoveryCacheKeyScopesByExecutable(t *testing.T) {// full TTL, reintroducing the catalog/binary mismatch the daemon-side fix// removes.func TestCachedDiscoveryDoesNotShareMemoAcrossExecutables(t *testing.T) {- builtinKey := discoveryCacheKey("hermes", "/usr/local/bin/hermes")- customKey := discoveryCacheKey("hermes", "/usr/local/bin/jcode")+ builtinKey := discoveryCacheKey("hermes", Command{Path: "/usr/local/bin/hermes"})+ customKey := discoveryCacheKey("hermes", Command{Path: "/usr/local/bin/jcode"})reset := func() {modelCacheMu.Lock()delete(modelCache, builtinKey)diff --git a/server/pkg/agent/models.go b/server/pkg/agent/models.goindex 309ce090bd..47871ced97 100644--- a/server/pkg/agent/models.go+++ b/server/pkg/agent/models.go@@ -128,9 +128,13 @@ const modelCacheTTL = 60 * time.Second// without a safe fallback leave Thinking nil, which makes the UI hide the// thinking picker.//-// executablePath lets the caller point at a non-default binary; pass-// "" to use the provider's default name on PATH.-func ListModels(ctx context.Context, providerType, executablePath string) (Catalog, error) {+// runtimeCmd lets the caller point at a non-default binary; pass the zero+// Command to use the provider's default name on PATH. Its launch prefix — a+// custom runtime profile's fixed_args — is carried into every discovery+// subprocess, so a wrapper that only reaches the real CLI through a+// subcommand (`ccms start q36`) is enumerated as the CLI it actually runs+// rather than as the wrapper (GH #7046).+func ListModels(ctx context.Context, providerType string, runtimeCmd Command) (Catalog, error) {// Built-in runtime identities (e.g. "omp") declare their model discovery// strategy in the descriptor. Resolve generically before the protocol-// family switch so no runtime-specific case is needed below. When the@@ -140,8 +144,8 @@ func ListModels(ctx context.Context, providerType, executablePath string) (Catal// degrading to manual entry.if desc, ok := BuiltinRuntimeByID(providerType); ok {if desc.ModelDiscovery != nil {- return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() (Catalog, error) {- return discovered(desc.ModelDiscovery(ctx, executablePath))+ return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {+ return discovered(desc.ModelDiscovery(ctx, runtimeCmd))})}return Catalog{Models: []Model{}}, nil@@ -149,82 +153,82 @@ func ListModels(ctx context.Context, providerType, executablePath string) (Catalswitch providerType {case "claude":models := claudeStaticModels()- annotateClaudeThinking(ctx, models, executablePath)+ annotateClaudeThinking(ctx, models, runtimeCmd)// Claude's catalog is static by design, not by failure: there is no// discovery step to fall back from, so this is authoritative.return Catalog{Models: models}, nilcase "codex":- return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() (Catalog, error) {- return discovered(discoverCodexModels(ctx, executablePath), nil)+ return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {+ return discovered(discoverCodexModels(ctx, runtimeCmd), nil)})case "antigravity":// agy 1.0.6 added a `--model` flag plus an `agy models` catalog// command (MUL-3125). Enumerate it on demand like the other// dynamic-discovery backends.- return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() (Catalog, error) {- return discovered(discoverAntigravityModels(ctx, executablePath))+ return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {+ return discovered(discoverAntigravityModels(ctx, runtimeCmd))})case "traecli":// Official TRAE CLI is ACP-native: it returns its model catalog from// session/new. Enumerate it on demand like the other ACP backends// (requires a logged-in traecli; falls back to manual entry on error).- return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() (Catalog, error) {- return discovered(discoverTraecliModels(ctx, executablePath))+ return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {+ return discovered(discoverTraecliModels(ctx, runtimeCmd))})case "cursor":- return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() (Catalog, error) {- return discoverCursorModels(ctx, executablePath)+ return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {+ return discoverCursorModels(ctx, runtimeCmd)})case "copilot":- return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() (Catalog, error) {- return discoverCopilotModels(ctx, executablePath)+ return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {+ return discoverCopilotModels(ctx, runtimeCmd)})case "hermes":- return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() (Catalog, error) {- return discovered(discoverHermesModels(ctx, executablePath))+ return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {+ return discovered(discoverHermesModels(ctx, runtimeCmd))})case "kimi":- return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() (Catalog, error) {- return discovered(discoverKimiModels(ctx, executablePath))+ return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {+ return discovered(discoverKimiModels(ctx, runtimeCmd))})case "reasonix":- return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() (Catalog, error) {- return discovered(discoverReasonixModels(ctx, executablePath))+ return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {+ return discovered(discoverReasonixModels(ctx, runtimeCmd))})case "dsh":- return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() (Catalog, error) {- return discovered(discoverDshModels(ctx, executablePath))+ return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {+ return discovered(discoverDshModels(ctx, runtimeCmd))})case "kiro":- return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() (Catalog, error) {- return discovered(discoverKiroModels(ctx, executablePath))+ return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {+ return discovered(discoverKiroModels(ctx, runtimeCmd))})case "qoder", "qoderclicn":- return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() (Catalog, error) {- return discovered(discoverQoderModels(ctx, executablePath, qoderDefaultBinary(providerType)))+ return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {+ return discovered(discoverQoderModels(ctx, runtimeCmd, qoderDefaultBinary(providerType)))})case "opencode":- return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() (Catalog, error) {- return discovered(discoverOpenCodeModels(ctx, executablePath))+ return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {+ return discovered(discoverOpenCodeModels(ctx, runtimeCmd))})case "deveco":- return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() (Catalog, error) {- return discovered(discoverDevecoModels(ctx, executablePath))+ return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {+ return discovered(discoverDevecoModels(ctx, runtimeCmd))})case "pi":- return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() (Catalog, error) {- return discovered(discoverPiModels(ctx, executablePath))+ return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {+ return discovered(discoverPiModels(ctx, runtimeCmd))})case "openclaw":- return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() (Catalog, error) {- return discovered(discoverOpenclawAgents(ctx, executablePath))+ return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {+ return discovered(discoverOpenclawAgents(ctx, runtimeCmd))})case "codebuddy":// discoverCodebuddyModels owns the thinking annotation too, so the one// `--help` capture feeds both catalogs. Annotating out here would run// the command a second time (MUL-5549).- return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() (Catalog, error) {- return discoverCodebuddyModels(ctx, executablePath)+ return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {+ return discoverCodebuddyModels(ctx, runtimeCmd)})case "qwen":// Qwen Code has no account-independent headless model catalog. An@@ -243,8 +247,8 @@ func ListModels(ctx context.Context, providerType, executablePath string) (Catal// xAI Grok Build is ACP-native (`grok agent stdio`); model catalog// comes from session/new. Falls back to a small static list so the// UI picker stays usable offline / unauthenticated.- return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() (Catalog, error) {- return discoverGrokModels(ctx, executablePath)+ return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {+ return discoverGrokModels(ctx, runtimeCmd)})default:return Catalog{}, fmt.Errorf("unknown agent type: %q", providerType)@@ -400,11 +404,15 @@ func cachedDiscovery(key string, fn func() (Catalog, error)) (Catalog, error) {// catalog for the TTL — the same mismatch the daemon's path resolution// fixes, reintroduced at the cache layer (MUL-5789). An empty path keeps// the bare provider key, which is what a built-in on PATH resolves to.-func discoveryCacheKey(providerType, executablePath string) string {- if executablePath == "" {+//+// The key spans the launch prefix too, not just the path: two profiles can+// wrap one binary with different fixed_args — `ccms start q36` and `ccms+// start opus` — and enumerate genuinely different catalogs out of it.+func discoveryCacheKey(providerType string, runtimeCmd Command) string {+ if runtimeCmd.Path == "" && len(runtimeCmd.Prefix) == 0 {return providerType}- return providerType + ":" + executablePath+ return providerType + ":" + runtimeCmd.cacheKey()}// ── Static catalogs ──@@ -488,8 +496,8 @@ func codexStaticModels() []Model {// and parses the model catalog traecli returns from session/new (same shape as// Kiro/Qoder). The official TRAE CLI must be logged in for the catalog to be// non-empty; on any failure the caller falls back to the manual-entry field.-func discoverTraecliModels(ctx context.Context, executablePath string) ([]Model, error) {- return discoverACPModels(ctx, executablePath, acpDiscoveryProvider{+func discoverTraecliModels(ctx context.Context, runtimeCmd Command) ([]Model, error) {+ return discoverACPModels(ctx, runtimeCmd, acpDiscoveryProvider{defaultBin: "traecli",clientName: "multica-model-discovery",tmpdirPrefix: "multica-traecli-discovery-",@@ -592,11 +600,11 @@ func isOpenAIReasoningSeriesID(id string) bool {// provider-specific reasoning-effort surface.// On any failure (CLI missing, parse error, timeout) we fall back to// an empty list so the creatable UI still works.-func discoverOpenCodeModels(ctx context.Context, executablePath string) ([]Model, error) {- if executablePath == "" {- executablePath = "opencode"+func discoverOpenCodeModels(ctx context.Context, runtimeCmd Command) ([]Model, error) {+ if runtimeCmd.Path == "" {+ runtimeCmd.Path = "opencode"}- if _, err := exec.LookPath(executablePath); err != nil {+ if _, err := exec.LookPath(runtimeCmd.Path); err != nil {return []Model{}, nil}// Newer opencode (1.15+) syncs its hosted free-model catalog over the@@ -605,7 +613,7 @@ func discoverOpenCodeModels(ctx context.Context, executablePath string) ([]Model// the model picker was empty. See multica-ai/multica#3627.runCtx, cancel := context.WithTimeout(ctx, 15*time.Second)defer cancel()- cmd := exec.CommandContext(runCtx, executablePath, "models", "--verbose")+ cmd := runtimeCmd.exec(runCtx, "models", "--verbose")hideAgentWindow(cmd)// Parse whatever the verbose command printed, even on a non-zero exit — a// stale config entry can make `opencode models` exit non-zero while still@@ -616,7 +624,7 @@ func discoverOpenCodeModels(ctx context.Context, executablePath string) ([]Model// Verbose yielded nothing usable (unsupported flag, error text, or an// empty list). Retry the plain command, which omits the per-model JSON// but still prints the IDs.- cmd = exec.CommandContext(runCtx, executablePath, "models")+ cmd = runtimeCmd.exec(runCtx, "models")hideAgentWindow(cmd)out, _ = cmd.Output()models = parseOpenCodeModels(string(out))@@ -845,15 +853,15 @@ type piRPCResponse struct {// human-readable `--list-models` table reduces to a yes/no column. Older Pi// versions and pi-family forks may not implement RPC, so discovery falls back// to the existing table parser without advertising a guessed thinking catalog.-func discoverPiModels(ctx context.Context, executablePath string) ([]Model, error) {- return discoverPiModelsWithin(ctx, executablePath, piRPCDiscoveryTimeout, piTableDiscoveryTimeout)+func discoverPiModels(ctx context.Context, runtimeCmd Command) ([]Model, error) {+ return discoverPiModelsWithin(ctx, runtimeCmd, piRPCDiscoveryTimeout, piTableDiscoveryTimeout)}-func discoverPiModelsWithin(ctx context.Context, executablePath string, rpcTimeout, tableTimeout time.Duration) ([]Model, error) {- if executablePath == "" {- executablePath = "pi"+func discoverPiModelsWithin(ctx context.Context, runtimeCmd Command, rpcTimeout, tableTimeout time.Duration) ([]Model, error) {+ if runtimeCmd.Path == "" {+ runtimeCmd.Path = "pi"}- lookedUp, err := exec.LookPath(executablePath)+ lookedUp, err := exec.LookPath(runtimeCmd.Path)if err != nil {return []Model{}, nil}@@ -861,7 +869,7 @@ func discoverPiModelsWithin(ctx context.Context, executablePath string, rpcTimeo// accepts the mode but never answers cannot starve the compatibility table// fallback. Both phase contexts still inherit caller cancellation.rpcCtx, rpcCancel := context.WithTimeout(ctx, rpcTimeout)- models, ok := discoverPiModelsRPC(rpcCtx, executablePath, lookedUp)+ models, ok := discoverPiModelsRPC(rpcCtx, runtimeCmd, lookedUp)rpcCancel()if ok {return models, nil@@ -869,14 +877,14 @@ func discoverPiModelsWithin(ctx context.Context, executablePath string, rpcTimeotableCtx, tableCancel := context.WithTimeout(ctx, tableTimeout)defer tableCancel()- return discoverPiModelsTable(tableCtx, executablePath)+ return discoverPiModelsTable(tableCtx, runtimeCmd)}// discoverPiModelsRPC starts a short-lived Pi RPC session and requests both// the available models and current state. The state identifies the model Pi// will choose when Multica omits --model; its thinking level is the runtime's// effective default for that selected model.-func discoverPiModelsRPC(ctx context.Context, executablePath, lookedUp string) ([]Model, bool) {+func discoverPiModelsRPC(ctx context.Context, runtimeCmd Command, lookedUp string) ([]Model, bool) {args := []string{"--mode", "rpc","--no-session",@@ -887,8 +895,7 @@ func discoverPiModelsRPC(ctx context.Context, executablePath, lookedUp string) ("--no-prompt-templates","--no-context-files",}- argv0, cmdArgs := choosePiInvocation(executablePath, lookedUp, args, slog.Default())- cmd := exec.CommandContext(ctx, argv0, cmdArgs...)+ cmd, _, _ := runtimeCmd.execVia(ctx, choosePiInvocation, lookedUp, args, slog.Default())hideAgentWindow(cmd)cmd.WaitDelay = time.Secondcmd.Stderr = io.Discard@@ -1044,7 +1051,7 @@ func piThinkingSupports(thinking *ModelThinking, value string) bool {// Older pi versions print the list to stderr; newer versions use stdout. We// capture both and parse whichever is non-empty. The fallback intentionally// leaves Thinking nil because the table exposes only a yes/no capability bit.-func discoverPiModelsTable(ctx context.Context, executablePath string) ([]Model, error) {+func discoverPiModelsTable(ctx context.Context, runtimeCmd Command) ([]Model, error) {// Newer pi fetches its catalog from each configured provider over the// network, so discovery time scales with provider count — a multi-provider// setup measured ~4.6-4.8s, right at the old 5s cap. When jitter pushed it@@ -1053,7 +1060,7 @@ func discoverPiModelsTable(ctx context.Context, executablePath string) ([]Model,// the opencode discovery cap (see #3729, same class as #3627).runCtx, cancel := context.WithTimeout(ctx, 15*time.Second)defer cancel()- cmd := exec.CommandContext(runCtx, executablePath, "--list-models")+ cmd := runtimeCmd.exec(runCtx, "--list-models")hideAgentWindow(cmd)var stderr strings.Buildercmd.Stderr = &stderr@@ -1178,16 +1185,16 @@ func isPiDiscoveryNoise(line string) bool {// An empty catalog (an omp with no provider credentials configured prints// `{"models":[]}`) or a non-zero exit (binary missing, omp too old) falls back// to an empty list so the UI degrades to manual entry instead of erroring.-func discoverOmpModels(ctx context.Context, executablePath string) ([]Model, error) {- if executablePath == "" {- executablePath = "omp"+func discoverOmpModels(ctx context.Context, runtimeCmd Command) ([]Model, error) {+ if runtimeCmd.Path == "" {+ runtimeCmd.Path = "omp"}- if _, err := exec.LookPath(executablePath); err != nil {+ if _, err := exec.LookPath(runtimeCmd.Path); err != nil {return []Model{}, nil}runCtx, cancel := context.WithTimeout(ctx, 15*time.Second)defer cancel()- cmd := exec.CommandContext(runCtx, executablePath, "models", "--json")+ cmd := runtimeCmd.exec(runCtx, "models", "--json")hideAgentWindow(cmd)stdout, err := cmd.Output()if err != nil || len(stdout) == 0 {@@ -1262,8 +1269,8 @@ func parseOmpModels(data []byte) ([]Model, error) {// Failure modes (hermes missing, no credentials, config resolution// error) all return an empty list so the UI falls back to the// creatable manual-entry input instead of blocking the form.-func discoverHermesModels(ctx context.Context, executablePath string) ([]Model, error) {- return discoverACPModels(ctx, executablePath, acpDiscoveryProvider{+func discoverHermesModels(ctx context.Context, runtimeCmd Command) ([]Model, error) {+ return discoverACPModels(ctx, runtimeCmd, acpDiscoveryProvider{defaultBin: "hermes",clientName: "multica-model-discovery",extraEnv: []string{"HERMES_YOLO_MODE=1"},@@ -1314,9 +1321,9 @@ func discoverHermesModels(ctx context.Context, executablePath string) ([]Model,//// Failure modes (kimi missing, not logged in, config error) return an empty// list so the UI falls back to manual entry.-func discoverKimiModels(ctx context.Context, executablePath string) ([]Model, error) {+func discoverKimiModels(ctx context.Context, runtimeCmd Command) ([]Model, error) {var acpVersion string- models, err := discoverACPModels(ctx, executablePath, acpDiscoveryProvider{+ models, err := discoverACPModels(ctx, runtimeCmd, acpDiscoveryProvider{defaultBin: "kimi",clientName: "multica-model-discovery",tmpdirPrefix: "multica-kimi-discovery-",@@ -1338,7 +1345,7 @@ func discoverKimiModels(ctx context.Context, executablePath string) ([]Model, erreturn models, nil}- perModel, err := discoverKimiProviderThinking(ctx, executablePath)+ perModel, err := discoverKimiProviderThinking(ctx, runtimeCmd)if err != nil {// Do not include err or command output here: provider JSON can contain// credentials. The fixed reason explains why thinking controls are hidden@@ -1403,14 +1410,14 @@ func acpAgentInfoVersion(raw json.RawMessage) string {return strings.TrimSpace(response.AgentInfoSnake.Version)}-func discoverKimiProviderThinking(ctx context.Context, executablePath string) (map[string]*ModelThinking, error) {- if executablePath == "" {- executablePath = "kimi"+func discoverKimiProviderThinking(ctx context.Context, runtimeCmd Command) (map[string]*ModelThinking, error) {+ if runtimeCmd.Path == "" {+ runtimeCmd.Path = "kimi"}runCtx, cancel := context.WithTimeout(ctx, 15*time.Second)defer cancel()- cmd := exec.CommandContext(runCtx, executablePath, "provider", "list", "--json")+ cmd := runtimeCmd.exec(runCtx, "provider", "list", "--json")hideAgentWindow(cmd)cmd.Stderr = io.Discardraw, err := cmd.Output()@@ -1548,8 +1555,8 @@ func acpConfigOptionCurrentValue(raw json.RawMessage, configID string) (string,// describes that model alone. Every other model keeps a nil Thinking and shows// no picker until per-model probing exists. See// annotateACPThinkingForSessionModel.-func discoverReasonixModels(ctx context.Context, executablePath string) ([]Model, error) {- return discoverACPModels(ctx, executablePath, acpDiscoveryProvider{+func discoverReasonixModels(ctx context.Context, runtimeCmd Command) ([]Model, error) {+ return discoverACPModels(ctx, runtimeCmd, acpDiscoveryProvider{defaultBin: "reasonix",clientName: "multica-model-discovery",acpArgs: reasonixACPLaunchArgs(),@@ -1561,8 +1568,8 @@ func discoverReasonixModels(ctx context.Context, executablePath string) ([]Model// discoverKiroModels spins up a throwaway `kiro-cli acp` process and parses// the models block Kiro returns from session/new.-func discoverKiroModels(ctx context.Context, executablePath string) ([]Model, error) {- return discoverACPModels(ctx, executablePath, acpDiscoveryProvider{+func discoverKiroModels(ctx context.Context, runtimeCmd Command) ([]Model, error) {+ return discoverACPModels(ctx, runtimeCmd, acpDiscoveryProvider{defaultBin: "kiro-cli",clientName: "multica-model-discovery",tmpdirPrefix: "multica-kiro-discovery-",@@ -1588,8 +1595,8 @@ func discoverKiroModels(ctx context.Context, executablePath string) ([]Model, er// drives `initialize` + `session/new`, neither of which triggers// a tool-permission prompt — the model catalog is part of the// session/new response itself.-func discoverCopilotModels(ctx context.Context, executablePath string) (Catalog, error) {- models, err := discoverACPModels(ctx, executablePath, acpDiscoveryProvider{+func discoverCopilotModels(ctx context.Context, runtimeCmd Command) (Catalog, error) {+ models, err := discoverACPModels(ctx, runtimeCmd, acpDiscoveryProvider{defaultBin: "copilot",clientName: "multica-model-discovery",tmpdirPrefix: "multica-copilot-discovery-",@@ -1608,8 +1615,8 @@ func discoverCopilotModels(ctx context.Context, executablePath string) (Catalog,// discoverQoderModels spins up a Qoder CLI binary with `--yolo --acp` and// parses models from session/new.-func discoverQoderModels(ctx context.Context, executablePath, defaultBin string) ([]Model, error) {- return discoverACPModels(ctx, executablePath, acpDiscoveryProvider{+func discoverQoderModels(ctx context.Context, runtimeCmd Command, defaultBin string) ([]Model, error) {+ return discoverACPModels(ctx, runtimeCmd, acpDiscoveryProvider{defaultBin: defaultBin,clientName: "multica-model-discovery",acpArgs: []string{"--yolo", "--acp"},@@ -1663,17 +1670,17 @@ type acpDiscoveryProvider struct {// `models.availableModels` / `models.currentModelId`, or under the// newer `configOptions` list. Provider-specific `launchArgs` select// ACP mode (e.g. `acp` vs `--acp`).-func discoverACPModels(ctx context.Context, executablePath string, p acpDiscoveryProvider) ([]Model, error) {+func discoverACPModels(ctx context.Context, runtimeCmd Command, p acpDiscoveryProvider) ([]Model, error) {fail := func(stage string, err error) ([]Model, error) {if p.strictErrors {return nil, fmt.Errorf("ACP model discovery %s failed: %w", stage, err)}return []Model{}, nil}- if executablePath == "" {- executablePath = p.defaultBin+ if runtimeCmd.Path == "" {+ runtimeCmd.Path = p.defaultBin}- if _, err := exec.LookPath(executablePath); err != nil {+ if _, err := exec.LookPath(runtimeCmd.Path); err != nil {return fail("executable lookup", err)}runCtx, cancel := context.WithTimeout(ctx, 15*time.Second)@@ -1692,7 +1699,7 @@ func discoverACPModels(ctx context.Context, executablePath string, p acpDiscoverif len(cmdArgs) == 0 {cmdArgs = []string{"acp"}}- cmd := exec.CommandContext(runCtx, executablePath, cmdArgs...)+ cmd := runtimeCmd.exec(runCtx, cmdArgs...)hideAgentWindow(cmd)childEnv := append(os.Environ(), p.extraEnv...)if isolatedStateDir != "" {@@ -1836,7 +1843,7 @@ func discoverACPModels(ctx context.Context, executablePath string, p acpDiscover// really has no models". Log the top-level keys only — never the// response body, which carries session ids and account-shaped data.slog.Debug("ACP model discovery found no models in session/new response",- "binary", executablePath,+ "binary", runtimeCmd.Path,"result_keys", strings.Join(acpResultTopLevelKeys(sessionResult), ","),)}@@ -2065,18 +2072,18 @@ func acpModelLabel(name, modelID string) string {// catalog instead; agent.model stays unset and agy resolves its own// default. cachedDiscovery never caches empty results, so this retries on// the next request once the cause clears.-func discoverAntigravityModels(ctx context.Context, executablePath string) ([]Model, error) {- if executablePath == "" {- executablePath = "agy"+func discoverAntigravityModels(ctx context.Context, runtimeCmd Command) ([]Model, error) {+ if runtimeCmd.Path == "" {+ runtimeCmd.Path = "agy"}- if _, err := exec.LookPath(executablePath); err != nil {+ if _, err := exec.LookPath(runtimeCmd.Path); err != nil {return nil, nil}// `agy models` is a local enumeration (no network round-trip), so a// short cap is plenty; keep it generous enough to absorb cold starts.runCtx, cancel := context.WithTimeout(ctx, 10*time.Second)defer cancel()- cmd := exec.CommandContext(runCtx, executablePath, "models")+ cmd := runtimeCmd.exec(runCtx, "models")hideAgentWindow(cmd)out, err := cmd.Output()if err != nil && len(out) == 0 {@@ -2112,11 +2119,11 @@ func parseAntigravityModels(output string) []Model {// discoverGrokModels spins up `grok agent --always-approve stdio` and parses// the model catalog from session/new (same shape as Kiro/Qoder/Trae). Requires// an authenticated Grok CLI; on any failure falls back to grokStaticModels.-func discoverGrokModels(ctx context.Context, executablePath string) (Catalog, error) {+func discoverGrokModels(ctx context.Context, runtimeCmd Command) (Catalog, error) {// Match the daemon's runtime launch: `--no-auto-update` (global) so a// background update check can't stall discovery. Auth is selected only// after initialize returns the methods this installed CLI actually offers.- models, err := discoverACPModels(ctx, executablePath, acpDiscoveryProvider{+ models, err := discoverACPModels(ctx, runtimeCmd, acpDiscoveryProvider{defaultBin: "grok",clientName: "multica-model-discovery",tmpdirPrefix: "multica-grok-discovery-",@@ -2175,11 +2182,11 @@ func annotateGrokThinking(models []Model) {// suffixes) — static baking would be obsolete within weeks. On any// failure we fall back to the minimal static catalog so the UI// stays usable when cursor-agent isn't installed on the daemon host.-func discoverCursorModels(ctx context.Context, executablePath string) (Catalog, error) {- if executablePath == "" {- executablePath = "cursor-agent"+func discoverCursorModels(ctx context.Context, runtimeCmd Command) (Catalog, error) {+ if runtimeCmd.Path == "" {+ runtimeCmd.Path = "cursor-agent"}- if _, err := exec.LookPath(executablePath); err != nil {+ if _, err := exec.LookPath(runtimeCmd.Path); err != nil {return Catalog{Models: cursorStaticModels(), Fallback: true}, nil}// 15s to match the other network-backed discovery paths (pi/opencode/ACP);@@ -2187,7 +2194,7 @@ func discoverCursorModels(ctx context.Context, executablePath string) (Catalog,// time out and fall back to the minimal static list. See #3729.runCtx, cancel := context.WithTimeout(ctx, 15*time.Second)defer cancel()- cmd := exec.CommandContext(runCtx, executablePath, "--list-models")+ cmd := runtimeCmd.exec(runCtx, "--list-models")hideAgentWindow(cmd)out, err := cmd.Output()if err != nil && len(out) == 0 {@@ -2267,11 +2274,11 @@ func parseCursorModels(output string) []Model {// headers. On any ambiguity we return an empty list and let the// creatable dropdown handle manual entry — a silently-wrong// enumeration would be worse than none.-func discoverOpenclawAgents(ctx context.Context, executablePath string) ([]Model, error) {- if executablePath == "" {- executablePath = "openclaw"+func discoverOpenclawAgents(ctx context.Context, runtimeCmd Command) ([]Model, error) {+ if runtimeCmd.Path == "" {+ runtimeCmd.Path = "openclaw"}- if _, err := exec.LookPath(executablePath); err != nil {+ if _, err := exec.LookPath(runtimeCmd.Path); err != nil {return []Model{}, nil}runCtx, cancel := context.WithTimeout(ctx, 30*time.Second)@@ -2284,7 +2291,7 @@ func discoverOpenclawAgents(ctx context.Context, executablePath string) ([]Model{"agents", "list", "--output", "json"},{"agents", "list", "-o", "json"},} {- cmd := exec.CommandContext(runCtx, executablePath, jsonArgs...)+ cmd := runtimeCmd.exec(runCtx, jsonArgs...)hideAgentWindow(cmd)out, err := cmd.Output()if err != nil && len(out) == 0 {@@ -2298,7 +2305,7 @@ func discoverOpenclawAgents(ctx context.Context, executablePath string) ([]Model// Text fallback. Be strict — the default output is a decorated// banner with box-drawing and section headers, and picking up// the wrong tokens produces nonsense entries like "Identity:".- cmd := exec.CommandContext(runCtx, executablePath, "agents", "list")+ cmd := runtimeCmd.exec(runCtx, "agents", "list")hideAgentWindow(cmd)out, err := cmd.Output()if err != nil && len(out) == 0 {@@ -2462,8 +2469,8 @@ func isOpenclawIdentifier(s string) bool {// Falls back to the static catalog (marked Fallback, so it can never be cached// as authoritative) when the handshake fails — including the not-logged-in case,// where session/new may legitimately refuse.-func discoverCodebuddyModels(ctx context.Context, executablePath string) (Catalog, error) {- models, err := discoverACPModels(ctx, executablePath, acpDiscoveryProvider{+func discoverCodebuddyModels(ctx context.Context, runtimeCmd Command) (Catalog, error) {+ models, err := discoverACPModels(ctx, runtimeCmd, acpDiscoveryProvider{defaultBin: "codebuddy",clientName: "multica-model-discovery",tmpdirPrefix: "multica-codebuddy-discovery-",diff --git a/server/pkg/agent/models_test.go b/server/pkg/agent/models_test.goindex d090b4dbbf..4b69cc4798 100644--- a/server/pkg/agent/models_test.go+++ b/server/pkg/agent/models_test.go@@ -36,7 +36,7 @@ func TestStaticModelCatalogsHaveValidEntries(t *testing.T) {func TestListModelsQwenUsesRuntimeDefaultAndManualEntry(t *testing.T) {// Qwen returns its manual-entry catalog without resolving or executing a CLI.- got, err := ListModels(context.Background(), "qwen", "")+ got, err := ListModels(context.Background(), "qwen", Command{Path: ""})if err != nil {t.Fatalf("ListModels(qwen) error: %v", err)}@@ -59,7 +59,7 @@ func TestListModelsCopilotFallsBackToStatic(t *testing.T) {delete(modelCache, "copilot")modelCacheMu.Unlock()- got, err := ListModels(ctx, "copilot", missingAgentExecutable(t, "copilot"))+ got, err := ListModels(ctx, "copilot", Command{Path: missingAgentExecutable(t, "copilot")})if err != nil {t.Fatalf("ListModels(copilot) error: %v", err)}@@ -178,7 +178,7 @@ donefake := filepath.Join(t.TempDir(), "kimi")writeTestExecutable(t, fake, []byte(script))- models, err := discoverKimiModels(context.Background(), fake)+ models, err := discoverKimiModels(context.Background(), Command{Path: fake})if err != nil {t.Fatalf("discoverKimiModels: %v", err)}@@ -197,18 +197,18 @@ done}}- valid, err := ValidateThinkingLevel(context.Background(), "kimi", fake, "kimi-code/k3", "high")+ valid, err := ValidateThinkingLevel(context.Background(), "kimi", Command{Path: fake}, "kimi-code/k3", "high")if err != nil || !valid {t.Errorf("ValidateThinkingLevel(k3, high) = (%v, %v), want (true, nil)", valid, err)}// Unsupported persisted values are ordinary catalog results, not discovery// errors. The daemon logs a warning, ignores the value, and starts the task// with the runtime's own setting, just as it does for other providers.- valid, err = ValidateThinkingLevel(context.Background(), "kimi", fake, "kimi-code/k3", "medium")+ valid, err = ValidateThinkingLevel(context.Background(), "kimi", Command{Path: fake}, "kimi-code/k3", "medium")if err != nil || valid {t.Errorf("ValidateThinkingLevel(k3, medium) = (%v, %v), want unsupported without an error", valid, err)}- valid, err = ValidateThinkingLevel(context.Background(), "kimi", fake, "kimi-code/kimi-for-coding", "high")+ valid, err = ValidateThinkingLevel(context.Background(), "kimi", Command{Path: fake}, "kimi-code/kimi-for-coding", "high")if err != nil || valid {t.Errorf("ValidateThinkingLevel(kimi-for-coding, high) = (%v, %v), want unsupported without an error", valid, err)}@@ -239,7 +239,7 @@ donefake := filepath.Join(t.TempDir(), "kimi")writeTestExecutable(t, fake, []byte(script))- models, err := discoverKimiModels(context.Background(), fake)+ models, err := discoverKimiModels(context.Background(), Command{Path: fake})if err != nil {t.Fatalf("discoverKimiModels: %v", err)}@@ -280,7 +280,7 @@ donefake := filepath.Join(t.TempDir(), "kimi")writeTestExecutable(t, fake, []byte(script))- models, err := discoverKimiModels(context.Background(), fake)+ models, err := discoverKimiModels(context.Background(), Command{Path: fake})if err != nil {t.Fatalf("discoverKimiModels: %v", err)}@@ -324,7 +324,7 @@ donefake := filepath.Join(t.TempDir(), "kimi")writeTestExecutable(t, fake, []byte(script))- models, err := discoverKimiModels(context.Background(), fake)+ models, err := discoverKimiModels(context.Background(), Command{Path: fake})if err != nil {t.Fatalf("discoverKimiModels: %v", err)}@@ -388,7 +388,7 @@ donefake := filepath.Join(t.TempDir(), "kimi")writeTestExecutable(t, fake, []byte(strings.Replace(script, "VERSION", tt.version, 1)))- models, err := discoverKimiModels(context.Background(), fake)+ models, err := discoverKimiModels(context.Background(), Command{Path: fake})if err != nil {t.Fatalf("discoverKimiModels: %v", err)}@@ -795,7 +795,7 @@ func TestListModelsHermesWithoutBinary(t *testing.T) {delete(modelCache, "hermes")modelCacheMu.Unlock()- got, err := ListModels(ctx, "hermes", missingAgentExecutable(t, "hermes"))+ got, err := ListModels(ctx, "hermes", Command{Path: missingAgentExecutable(t, "hermes")})if err != nil {t.Fatalf("ListModels(hermes) error: %v", err)}@@ -810,7 +810,7 @@ func TestListModelsKiroWithoutBinary(t *testing.T) {delete(modelCache, "kiro")modelCacheMu.Unlock()- got, err := ListModels(ctx, "kiro", missingAgentExecutable(t, "kiro-cli"))+ got, err := ListModels(ctx, "kiro", Command{Path: missingAgentExecutable(t, "kiro-cli")})if err != nil {t.Fatalf("ListModels(kiro) error: %v", err)}@@ -825,7 +825,7 @@ func TestListModelsQoderWithoutBinary(t *testing.T) {delete(modelCache, "qoder")modelCacheMu.Unlock()- got, err := ListModels(ctx, "qoder", missingAgentExecutable(t, "qodercli"))+ got, err := ListModels(ctx, "qoder", Command{Path: missingAgentExecutable(t, "qodercli")})if err != nil {t.Fatalf("ListModels(qoder) error: %v", err)}@@ -840,7 +840,7 @@ func TestListModelsQoderCNWithoutBinary(t *testing.T) {delete(modelCache, "qoderclicn")modelCacheMu.Unlock()- got, err := ListModels(ctx, "qoderclicn", missingAgentExecutable(t, "qoderclicn"))+ got, err := ListModels(ctx, "qoderclicn", Command{Path: missingAgentExecutable(t, "qoderclicn")})if err != nil {t.Fatalf("ListModels(qoderclicn) error: %v", err)}@@ -851,7 +851,7 @@ func TestListModelsQoderCNWithoutBinary(t *testing.T) {func TestListModelsUnknownProvider(t *testing.T) {ctx := context.Background()- _, err := ListModels(ctx, "nonexistent", "")+ _, err := ListModels(ctx, "nonexistent", Command{Path: ""})if err == nil {t.Fatal("ListModels(unknown) expected error")}@@ -1007,7 +1007,7 @@ exit 1`writeTestExecutable(t, fake, []byte(script))- models, err := discoverOpenCodeModels(context.Background(), fake)+ models, err := discoverOpenCodeModels(context.Background(), Command{Path: fake})if err != nil {t.Fatalf("discoverOpenCodeModels: %v", err)}@@ -1094,7 +1094,7 @@ func TestDiscoverPiModelsRPCThinkingCatalog(t *testing.T) {}fakePath := writeFakePiRPCModelsBinary(t)- models, err := discoverPiModels(context.Background(), fakePath)+ models, err := discoverPiModels(context.Background(), Command{Path: fakePath})if err != nil {t.Fatalf("discoverPiModels: %v", err)}@@ -1155,7 +1155,7 @@ printf '%s\n' 'fallback fallback-model 128K 8K yes no'ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)defer cancel()- models, err := discoverPiModels(ctx, fakePath)+ models, err := discoverPiModels(ctx, Command{Path: fakePath})if err != nil {t.Fatalf("discoverPiModels: %v", err)}@@ -1182,7 +1182,7 @@ printf '%s\n' 'fallback fallback-model 128K 8K yes no'writeTestExecutable(t, fakePath, []byte(script))started := time.Now()- models, err := discoverPiModelsWithin(context.Background(), fakePath, 100*time.Millisecond, time.Second)+ models, err := discoverPiModelsWithin(context.Background(), Command{Path: fakePath}, 100*time.Millisecond, time.Second)elapsed := time.Since(started)if err != nil {t.Fatalf("discoverPiModels: %v", err)@@ -1330,7 +1330,7 @@ func TestDiscoverPiModelsNonZeroExit(t *testing.T) {fakePath := filepath.Join(t.TempDir(), "pi")writeTestExecutable(t, fakePath, []byte(tc.script))- models, err := discoverPiModels(context.Background(), fakePath)+ models, err := discoverPiModels(context.Background(), Command{Path: fakePath})if err != nil {t.Fatalf("discoverPiModels: %v", err)}@@ -1368,7 +1368,7 @@ func TestDiscoverOpenCodeModelsFallsBackOnVerboseNoise(t *testing.T) {fakePath := filepath.Join(t.TempDir(), "opencode")writeTestExecutable(t, fakePath, []byte(script))- models, err := discoverOpenCodeModels(context.Background(), fakePath)+ models, err := discoverOpenCodeModels(context.Background(), Command{Path: fakePath})if err != nil {t.Fatalf("discoverOpenCodeModels: %v", err)}diff --git a/server/pkg/agent/omp_test.go b/server/pkg/agent/omp_test.goindex 7dce618f64..37fd944c45 100644--- a/server/pkg/agent/omp_test.go+++ b/server/pkg/agent/omp_test.go@@ -391,7 +391,7 @@ func TestDiscoverOmpModelsNonZeroExit(t *testing.T) {ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()- models, err := discoverOmpModels(ctx, fakePath)+ models, err := discoverOmpModels(ctx, Command{Path: fakePath})if err != nil {t.Fatalf("discoverOmpModels: %v", err)}@@ -405,7 +405,7 @@ func TestDiscoverOmpModelsNonZeroExit(t *testing.T) {func TestDiscoverOmpModelsMissingBinary(t *testing.T) {ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)defer cancel()- models, err := discoverOmpModels(ctx, "/nonexistent/omp-binary")+ models, err := discoverOmpModels(ctx, Command{Path: "/nonexistent/omp-binary"})if err != nil {t.Fatalf("discoverOmpModels: %v", err)}diff --git a/server/pkg/agent/openclaw.go b/server/pkg/agent/openclaw.goindex 81a4e00047..a7688a3640 100644--- a/server/pkg/agent/openclaw.go+++ b/server/pkg/agent/openclaw.go@@ -61,7 +61,7 @@ func (b *openclawBackend) Execute(ctx context.Context, prompt string, opts ExecOreturn nil, fmt.Errorf("openclaw executable not found at %q: %w", execPath, err)}- if err := checkOpenclawVersion(ctx, execPath); err != nil {+ if err := checkOpenclawVersion(ctx, b.cfg.commandAt(execPath)); err != nil {return nil, err}@@ -74,7 +74,7 @@ func (b *openclawBackend) Execute(ctx context.Context, prompt string, opts ExecO}args := buildOpenclawArgs(prompt, sessionID, opts, b.cfg.Logger)- cmd := exec.CommandContext(runCtx, execPath, args...)+ cmd := b.cfg.commandAt(execPath).exec(runCtx, args...)hideAgentWindow(cmd)b.cfg.Logger.Info("agent command", "exec", execPath, "args", args)// 500ms, matching cursor-agent — the other backend whose CLI can deliver a@@ -286,8 +286,8 @@ func customArgsContains(args []string, flag string) bool {// minOpenclawVersion. The returned error becomes the task's failure// comment, so the message intentionally names the detected version// and the upgrade command.-func checkOpenclawVersion(ctx context.Context, execPath string) error {- cmd := exec.CommandContext(ctx, execPath, "--version")+func checkOpenclawVersion(ctx context.Context, runtimeCmd Command) error {+ cmd := runtimeCmd.exec(ctx, "--version")hideAgentWindow(cmd)out, err := cmd.CombinedOutput()if err != nil {diff --git a/server/pkg/agent/opencode.go b/server/pkg/agent/opencode.goindex d6aad25db4..ec2cf2a12a 100644--- a/server/pkg/agent/opencode.go+++ b/server/pkg/agent/opencode.go@@ -109,7 +109,7 @@ func (b *opencodeBackend) Execute(ctx context.Context, prompt string, opts ExecO// extension is too long" (#6538). Keeping the prompt off argv also stops it// from being echoed into the "agent command" log line below.- cmd := exec.CommandContext(runCtx, execPath, args...)+ cmd := b.cfg.commandAt(execPath).exec(runCtx, args...)hideAgentWindow(cmd)// Run opencode in its own process group so cancellation can reach the// whole tree (opencode plus any tool subprocess it spawns), not just thediff --git a/server/pkg/agent/pi.go b/server/pkg/agent/pi.goindex 7e3d88f589..3943e3ecda 100644--- a/server/pkg/agent/pi.go+++ b/server/pkg/agent/pi.go@@ -230,9 +230,7 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptionsrunCtx, cancel := runContext(ctx, timeout)args := buildPiArgs(sessionPath, opts, b.cfg.Logger)- argv0, cmdArgs := choosePiInvocation(execName, lookedUp, args, b.cfg.Logger)-- cmd := exec.CommandContext(runCtx, argv0, cmdArgs...)+ cmd, argv0, cmdArgs := b.cfg.commandAt(execName).execVia(runCtx, choosePiInvocation, lookedUp, args, b.cfg.Logger)hideAgentWindow(cmd)b.cfg.Logger.Info("agent command", "exec", argv0, "args", cmdArgs)cmd.WaitDelay = 10 * time.Seconddiff --git a/server/pkg/agent/qoder.go b/server/pkg/agent/qoder.goindex ee3dd56f7d..c9ddbede53 100644--- a/server/pkg/agent/qoder.go+++ b/server/pkg/agent/qoder.go@@ -101,7 +101,7 @@ func (b *qoderBackend) Execute(ctx context.Context, prompt string, opts ExecOpti[]string{"--yolo", "--acp"},filterCustomArgs(opts.CustomArgs, qoderBlockedArgs, b.cfg.Logger)...,)- cmd := exec.CommandContext(runCtx, execPath, qoderArgs...)+ cmd := b.cfg.commandAt(execPath).exec(runCtx, qoderArgs...)hideAgentWindow(cmd)b.cfg.Logger.Info("agent command", "exec", execPath, "args", qoderArgs)if opts.Cwd != "" {diff --git a/server/pkg/agent/qwen.go b/server/pkg/agent/qwen.goindex 963edc2e93..ba6b6c9860 100644--- a/server/pkg/agent/qwen.go+++ b/server/pkg/agent/qwen.go@@ -96,7 +96,7 @@ func (b *qwenBackend) Execute(ctx context.Context, prompt string, opts ExecOptiomcpFileCleanup()}}()- cmd := exec.CommandContext(runCtx, execPath, args...)+ cmd := b.cfg.commandAt(execPath).exec(runCtx, args...)hideAgentWindow(cmd)// args contain the task prompt; never expose it in daemon logs.b.cfg.Logger.Info("agent command", "exec", execPath, "provider", "qwen")diff --git a/server/pkg/agent/qwenpaw.go b/server/pkg/agent/qwenpaw.goindex 3abd484d0b..447202dcb0 100644--- a/server/pkg/agent/qwenpaw.go+++ b/server/pkg/agent/qwenpaw.go@@ -86,7 +86,7 @@ func (b *qwenpawBackend) Execute(ctx context.Context, prompt string, opts ExecOpqwenpawArgs = append(qwenpawArgs, "--workspace", opts.QwenpawWorkspace)}- cmd := exec.CommandContext(runCtx, execPath, qwenpawArgs...)+ cmd := b.cfg.commandAt(execPath).exec(runCtx, qwenpawArgs...)hideAgentWindow(cmd)b.cfg.Logger.Info("agent command", "exec", execPath, "args", qwenpawArgs)if opts.Cwd != "" {diff --git a/server/pkg/agent/qwenpaw_test.go b/server/pkg/agent/qwenpaw_test.goindex 24ea402bbe..95e9d89a7d 100644--- a/server/pkg/agent/qwenpaw_test.go+++ b/server/pkg/agent/qwenpaw_test.go@@ -220,7 +220,7 @@ func TestQwenpawListModels(t *testing.T) {marker := filepath.Join(dir, "invoked")bin := writeFakeQwenpawScript(t, "#!/bin/sh\ntouch '"+marker+"'\nexit 0\n")- cat, err := ListModels(context.Background(), "qwenpaw", bin)+ cat, err := ListModels(context.Background(), "qwenpaw", Command{Path: bin})if err != nil {t.Fatalf("qwenpaw ListModels should not error, got: %v", err)}diff --git a/server/pkg/agent/reasonix.go b/server/pkg/agent/reasonix.goindex 636cf2a17c..d5512fffcf 100644--- a/server/pkg/agent/reasonix.go+++ b/server/pkg/agent/reasonix.go@@ -85,7 +85,7 @@ func (b *reasonixBackend) Execute(ctx context.Context, prompt string, opts ExecO// narrows the generic auto-approval policy; --workspace-only independently// keeps configured extra write roots out of unattended tasks.reasonixArgs := append(reasonixACPLaunchArgs(), filterCustomArgs(opts.CustomArgs, reasonixBlockedArgs, b.cfg.Logger)...)- cmd := exec.CommandContext(runCtx, execPath, reasonixArgs...)+ cmd := b.cfg.commandAt(execPath).exec(runCtx, reasonixArgs...)hideAgentWindow(cmd)b.cfg.Logger.Info("agent command", "exec", execPath, "args", reasonixArgs)if opts.Cwd != "" {diff --git a/server/pkg/agent/reasonix_execute_unix_test.go b/server/pkg/agent/reasonix_execute_unix_test.goindex 9cc3a96d8e..7c1e3432eb 100644--- a/server/pkg/agent/reasonix_execute_unix_test.go+++ b/server/pkg/agent/reasonix_execute_unix_test.go@@ -362,7 +362,7 @@ donefakePath := filepath.Join(tempDir, "reasonix")writeTestExecutable(t, fakePath, []byte(script))- models, err := discoverReasonixModels(context.Background(), fakePath)+ models, err := discoverReasonixModels(context.Background(), Command{Path: fakePath})if err != nil {t.Fatalf("discoverReasonixModels: %v", err)}diff --git a/server/pkg/agent/thinking.go b/server/pkg/agent/thinking.goindex 00e7a44e3f..688f5c6ad0 100644--- a/server/pkg/agent/thinking.go+++ b/server/pkg/agent/thinking.go@@ -3,7 +3,6 @@ package agentimport ("context""encoding/json"- "os/exec""regexp""strings""sync"@@ -24,15 +23,19 @@ import (// ── Cache ────────────────────────────────────────────────────────────//-// Discovery is keyed on (provider, executablePath, cliVersion). Bumping+// Discovery is keyed on (provider, command, cliVersion). Bumping// the local CLI invalidates entries that referenced the older version's// help/`debug models` output, which is exactly the failure mode we hit// when Anthropic / OpenAI add or remove a level (Elon's review note).+//+// command is Command.cacheKey(), not a bare path: two custom runtime+// profiles can wrap one binary behind different launch prefixes and get+// different answers out of it.type thinkingCacheKey struct {- provider string- executablePath string- cliVersion string+ provider string+ command string+ cliVersion string}type thinkingCacheEntry struct {@@ -131,8 +134,8 @@ var claudeStaticEffortFullSuperset = []string{"low", "medium", "high", "xhigh",// through claudeModelEffortAllow. Errors are silently absorbed so a// missing CLI doesn't break model listing — the UI just hides the// picker for that model.-func annotateClaudeThinking(ctx context.Context, models []Model, executablePath string) {- mapping := loadClaudeThinkingByModel(ctx, executablePath)+func annotateClaudeThinking(ctx context.Context, models []Model, cmd Command) {+ mapping := loadClaudeThinkingByModel(ctx, cmd)for i := range models {if t, ok := mapping[models[i].ID]; ok && t != nil {models[i].Thinking = t@@ -140,17 +143,17 @@ func annotateClaudeThinking(ctx context.Context, models []Model, executablePath}}-func loadClaudeThinkingByModel(ctx context.Context, executablePath string) map[string]*ModelThinking {- if executablePath == "" {- executablePath = "claude"+func loadClaudeThinkingByModel(ctx context.Context, cmd Command) map[string]*ModelThinking {+ if cmd.Path == "" {+ cmd.Path = "claude"}- version, _ := DetectVersion(ctx, executablePath)- key := thinkingCacheKey{provider: "claude", executablePath: executablePath, cliVersion: version}+ version, _ := DetectVersion(ctx, cmd)+ key := thinkingCacheKey{provider: "claude", command: cmd.cacheKey(), cliVersion: version}if cached, ok := thinkingCacheGet(key); ok {return cached}- superset := claudeEffortSuperset(ctx, executablePath)+ superset := claudeEffortSuperset(ctx, cmd)result := map[string]*ModelThinking{}for _, m := range claudeStaticModels() {allow := claudeModelEffortAllow[m.ID]@@ -171,8 +174,8 @@ func loadClaudeThinkingByModel(ctx context.Context, executablePath string) map[s// the help output can't be captured at all it returns the static// fallback rather than nothing so callers can still render a usable// picker.-func claudeEffortSuperset(ctx context.Context, executablePath string) []string {- cmd := exec.CommandContext(ctx, executablePath, "--help")+func claudeEffortSuperset(ctx context.Context, runtimeCmd Command) []string {+ cmd := runtimeCmd.exec(ctx, "--help")hideAgentWindow(cmd)out, err := cmd.CombinedOutput()if err != nil {@@ -312,16 +315,16 @@ type codexDebugServiceTier struct {// catalog, including reasoning metadata. Version detection happens before the// debug command so old binaries do not log a predictable "unknown command"// failure on every cache refresh.-func discoverCodexModels(ctx context.Context, executablePath string) []Model {- if executablePath == "" {- executablePath = "codex"+func discoverCodexModels(ctx context.Context, cmd Command) []Model {+ if cmd.Path == "" {+ cmd.Path = "codex"}- version, err := DetectVersion(ctx, executablePath)+ version, err := DetectVersion(ctx, cmd)if err != nil || !codexSupportsDebugModels(version) {return codexStaticModels()}- raw, err := runCodexDebugModels(ctx, executablePath)+ raw, err := runCodexDebugModels(ctx, cmd)if err != nil {return codexStaticModels()}@@ -352,8 +355,8 @@ func codexSupportsDebugModels(version string) bool {// in thinking_test.go.var codexDebugModelsArgs = []string{"debug", "models", "--bundled"}-func runCodexDebugModels(ctx context.Context, executablePath string) ([]byte, error) {- cmd := exec.CommandContext(ctx, executablePath, codexDebugModelsArgs...)+func runCodexDebugModels(ctx context.Context, runtimeCmd Command) ([]byte, error) {+ cmd := runtimeCmd.exec(ctx, codexDebugModelsArgs...)hideAgentWindow(cmd)return cmd.Output()}@@ -616,7 +619,7 @@ func parseACPCodebuddyEffort(raw json.RawMessage) (levels []string, defaultLevel// map. The function is intentionally pure of HTTP concerns so the// daemon's pre-execution guard and the server's UpdateAgent gate can// share the same source of truth.-func ValidateThinkingLevel(ctx context.Context, providerType, executablePath, model, value string) (bool, error) {+func ValidateThinkingLevel(ctx context.Context, providerType string, cmd Command, model, value string) (bool, error) {if value == "" {return true, nil}@@ -627,7 +630,7 @@ func ValidateThinkingLevel(ctx context.Context, providerType, executablePath, moif model == "" && providerType == "codex" {return false, nil}- catalog, err := ListModels(ctx, providerType, executablePath)+ catalog, err := ListModels(ctx, providerType, cmd)if err != nil {return false, err}@@ -672,14 +675,14 @@ func ValidateThinkingLevel(ctx context.Context, providerType, executablePath, mo// Codex catalog for the explicit model. An empty value is always valid and// 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, executablePath, model, value string) (bool, error) {+func ValidateServiceTier(ctx context.Context, providerType string, cmd Command, model, value string) (bool, error) {if value == "" {return true, nil}if providerType != "codex" || model == "" {return false, nil}- catalog, err := ListModels(ctx, providerType, executablePath)+ catalog, err := ListModels(ctx, providerType, cmd)if err != nil {return false, err}diff --git a/server/pkg/agent/thinking_test.go b/server/pkg/agent/thinking_test.goindex d81f27eaad..8bb3399217 100644--- a/server/pkg/agent/thinking_test.go+++ b/server/pkg/agent/thinking_test.go@@ -179,7 +179,7 @@ func TestRunCodexDebugModels_ArgvSeenByBinary(t *testing.T) {// Linux ETXTBSY when we exec the file (Go #22315).writeTestExecutable(t, fake, []byte(script))- raw, err := runCodexDebugModels(context.Background(), fake)+ raw, err := runCodexDebugModels(context.Background(), Command{Path: fake})if err != nil {t.Fatalf("runCodexDebugModels: %v (output=%q)", err, raw)}@@ -345,7 +345,7 @@ echo '{"models":[{"slug":"runtime-model","display_name":"Runtime Model","visibil`writeTestExecutable(t, fake, []byte(script))- got := discoverCodexModels(context.Background(), fake)+ got := discoverCodexModels(context.Background(), Command{Path: fake})if len(got) != 1 || got[0].ID != "runtime-model" || got[0].Thinking == nil || !hasThinkingLevel(got[0].Thinking, "high") {t.Fatalf("expected runtime catalog, got %+v", got)}@@ -359,7 +359,7 @@ echo '{"models":[{"slug":"runtime-model","display_name":"Runtime Model","visibil"exit 99\n"writeTestExecutable(t, fake, []byte(script))- got := discoverCodexModels(context.Background(), fake)+ got := discoverCodexModels(context.Background(), Command{Path: fake})if len(got) == 0 || got[0].ID != "gpt-5.6-sol" {t.Fatalf("expected static fallback, got %+v", got)}@@ -373,7 +373,7 @@ echo '{"models":[{"slug":"runtime-model","display_name":"Runtime Model","visibil"exit 1\n"writeTestExecutable(t, fake, []byte(script))- got := discoverCodexModels(context.Background(), fake)+ got := discoverCodexModels(context.Background(), Command{Path: fake})if len(got) == 0 || got[0].ID != "gpt-5.6-sol" || got[0].Thinking == nil {t.Fatalf("expected model + thinking fallback, got %+v", got)}@@ -394,7 +394,7 @@ func TestValidateThinkingLevelCodexPerModelFallbackCatalog(t *testing.T) {{model: "gpt-5.3-codex", level: "xhigh", want: true},{model: "gpt-5.3-codex", level: "max", want: false},} {- got, err := ValidateThinkingLevel(context.Background(), "codex", "/nonexistent/codex", tc.model, tc.level)+ got, err := ValidateThinkingLevel(context.Background(), "codex", Command{Path: "/nonexistent/codex"}, tc.model, tc.level)if err != nil {t.Fatalf("ValidateThinkingLevel(%q, %q): %v", tc.model, tc.level, err)}@@ -618,12 +618,12 @@ func TestValidateThinkingLevel_PiRPCPerModelCatalog(t *testing.T) {check := func(model, value string, want bool) {t.Helper()- ok, err := ValidateThinkingLevel(ctx, "pi", fakePi, model, value)+ ok, err := ValidateThinkingLevel(ctx, "pi", Command{Path: fakePi}, model, value)if err != nil {- t.Fatalf("ValidateThinkingLevel(pi, %q, %q): %v", model, value, err)+ t.Fatalf("ValidateThinkingLevel(pi, %q, Command{Path: %q}): %v", model, value, err)}if ok != want {- t.Errorf("ValidateThinkingLevel(pi, %q, %q) = %v, want %v", model, value, ok, want)+ t.Errorf("ValidateThinkingLevel(pi, %q, Command{Path: %q}) = %v, want %v", model, value, ok, want)}}@@ -658,7 +658,7 @@ func TestValidateThinkingLevel_EmptyModelResolvesToDefault(t *testing.T) {// Claude's catalog flags Sonnet 4.6 as Default. Sonnet supports// low/medium/high/max (no xhigh) per claudeModelEffortAllow, so// "high" must round-trip when model is left empty.- ok, err := ValidateThinkingLevel(ctx, "claude", fakeClaude, "", "high")+ ok, err := ValidateThinkingLevel(ctx, "claude", Command{Path: fakeClaude}, "", "high")if err != nil {t.Fatalf("unexpected err: %v", err)}@@ -670,7 +670,7 @@ func TestValidateThinkingLevel_EmptyModelResolvesToDefault(t *testing.T) {t.Run("invalid level on default model fails", func(t *testing.T) {// "xhigh" is opus-only; resolving "" to default (sonnet 4.6)// should reject it, not silently accept.- ok, err := ValidateThinkingLevel(ctx, "claude", fakeClaude, "", "xhigh")+ ok, err := ValidateThinkingLevel(ctx, "claude", Command{Path: fakeClaude}, "", "xhigh")if err != nil {t.Fatalf("unexpected err: %v", err)}@@ -682,7 +682,7 @@ func TestValidateThinkingLevel_EmptyModelResolvesToDefault(t *testing.T) {t.Run("empty value always valid", func(t *testing.T) {// Empty value means "use runtime default" — should pass// regardless of model resolution.- ok, err := ValidateThinkingLevel(ctx, "claude", fakeClaude, "", "")+ ok, err := ValidateThinkingLevel(ctx, "claude", Command{Path: fakeClaude}, "", "")if err != nil {t.Fatalf("unexpected err: %v", err)}@@ -704,7 +704,7 @@ func TestValidateThinkingLevel_ExplicitModel(t *testing.T) {ctx := context.Background()// xhigh IS valid on Opus 4.7.- ok, err := ValidateThinkingLevel(ctx, "claude", fakeClaude, "claude-opus-4-7", "xhigh")+ ok, err := ValidateThinkingLevel(ctx, "claude", Command{Path: fakeClaude}, "claude-opus-4-7", "xhigh")if err != nil {t.Fatalf("unexpected err: %v", err)}@@ -716,7 +716,7 @@ func TestValidateThinkingLevel_ExplicitModel(t *testing.T) {// adding it to the catalog: an agent pinned to it can still carry a// persisted thinking_level without the daemon dropping the flag.for _, level := range []string{"low", "medium", "high", "xhigh", "max"} {- ok, err := ValidateThinkingLevel(ctx, "claude", fakeClaude, "claude-opus-5", level)+ ok, err := ValidateThinkingLevel(ctx, "claude", Command{Path: fakeClaude}, "claude-opus-5", level)if err != nil {t.Fatalf("unexpected err for opus-5 %q: %v", level, err)}@@ -728,7 +728,7 @@ func TestValidateThinkingLevel_ExplicitModel(t *testing.T) {// Claude Code appends a bracketed context-window tag to the model ID for// long-context sessions. Capability validation must inherit the base// model's effort catalog without rewriting the model passed to the CLI.- ok, err = ValidateThinkingLevel(ctx, "claude", fakeClaude, "claude-opus-5[1m]", "xhigh")+ ok, err = ValidateThinkingLevel(ctx, "claude", Command{Path: fakeClaude}, "claude-opus-5[1m]", "xhigh")if err != nil {t.Fatalf("unexpected err for context-tagged opus-5: %v", err)}@@ -736,7 +736,7 @@ func TestValidateThinkingLevel_ExplicitModel(t *testing.T) {t.Error("xhigh should be valid on the opus-5[1m] context variant")}- ok, err = ValidateThinkingLevel(ctx, "claude", fakeClaude, "claude-opus-5[500k]", "high")+ ok, err = ValidateThinkingLevel(ctx, "claude", Command{Path: fakeClaude}, "claude-opus-5[500k]", "high")if err != nil {t.Fatalf("unexpected err for future context-tag shape: %v", err)}@@ -746,7 +746,7 @@ func TestValidateThinkingLevel_ExplicitModel(t *testing.T) {// Arbitrary bracket suffixes are not context-window tags. Keep malformed// variants fail-closed even when their apparent base model is known.- ok, err = ValidateThinkingLevel(ctx, "claude", fakeClaude, "claude-opus-5[weird]", "high")+ ok, err = ValidateThinkingLevel(ctx, "claude", Command{Path: fakeClaude}, "claude-opus-5[weird]", "high")if err != nil {t.Fatalf("unexpected err for malformed context tag: %v", err)}@@ -755,7 +755,7 @@ func TestValidateThinkingLevel_ExplicitModel(t *testing.T) {}// xhigh is NOT valid on Sonnet — should fail.- ok, err = ValidateThinkingLevel(ctx, "claude", fakeClaude, "claude-sonnet-4-6[1m]", "xhigh")+ ok, err = ValidateThinkingLevel(ctx, "claude", Command{Path: fakeClaude}, "claude-sonnet-4-6[1m]", "xhigh")if err != nil {t.Fatalf("unexpected err: %v", err)}@@ -764,7 +764,7 @@ func TestValidateThinkingLevel_ExplicitModel(t *testing.T) {}// An unknown model with a valid token still fails closed (no guess).- ok, err = ValidateThinkingLevel(ctx, "claude", fakeClaude, "claude-nonexistent", "high")+ ok, err = ValidateThinkingLevel(ctx, "claude", Command{Path: fakeClaude}, "claude-nonexistent", "high")if err != nil {t.Fatalf("unexpected err: %v", err)}@@ -791,12 +791,12 @@ func TestValidateThinkingLevel_CodexEmptyModelFailsClosed(t *testing.T) {check := func(model, value string, want bool) {t.Helper()- ok, err := ValidateThinkingLevel(ctx, "codex", fakeCodex, model, value)+ ok, err := ValidateThinkingLevel(ctx, "codex", Command{Path: fakeCodex}, model, value)if err != nil {- t.Fatalf("ValidateThinkingLevel(codex, %q, %q): unexpected err: %v", model, value, err)+ t.Fatalf("ValidateThinkingLevel(codex, %q, Command{Path: %q}): unexpected err: %v", model, value, err)}if ok != want {- t.Errorf("ValidateThinkingLevel(codex, %q, %q) = %v, want %v", model, value, ok, want)+ t.Errorf("ValidateThinkingLevel(codex, %q, Command{Path: %q}) = %v, want %v", model, value, ok, want)}}@@ -837,7 +837,7 @@ func TestValidateThinkingLevel_PreEffortCLIRejectsAllLevels(t *testing.T) {ctx := context.Background()for _, level := range []string{"low", "medium", "high", "xhigh", "max"} {- ok, err := ValidateThinkingLevel(ctx, "claude", fakeClaude, "claude-fable-5", level)+ ok, err := ValidateThinkingLevel(ctx, "claude", Command{Path: fakeClaude}, "claude-fable-5", level)if err != nil {t.Fatalf("unexpected err for %q: %v", level, err)}@@ -847,7 +847,7 @@ func TestValidateThinkingLevel_PreEffortCLIRejectsAllLevels(t *testing.T) {}// Empty value still means "use runtime default" and must stay valid.- ok, err := ValidateThinkingLevel(ctx, "claude", fakeClaude, "claude-fable-5", "")+ ok, err := ValidateThinkingLevel(ctx, "claude", Command{Path: fakeClaude}, "claude-fable-5", "")if err != nil {t.Fatalf("unexpected err: %v", err)}@@ -892,7 +892,7 @@ echo "opencode 9.9.9"writeTestExecutable(t, fake, []byte(script))ctx := context.Background()- ok, err := ValidateThinkingLevel(ctx, "opencode", fake, "", "max")+ ok, err := ValidateThinkingLevel(ctx, "opencode", Command{Path: fake}, "", "max")if err != nil {t.Fatalf("unexpected err: %v", err)}@@ -900,7 +900,7 @@ echo "opencode 9.9.9"t.Fatalf("expected empty-model opencode max to pass when any advertised model supports it")}- ok, err = ValidateThinkingLevel(ctx, "opencode", fake, "", "xhigh")+ ok, err = ValidateThinkingLevel(ctx, "opencode", Command{Path: fake}, "", "xhigh")if err != nil {t.Fatalf("unexpected err: %v", err)}@@ -990,12 +990,12 @@ func TestValidateServiceTierCodexPerModelCatalog(t *testing.T) {{provider: "claude", model: "gpt-5.6-sol", tier: "priority", want: false},{provider: "codex", model: "gpt-5.6-sol", tier: "", want: true},} {- got, err := ValidateServiceTier(context.Background(), tc.provider, fake, tc.model, tc.tier)+ got, err := ValidateServiceTier(context.Background(), tc.provider, Command{Path: fake}, tc.model, tc.tier)if err != nil {- t.Fatalf("ValidateServiceTier(%q, %q, %q): %v", tc.provider, tc.model, tc.tier, err)+ t.Fatalf("ValidateServiceTier(%q, %q, Command{Path: %q}): %v", tc.provider, tc.model, tc.tier, err)}if got != tc.want {- t.Errorf("ValidateServiceTier(%q, %q, %q) = %v, want %v", tc.provider, tc.model, tc.tier, got, tc.want)+ t.Errorf("ValidateServiceTier(%q, %q, Command{Path: %q}) = %v, want %v", tc.provider, tc.model, tc.tier, got, tc.want)}}}@@ -1027,9 +1027,9 @@ func TestThinkingCacheKeyDistinct(t *testing.T) {resetThinkingCacheForTests()defer resetThinkingCacheForTests()- a := thinkingCacheKey{provider: "claude", executablePath: "/bin/claude", cliVersion: "2.1.121"}- b := thinkingCacheKey{provider: "claude", executablePath: "/bin/claude", cliVersion: "2.1.122"}- c := thinkingCacheKey{provider: "claude", executablePath: "/opt/claude", cliVersion: "2.1.121"}+ a := thinkingCacheKey{provider: "claude", command: "/bin/claude", cliVersion: "2.1.121"}+ b := thinkingCacheKey{provider: "claude", command: "/bin/claude", cliVersion: "2.1.122"}+ c := thinkingCacheKey{provider: "claude", command: "/opt/claude", cliVersion: "2.1.121"}thinkingCachePut(a, map[string]*ModelThinking{"x": {DefaultLevel: "a"}})thinkingCachePut(b, map[string]*ModelThinking{"x": {DefaultLevel: "b"}})diff --git a/server/pkg/agent/traecli.go b/server/pkg/agent/traecli.goindex 63ea45a511..9c7f9459e7 100644--- a/server/pkg/agent/traecli.go+++ b/server/pkg/agent/traecli.go@@ -111,7 +111,7 @@ func (b *traecliBackend) Execute(ctx context.Context, prompt string, opts ExecOp[]string{"acp", "serve", "--yolo"},filterCustomArgs(opts.CustomArgs, traecliBlockedArgs, b.cfg.Logger)...,)- cmd := exec.CommandContext(runCtx, execPath, traecliArgs...)+ cmd := b.cfg.commandAt(execPath).exec(runCtx, traecliArgs...)hideAgentWindow(cmd)b.cfg.Logger.Info("agent command", "exec", execPath, "args", traecliArgs)if opts.Cwd != "" {