Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agent/cursor): route Windows launcher through PowerShell -File to preserve multi-line prompts (#1709)
carmake805071b5b142
diff --git a/server/pkg/agent/cursor.go b/server/pkg/agent/cursor.goindex 76c3957e07..e5f1acf5fd 100644--- a/server/pkg/agent/cursor.go+++ b/server/pkg/agent/cursor.go@@ -21,12 +21,13 @@ type cursorBackend struct {}func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOptions) (*Session, error) {- execPath := b.cfg.ExecutablePath- if execPath == "" {- execPath = "cursor-agent"+ execName := b.cfg.ExecutablePath+ if execName == "" {+ execName = "cursor-agent"}- if _, err := exec.LookPath(execPath); err != nil {- return nil, fmt.Errorf("cursor-agent executable not found at %q: %w", execPath, err)+ lookedUp, err := exec.LookPath(execName)+ if err != nil {+ return nil, fmt.Errorf("cursor-agent executable not found at %q: %w", execName, err)}timeout := opts.Timeout@@ -36,10 +37,11 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOptrunCtx, cancel := context.WithTimeout(ctx, timeout)args := buildCursorArgs(prompt, opts, b.cfg.Logger)+ argv0, cmdArgs := chooseCursorInvocation(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 = 20 * time.Secondif opts.Cwd != "" {cmd.Dir = opts.Cwd@@ -280,10 +282,10 @@ func (b *cursorBackend) accumulateResultUsage(usage map[string]TokenUsage, evt *// ── Cursor stream-json types ──type cursorStreamEvent struct {- Type string `json:"type"`- Subtype string `json:"subtype,omitempty"`- SessionID string `json:"session_id,omitempty"`- Model string `json:"model,omitempty"`+ Type string `json:"type"`+ Subtype string `json:"subtype,omitempty"`+ SessionID string `json:"session_id,omitempty"`+ Model string `json:"model,omitempty"`// assistant fieldsMessage json.RawMessage `json:"message,omitempty"`@@ -297,10 +299,10 @@ type cursorStreamEvent struct {Output string `json:"output,omitempty"`// result fields- ResultText string `json:"result,omitempty"`- IsError bool `json:"is_error,omitempty"`- Usage *cursorUsage `json:"usage,omitempty"`- TotalCost float64 `json:"total_cost_usd,omitempty"`+ ResultText string `json:"result,omitempty"`+ IsError bool `json:"is_error,omitempty"`+ Usage *cursorUsage `json:"usage,omitempty"`+ TotalCost float64 `json:"total_cost_usd,omitempty"`// error fieldsErrorMsg string `json:"error,omitempty"`diff --git a/server/pkg/agent/cursor_invocation.go b/server/pkg/agent/cursor_invocation.gonew file mode 100644index 0000000000..0d2226571f--- /dev/null+++ b/server/pkg/agent/cursor_invocation.go@@ -0,0 +1,28 @@+package agent++import "log/slog"++// chooseCursorInvocation selects the actual program (argv[0]) and the full+// argv to spawn a cursor-agent run.+//+// Background:+// - On macOS/Linux, cursor-agent is a real binary and we can pass argv+// directly via os/exec — no rewriting needed.+// - On Windows, the official installer ships cursor-agent.cmd whose body is+// "powershell ... -File cursor-agent.ps1 %*". CreateProcess for a .cmd+// file goes through cmd.exe, and %* in a .cmd batch file is expanded by+// re-tokenising the original command line, which mangles arguments that+// contain newlines or other whitespace (e.g. multi-line `-p` prompts).+// To stay on the official launch path while avoiding that re-tokenisation,+// we resolve cursor-agent.ps1 next to the .cmd and invoke PowerShell with+// `-File <ps1>` directly, letting Go pass each argv as a separate token.+//+// The Windows-specific behaviour is implemented in+// cursor_invocation_windows.go; on other platforms we fall through to a+// passthrough.+func chooseCursorInvocation(execName, lookedUp string, args []string, logger *slog.Logger) (string, []string) {+ if argv0, full, ok := platformCursorInvocation(lookedUp, args, logger); ok {+ return argv0, full+ }+ return execName, args+}diff --git a/server/pkg/agent/cursor_invocation_other.go b/server/pkg/agent/cursor_invocation_other.gonew file mode 100644index 0000000000..e9683e7e8a--- /dev/null+++ b/server/pkg/agent/cursor_invocation_other.go@@ -0,0 +1,11 @@+//go:build !windows++package agent++import "log/slog"++// platformCursorInvocation is a no-op on non-Windows platforms: cursor-agent+// is a native binary and Go's os/exec can pass argv unchanged.+func platformCursorInvocation(_ string, _ []string, _ *slog.Logger) (string, []string, bool) {+ return "", nil, false+}diff --git a/server/pkg/agent/cursor_invocation_test.go b/server/pkg/agent/cursor_invocation_test.gonew file mode 100644index 0000000000..ecd16d2f2e--- /dev/null+++ b/server/pkg/agent/cursor_invocation_test.go@@ -0,0 +1,31 @@+package agent++import (+ "io"+ "log/slog"+ "path/filepath"+ "reflect"+ "testing"+)++// TestChooseCursorInvocation_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 TestChooseCursorInvocation_PassthroughForNonLauncher(t *testing.T) {+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))++ execName := "cursor-agent"+ lookedUp := filepath.Join(t.TempDir(), "cursor-agent") // no .cmd / .bat+ args := []string{"chat", "-p", "hello\nworld", "--output-format", "stream-json", "--yolo"}++ gotExec, gotArgs := chooseCursorInvocation(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/cursor_invocation_windows.go b/server/pkg/agent/cursor_invocation_windows.gonew file mode 100644index 0000000000..cd7e95e345--- /dev/null+++ b/server/pkg/agent/cursor_invocation_windows.go@@ -0,0 +1,80 @@+//go:build windows++package agent++import (+ "log/slog"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+)++// powerShellLookup resolves the PowerShell host to use. It is overridable in+// 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.+//+// We replace+//+// cursor-agent.cmd <args...>+//+// 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) {+ 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")+ 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("cursor-agent: routing through powershell -File to preserve argv tokens",+ "powershell", psExe,+ "ps1", ps1,+ "original", lookedUp,+ )+ }+ return psExe, full, true+}++// 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.+func defaultPowerShellLookup() (string, bool) {+ for _, name := range []string{"pwsh.exe", "powershell.exe"} {+ if p, err := exec.LookPath(name); err == nil {+ return p, true+ }+ }+ root := os.Getenv("SystemRoot")+ if root == "" {+ root = `C:\Windows`+ }+ candidate := filepath.Join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")+ if st, err := os.Stat(candidate); err == nil && !st.IsDir() {+ return candidate, true+ }+ return "", false+}diff --git a/server/pkg/agent/cursor_invocation_windows_test.go b/server/pkg/agent/cursor_invocation_windows_test.gonew file mode 100644index 0000000000..e43c26a740--- /dev/null+++ b/server/pkg/agent/cursor_invocation_windows_test.go@@ -0,0 +1,125 @@+//go:build windows++package agent++import (+ "io"+ "log/slog"+ "os"+ "path/filepath"+ "reflect"+ "testing"+)++// stubPowerShell installs a deterministic PowerShell lookup for the duration+// of a test and restores the original on cleanup.+func stubPowerShell(t *testing.T, path string, ok bool) {+ t.Helper()+ prev := powerShellLookup+ powerShellLookup = func() (string, bool) { return path, ok }+ t.Cleanup(func() { powerShellLookup = prev })+}++func writeFile(t *testing.T, path, body string) {+ t.Helper()+ if err := os.WriteFile(path, []byte(body), 0o644); err != nil {+ t.Fatalf("write %s: %v", path, err)+ }+}++// TestPlatformCursorInvocation_RewritesCmdLauncherToPowerShellFile is the core+// Windows test: when LookPath resolves cursor-agent to the official .cmd+// launcher and a sibling cursor-agent.ps1 exists, we should invoke+// PowerShell with -File <ps1> and forward every original arg unchanged+// (including a multi-line -p prompt that would otherwise be mangled by the+// cmd.exe %* re-expansion in the .cmd launcher).+func TestPlatformCursorInvocation_RewritesCmdLauncherToPowerShellFile(t *testing.T) {+ dir := t.TempDir()+ cmdPath := filepath.Join(dir, "cursor-agent.cmd")+ ps1Path := filepath.Join(dir, "cursor-agent.ps1")+ writeFile(t, cmdPath, "@echo off\r\npowershell -NoProfile -ExecutionPolicy Bypass -File \"%~dp0cursor-agent.ps1\" %*\r\n")+ writeFile(t, ps1Path, "# fake cursor-agent.ps1\r\n")++ fakePS := filepath.Join(dir, "powershell.exe")+ writeFile(t, fakePS, "")+ stubPowerShell(t, fakePS, true)++ args := []string{+ "chat",+ "-p", "line1\nline2\nline3",+ "--output-format", "stream-json",+ "--yolo",+ "--workspace", `C:\some\workspace`,+ }+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))++ gotExec, gotArgs, ok := platformCursorInvocation(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)+ }+}++// TestPlatformCursorInvocation_SkipsWhenNotCmdOrBat ensures we leave argv+// alone when the user explicitly resolved cursor-agent to something that+// isn't a batch launcher (e.g. a real binary or a node script).+func TestPlatformCursorInvocation_SkipsWhenNotCmdOrBat(t *testing.T) {+ dir := t.TempDir()+ exePath := filepath.Join(dir, "cursor-agent.exe")+ writeFile(t, exePath, "")+ // A sibling .ps1 must not trick us into rewriting a non-launcher exec.+ writeFile(t, filepath.Join(dir, "cursor-agent.ps1"), "")++ stubPowerShell(t, filepath.Join(dir, "powershell.exe"), true)++ logger := slog.New(slog.NewTextHandler(io.Discard, nil))+ if _, _, ok := platformCursorInvocation(exePath, []string{"chat"}, logger); ok {+ t.Fatalf("expected ok=false for non-.cmd/.bat launcher")+ }+}++// TestPlatformCursorInvocation_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 TestPlatformCursorInvocation_SkipsWhenPS1Missing(t *testing.T) {+ dir := t.TempDir()+ cmdPath := filepath.Join(dir, "cursor-agent.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 := platformCursorInvocation(cmdPath, []string{"chat"}, logger); ok {+ t.Fatalf("expected ok=false when cursor-agent.ps1 is missing")+ }+}++// TestPlatformCursorInvocation_SkipsWhenPowerShellMissing covers a stripped+// down environment in which neither pwsh.exe nor powershell.exe can be+// resolved. We must not fabricate an empty-string argv[0].+func TestPlatformCursorInvocation_SkipsWhenPowerShellMissing(t *testing.T) {+ dir := t.TempDir()+ cmdPath := filepath.Join(dir, "cursor-agent.cmd")+ ps1Path := filepath.Join(dir, "cursor-agent.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 := platformCursorInvocation(cmdPath, []string{"chat"}, logger); ok {+ t.Fatalf("expected ok=false when no powershell host is available")+ }+}