Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(daemon): fix Copilot CLI invocation on Windows and strip shell quotes from custom args (MUL-2876)
Jan De Dobbeleer1e1a4f784562
diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.goindex f59f526e56..be48ccb632 100644--- a/server/pkg/agent/claude.go+++ b/server/pkg/agent/claude.go@@ -610,18 +610,24 @@ const (// only block args that would break the communication protocol, not every// possible dangerous flag. Workspace members are trusted to configure agents// sensibly, same as with custom_env.+//+// Shell quoting is stripped from each arg before processing: users commonly+// type custom_args in config fields using shell syntax (e.g.+// --deny-tool='write'). Since the daemon spawns processes directly without a+// shell, those quotes would otherwise be passed literally to the child process,+// which typically rejects them as unrecognised flag values.func filterCustomArgs(args []string, blocked map[string]blockedArgMode, logger *slog.Logger) []string {if len(args) == 0 {return args}filtered := make([]string, 0, len(args))skip := false- for _, arg := range args {+ for _, raw := range args {if skip {skip = falsecontinue}- // Check if this arg is a blocked flag or starts with "blockedFlag=".+ arg := unshellQuoteArg(raw)flag := arghasInlineValue := falseif idx := strings.Index(arg, "="); idx > 0 {@@ -642,6 +648,44 @@ func filterCustomArgs(args []string, blocked map[string]blockedArgMode, logger *return filtered}+// unshellQuoteArg strips a single layer of shell-style single or double quotes+// from an argument. It handles two forms:+//+// - --flag='value' or --flag="value" → --flag=value+// - 'standalone' or "standalone" → standalone+//+// Only flag-style args (`-x=…`, `--flag=…`) get inline value unquoting. Plain+// assignment syntax like `model="o3"` is left alone because the quotes may be+// semantic for the child process (for example Codex `-c model="o3"`). Only+// matching outer quotes are stripped; no escape processing is done.+func unshellQuoteArg(arg string) string {+ if strings.HasPrefix(arg, "-") {+ if idx := strings.Index(arg, "="); idx > 0 {+ value := arg[idx+1:]+ if unquoted, ok := stripSurroundingQuotes(value); ok {+ return arg[:idx+1] + unquoted+ }+ return arg+ }+ }+ if unquoted, ok := stripSurroundingQuotes(arg); ok {+ return unquoted+ }+ return arg+}++// stripSurroundingQuotes removes a matching outer pair of single or double+// quotes from s and returns (unquoted, true). Returns (s, false) if s does not+// start and end with the same quote character.+func stripSurroundingQuotes(s string) (string, bool) {+ if len(s) >= 2 {+ if (s[0] == '\'' && s[len(s)-1] == '\'') || (s[0] == '"' && s[len(s)-1] == '"') {+ return s[1 : len(s)-1], true+ }+ }+ return s, false+}+// writeMcpConfigToTemp writes raw MCP config JSON to a temporary file and returns// its path. The caller is responsible for removing the file when done.func writeMcpConfigToTemp(raw json.RawMessage) (string, error) {diff --git a/server/pkg/agent/claude_test.go b/server/pkg/agent/claude_test.goindex f96dee0367..7e8ec6917b 100644--- a/server/pkg/agent/claude_test.go+++ b/server/pkg/agent/claude_test.go@@ -270,6 +270,57 @@ func TestFilterCustomArgsBlocksProtocolFlags(t *testing.T) {}}+func TestFilterCustomArgsStripsShellQuotes(t *testing.T) {+ t.Parallel()++ logger := slog.Default()++ // Single-quoted inline value: --deny-tool='write' → --deny-tool=write+ result := filterCustomArgs([]string{"--deny-tool='write'"}, nil, logger)+ if len(result) != 1 || result[0] != "--deny-tool=write" {+ t.Fatalf("expected [--deny-tool=write], got %v", result)+ }++ // Double-quoted inline value: --deny-tool="write" → --deny-tool=write+ result = filterCustomArgs([]string{`--deny-tool="write"`}, nil, logger)+ if len(result) != 1 || result[0] != "--deny-tool=write" {+ t.Fatalf("expected [--deny-tool=write], got %v", result)+ }++ // Standalone quoted value: 'write' → write+ result = filterCustomArgs([]string{"'write'"}, nil, logger)+ if len(result) != 1 || result[0] != "write" {+ t.Fatalf("expected [write], got %v", result)+ }++ // Non-flag assignments may use quotes semantically (for example Codex+ // `-c model="o3"`), so they must survive unchanged.+ result = filterCustomArgs([]string{`model="o3"`}, nil, logger)+ if len(result) != 1 || result[0] != `model="o3"` {+ t.Fatalf("expected [model=\"o3\"], got %v", result)+ }++ // Unquoted arg passes through unchanged+ result = filterCustomArgs([]string{"--deny-tool=write"}, nil, logger)+ if len(result) != 1 || result[0] != "--deny-tool=write" {+ t.Fatalf("expected [--deny-tool=write], got %v", result)+ }++ // Mismatched quotes are not stripped+ result = filterCustomArgs([]string{"--flag='val\""}, nil, logger)+ if len(result) != 1 || result[0] != "--flag='val\"" {+ t.Fatalf("mismatched quotes should not be stripped, got %v", result)+ }++ // Blocked flag with quoted value: the blocking still fires, the unquoted+ // form passes the flag-match, and the arg is dropped.+ blocked := map[string]blockedArgMode{"--output-format": blockedWithValue}+ result = filterCustomArgs([]string{"--output-format='json'", "--verbose"}, blocked, logger)+ if len(result) != 1 || result[0] != "--verbose" {+ t.Fatalf("quoted blocked flag should still be dropped, got %v", result)+ }+}+func TestBuildClaudeArgsPassesThroughCustomArgs(t *testing.T) {t.Parallel()diff --git a/server/pkg/agent/copilot.go b/server/pkg/agent/copilot.goindex da725b2f74..edf266fd63 100644--- a/server/pkg/agent/copilot.go+++ b/server/pkg/agent/copilot.go@@ -193,12 +193,13 @@ func withCopilotExitCode(msg string, exitCode int) string {}func (b *copilotBackend) Execute(ctx context.Context, prompt string, opts ExecOptions) (*Session, error) {- execPath := b.cfg.ExecutablePath- if execPath == "" {- execPath = "copilot"+ execName := b.cfg.ExecutablePath+ if execName == "" {+ execName = "copilot"}- if _, err := exec.LookPath(execPath); err != nil {- return nil, fmt.Errorf("copilot executable not found at %q: %w", execPath, err)+ lookedUp, err := exec.LookPath(execName)+ if err != nil {+ return nil, fmt.Errorf("copilot executable not found at %q: %w", execName, err)}timeout := opts.Timeout@@ -208,10 +209,11 @@ func (b *copilotBackend) Execute(ctx context.Context, prompt string, opts ExecOprunCtx, cancel := context.WithTimeout(ctx, timeout)args := buildCopilotArgs(prompt, opts, b.cfg.Logger)+ argv0, cmdArgs := chooseCopilotInvocation(execName, lookedUp, args, b.cfg.Logger)- cmd := exec.CommandContext(runCtx, execPath, args...)+ cmd := exec.CommandContext(runCtx, argv0, cmdArgs...)hideAgentWindow(cmd)- b.cfg.Logger.Info("agent command", "exec", execPath, "args", args)+ b.cfg.Logger.Info("agent command", "exec", argv0, "args", cmdArgs)cmd.WaitDelay = 10 * time.Secondif opts.Cwd != "" {cmd.Dir = opts.Cwddiff --git a/server/pkg/agent/copilot_invocation.go b/server/pkg/agent/copilot_invocation.gonew file mode 100644index 0000000000..026af73da3--- /dev/null+++ b/server/pkg/agent/copilot_invocation.go@@ -0,0 +1,22 @@+package agent++import "log/slog"++// chooseCopilotInvocation selects the actual program (argv[0]) and the full+// argv to spawn a Copilot CLI run.+//+// On macOS/Linux the npm binstub is a shebang script that execs node directly,+// so argv passes through unchanged. On Windows the npm installer ships+// copilot.cmd, which routes through cmd.exe; cmd.exe re-tokenises the raw+// command line via %*, mangling arguments that contain newlines or whitespace+// (e.g. the multi-line -p prompt). To avoid that, we find the sibling+// copilot.ps1 and invoke PowerShell with -File <ps1> directly, so Go passes+// each argument as a discrete token.+//+// The Windows rewrite lives in copilot_invocation_windows.go.+func chooseCopilotInvocation(execName, lookedUp string, args []string, logger *slog.Logger) (string, []string) {+ if argv0, full, ok := platformCopilotInvocation(lookedUp, args, logger); ok {+ return argv0, full+ }+ return execName, args+}diff --git a/server/pkg/agent/copilot_invocation_other.go b/server/pkg/agent/copilot_invocation_other.gonew file mode 100644index 0000000000..8b7c5595b5--- /dev/null+++ b/server/pkg/agent/copilot_invocation_other.go@@ -0,0 +1,12 @@+//go:build !windows++package agent++import "log/slog"++// platformCopilotInvocation is a no-op on non-Windows platforms: Copilot+// CLI's binstub invokes node directly via shebang and Go's os/exec can pass+// argv unchanged.+func platformCopilotInvocation(_ string, _ []string, _ *slog.Logger) (string, []string, bool) {+ return "", nil, false+}diff --git a/server/pkg/agent/copilot_invocation_test.go b/server/pkg/agent/copilot_invocation_test.gonew file mode 100644index 0000000000..6e6fef0686--- /dev/null+++ b/server/pkg/agent/copilot_invocation_test.go@@ -0,0 +1,36 @@+package agent++import (+ "io"+ "log/slog"+ "path/filepath"+ "reflect"+ "testing"+)++// TestChooseCopilotInvocation_PassthroughForNonLauncher verifies that when+// the resolved executable is not a Windows .cmd/.bat launcher, both argv[0]+// and the argv list are returned unchanged on every platform. This guards+// against accidental rewriting on macOS/Linux and for direct binary launches+// on Windows.+func TestChooseCopilotInvocation_PassthroughForNonLauncher(t *testing.T) {+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))++ execName := "copilot"+ lookedUp := filepath.Join(t.TempDir(), "copilot") // no .cmd / .bat+ args := []string{+ "-p", "You are running as a local coding agent.\n\nDo something.",+ "--output-format", "json",+ "--allow-all",+ "--no-ask-user",+ }++ gotExec, gotArgs := chooseCopilotInvocation(execName, lookedUp, args, logger)++ if gotExec != execName {+ t.Errorf("argv0 changed unexpectedly: got %q want %q", gotExec, execName)+ }+ if !reflect.DeepEqual(gotArgs, args) {+ t.Errorf("argv changed unexpectedly:\n got %#v\n want %#v", gotArgs, args)+ }+}diff --git a/server/pkg/agent/copilot_invocation_windows.go b/server/pkg/agent/copilot_invocation_windows.gonew file mode 100644index 0000000000..70ca1a4d9c--- /dev/null+++ b/server/pkg/agent/copilot_invocation_windows.go@@ -0,0 +1,13 @@+//go:build windows++package agent++import "log/slog"++// platformCopilotInvocation rewrites copilot.cmd → PowerShell -File+// copilot.ps1 on Windows to avoid cmd.exe %* re-tokenisation mangling+// the multi-line -p prompt built by buildCopilotArgs.+// powerShellLookup and rewriteCmdToPS1 are defined in cursor_invocation_windows.go.+func platformCopilotInvocation(lookedUp string, args []string, logger *slog.Logger) (string, []string, bool) {+ return rewriteCmdToPS1("copilot", lookedUp, args, logger)+}diff --git a/server/pkg/agent/copilot_invocation_windows_test.go b/server/pkg/agent/copilot_invocation_windows_test.gonew file mode 100644index 0000000000..03c355802d--- /dev/null+++ b/server/pkg/agent/copilot_invocation_windows_test.go@@ -0,0 +1,125 @@+//go:build windows++package agent++import (+ "io"+ "log/slog"+ "path/filepath"+ "reflect"+ "testing"+)++// TestPlatformCopilotInvocation_RewritesCmdLauncherToPowerShellFile is the+// core Windows test: when LookPath resolves copilot to the npm-installed .cmd+// launcher and a sibling copilot.ps1 exists, we should invoke PowerShell with+// -File <ps1> and forward every original arg unchanged — including the+// multi-line -p prompt that would otherwise be mangled by cmd.exe's %*+// re-expansion inside copilot.cmd.+func TestPlatformCopilotInvocation_RewritesCmdLauncherToPowerShellFile(t *testing.T) {+ dir := t.TempDir()+ cmdPath := filepath.Join(dir, "copilot.cmd")+ ps1Path := filepath.Join(dir, "copilot.ps1")+ writeFile(t, cmdPath, "@echo off\r\npowershell -NoProfile -ExecutionPolicy Bypass -File \"%~dp0copilot.ps1\" %*\r\n")+ writeFile(t, ps1Path, "# fake copilot.ps1\r\n")++ fakePS := filepath.Join(dir, "powershell.exe")+ writeFile(t, fakePS, "")+ stubPowerShell(t, fakePS, true)++ multiLinePrompt := "You are running as a local coding agent.\n\n# Context\nDo the task.\n"+ args := []string{+ "-p", multiLinePrompt,+ "--output-format", "json",+ "--allow-all",+ "--no-ask-user",+ }+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))++ gotExec, gotArgs, ok := platformCopilotInvocation(cmdPath, args, logger)+ if !ok {+ t.Fatalf("expected platform rewrite to be applied, got ok=false")+ }+ if gotExec != fakePS {+ t.Errorf("argv0: got %q want %q", gotExec, fakePS)+ }++ wantArgs := append([]string{+ "-NoProfile",+ "-ExecutionPolicy", "Bypass",+ "-File", ps1Path,+ }, args...)+ if !reflect.DeepEqual(gotArgs, wantArgs) {+ t.Errorf("argv mismatch:\n got %#v\n want %#v", gotArgs, wantArgs)+ }++ // Confirm the multi-line prompt value survived intact. Find the -p flag and+ // check the next element, so the assertion stays correct even if+ // rewriteCmdToPS1 prepends additional PowerShell flags in the future.+ promptIdx := -1+ for i, a := range gotArgs {+ if a == "-p" {+ promptIdx = i + 1+ break+ }+ }+ if promptIdx < 0 || promptIdx >= len(gotArgs) {+ t.Fatalf("could not find -p flag in gotArgs: %#v", gotArgs)+ }+ if gotArgs[promptIdx] != multiLinePrompt {+ t.Errorf("multi-line prompt was mangled:\n got %q\n want %q", gotArgs[promptIdx], multiLinePrompt)+ }+}++// TestPlatformCopilotInvocation_SkipsWhenNotCmdOrBat ensures we leave argv+// alone when the user explicitly resolved copilot to something that isn't a+// batch launcher (e.g. a real binary or a node shebang shim).+func TestPlatformCopilotInvocation_SkipsWhenNotCmdOrBat(t *testing.T) {+ dir := t.TempDir()+ exePath := filepath.Join(dir, "copilot.exe")+ writeFile(t, exePath, "")+ // A sibling .ps1 must not trick us into rewriting a non-launcher exec.+ writeFile(t, filepath.Join(dir, "copilot.ps1"), "")++ stubPowerShell(t, filepath.Join(dir, "powershell.exe"), true)++ logger := slog.New(slog.NewTextHandler(io.Discard, nil))+ if _, _, ok := platformCopilotInvocation(exePath, []string{"-p", "hello"}, logger); ok {+ t.Fatalf("expected ok=false for non-.cmd/.bat launcher")+ }+}++// TestPlatformCopilotInvocation_SkipsWhenPS1Missing covers the rare case+// where a .cmd was found but its companion .ps1 is missing (e.g. a partial+// install). We must fall back to the original launcher rather than+// synthesising an invalid powershell -File invocation.+func TestPlatformCopilotInvocation_SkipsWhenPS1Missing(t *testing.T) {+ dir := t.TempDir()+ cmdPath := filepath.Join(dir, "copilot.cmd")+ writeFile(t, cmdPath, "@echo off\r\n")++ stubPowerShell(t, filepath.Join(dir, "powershell.exe"), true)++ logger := slog.New(slog.NewTextHandler(io.Discard, nil))+ if _, _, ok := platformCopilotInvocation(cmdPath, []string{"-p", "hello"}, logger); ok {+ t.Fatalf("expected ok=false when copilot.ps1 is missing")+ }+}++// TestPlatformCopilotInvocation_SkipsWhenPowerShellMissing covers a stripped+// environment in which neither pwsh.exe nor powershell.exe can be resolved.+// We must not fabricate an empty-string argv[0].+func TestPlatformCopilotInvocation_SkipsWhenPowerShellMissing(t *testing.T) {+ dir := t.TempDir()+ cmdPath := filepath.Join(dir, "copilot.cmd")+ ps1Path := filepath.Join(dir, "copilot.ps1")+ writeFile(t, cmdPath, "@echo off\r\n")+ writeFile(t, ps1Path, "# fake\r\n")++ stubPowerShell(t, "", false)++ logger := slog.New(slog.NewTextHandler(io.Discard, nil))+ if _, _, ok := platformCopilotInvocation(cmdPath, []string{"-p", "hello"}, logger); ok {+ t.Fatalf("expected ok=false when no powershell host is available")+ }+}diff --git a/server/pkg/agent/cursor_invocation_windows.go b/server/pkg/agent/cursor_invocation_windows.goindex cd7e95e345..2883c0f611 100644--- a/server/pkg/agent/cursor_invocation_windows.go+++ b/server/pkg/agent/cursor_invocation_windows.go@@ -14,28 +14,27 @@ import (// tests; production callers should leave it at its default.var powerShellLookup = defaultPowerShellLookup-// platformCursorInvocation rewrites the cursor-agent invocation on Windows-// when the resolved executable is the official cursor-agent.cmd launcher-// (or a .bat alias) that delegates to cursor-agent.ps1.+// rewriteCmdToPS1 handles the .cmd → PowerShell rewrite for npm-installed+// agent CLIs on Windows. Each CLI ships a <name>.cmd launcher whose body is+// effectively//-// We replace+// powershell -NoProfile -ExecutionPolicy Bypass -File <name>.ps1 %*//-// cursor-agent.cmd <args...>+// Going through cmd.exe causes %* re-expansion to re-tokenise the raw+// command-line string, which mangles multi-line arguments (most critically+// the -p prompt). We instead invoke PowerShell with -File <name>.ps1+// directly so Go passes each argv element as a discrete token.//-// with-//-// powershell.exe -NoProfile -ExecutionPolicy Bypass -File cursor-agent.ps1 <args...>-//-// which is exactly what the .cmd does internally, but lets Go pass each arg-// as a discrete token instead of routing through cmd.exe's %* re-expansion-// (which mangles multi-line / whitespace-heavy prompts such as a long -p).-func platformCursorInvocation(lookedUp string, args []string, logger *slog.Logger) (string, []string, bool) {+// toolName is used both for the log message and to derive the canonical ps1+// filename (toolName + ".ps1" in the same directory as lookedUp). Using the+// canonical name rather than the launcher basename ensures we find the right+// script even when the user has a custom .bat wrapper with a different name.+func rewriteCmdToPS1(toolName, lookedUp string, args []string, logger *slog.Logger) (string, []string, bool) {ext := strings.ToLower(filepath.Ext(lookedUp))if ext != ".cmd" && ext != ".bat" {return "", nil, false}- dir := filepath.Dir(lookedUp)- ps1 := filepath.Join(dir, "cursor-agent.ps1")+ ps1 := filepath.Join(filepath.Dir(lookedUp), toolName+".ps1")if st, err := os.Stat(ps1); err != nil || st.IsDir() {return "", nil, false}@@ -50,7 +49,7 @@ func platformCursorInvocation(lookedUp string, args []string, logger *slog.Loggefull = append(full, args...)if logger != nil {- logger.Info("cursor-agent: routing through powershell -File to preserve argv tokens",+ logger.Info(toolName+": routing through powershell -File to preserve argv tokens","powershell", psExe,"ps1", ps1,"original", lookedUp,@@ -59,6 +58,12 @@ func platformCursorInvocation(lookedUp string, args []string, logger *slog.Loggereturn psExe, full, true}+// platformCursorInvocation rewrites cursor-agent.cmd → PowerShell -File+// cursor-agent.ps1 on Windows to avoid cmd.exe %* re-tokenisation.+func platformCursorInvocation(lookedUp string, args []string, logger *slog.Logger) (string, []string, bool) {+ return rewriteCmdToPS1("cursor-agent", lookedUp, args, logger)+}+// defaultPowerShellLookup prefers PowerShell on PATH (PowerShell 7's pwsh.exe// or any user-overridden powershell.exe) and falls back to the system path// shipped with Windows.diff --git a/server/pkg/agent/pi_invocation_windows.go b/server/pkg/agent/pi_invocation_windows.goindex c5eeec3632..40f1e13edc 100644--- a/server/pkg/agent/pi_invocation_windows.go+++ b/server/pkg/agent/pi_invocation_windows.go@@ -2,59 +2,11 @@package agent-import (- "log/slog"- "os"- "path/filepath"- "strings"-)+import "log/slog"-// platformPiInvocation rewrites the pi invocation on Windows when the-// resolved executable is the npm-installed pi.cmd launcher (or a .bat-// alias) that delegates to pi.ps1.-//-// We replace-//-// pi.cmd <args...>-//-// with-//-// powershell.exe -NoProfile -ExecutionPolicy Bypass -File pi.ps1 <args...>-//-// which is what the .cmd does internally, but lets Go pass each arg as-// a discrete token instead of routing through cmd.exe's %* re-expansion-// (which mangles the multi-line positional prompt the daemon builds in-// buildPiArgs — see #3306).-//-// powerShellLookup is shared with the cursor backend: both npm shims-// have the same launcher shape and need the same PowerShell host on the-// same Windows installation.+// platformPiInvocation rewrites pi.cmd → PowerShell -File pi.ps1 on+// Windows to avoid cmd.exe %* re-tokenisation (see #3306).+// powerShellLookup and rewriteCmdToPS1 are defined in cursor_invocation_windows.go.func platformPiInvocation(lookedUp string, args []string, logger *slog.Logger) (string, []string, bool) {- ext := strings.ToLower(filepath.Ext(lookedUp))- if ext != ".cmd" && ext != ".bat" {- return "", nil, false- }- dir := filepath.Dir(lookedUp)- ps1 := filepath.Join(dir, "pi.ps1")- if st, err := os.Stat(ps1); err != nil || st.IsDir() {- return "", nil, false- }-- psExe, ok := powerShellLookup()- if !ok {- return "", nil, false- }-- full := make([]string, 0, 5+len(args))- full = append(full, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", ps1)- full = append(full, args...)-- if logger != nil {- logger.Info("pi: routing through powershell -File to preserve argv tokens",- "powershell", psExe,- "ps1", ps1,- "original", lookedUp,- )- }- return psExe, full, true+ return rewriteCmdToPS1("pi", lookedUp, args, logger)}