Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8620 fix(agent): isolate runtime probes and reject wrapper logs (#9957)
Bohan Jiangb3f1e6bf612b
diff --git a/apps/docs/content/docs/daemon-runtimes.mdx b/apps/docs/content/docs/daemon-runtimes.mdxindex 9c492f48a4..ae79500408 100644--- a/apps/docs/content/docs/daemon-runtimes.mdx+++ b/apps/docs/content/docs/daemon-runtimes.mdx@@ -232,6 +232,8 @@ 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.+Version checks and Pi model discovery run in an empty temporary directory so sandbox wrappers can refuse launches from your home directory. Your home environment and user-level configuration remain available. Use absolute paths for scripts or configuration files in fixed arguments; probes do not discover configuration relative to the daemon's launch directory. Task execution still uses the task's working directory.+### How your arguments are orderedEverything you type in the command field stays directly after the executable, ahead of the arguments Multica adds:diff --git a/apps/docs/content/docs/daemon-runtimes.zh.mdx b/apps/docs/content/docs/daemon-runtimes.zh.mdxindex be2e55e4ca..5e8b014496 100644--- a/apps/docs/content/docs/daemon-runtimes.zh.mdx+++ b/apps/docs/content/docs/daemon-runtimes.zh.mdx@@ -233,6 +233,8 @@ Codex 原生子智能体同样默认关闭:父线程结束时,Multica 就把这里填写的是可执行文件和参数,不是 shell 脚本。可以使用普通参数、引号和反斜杠转义,但不能使用管道、重定向、`&&`、`;`、反引号或环境变量展开。需要这些行为时,把它们放进 wrapper script,再把该脚本作为命令填写。+版本检查和 Pi 模型探测会在空临时目录中运行,以兼容禁止从主目录启动的沙箱包装器。主目录环境和用户级配置仍然可用。固定参数中的脚本或配置文件请使用绝对路径;探测不再读取相对于 daemon 启动目录的配置。任务执行仍使用任务的工作目录。+### 参数的排列顺序命令字段里填写的内容会紧跟在可执行文件之后,排在 Multica 追加的参数之前:diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.goindex 347cd7b556..d09e863a2d 100644--- a/server/pkg/agent/claude.go+++ b/server/pkg/agent/claude.go@@ -1553,6 +1553,12 @@ var detectVersionTimeout = 10 * time.Secondfunc detectCLIVersion(ctx context.Context, runtimeCmd Command) (string, error) {ctx, cancel := context.WithTimeout(ctx, detectVersionTimeout)defer cancel()+ probeCmd, cleanup, err := runtimeCmd.withProbeDirectory()+ if err != nil {+ return "", fmt.Errorf("detect version for %s: %w", runtimeCmd, ExplainExecError(err))+ }+ defer cleanup()+ runtimeCmd = probeCmdif runtime.GOOS == "windows" {if native := resolveCodeArtsNativeFromShim(runtimeCmd.Path, os.Stat); native != "" {runtimeCmd.Path = nativediff --git a/server/pkg/agent/launch.go b/server/pkg/agent/launch.goindex 9a101c67b7..903fc70332 100644--- a/server/pkg/agent/launch.go+++ b/server/pkg/agent/launch.go@@ -6,7 +6,9 @@ import ("errors""fmt""log/slog"+ "os""os/exec"+ "path/filepath""strings""syscall""time"@@ -80,6 +82,9 @@ type Command struct {// logger reports prefix/argument conflicts at the moment a process is// built. Optional: a zero Command logs nothing.logger *slog.Logger+ // probeDir isolates discovery from the daemon's inherited directory.+ // Task commands leave it empty and keep their execution directory.+ probeDir string}// NewCommand builds a Command from a resolved executable path and a launch@@ -112,7 +117,31 @@ func (c Command) Argv(args ...string) []string {// reintroduce GH #7046. TestOnlyLaunchGoSpawnsRuntimeProcesses enforces it.func (c Command) exec(ctx context.Context, args ...string) *exec.Cmd {warnLaunchPrefixOverlap(c.Prefix, args, c.logger)- return newRuntimeCmd(exec.CommandContext(ctx, c.Path, c.Argv(args...)...))+ cmd := exec.CommandContext(ctx, c.Path, c.Argv(args...)...)+ cmd.Dir = c.probeDir+ return newRuntimeCmd(cmd)+}++// withProbeDirectory resolves the executable before moving into an empty+// directory. Sandboxed wrappers may refuse to launch from the daemon's cwd+// (notably HOME for GUI launches). HOME and the rest of the environment remain+// intact so user-level credentials, configuration and extensions still load.+func (c Command) withProbeDirectory() (Command, func(), error) {+ path, err := exec.LookPath(c.Path)+ if err != nil {+ return c, nil, err+ }+ path, err = filepath.Abs(path)+ if err != nil {+ return c, nil, err+ }+ dir, err := os.MkdirTemp("", "multica-probe-*")+ if err != nil {+ return c, nil, err+ }+ c.Path = path+ c.probeDir = dir+ return c, func() { _ = os.RemoveAll(dir) }, nil}// newRuntimeCmd applies the process-lifecycle defaults every runtime process in@@ -270,7 +299,9 @@ type invocationChooser func(execName, lookedUp string, args []string, logger *slfunc (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 newRuntimeCmd(exec.CommandContext(ctx, argv0, cmdArgs...)), argv0, cmdArgs+ cmd := exec.CommandContext(ctx, argv0, cmdArgs...)+ cmd.Dir = c.probeDir+ return newRuntimeCmd(cmd), argv0, cmdArgs}// withFilteredPrefix returns a copy of the command whose prefix has beendiff --git a/server/pkg/agent/models.go b/server/pkg/agent/models.goindex ece626f69e..163383d788 100644--- a/server/pkg/agent/models.go+++ b/server/pkg/agent/models.go@@ -1137,6 +1137,13 @@ func discoverPiModelsWithin(ctx context.Context, runtimeCmd Command, rpcTimeout,// will choose when Multica omits --model; its thinking level is the runtime's// effective default for that selected model.func discoverPiModelsRPC(ctx context.Context, runtimeCmd Command, lookedUp string) ([]Model, bool) {+ runtimeCmd.Path = lookedUp+ probeCmd, cleanup, err := runtimeCmd.withProbeDirectory()+ if err != nil {+ return nil, false+ }+ defer cleanup()+ runtimeCmd = probeCmdargs := []string{"--mode", "rpc","--no-session",@@ -1147,7 +1154,7 @@ func discoverPiModelsRPC(ctx context.Context, runtimeCmd Command, lookedUp strin"--no-prompt-templates","--no-context-files",}- cmd, _, _ := runtimeCmd.execVia(ctx, choosePiInvocation, lookedUp, args, slog.Default())+ cmd, _, _ := runtimeCmd.execVia(ctx, choosePiInvocation, runtimeCmd.Path, args, slog.Default())hideAgentWindow(cmd)cmd.WaitDelay = time.Secondcmd.Stderr = io.Discard@@ -1305,6 +1312,12 @@ func piThinkingSupports(thinking *ModelThinking, value string) bool {// 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, runtimeCmd Command) ([]Model, error) {+ probeCmd, cleanup, err := runtimeCmd.withProbeDirectory()+ if err != nil {+ return nil, fmt.Errorf("pi model discovery: %w", err)+ }+ defer cleanup()+ runtimeCmd = probeCmd// 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@@ -1340,6 +1353,7 @@ func parsePiModels(output string) []Model {scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)var models []Modelseen := map[string]bool{}+ tableColumns := 0for scanner.Scan() {line := strings.TrimSpace(scanner.Text())if line == "" {@@ -1358,16 +1372,21 @@ func parsePiModels(output string) []Model {continue}first := fields[0]- if strings.EqualFold(first, "provider") {+ if len(fields) >= 3 && strings.EqualFold(first, "provider") && strings.EqualFold(fields[1], "model") {+ tableColumns = len(fields)continue}var id string- if strings.ContainsAny(first, ":/") {- // Legacy `provider:model` format — normalize colon to slash.- // Restricted to this branch so a model name with a `:` in- // the table format's column 1 is not silently rewritten.- id = strings.Replace(first, ":", "/", 1)- } else if len(fields) >= 2 {+ if len(fields) == 1 && strings.ContainsAny(first, ":/") {+ // The first delimiter separates the provider. Legacy model IDs+ // can contain slashes (provider:org/model), while later colons in+ // provider/model:version belong to the model and stay unchanged.+ id = first+ colon, slash := strings.IndexByte(first, ':'), strings.IndexByte(first, '/')+ if colon >= 0 && (slash < 0 || colon < slash) {+ id = strings.Replace(first, ":", "/", 1)+ }+ } else if tableColumns >= 3 && len(fields) == tableColumns && piModelContextPattern.MatchString(fields[2]) {id = first + "/" + fields[1]} else {continue@@ -1391,6 +1410,11 @@ func parsePiModels(output string) []Model {return models}+// The table's context window is numeric, optionally abbreviated (128K, 1M).+// Requiring its structure as well as the header keeps wrapper prose out even+// when it appears between real catalog rows. Custom provider IDs stay valid.+var piModelContextPattern = regexp.MustCompile(`(?i)^\d+(?:\.\d+)?[kmg]?$`)+// isPiDiscoveryNoise reports whether a `pi --list-models` line is a diagnostic// message rather than a catalog row. pi prints these alongside the table when// an agent config references stale provider/model patterns, e.g.diff --git a/server/pkg/agent/models_test.go b/server/pkg/agent/models_test.goindex 9dfc68753b..1344764722 100644--- a/server/pkg/agent/models_test.go+++ b/server/pkg/agent/models_test.go@@ -1023,6 +1023,50 @@ bareword}}+func TestParsePiModelsQualifiedIDs(t *testing.T) {+ t.Parallel()+ for _, tc := range []struct {+ input string+ want string+ provider string+ }{+ {"openrouter:anthropic/claude-sonnet-4", "openrouter/anthropic/claude-sonnet-4", "openrouter"},+ {"custom:org/model:version", "custom/org/model:version", "custom"},+ {"openrouter/anthropic/claude-sonnet-4", "openrouter/anthropic/claude-sonnet-4", "openrouter"},+ {"custom/org/model:version", "custom/org/model:version", "custom"},+ {"custom/model:version", "custom/model:version", "custom"},+ } {+ t.Run(tc.input, func(t *testing.T) {+ models := parsePiModels(tc.input + "\n")+ if len(models) != 1 || models[0].ID != tc.want || models[0].Provider != tc.provider {+ t.Fatalf("parsePiModels(%q) = %+v, want ID %q and provider %q", tc.input, models, tc.want, tc.provider)+ }+ })+ }+}++func TestParsePiModelsRejectsProseAlongsideCatalog(t *testing.T) {+ input := `Some random log lines printed at the starting of the sandbox+Disallowing sandbox creation from $HOME+provider model context max-out thinking images+custom my/model:version 128K 8K yes no+Some random log lines printed at the starting of the sandbox+/private/config: permission denied+custom/legacy-model+custom/legacy:version+custom:legacy-colon+`+ models := parsePiModels(input)+ want := []string{"custom/my/model:version", "custom/legacy-model", "custom/legacy:version", "custom/legacy-colon"}+ var got []string+ for _, model := range models {+ got = append(got, model.ID)+ }+ if !reflect.DeepEqual(got, want) {+ t.Fatalf("models = %v, want %v", got, want)+ }+}+func TestParsePiModelsTableFormat(t *testing.T) {input := `provider model context max-out thinking imagesbailian-coding-plan glm-4.7 202.8K 16.4K no nodiff --git a/server/pkg/agent/pi_probe_integration_test.go b/server/pkg/agent/pi_probe_integration_test.gonew file mode 100644index 0000000000..e12d0fee44--- /dev/null+++ b/server/pkg/agent/pi_probe_integration_test.go@@ -0,0 +1,82 @@+//go:build agentintegration && !windows++package agent++import (+ "context"+ "os"+ "os/exec"+ "path/filepath"+ "testing"+ "time"+)++func TestPiSandboxWrapperProbeReal(t *testing.T) {+ requireRealAgentSmoke(t)+ pi, err := exec.LookPath("pi")+ if err != nil {+ t.Skip("pi is not installed")+ }+ pi, err = filepath.Abs(pi)+ if err != nil {+ t.Fatal(err)+ }+ home, err := os.UserHomeDir()+ if err != nil {+ t.Fatal(err)+ }+ t.Chdir(home)+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)+ defer cancel()+ baseline, err := discoverPiModelsTable(ctx, NewCommand(pi, nil))+ if err != nil {+ t.Fatal(err)+ }+ if len(baseline) == 0 {+ t.Skip("pi has no configured models to compare")+ }+ version, err := DetectVersion(ctx, NewCommand(pi, nil))+ if err != nil {+ t.Fatal(err)+ }+ wrapper := filepath.Join(t.TempDir(), "pi")+ writeTestExecutable(t, wrapper, []byte(`#!/bin/sh+if [ "$PWD" -ef "$HOME" ]; then+ echo 'Disallowing sandbox creation from $HOME'+ exit 1+fi+echo 'Some random log lines printed at the starting of the sandbox' >&2+exec `+shellQuote(pi)+` "$@"+`))+ gotVersion, err := DetectVersion(ctx, NewCommand(wrapper, nil))+ if err != nil || gotVersion != version {+ t.Fatalf("wrapped version = %q, %v; want %q", gotVersion, err, version)+ }+ for _, tc := range []struct {+ name string+ discover func(context.Context, Command) ([]Model, error)+ }{+ {"RPC with table fallback", discoverPiModels},+ {"table", discoverPiModelsTable},+ } {+ t.Run(tc.name, func(t *testing.T) {+ models, err := tc.discover(ctx, NewCommand(wrapper, nil))+ if err != nil {+ t.Fatal(err)+ }+ want := make(map[string]bool, len(baseline))+ for _, model := range baseline {+ want[model.ID] = true+ }+ if len(models) != len(want) {+ t.Fatalf("got %d models, want %d", len(models), len(want))+ }+ for _, model := range models {+ if !want[model.ID] {+ t.Fatalf("unexpected model %q", model.ID)+ }+ }+ t.Logf("pi %s: %d models, no wrapper log entries", version, len(models))+ })+ }+}diff --git a/server/pkg/agent/probe_directory_test.go b/server/pkg/agent/probe_directory_test.gonew file mode 100644index 0000000000..af0a60874e--- /dev/null+++ b/server/pkg/agent/probe_directory_test.go@@ -0,0 +1,95 @@+//go:build !windows++package agent++import (+ "context"+ "fmt"+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func TestRuntimeProbesUseEmptyDirectory(t *testing.T) {+ // Reproduce a wrapper refusing to grant write access to the daemon's cwd.+ dir := t.TempDir()+ t.Chdir(dir)+ t.Setenv("HOME", dir)+ t.Setenv("MUL_TEST_PROBE_LOG", filepath.Join(dir, "probes"))+ if err := os.WriteFile(filepath.Join(dir, "config"), []byte("global-config"), 0600); err != nil {+ t.Fatal(err)+ }+ guard := `#!/bin/sh+if [ "$PWD" = "$HOME" ]; then+ echo 'Disallowing sandbox creation from $HOME' >&2+ exit 1+fi+test -z "$(ls -A)" || exit 2+test "$(cat "$HOME/config")" = global-config || exit 3+printf '%s\n' "$PWD" >> "$MUL_TEST_PROBE_LOG"+echo 'Some random log lines printed at the starting of the sandbox' >&2+`+ version := filepath.Join(dir, "version")+ writeTestExecutable(t, version, []byte(guard+"test \"$1\" = start || exit 4\ntest \"$2\" = --version || exit 5\necho 1.0.0\n"))+ // Executable resolution must happen before changing the child directory.+ got, err := DetectVersion(context.Background(), NewCommand("./version", []string{"start"}))+ if err != nil || got != "1.0.0" {+ t.Fatalf("version = %q, %v", got, err)+ }+ rpc := writeFakePiRPCModelsBinary(t)+ rpcBody, err := os.ReadFile(rpc)+ if err != nil {+ t.Fatal(err)+ }+ writeTestExecutable(t, rpc, []byte(guard+strings.TrimPrefix(string(rpcBody), "#!/bin/sh\n")))+ models, err := discoverPiModels(context.Background(), NewCommand(rpc, nil))+ if err != nil || len(models) != 3 {+ t.Fatalf("RPC models = %+v, %v", models, err)+ }+ table := filepath.Join(dir, "table")+ writeTestExecutable(t, table, []byte(guard+"test \"$1\" = --list-models || exit 6\necho 'provider model context'\necho 'custom local-model 128K'\n"))+ models, err = discoverPiModels(context.Background(), NewCommand(table, nil))+ if err != nil || len(models) != 1 || models[0].ID != "custom/local-model" {+ t.Fatalf("table models = %+v, %v", models, err)+ }+ data, err := os.ReadFile(filepath.Join(dir, "probes"))+ if err != nil {+ t.Fatal(err)+ }+ probes := strings.Fields(string(data))+ if len(probes) != 4 {+ t.Fatalf("got %d probes, want version, RPC, failed RPC and table", len(probes))+ }+ for _, probeDir := range probes {+ if _, err := os.Stat(probeDir); !os.IsNotExist(err) {+ t.Errorf("probe directory was not cleaned up: %s (%v)", probeDir, err)+ }+ }+ if cwd, _ := os.Getwd(); cwd != dir {+ t.Fatalf("parent cwd changed: %q", cwd)+ }+}++func TestDiscoverPiModelsRejectsWrapperLogs(t *testing.T) {+ for _, stream := range []string{"stdout", "stderr"} {+ for _, exitCode := range []int{0, 1} {+ t.Run(fmt.Sprintf("%s/exit%d", stream, exitCode), func(t *testing.T) {+ redirect := ""+ if stream == "stderr" {+ redirect = " >&2"+ }+ path := filepath.Join(t.TempDir(), "pi")+ script := "#!/bin/sh\necho 'Disallowing sandbox creation from $HOME'" + redirect + "\necho 'Some random log lines printed at the starting of the sandbox'" + redirect + fmt.Sprintf("\nexit %d\n", exitCode)+ writeTestExecutable(t, path, []byte(script))+ models, err := discoverPiModels(context.Background(), NewCommand(path, nil))+ if len(models) != 0 {+ t.Fatalf("logs returned as models: %+v", models)+ }+ if exitCode != 0 && err == nil {+ t.Fatal("failed wrapper must report an error")+ }+ })+ }+ }+}