Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(agent): preserve Pi RPC stdin on Windows (#7111)

XuSt0b9dcc6799cc
diff --git a/server/pkg/agent/pi_invocation_windows.go b/server/pkg/agent/pi_invocation_windows.go
index 40f1e13edc..bccad85b8d 100644
--- a/server/pkg/agent/pi_invocation_windows.go
+++ b/server/pkg/agent/pi_invocation_windows.go
@@ -2,11 +2,62 @@
package agent
-import "log/slog"
+import (
+ "log/slog"
+ "os"
+ "path/filepath"
+ "strings"
+)
// 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) {
+ if isPiRPCInvocation(args) {
+ return rewriteCmdToPS1Command("pi", lookedUp, args, logger)
+ }
return rewriteCmdToPS1("pi", lookedUp, args, logger)
}
+
+func isPiRPCInvocation(args []string) bool {
+ for i := 0; i < len(args); i++ {
+ arg := args[i]
+ if arg == "--mode" && i+1 < len(args) && args[i+1] == "rpc" {
+ return true
+ }
+ if arg == "--mode=rpc" {
+ return true
+ }
+ }
+ return false
+}
+
+func rewriteCmdToPS1Command(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
+ }
+ ps1 := filepath.Join(filepath.Dir(lookedUp), toolName+".ps1")
+ if st, err := os.Stat(ps1); err != nil || st.IsDir() {
+ return "", nil, false
+ }
+
+ psExe, ok := powerShellLookup()
+ if !ok {
+ return "", nil, false
+ }
+
+ quotedPS1 := strings.ReplaceAll(ps1, "'", "''")
+ full := make([]string, 0, 6+len(args))
+ full = append(full, "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", "& '"+quotedPS1+"' @args")
+ full = append(full, args...)
+
+ if logger != nil {
+ logger.Info(toolName+": routing RPC through powershell -Command to preserve stdin",
+ "powershell", psExe,
+ "ps1", ps1,
+ "original", lookedUp,
+ )
+ }
+ return psExe, full, true
+}
diff --git a/server/pkg/agent/pi_invocation_windows_test.go b/server/pkg/agent/pi_invocation_windows_test.go
index 51899a6440..e2396892f1 100644
--- a/server/pkg/agent/pi_invocation_windows_test.go
+++ b/server/pkg/agent/pi_invocation_windows_test.go
@@ -62,6 +62,48 @@ func TestPlatformPiInvocation_RewritesCmdLauncherToPowerShellFile(t *testing.T)
}
}
+// TestPlatformPiInvocation_RPCRoutesThroughPowerShellCommand pins the model
+// discovery path. Pi RPC keeps stdin open for bidirectional JSON-RPC, while the
+// npm pi.ps1 -File wrapper can wait for EOF before forwarding stdin. Use
+// -Command with @args only for RPC so ordinary task execution keeps the
+// established -File launcher behaviour above.
+func TestPlatformPiInvocation_RPCRoutesThroughPowerShellCommand(t *testing.T) {
+ dir := t.TempDir()
+ cmdPath := filepath.Join(dir, "pi.cmd")
+ ps1Path := filepath.Join(dir, "pi.ps1")
+ writeFile(t, cmdPath, "@echo off\r\npowershell -NoProfile -ExecutionPolicy Bypass -File \"%~dp0pi.ps1\" %*\r\n")
+ writeFile(t, ps1Path, "# fake pi.ps1\r\n")
+
+ fakePS := filepath.Join(dir, "powershell.exe")
+ writeFile(t, fakePS, "")
+ stubPowerShell(t, fakePS, true)
+
+ args := []string{"--mode", "rpc", "--no-session", "--no-skills"}
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+
+ gotExec, gotArgs, ok := platformPiInvocation(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",
+ "-Command", "& '" + ps1Path + "' @args",
+ }, args...)
+ if !reflect.DeepEqual(gotArgs, wantArgs) {
+ t.Errorf("argv mismatch:\n got %#v\n want %#v", gotArgs, wantArgs)
+ }
+ for _, arg := range gotArgs {
+ if arg == "-File" {
+ t.Fatalf("RPC model discovery must not use powershell -File: %#v", gotArgs)
+ }
+ }
+}
+
// TestPlatformPiInvocation_SkipsWhenNotCmdOrBat ensures we leave argv alone
// when the user explicitly resolved pi to something that isn't a batch
// launcher (e.g. a real binary or a node script via shebang shim).
diff --git a/server/pkg/agent/pi_stdin_windows_test.go b/server/pkg/agent/pi_stdin_windows_test.go
index 3ff3977125..a007ab8ab7 100644
--- a/server/pkg/agent/pi_stdin_windows_test.go
+++ b/server/pkg/agent/pi_stdin_windows_test.go
@@ -3,6 +3,8 @@
package agent
import (
+ "bufio"
+ "context"
"fmt"
"io"
"log/slog"
@@ -15,6 +17,7 @@ import (
const (
piShimHelperEnv = "MULTICA_PI_SHIM_HELPER"
+ piShimHelperRPCEnv = "MULTICA_PI_SHIM_RPC_HELPER"
piShimHelperArgvFile = "MULTICA_PI_SHIM_ARGV_FILE"
piShimHelperInFile = "MULTICA_PI_SHIM_STDIN_FILE"
)
@@ -39,6 +42,10 @@ func TestPiShimHelperProcess(t *testing.T) {
fmt.Fprintf(os.Stderr, "helper: write argv: %v\n", err)
os.Exit(1)
}
+ if os.Getenv(piShimHelperRPCEnv) == "1" {
+ runPiRPCHelper()
+ os.Exit(0)
+ }
stdin, err := io.ReadAll(os.Stdin)
if err != nil {
fmt.Fprintf(os.Stderr, "helper: read stdin: %v\n", err)
@@ -54,6 +61,19 @@ func TestPiShimHelperProcess(t *testing.T) {
os.Exit(0)
}
+func runPiRPCHelper() {
+ scanner := bufio.NewScanner(os.Stdin)
+ for scanner.Scan() {
+ line := scanner.Text()
+ switch {
+ case strings.Contains(line, `"get_state"`):
+ fmt.Println(`{"id":"multica-state","type":"response","command":"get_state","success":true,"data":{"model":{"id":"reasoning-model","provider":"provider","reasoning":true,"thinkingLevelMap":{"xhigh":"xhigh","max":"max"}},"thinkingLevel":"max"}}`)
+ case strings.Contains(line, `"get_available_models"`):
+ fmt.Println(`{"id":"multica-models","type":"response","command":"get_available_models","success":true,"data":{"models":[{"id":"reasoning-model","provider":"provider","reasoning":true,"thinkingLevelMap":{"xhigh":"xhigh","max":"max"}}]}}`)
+ }
+ }
+}
+
// TestPiExecutePromptSurvivesPowerShellShim exercises the complete Windows
// production boundary that #6457 crosses:
//
@@ -76,6 +96,82 @@ func TestPiExecutePromptSurvivesPowerShellShim(t *testing.T) {
}
}
+// TestPiExecutePromptSurvivesPowerShellShimRPCDiscoveryBeforeStdinEOF exercises
+// the complete Windows model discovery boundary:
+//
+// Go -> powershell -Command pi.ps1 @args -> native child
+//
+// The fake Pi child answers both RPC requests while stdin is still open. A
+// -File entrypoint simulates the npm wrapper behaviour that waits for stdin EOF
+// before forwarding input; the test therefore fails against the old launcher
+// path by timing out and returning the fallback catalog with no Thinking data.
+func TestPiExecutePromptSurvivesPowerShellShimRPCDiscoveryBeforeStdinEOF(t *testing.T) {
+ hosts := availablePowerShellHosts()
+ if len(hosts) == 0 {
+ t.Skip("no PowerShell host available")
+ }
+ for _, host := range hosts {
+ t.Run(filepath.Base(host), func(t *testing.T) {
+ stubPowerShell(t, host, true)
+ assertPiRPCDiscoveryBeforeStdinEOF(t)
+ })
+ }
+}
+
+func assertPiRPCDiscoveryBeforeStdinEOF(t *testing.T) {
+ t.Helper()
+
+ self, err := os.Executable()
+ if err != nil {
+ t.Fatalf("locate test binary: %v", err)
+ }
+ dir := t.TempDir()
+ argvPath := filepath.Join(dir, "rpc-argv.txt")
+
+ cmdPath := filepath.Join(dir, "pi.cmd")
+ writeFile(t, cmdPath, "@echo off\r\npowershell -NoProfile -ExecutionPolicy Bypass -File \"%~dp0pi.ps1\" %*\r\n")
+ ps1 := fmt.Sprintf(""+
+ "$env:%s = '1'\r\n"+
+ "$env:%s = '1'\r\n"+
+ "$env:%s = '%s'\r\n"+
+ "if ($MyInvocation.Line -notlike '*@args*') { [Console]::In.ReadToEnd() | Out-Null }\r\n"+
+ "& '%s' '-test.run=^TestPiShimHelperProcess$' '--' $args\r\n"+
+ "exit $LASTEXITCODE\r\n",
+ piShimHelperEnv,
+ piShimHelperRPCEnv,
+ piShimHelperArgvFile, argvPath,
+ self)
+ writeFile(t, filepath.Join(dir, "pi.ps1"), ps1)
+
+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
+ defer cancel()
+ models, ok := discoverPiModelsRPC(ctx, Command{Path: cmdPath}, cmdPath)
+ if !ok {
+ t.Fatalf("Pi RPC discovery did not complete before stdin EOF")
+ }
+ if len(models) != 1 {
+ t.Fatalf("expected one discovered model, got %+v", models)
+ }
+ model := models[0]
+ if model.ID != "provider/reasoning-model" || model.Provider != "provider" {
+ t.Fatalf("unexpected model: %+v", model)
+ }
+ if model.Thinking == nil || !piThinkingSupports(model.Thinking, "max") || model.Thinking.DefaultLevel != "max" {
+ t.Fatalf("expected max thinking metadata from RPC, got %+v", model.Thinking)
+ }
+
+ argvRaw, err := os.ReadFile(argvPath)
+ if err != nil {
+ t.Fatalf("native child never recorded RPC argv: %v", err)
+ }
+ gotArgv := string(argvRaw)
+ for _, want := range []string{"--mode", "rpc", "--no-session", "--no-skills", "--no-prompt-templates", "--no-context-files"} {
+ if !strings.Contains(gotArgv, want) {
+ t.Errorf("expected %q to reach native child; argv=%q", want, gotArgv)
+ }
+ }
+}
+
func assertPiPromptSurvivesShim(t *testing.T) {
t.Helper()