Skip to content

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

Go

MUL-6658 fix(agent): own the runtime process tree on every backend (#7522) (#7531)

Bohan Jiang46b5d9e6d1c0
diff --git a/server/pkg/agent/acp_terminal.go b/server/pkg/agent/acp_terminal.go
index dc93ee72a8..9905a38ace 100644
--- a/server/pkg/agent/acp_terminal.go
+++ b/server/pkg/agent/acp_terminal.go
@@ -156,11 +156,6 @@ func (c *hermesClient) acpTerminalCreate(params json.RawMessage) (map[string]any
cmd = NewCommand("/bin/sh", nil).exec(c.terminalContext(), "-c", p.Command)
}
hideAgentWindow(cmd)
- configureProcessGroup(cmd)
- cmd.Cancel = func() error {
- signalProcessGroup(cmd, syscall.SIGKILL)
- return nil
- }
cmd.Dir = cwd
cmd.Env = env
diff --git a/server/pkg/agent/antigravity.go b/server/pkg/agent/antigravity.go
index 7fe10dd99f..10df05f70f 100644
--- a/server/pkg/agent/antigravity.go
+++ b/server/pkg/agent/antigravity.go
@@ -97,7 +97,7 @@ func (b *antigravityBackend) Execute(ctx context.Context, prompt string, opts Ex
stderrBuf := newStderrTail(newLogWriter(b.cfg.Logger, "[agy:stderr] "), agentStderrTailBytes)
cmd.Stderr = stderrBuf
- if err := cmd.Start(); err != nil {
+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
cancel()
_ = os.Remove(logPath)
return nil, fmt.Errorf("start agy: %w", err)
@@ -153,6 +153,7 @@ func (b *antigravityBackend) Execute(ctx context.Context, prompt string, opts Ex
}
waitErr := cmd.Wait()
+ releaseProcessGroup(cmd)
duration := time.Since(startTime)
sessionID := readAntigravityConversationID(logPath)
diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.go
index c23aba0c13..fecf3f3498 100644
--- a/server/pkg/agent/claude.go
+++ b/server/pkg/agent/claude.go
@@ -74,17 +74,8 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
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
- // spawns — not just the direct child. The default CommandContext behaviour
- // SIGKILLs only the leader, which orphans those descendants; on a resumed
- // stream-json session with no wall-clock timeout they then keep running and
- // burning model budget long after the task was cancelled, and under
- // --max-concurrent-tasks 1 starve every queued task (#5918). This mirrors
- // the fix already made for codex (#4520) and opencode (#4533).
- configureProcessGroup(cmd)
- // Take over context cancellation: the default would SIGKILL only the leader
- // the instant runCtx is done. We instead drive a graceful group-wide
+ // Take over context cancellation: the default kills the whole group the
+ // instant runCtx is done. We instead drive a graceful group-wide
// SIGTERM→SIGKILL from the cancellation goroutine below and close stdout
// only after the tree has been signalled. Returning nil keeps os/exec from
// racing us with its own kill; WaitDelay remains the hard backstop.
@@ -120,7 +111,7 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
stderrBuf := newStderrTail(newLogWriter(b.cfg.Logger, "[claude:stderr] "), agentStderrTailBytes)
cmd.Stderr = stderrBuf
- if err := cmd.Start(); err != nil {
+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
closeStdin()
cancel()
return nil, fmt.Errorf("start claude: %w", err)
@@ -128,7 +119,7 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
b.cfg.Logger.Info("claude started", "pid", cmd.Process.Pid, "cwd", opts.Cwd, "model", opts.Model)
- // cmd.Start() succeeded — transfer temp file ownership to the goroutine.
+ // The process started — transfer temp file ownership to the goroutine.
mcpFileCleanup = nil
msgCh := make(chan Message, 256)
@@ -284,6 +275,10 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
// Wait for process exit, then release the cancellation handler.
exitErr := cmd.Wait()
close(procDone)
+ // The leader is reaped; drop ownership. On Windows that closes the Job
+ // Object, which kills anything still inside it — precisely what should
+ // happen to a descendant that outlived the CLI (GH #7522).
+ releaseProcessGroup(cmd)
duration := time.Since(startTime)
// writeDone is buffered (cap 1) and the writer always sends — by the
// time cmd has exited, the prompt write has either succeeded, hit a
@@ -1118,7 +1113,7 @@ func detectCLIVersion(ctx context.Context, runtimeCmd Command) (string, error) {
// closes — defeating the timeout above. WaitDelay forces the pipes shut and
// reaps shortly after the context fires so this call always returns.
cmd.WaitDelay = 2 * time.Second
- data, err := cmd.Output()
+ data, err := outputOwned(cmd, runtimeCmd.logger)
if err != nil {
// One provider-agnostic boundary for probes: DetectVersion routes every
// provider through here, so an ENOEXEC diagnosis added at this point
diff --git a/server/pkg/agent/codebuddy.go b/server/pkg/agent/codebuddy.go
index 7cd79a5fbf..0d566e9be6 100644
--- a/server/pkg/agent/codebuddy.go
+++ b/server/pkg/agent/codebuddy.go
@@ -160,7 +160,7 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Exec
stderrBuf := newStderrTail(newLogWriter(b.cfg.Logger, "[codebuddy:stderr] "), agentStderrTailBytes)
cmd.Stderr = stderrBuf
- if err := cmd.Start(); err != nil {
+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
closeStdin()
cancel()
return nil, fmt.Errorf("start codebuddy: %w", err)
@@ -279,6 +279,7 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Exec
// Wait for process exit.
exitErr := cmd.Wait()
+ releaseProcessGroup(cmd)
duration := time.Since(startTime)
// writeDone is buffered (cap 1) and the writer always sends — by the
// time cmd has exited, the prompt write has either succeeded, hit a
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index 1fe1c16292..ae8b6238c8 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -1025,7 +1025,6 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
// scanner overflow during thread/resume otherwise leaked Codex
// processes indefinitely. configureProcessGroup is a no-op on
// Windows.
- configureProcessGroup(cmd)
// Override the default exec.CommandContext cancel behaviour. The
// default sends SIGKILL only to cmd.Process (the leader); we instead
// signal the whole process group so descendants die too. Returning
@@ -2067,7 +2066,7 @@ func detectCodexVersionForDiagnostics(ctx context.Context, runtimeCmd Command, e
cmd := runtimeCmd.exec(versionCtx, "--version")
cmd.Env = env
- data, err := cmd.Output()
+ data, err := outputOwned(cmd, logger)
if err != nil {
if logger != nil {
logger.Debug("codex version diagnostic failed", "error", err)
diff --git a/server/pkg/agent/copilot.go b/server/pkg/agent/copilot.go
index e3ed3c1752..ad8a205485 100644
--- a/server/pkg/agent/copilot.go
+++ b/server/pkg/agent/copilot.go
@@ -365,7 +365,7 @@ func (b *copilotBackend) Execute(ctx context.Context, prompt string, opts ExecOp
stderrBuf := newStderrTail(newLogWriter(b.cfg.Logger, "[copilot:stderr] "), agentStderrTailBytes)
cmd.Stderr = stderrBuf
- if err := cmd.Start(); err != nil {
+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
cancel()
return nil, fmt.Errorf("start copilot: %w", err)
}
@@ -415,6 +415,7 @@ func (b *copilotBackend) Execute(ctx context.Context, prompt string, opts ExecOp
}
exitErr := cmd.Wait()
+ releaseProcessGroup(cmd)
duration := time.Since(startTime)
if runCtx.Err() == context.DeadlineExceeded {
diff --git a/server/pkg/agent/cursor.go b/server/pkg/agent/cursor.go
index 783268116e..8864bb4768 100644
--- a/server/pkg/agent/cursor.go
+++ b/server/pkg/agent/cursor.go
@@ -60,7 +60,7 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
stderrBuf := newStderrTail(newLogWriter(b.cfg.Logger, "[cursor:stderr] "), agentStderrTailBytes)
cmd.Stderr = stderrBuf
- if err := cmd.Start(); err != nil {
+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
closeStdin()
cancel()
return nil, fmt.Errorf("start cursor-agent: %w", err)
@@ -332,6 +332,7 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
}
exitErr := cmd.Wait()
+ releaseProcessGroup(cmd)
duration := time.Since(startTime)
// Wait has already closed the stdin pipe, so a prompt write still blocked
diff --git a/server/pkg/agent/deveco.go b/server/pkg/agent/deveco.go
index 7cc6ba578f..e31b0d596f 100644
--- a/server/pkg/agent/deveco.go
+++ b/server/pkg/agent/deveco.go
@@ -121,10 +121,6 @@ func (b *devecoBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
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 direct
- // child — otherwise a cancelled or restarted run can orphan a descendant.
- configureProcessGroup(cmd)
// Take over context cancellation: drive a graceful, group-wide
// SIGTERM→SIGKILL from the cancellation goroutine below and close the
// stdout read end only after the tree has been signalled. Returning nil
@@ -154,7 +150,7 @@ func (b *devecoBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
}
cmd.Stderr = newLogWriter(b.cfg.Logger, "[deveco:stderr] ")
- if err := cmd.Start(); err != nil {
+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
cancel()
return nil, fmt.Errorf("start deveco: %w", err)
}
@@ -202,6 +198,7 @@ func (b *devecoBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
exitErr := cmd.Wait()
close(procDone)
+ releaseProcessGroup(cmd)
duration := time.Since(startTime)
if runCtx.Err() == context.DeadlineExceeded {
diff --git a/server/pkg/agent/deveco_models.go b/server/pkg/agent/deveco_models.go
index 888bc22688..56d4459145 100644
--- a/server/pkg/agent/deveco_models.go
+++ b/server/pkg/agent/deveco_models.go
@@ -30,7 +30,7 @@ func discoverDevecoModels(ctx context.Context, runtimeCmd Command) ([]Model, err
defer cancel()
cmd := runtimeCmd.exec(runCtx, "models")
hideAgentWindow(cmd)
- out, _ := cmd.Output()
+ out, _ := outputOwned(cmd, runtimeCmd.logger)
models := parseDevecoModels(string(out))
if len(models) == 0 {
return []Model{}, nil
diff --git a/server/pkg/agent/dim.go b/server/pkg/agent/dim.go
index 3aad72bf01..419275e99c 100644
--- a/server/pkg/agent/dim.go
+++ b/server/pkg/agent/dim.go
@@ -193,11 +193,10 @@ func (b *dimBackend) Execute(ctx context.Context, prompt string, opts ExecOption
cmd := b.cfg.commandAt(execPath).exec(runCtx, dimArgs...)
hideAgentWindow(cmd)
- configureProcessGroup(cmd)
- // Take over context cancellation: the default would SIGKILL only the
- // leader the instant runCtx is done, orphaning descendants. We instead
- // drive a group-wide SIGKILL from the deferred cleanup below. Returning
- // nil keeps os/exec from racing us with its own kill.
+ // Take over context cancellation: the default kills the group the instant
+ // runCtx is done, leaving no chance to shut the ACP session down first. We
+ // instead drive a group-wide SIGKILL from the deferred cleanup below.
+ // Returning nil keeps os/exec from racing us with its own kill.
cmd.Cancel = func() error { return nil }
cmd.WaitDelay = 10 * time.Second
b.cfg.logAgentCommand(cmd, newAgentCommandLogArgs(dimArgs, trustAgentCommandPositional(0, "acp")))
diff --git a/server/pkg/agent/dsh.go b/server/pkg/agent/dsh.go
index b7eb9dbeb4..f6e794c960 100644
--- a/server/pkg/agent/dsh.go
+++ b/server/pkg/agent/dsh.go
@@ -222,7 +222,6 @@ func (b *dshBackend) Execute(ctx context.Context, prompt string, opts ExecOption
args := dshLaunchArgs()
cmd := b.cfg.commandAt(execPath).exec(runCtx, args...)
hideAgentWindow(cmd)
- configureProcessGroup(cmd)
cmd.Cancel = func() error { return nil }
cmd.WaitDelay = 10 * time.Second
if opts.Cwd != "" {
@@ -242,7 +241,7 @@ func (b *dshBackend) Execute(ctx context.Context, prompt string, opts ExecOption
}
stderrBuf := newStderrTail(newLogWriter(b.cfg.Logger, "[dsh:stderr] "), agentStderrTailBytes)
cmd.Stderr = stderrBuf
- if err := cmd.Start(); err != nil {
+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
cancel()
return nil, fmt.Errorf("start dsh: %w", err)
}
@@ -266,6 +265,7 @@ func (b *dshBackend) Execute(ctx context.Context, prompt string, opts ExecOption
if err := writeFrame(command); err != nil {
signalProcessGroup(cmd, syscall.SIGKILL)
_ = cmd.Wait()
+ releaseProcessGroup(cmd)
cancel()
return nil, fmt.Errorf("send dsh execute command: %w", err)
}
@@ -323,6 +323,7 @@ func (b *dshBackend) Execute(ctx context.Context, prompt string, opts ExecOption
}
exitErr := cmd.Wait()
close(procDone)
+ releaseProcessGroup(cmd)
result := state.result
if result == nil {
@@ -441,7 +442,7 @@ func discoverDshModels(ctx context.Context, runtimeCmd Command) ([]Model, error)
return nil, err
}
cmd.Stderr = io.Discard
- if err := cmd.Start(); err != nil {
+ if err := startOwnedProcessTree(cmd, runtimeCmd.logger); err != nil {
return nil, err
}
var models []Model
@@ -461,6 +462,7 @@ func discoverDshModels(ctx context.Context, runtimeCmd Command) ([]Model, error)
}
scanErr := scanner.Err()
exitErr := cmd.Wait()
+ releaseProcessGroup(cmd)
if scanErr != nil {
return nil, scanErr
}
diff --git a/server/pkg/agent/grok.go b/server/pkg/agent/grok.go
index f2e7ffd3d8..7b63571dd0 100644
--- a/server/pkg/agent/grok.go
+++ b/server/pkg/agent/grok.go
@@ -175,7 +175,7 @@ func (b *grokBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
return nil, fmt.Errorf("grok stderr pipe: %w", err)
}
- if err := cmd.Start(); err != nil {
+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
cancel()
return nil, fmt.Errorf("start grok: %w", err)
}
@@ -259,6 +259,7 @@ func (b *grokBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
defer func() {
stdin.Close()
_ = cmd.Wait()
+ releaseProcessGroup(cmd)
}()
startTime := time.Now()
diff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.go
index ecbd267792..ed560210fc 100644
--- a/server/pkg/agent/hermes.go
+++ b/server/pkg/agent/hermes.go
@@ -340,7 +340,7 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
return nil, fmt.Errorf("hermes stderr pipe: %w", err)
}
- if err := cmd.Start(); err != nil {
+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
cancel()
return nil, fmt.Errorf("start hermes: %w", err)
}
@@ -437,6 +437,7 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
// task timeout and make a later deferred cancel ineffective.
cancel()
_ = cmd.Wait()
+ releaseProcessGroup(cmd)
}()
startTime := time.Now()
diff --git a/server/pkg/agent/kimi.go b/server/pkg/agent/kimi.go
index b51a1e5b47..a6504a5b39 100644
--- a/server/pkg/agent/kimi.go
+++ b/server/pkg/agent/kimi.go
@@ -102,7 +102,7 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
return nil, fmt.Errorf("kimi stderr pipe: %w", err)
}
- if err := cmd.Start(); err != nil {
+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
cancel()
return nil, fmt.Errorf("start kimi: %w", err)
}
@@ -205,6 +205,7 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
defer func() {
stdin.Close()
_ = cmd.Wait()
+ releaseProcessGroup(cmd)
}()
startTime := time.Now()
diff --git a/server/pkg/agent/kiro.go b/server/pkg/agent/kiro.go
index fb75413594..ea6f0b1ba2 100644
--- a/server/pkg/agent/kiro.go
+++ b/server/pkg/agent/kiro.go
@@ -91,7 +91,7 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
return nil, fmt.Errorf("kiro stderr pipe: %w", err)
}
- if err := cmd.Start(); err != nil {
+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
cancel()
return nil, fmt.Errorf("start kiro: %w", err)
}
@@ -222,6 +222,7 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
defer func() {
stdin.Close()
_ = cmd.Wait()
+ releaseProcessGroup(cmd)
}()
startTime := time.Now()
diff --git a/server/pkg/agent/launch.go b/server/pkg/agent/launch.go
index 563d5d45d7..989ff3d443 100644
--- a/server/pkg/agent/launch.go
+++ b/server/pkg/agent/launch.go
@@ -1,10 +1,14 @@
package agent
import (
+ "bytes"
"context"
+ "errors"
"log/slog"
"os/exec"
"strings"
+ "syscall"
+ "time"
)
const redactedAgentCommandArg = "<redacted>"
@@ -107,9 +111,145 @@ 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 exec.CommandContext(ctx, c.Path, c.Argv(args...)...)
+ return newRuntimeCmd(exec.CommandContext(ctx, c.Path, c.Argv(args...)...))
}
+// newRuntimeCmd applies the process-lifecycle defaults every runtime process in
+// this package gets. It runs at construction because both of them have to be in
+// place before the process exists.
+//
+// Both used to be opt-in, and opt-in is why GH #7522 happened. Of the 27 places
+// this package starts a process, 8 asked for a process group; the rest left
+// their CLI in the daemon's group, where a group-wide signal cannot reach it.
+// os/exec's default Cancel is the same leak by another route: it kills the
+// leader alone, so a cancelled task's tool subprocesses — MCP servers, shells,
+// whatever the agent spawned — survive it. On Linux that was #5918. On Windows,
+// where the leader is often a cmd.exe shim and the real CLI is already a
+// grandchild, a cancelled agent kept working for 40 minutes.
+//
+// A backend that wants a graceful shutdown instead of an immediate kill assigns
+// its own cmd.Cancel after construction and wins; claude, dsh and deveco do,
+// because they drive SIGTERM → grace → SIGKILL themselves.
+func newRuntimeCmd(cmd *exec.Cmd) *exec.Cmd {
+ configureProcessGroup(cmd)
+ cmd.Cancel = func() error {
+ signalProcessGroup(cmd, syscall.SIGKILL)
+ return nil
+ }
+ return cmd
+}
+
+// runOwned is Run() over an owned process tree: start, wait, drop ownership.
+//
+// os/exec's Run/Output/CombinedOutput call Start themselves, so a probe written
+// with them never reaches startOwnedProcessTree and owns nothing on Windows —
+// where the direct child of a `--version` probe is typically the shim, not the
+// CLI. That is the same escape GH #7522 was reported for, in a path nobody was
+// looking at: detectCLIVersion's own comment already describes a broken CLI
+// leaving grandchildren behind. These three helpers are how a synchronous probe
+// gets the same ownership a task launch has.
+func runOwned(cmd *exec.Cmd, logger *slog.Logger) error {
+ // Without a bound this waits for its own cleanup and never returns. A
+ // descendant that inherited the output pipes holds them open after the
+ // leader exits; cmd.Wait blocks until the copy goroutines see EOF; and the
+ // thing that would close those pipes is the release below, which runs
+ // after Wait. WaitDelay is defined for exactly this case — "a child
+ // process that exits but leaves its I/O pipes unclosed" — and cancellation
+ // is no help, because a probe like checkOpenclawVersion runs on the
+ // caller's context before any task timeout exists.
+ //
+ // A caller that set its own bound keeps it; detectCLIVersion has had one
+ // since MUL-3812 for this exact shape.
+ if cmd.WaitDelay == 0 {
+ cmd.WaitDelay = probeWaitDelay
+ }
+ if err := startOwnedProcessTree(cmd, logger); err != nil {
+ return err
+ }
+ err := cmd.Wait()
+ // The probe is over the moment its leader is: nothing it spawned should
+ // outlive the answer. Signalling before the release covers Unix, where
+ // releasing a process group is a no-op; on Windows closing the Job Object
+ // would take the tree down on its own.
+ signalProcessGroup(cmd, syscall.SIGKILL)
+ releaseProcessGroup(cmd)
+ return err
+}
+
+// probeWaitDelay bounds how long a finished probe waits on output pipes its
+// descendants left open. It matches the bound detectCLIVersion already sets by
+// hand. The timer only starts once the child has exited or the context is
+// done, so a healthy probe never pays it.
+const probeWaitDelay = 2 * time.Second
+
+// outputOwned is cmd.Output() over an owned process tree. It matches the
+// stdlib's contract — stdout returned, a failed run's stderr attached to the
+// *exec.ExitError — except that the stderr sample is the last
+// probeStderrSampleBytes rather than the stdlib's head-and-tail, which is where
+// a CLI's actual failure line ends up.
+func outputOwned(cmd *exec.Cmd, logger *slog.Logger) ([]byte, error) {
+ if cmd.Stdout != nil {
+ return nil, errors.New("exec: Stdout already set")
+ }
+ var stdout bytes.Buffer
+ cmd.Stdout = &stdout
+
+ // A caller that set its own Stderr wants it; only fill in the sample when
+ // nothing else is watching, exactly as Output() does.
+ var stderr *tailBuffer
+ if cmd.Stderr == nil {
+ stderr = &tailBuffer{max: probeStderrSampleBytes}
+ cmd.Stderr = stderr
+ }
+
+ err := runOwned(cmd, logger)
+ var exitErr *exec.ExitError
+ if stderr != nil && errors.As(err, &exitErr) {
+ exitErr.Stderr = stderr.Bytes()
+ }
+ return stdout.Bytes(), err
+}
+
+// combinedOutputOwned is cmd.CombinedOutput() over an owned process tree.
+// Stdout and Stderr are the same writer value, which is what makes os/exec give
+// them one pipe and therefore one interleaving, as the stdlib does.
+func combinedOutputOwned(cmd *exec.Cmd, logger *slog.Logger) ([]byte, error) {
+ if cmd.Stdout != nil {
+ return nil, errors.New("exec: Stdout already set")
+ }
+ if cmd.Stderr != nil {
+ return nil, errors.New("exec: Stderr already set")
+ }
+ var combined bytes.Buffer
+ cmd.Stdout = &combined
+ cmd.Stderr = &combined
+ err := runOwned(cmd, logger)
+ return combined.Bytes(), err
+}
+
+// probeStderrSampleBytes bounds the stderr kept for a failed probe's error.
+// os/exec bounds the same sample at 32 KiB; a CLI stuck in a log loop should
+// not be able to grow the daemon's heap through a `--version` call.
+const probeStderrSampleBytes = 32 << 10
+
+// tailBuffer keeps the last max bytes written to it and discards the rest. It
+// always reports a full write, so a child is never blocked or shortened by the
+// bound.
+type tailBuffer struct {
+ buf []byte
+ max int
+}
+
+func (t *tailBuffer) Write(p []byte) (int, error) {
+ t.buf = append(t.buf, p...)
+ if len(t.buf) > t.max {
+ t.buf = t.buf[len(t.buf)-t.max:]
+ }
+ return len(p), nil
+}
+
+func (t *tailBuffer) Bytes() []byte { return t.buf }
+
// 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
@@ -127,7 +267,7 @@ type invocationChooser func(execName, lookedUp string, args []string, logger *sl
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
+ return newRuntimeCmd(exec.CommandContext(ctx, argv0, cmdArgs...)), argv0, cmdArgs
}
// withFilteredPrefix returns a copy of the command whose prefix has been
diff --git a/server/pkg/agent/launch_process_unix_test.go b/server/pkg/agent/launch_process_unix_test.go
new file mode 100644
index 0000000000..546c8435ce
--- /dev/null
+++ b/server/pkg/agent/launch_process_unix_test.go
@@ -0,0 +1,202 @@
+//go:build unix
+
+package agent
+
+import (
+ "context"
+ "errors"
+ "log/slog"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+// TestRuntimeCommandsGetTheirOwnProcessGroup pins the default that GH #7522
+// showed was missing. Before, each backend had to remember to ask for a process
+// group and most did not, so a group-wide signal could not reach their CLI at
+// all. The group now comes from the one place a runtime process is built, which
+// means a backend cannot be launched without it.
+func TestRuntimeCommandsGetTheirOwnProcessGroup(t *testing.T) {
+ t.Parallel()
+
+ cmd := NewCommand("/bin/sh", nil).exec(context.Background(), "-c", "true")
+ if cmd.SysProcAttr == nil || !cmd.SysProcAttr.Setpgid {
+ t.Fatal("a runtime command must be built with Setpgid so cancellation can signal the whole tree")
+ }
+}
+
+// TestRuntimeCommandCancellationKillsDescendants is the behaviour the default
+// buys, on a command with no backend-specific cancellation logic at all: the
+// tool subprocesses an agent spawned must die with it.
+//
+// os/exec's own Cancel kills the leader alone, which is what left a cancelled
+// agent's descendants running. The fake here spawns a grandchild that outlives
+// its parent, so killing the leader is not enough to pass.
+func TestRuntimeCommandCancellationKillsDescendants(t *testing.T) {
+ t.Parallel()
+
+ tempDir := t.TempDir()
+ pidFile := filepath.Join(tempDir, "pids")
+ fakePath := filepath.Join(tempDir, "runtime")
+ writeTestExecutable(t, fakePath, []byte("#!/bin/sh\n"+
+ `( sleep 300 ) </dev/null >/dev/null 2>&1 &
+printf '%s %s\n' "$$" "$!" > "$1"
+sleep 300
+`))
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ cmd := NewCommand(fakePath, nil).exec(ctx, pidFile)
+ if err := startOwnedProcessTree(cmd, slog.Default()); err != nil {
+ t.Fatalf("start: %v", err)
+ }
+ defer releaseProcessGroup(cmd)
+
+ pids := waitForPids(t, pidFile)
+ cancel()
+
+ done := make(chan struct{})
+ go func() { _ = cmd.Wait(); close(done) }()
+ select {
+ case <-done:
+ case <-time.After(10 * time.Second):
+ t.Fatal("the cancelled process was never reaped")
+ }
+ for _, pid := range pids {
+ waitProcessGone(t, pid)
+ }
+}
+
+// TestProbeOutputCancellationKillsDescendants is the probe half of GH #7522.
+//
+// outputOwned exists because cmd.Output() calls Start itself and so can never
+// reach the ownership boundary. detectCLIVersion's own comment describes the
+// shape this reproduces: a CLI shim that leaves a grandchild behind. Cancelling
+// the probe has to reap both, not just the shim.
+func TestProbeOutputCancellationKillsDescendants(t *testing.T) {
+ t.Parallel()
+
+ tempDir := t.TempDir()
+ pidFile := filepath.Join(tempDir, "pids")
+ fakePath := filepath.Join(tempDir, "probe")
+ writeTestExecutable(t, fakePath, []byte("#!/bin/sh\n"+
+ `( sleep 300 ) </dev/null >/dev/null 2>&1 &
+printf '%s %s\n' "$$" "$!" > "$1"
+sleep 300
+`))
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ cmd := NewCommand(fakePath, nil).exec(ctx, pidFile)
+ cmd.WaitDelay = 5 * time.Second
+
+ done := make(chan error, 1)
+ go func() {
+ _, err := outputOwned(cmd, slog.Default())
+ done <- err
+ }()
+
+ pids := waitForPids(t, pidFile)
+ cancel()
+
+ select {
+ case <-done:
+ case <-time.After(20 * time.Second):
+ t.Fatal("outputOwned never returned after the probe was cancelled")
+ }
+ for _, pid := range pids {
+ waitProcessGone(t, pid)
+ }
+}
+
+// TestOutputOwnedMatchesStdlibContract keeps the owned probe helpers drop-in:
+// callers were using cmd.Output() and cmd.CombinedOutput() and must keep
+// getting the same bytes back.
+func TestOutputOwnedMatchesStdlibContract(t *testing.T) {
+ t.Parallel()
+
+ tempDir := t.TempDir()
+ fakePath := filepath.Join(tempDir, "noisy")
+ writeTestExecutable(t, fakePath, []byte("#!/bin/sh\n"+
+ `printf 'to-stdout\n'
+printf 'to-stderr\n' >&2
+exit 3
+`))
+
+ out, err := outputOwned(NewCommand(fakePath, nil).exec(context.Background()), slog.Default())
+ if string(out) != "to-stdout\n" {
+ t.Errorf("stdout = %q, want %q", out, "to-stdout\n")
+ }
+ var exitErr *exec.ExitError
+ if !errors.As(err, &exitErr) {
+ t.Fatalf("err = %v, want an *exec.ExitError", err)
+ }
+ if exitErr.ExitCode() != 3 {
+ t.Errorf("exit code = %d, want 3", exitErr.ExitCode())
+ }
+ if !strings.Contains(string(exitErr.Stderr), "to-stderr") {
+ t.Errorf("ExitError.Stderr = %q, want it to carry the probe's stderr", exitErr.Stderr)
+ }
+
+ combined, err := combinedOutputOwned(NewCommand(fakePath, nil).exec(context.Background()), slog.Default())
+ if err == nil {
+ t.Error("combinedOutputOwned should report the non-zero exit")
+ }
+ for _, want := range []string{"to-stdout", "to-stderr"} {
+ if !strings.Contains(string(combined), want) {
+ t.Errorf("combined output %q missing %q", combined, want)
+ }
+ }
+}
+
+// TestProbeReturnsWhenLeaderExitsHoldingPipes is the normal-exit counterpart to
+// the cancellation tests: nobody cancels anything here.
+//
+// The fake exits straight away but leaves a descendant holding the stdout and
+// stderr write ends. cmd.Wait() cannot return until those close, and on Windows
+// what closes them is releaseProcessGroup — which runs after Wait. A probe that
+// waits for its own cleanup never returns, and checkOpenclawVersion runs on the
+// caller's context before any task timeout exists, so the task would hang until
+// someone cancelled it by hand.
+func TestProbeReturnsWhenLeaderExitsHoldingPipes(t *testing.T) {
+ t.Parallel()
+
+ tempDir := t.TempDir()
+ pidFile := filepath.Join(tempDir, "pids")
+ fakePath := filepath.Join(tempDir, "wrapper")
+ // The descendant inherits stdout/stderr on purpose — that is what holds the
+ // pipe open after the leader is gone.
+ writeTestExecutable(t, fakePath, []byte("#!/bin/sh\n"+
+ `( sleep 300 ) &
+printf '%s %s\n' "$$" "$!" > "$1"
+printf 'v1.2.3\n'
+exit 0
+`))
+
+ done := make(chan []byte, 1)
+ go func() {
+ out, _ := outputOwned(NewCommand(fakePath, nil).exec(context.Background(), pidFile), slog.Default())
+ done <- out
+ }()
+
+ pids := waitForPids(t, pidFile)
+
+ select {
+ case out := <-done:
+ if string(out) != "v1.2.3\n" {
+ t.Errorf("stdout = %q, want the version line", out)
+ }
+ case <-time.After(15 * time.Second):
+ t.Fatal("outputOwned never returned: the leader exited, but Wait is still waiting for a pipe " +
+ "that only releaseProcessGroup can close, and releaseProcessGroup runs after Wait")
+ }
+
+ // Nothing the probe spawned may outlive the answer.
+ for _, pid := range pids {
+ waitProcessGone(t, pid)
+ }
+}
diff --git a/server/pkg/agent/launch_test.go b/server/pkg/agent/launch_test.go
index 66a59163d0..47a0739a47 100644
--- a/server/pkg/agent/launch_test.go
+++ b/server/pkg/agent/launch_test.go
@@ -384,6 +384,259 @@ func TestOnlyLaunchGoSpawnsRuntimeProcesses(t *testing.T) {
}
}
+// bareProcessStartCalls reports every os/exec call in file that starts a
+// process without going through startOwnedProcessTree.
+//
+// Run, Output and CombinedOutput are on the list because they call Start
+// themselves: a probe written with cmd.Output() never reaches the ownership
+// boundary at all, which is how the `--version` and model-discovery probes
+// stayed unowned on Windows after the first pass at GH #7522.
+func bareProcessStartCalls(fset *token.FileSet, file *ast.File) []string {
+ unowned := map[string]bool{"Start": true, "Run": true, "Output": true, "CombinedOutput": true}
+ var offenders []string
+ 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 || len(call.Args) != 0 || !unowned[sel.Sel.Name] {
+ return true
+ }
+ offenders = append(offenders, fset.Position(call.Pos()).String()+": ."+sel.Sel.Name+"()")
+ return true
+ })
+ return offenders
+}
+
+// unreleasedProcessTrees reports every function in file that takes ownership of
+// a process tree without dropping it.
+//
+// The rule is one owned start per function, paired with at least one release in
+// the same function. Equal counts would be the obvious rule and is the wrong
+// one: dsh's Execute has one start and two releases because it has two exit
+// paths, and both have to release. Capping starts at one is what makes the
+// "at least one release" side meaningful — without it, a function could add a
+// second, unreleased start and still pass on the strength of the first one's
+// release.
+func unreleasedProcessTrees(fset *token.FileSet, file *ast.File) []string {
+ var offenders []string
+ for _, decl := range file.Decls {
+ fn, ok := decl.(*ast.FuncDecl)
+ if !ok {
+ continue
+ }
+ starts, releases := 0, 0
+ ast.Inspect(fn, func(n ast.Node) bool {
+ call, ok := n.(*ast.CallExpr)
+ if !ok {
+ return true
+ }
+ ident, ok := call.Fun.(*ast.Ident)
+ if !ok {
+ return true
+ }
+ switch ident.Name {
+ case "startOwnedProcessTree":
+ starts++
+ case "releaseProcessGroup":
+ releases++
+ }
+ return true
+ })
+ where := fset.Position(fn.Pos()).String() + ": " + fn.Name.Name
+ switch {
+ case starts > 1:
+ offenders = append(offenders, where+" starts more than one owned process tree; "+
+ "split it so each start has a checkable release")
+ case starts == 1 && releases == 0:
+ offenders = append(offenders, where+" takes ownership of a process tree and never releases it")
+ }
+ }
+ return offenders
+}
+
+// TestOnlyOwnedProcessTreesAreStarted is the structural half of GH #7522.
+//
+// Whole-tree ownership shipped as an opt-in each backend had to remember, and
+// it rotted exactly the way distributed opt-in always does here: of the 23
+// backends in this package, 3 called startOwnedProcessTree and 20 called
+// cmd.Start. On Windows those 20 own nothing, so cancelling a task kills the
+// direct child — often a cmd.exe shim — and leaves the real CLI running. One of
+// them kept working for forty minutes after it was cancelled.
+//
+// Fixing the reported backend alone would have left 19. So the rule is
+// mechanical instead: startOwnedProcessTree is the only way this package starts
+// a runtime process, and a new backend that reaches for cmd.Start — or for the
+// Run/Output/CombinedOutput that call it — fails here.
+//
+// The exemptions are the two platform implementations of that function, which
+// is where the real Start lives.
+func TestOnlyOwnedProcessTreesAreStarted(t *testing.T) {
+ t.Parallel()
+
+ var offenders []string
+ forEachPackageFile(t, func(name string, fset *token.FileSet, file *ast.File) {
+ if strings.HasPrefix(name, "proc_") {
+ return
+ }
+ offenders = append(offenders, bareProcessStartCalls(fset, file)...)
+ })
+
+ if len(offenders) > 0 {
+ t.Fatalf("runtime processes must be started through startOwnedProcessTree (use runOwned / "+
+ "outputOwned / combinedOutputOwned for synchronous probes), otherwise cancelling or timing "+
+ "out leaves the CLI's descendants running (GH #7522). Offending sites:\n%s",
+ strings.Join(offenders, "\n"))
+ }
+}
+
+// TestBareProcessStartCallsAreDetected proves the guard above fails closed,
+// without needing a real regression committed to a backend to find out.
+func TestBareProcessStartCallsAreDetected(t *testing.T) {
+ t.Parallel()
+
+ for _, tc := range []struct {
+ name string
+ body string
+ want bool
+ }{
+ {"start", "cmd.Start()", true},
+ {"run", "cmd.Run()", true},
+ {"output", "_, _ = cmd.Output()", true},
+ {"combined output", "_, _ = cmd.CombinedOutput()", true},
+ {"owned start", "_ = startOwnedProcessTree(cmd, nil)", false},
+ {"owned output", "_, _ = outputOwned(cmd, nil)", false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ fset := token.NewFileSet()
+ src := "package agent\nfunc f(cmd *exec.Cmd) {\n" + tc.body + "\n}\n"
+ file, err := parser.ParseFile(fset, "synthetic.go", src, 0)
+ if err != nil {
+ t.Fatalf("parse: %v", err)
+ }
+ if got := len(bareProcessStartCalls(fset, file)) > 0; got != tc.want {
+ t.Errorf("bareProcessStartCalls(%q) flagged = %v, want %v", tc.body, got, tc.want)
+ }
+ })
+ }
+}
+
+// TestEveryOwnedProcessTreeIsReleased is the other half of the same invariant.
+// Taking ownership without dropping it leaks a Job Object handle per task on
+// Windows, and the release is also what kills whatever outlived the reap — so a
+// backend that starts an owned tree and never releases it is worse off than one
+// that owns nothing.
+func TestEveryOwnedProcessTreeIsReleased(t *testing.T) {
+ t.Parallel()
+
+ var offenders []string
+ forEachPackageFile(t, func(name string, fset *token.FileSet, file *ast.File) {
+ if strings.HasPrefix(name, "proc_") {
+ return
+ }
+ offenders = append(offenders, unreleasedProcessTrees(fset, file)...)
+ })
+
+ if len(offenders) > 0 {
+ t.Fatalf("an owned process tree must be released after the reap, which drops the Windows Job "+
+ "Object handle and kills anything that outlived it:\n%s", strings.Join(offenders, "\n"))
+ }
+}
+
+// TestUnreleasedProcessTreesAreDetected covers the case a per-file counter
+// misses, and which the first version of this guard did miss: a file that
+// already contains a correctly paired start and release, plus a second start
+// that releases nothing. models.go is exactly that shape today — two starts in
+// two functions — so the guard has to reason per function, not per file.
+func TestUnreleasedProcessTreesAreDetected(t *testing.T) {
+ t.Parallel()
+
+ const paired = `package agent
+func good(cmd *exec.Cmd) {
+ _ = startOwnedProcessTree(cmd, nil)
+ defer releaseProcessGroup(cmd)
+}
+`
+ for _, tc := range []struct {
+ name string
+ src string
+ want bool
+ }{
+ {"paired start and release", paired, false},
+ {"second unreleased start in a file that already pairs one", paired + `
+func added(cmd *exec.Cmd) {
+ _ = startOwnedProcessTree(cmd, nil)
+}
+`, true},
+ {"second unreleased start in the same function", `package agent
+func two(a, b *exec.Cmd) {
+ _ = startOwnedProcessTree(a, nil)
+ _ = startOwnedProcessTree(b, nil)
+ defer releaseProcessGroup(a)
+}
+`, true},
+ {"release from a nested closure counts", `package agent
+func closure(cmd *exec.Cmd) {
+ _ = startOwnedProcessTree(cmd, nil)
+ go func() {
+ _ = cmdWait()
+ releaseProcessGroup(cmd)
+ }()
+}
+`, false},
+ {"two exit paths may release twice", `package agent
+func twoPaths(cmd *exec.Cmd) error {
+ _ = startOwnedProcessTree(cmd, nil)
+ if err := send(); err != nil {
+ releaseProcessGroup(cmd)
+ return err
+ }
+ releaseProcessGroup(cmd)
+ return nil
+}
+`, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ fset := token.NewFileSet()
+ file, err := parser.ParseFile(fset, "synthetic.go", tc.src, 0)
+ if err != nil {
+ t.Fatalf("parse: %v", err)
+ }
+ if got := len(unreleasedProcessTrees(fset, file)) > 0; got != tc.want {
+ t.Errorf("unreleasedProcessTrees flagged = %v, want %v", got, tc.want)
+ }
+ })
+ }
+}
+
+// forEachPackageFile parses every non-test source file in this package and
+// hands it to fn.
+func forEachPackageFile(t *testing.T, fn func(name string, fset *token.FileSet, file *ast.File)) {
+ t.Helper()
+
+ entries, err := os.ReadDir(".")
+ if err != nil {
+ t.Fatalf("read package dir: %v", err)
+ }
+ fset := token.NewFileSet()
+ for _, entry := range entries {
+ name := entry.Name()
+ if entry.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.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)
+ }
+ fn(name, fset, file)
+ }
+}
+
func containsRuntimeArgReference(expr ast.Expr) bool {
found := false
ast.Inspect(expr, func(n ast.Node) bool {
diff --git a/server/pkg/agent/mcode.go b/server/pkg/agent/mcode.go
index e62ec427b1..7e3607ae45 100644
--- a/server/pkg/agent/mcode.go
+++ b/server/pkg/agent/mcode.go
@@ -95,7 +95,6 @@ func (b *mcodeBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
args = append(args, filterCustomArgs(opts.CustomArgs, mcodeBlockedArgs, b.cfg.Logger)...)
cmd := b.cfg.commandAt(execPath).exec(runCtx, args...)
hideAgentWindow(cmd)
- configureProcessGroup(cmd)
cmd.Cancel = func() error {
if cmd.Process != nil {
signalProcessGroup(cmd, syscall.SIGKILL)
diff --git a/server/pkg/agent/models.go b/server/pkg/agent/models.go
index 4b61256035..578c801235 100644
--- a/server/pkg/agent/models.go
+++ b/server/pkg/agent/models.go
@@ -14,6 +14,7 @@ import (
"sort"
"strings"
"sync"
+ "syscall"
"time"
"github.com/multica-ai/multica/server/pkg/taskfailure"
@@ -729,7 +730,7 @@ func discoverOpenCodeModels(ctx context.Context, runtimeCmd Command) ([]Model, e
// 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
// listing the resolvable catalog (mirrors the pi path; see #3729/#3627).
- out, _ := cmd.Output()
+ out, _ := outputOwned(cmd, runtimeCmd.logger)
models := parseOpenCodeModels(string(out))
if len(models) == 0 {
// Verbose yielded nothing usable (unsupported flag, error text, or an
@@ -737,7 +738,7 @@ func discoverOpenCodeModels(ctx context.Context, runtimeCmd Command) ([]Model, e
// but still prints the IDs.
cmd = runtimeCmd.exec(runCtx, "models")
hideAgentWindow(cmd)
- out, _ = cmd.Output()
+ out, _ = outputOwned(cmd, runtimeCmd.logger)
models = parseOpenCodeModels(string(out))
}
if len(models) == 0 {
@@ -1020,10 +1021,11 @@ func discoverPiModelsRPC(ctx context.Context, runtimeCmd Command, lookedUp strin
_ = stdin.Close()
return nil, false
}
- if err := cmd.Start(); err != nil {
+ if err := startOwnedProcessTree(cmd, runtimeCmd.logger); err != nil {
_ = stdin.Close()
return nil, false
}
+ defer releaseProcessGroup(cmd)
encoder := json.NewEncoder(stdin)
requests := []map[string]string{
@@ -1175,7 +1177,7 @@ func discoverPiModelsTable(ctx context.Context, runtimeCmd Command) ([]Model, er
hideAgentWindow(cmd)
var stderr strings.Builder
cmd.Stderr = &stderr
- stdout, err := cmd.Output()
+ stdout, err := outputOwned(cmd, runtimeCmd.logger)
if err != nil && len(stdout) == 0 && stderr.Len() == 0 {
return []Model{}, nil
}
@@ -1307,7 +1309,7 @@ func discoverOmpModels(ctx context.Context, runtimeCmd Command) ([]Model, error)
defer cancel()
cmd := runtimeCmd.exec(runCtx, "models", "--json")
hideAgentWindow(cmd)
- stdout, err := cmd.Output()
+ stdout, err := outputOwned(cmd, runtimeCmd.logger)
if err != nil || len(stdout) == 0 {
return []Model{}, nil
}
@@ -1588,7 +1590,7 @@ func discoverKimiProviderThinking(ctx context.Context, runtimeCmd Command) (map[
cmd := runtimeCmd.exec(runCtx, "provider", "list", "--json")
hideAgentWindow(cmd)
cmd.Stderr = io.Discard
- raw, err := cmd.Output()
+ raw, err := outputOwned(cmd, runtimeCmd.logger)
if err != nil {
return nil, fmt.Errorf("kimi provider list: %w", err)
}
@@ -1918,14 +1920,17 @@ func discoverACPModels(ctx context.Context, runtimeCmd Command, p acpDiscoveryPr
// Discard stderr; noisy logs here don't help us and we don't
// want them bleeding into the daemon log every 60s.
cmd.Stderr = io.Discard
- if err := cmd.Start(); err != nil {
+ if err := startOwnedProcessTree(cmd, runtimeCmd.logger); err != nil {
return fail("process start", err)
}
- // Ensure the child process is always reaped.
+ // Ensure the child process and everything it spawned are always reaped.
+ // This probe runs on a discovery schedule, so a leaked ACP server here
+ // accumulates rather than showing up once.
defer func() {
_ = stdin.Close()
- _ = cmd.Process.Kill()
+ signalProcessGroup(cmd, syscall.SIGKILL)
_, _ = cmd.Process.Wait()
+ releaseProcessGroup(cmd)
}()
scanner := bufio.NewScanner(stdout)
@@ -2285,7 +2290,7 @@ func discoverAntigravityModels(ctx context.Context, runtimeCmd Command) ([]Model
defer cancel()
cmd := runtimeCmd.exec(runCtx, "models")
hideAgentWindow(cmd)
- out, err := cmd.Output()
+ out, err := outputOwned(cmd, runtimeCmd.logger)
if err != nil && len(out) == 0 {
return nil, nil
}
@@ -2483,7 +2488,7 @@ func discoverCursorModels(ctx context.Context, runtimeCmd Command) (Catalog, err
defer cancel()
cmd := runtimeCmd.exec(runCtx, "--list-models")
hideAgentWindow(cmd)
- out, err := cmd.Output()
+ out, err := outputOwned(cmd, runtimeCmd.logger)
if err != nil && len(out) == 0 {
return Catalog{Models: cursorStaticModels(), Fallback: true}, nil
}
@@ -2580,7 +2585,7 @@ func discoverOpenclawAgents(ctx context.Context, runtimeCmd Command) ([]Model, e
} {
cmd := runtimeCmd.exec(runCtx, jsonArgs...)
hideAgentWindow(cmd)
- out, err := cmd.Output()
+ out, err := outputOwned(cmd, runtimeCmd.logger)
if err != nil && len(out) == 0 {
continue
}
@@ -2594,7 +2599,7 @@ func discoverOpenclawAgents(ctx context.Context, runtimeCmd Command) ([]Model, e
// the wrong tokens produces nonsense entries like "Identity:".
cmd := runtimeCmd.exec(runCtx, "agents", "list")
hideAgentWindow(cmd)
- out, err := cmd.Output()
+ out, err := outputOwned(cmd, runtimeCmd.logger)
if err != nil && len(out) == 0 {
return []Model{}, nil
}
diff --git a/server/pkg/agent/openclaw.go b/server/pkg/agent/openclaw.go
index c6a2e31dd5..5075c2cbda 100644
--- a/server/pkg/agent/openclaw.go
+++ b/server/pkg/agent/openclaw.go
@@ -110,7 +110,7 @@ func (b *openclawBackend) Execute(ctx context.Context, prompt string, opts ExecO
}
cmd.Stderr = newLogWriter(b.cfg.Logger, "[openclaw:stderr] ")
- if err := cmd.Start(); err != nil {
+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
cancel()
return nil, fmt.Errorf("start openclaw: %w", err)
}
@@ -148,6 +148,7 @@ func (b *openclawBackend) Execute(ctx context.Context, prompt string, opts ExecO
// Wait for process exit.
exitErr := cmd.Wait()
+ releaseProcessGroup(cmd)
duration := time.Since(startTime)
switch {
@@ -289,7 +290,7 @@ func customArgsContains(args []string, flag string) bool {
func checkOpenclawVersion(ctx context.Context, runtimeCmd Command) error {
cmd := runtimeCmd.exec(ctx, "--version")
hideAgentWindow(cmd)
- out, err := cmd.CombinedOutput()
+ out, err := combinedOutputOwned(cmd, runtimeCmd.logger)
if err != nil {
return fmt.Errorf("openclaw --version failed: %w", err)
}
diff --git a/server/pkg/agent/opencode.go b/server/pkg/agent/opencode.go
index 947785f319..10483db3e8 100644
--- a/server/pkg/agent/opencode.go
+++ b/server/pkg/agent/opencode.go
@@ -112,17 +112,13 @@ func (b *opencodeBackend) Execute(ctx context.Context, prompt string, opts ExecO
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 the
- // direct child — otherwise a cancelled or restarted run can orphan a
- // descendant that keeps spinning (#4533).
- configureProcessGroup(cmd)
- // Take over context cancellation. The default CommandContext behaviour
- // SIGKILLs only the leader the instant runCtx is done; we instead drive a
- // graceful, group-wide SIGTERM→SIGKILL from the cancellation goroutine
- // below and close the stdout read end only after the tree has been
- // signalled. Returning nil here keeps os/exec from racing us with its own
- // kill; WaitDelay remains the hard backstop.
+ // Take over context cancellation. The default kills the whole group the
+ // instant runCtx is done; we instead drive a graceful, group-wide
+ // SIGTERM→SIGKILL from the cancellation goroutine below and close the
+ // stdout read end only after the tree has been signalled — otherwise a
+ // cancelled run can orphan a descendant that keeps spinning (#4533).
+ // Returning nil here keeps os/exec from racing us with its own kill;
+ // WaitDelay remains the hard backstop.
cmd.Cancel = func() error { return nil }
b.cfg.logAgentCommandWithPrompt(cmd, newAgentCommandLogArgs(args, trustAgentCommandPositional(0, "run")), len(prompt))
cmd.WaitDelay = 10 * time.Second
@@ -184,7 +180,7 @@ func (b *opencodeBackend) Execute(ctx context.Context, prompt string, opts ExecO
closeStdin := func() { closeStdinOnce.Do(func() { _ = stdin.Close() }) }
cmd.Stderr = newLogWriter(b.cfg.Logger, "[opencode:stderr] ")
- if err := cmd.Start(); err != nil {
+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
closeStdin()
cancel()
return nil, fmt.Errorf("start opencode: %w", err)
@@ -254,6 +250,7 @@ func (b *opencodeBackend) Execute(ctx context.Context, prompt string, opts ExecO
// Wait for process exit, then release the cancellation handler.
exitErr := cmd.Wait()
close(procDone)
+ releaseProcessGroup(cmd)
duration := time.Since(startTime)
// Wait closes the process pipes, so a prompt write still blocked when
diff --git a/server/pkg/agent/pi.go b/server/pkg/agent/pi.go
index f3d046eddb..bd80d14346 100644
--- a/server/pkg/agent/pi.go
+++ b/server/pkg/agent/pi.go
@@ -258,7 +258,7 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
closeStdin := func() { closeStdinOnce.Do(func() { _ = stdin.Close() }) }
cmd.Stderr = newLogWriter(b.cfg.Logger, "["+label+":stderr] ")
- if err := cmd.Start(); err != nil {
+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
closeStdin()
cancel()
return nil, fmt.Errorf("start %s: %w", label, err)
@@ -415,6 +415,7 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
}
waitErr := cmd.Wait()
+ releaseProcessGroup(cmd)
duration := time.Since(startTime)
// Wait closes the process pipes, so a prompt write still blocked when the
diff --git a/server/pkg/agent/proc_other.go b/server/pkg/agent/proc_other.go
index 659b39c1ee..0fe2813626 100644
--- a/server/pkg/agent/proc_other.go
+++ b/server/pkg/agent/proc_other.go
@@ -19,6 +19,11 @@ func hideAgentWindow(cmd *exec.Cmd) {}
// spawns — in one call, instead of killing only the direct child and leaking
// grandchildren that keep running (and, for opencode, spinning on EPIPE) after
// a task is cancelled or the daemon restarts. See signalProcessGroup.
+//
+// Called by newRuntimeCmd in launch.go, which is the single point where a
+// runtime process is constructed. No backend calls it directly: the group has
+// to exist for every runtime process, and per-backend opt-in did not deliver
+// that (GH #7522).
func configureProcessGroup(cmd *exec.Cmd) {
if cmd.SysProcAttr == nil {
cmd.SysProcAttr = &syscall.SysProcAttr{}
@@ -27,9 +32,12 @@ func configureProcessGroup(cmd *exec.Cmd) {
}
// startOwnedProcessTree is a plain Start on non-Windows platforms:
-// configureProcessGroup already put the child in its own process group before
-// it existed, so there is nothing left to claim once it is running. The logger
-// is unused here; Windows needs it to report degraded ownership.
+// newRuntimeCmd already put the child in its own process group before it
+// existed, so there is nothing left to claim once it is running. The logger is
+// unused here; Windows needs it to report degraded ownership.
+//
+// It is still the only way this package starts a long-lived runtime process,
+// so the two platforms share one call site per backend.
func startOwnedProcessTree(cmd *exec.Cmd, _ *slog.Logger) error { return cmd.Start() }
// releaseProcessGroup is a no-op on non-Windows platforms: a process group needs
diff --git a/server/pkg/agent/proc_windows.go b/server/pkg/agent/proc_windows.go
index dcad4d42c2..4003bd0b40 100644
--- a/server/pkg/agent/proc_windows.go
+++ b/server/pkg/agent/proc_windows.go
@@ -44,8 +44,8 @@ func hideAgentWindow(cmd *exec.Cmd) {
// configureProcessGroup is a no-op on Windows: there is no Setpgid equivalent,
// and job membership cannot be requested before the process exists. Ownership
-// is taken by startOwnedProcessTree instead, which a backend opts into by
-// calling it in place of cmd.Start.
+// is taken by startOwnedProcessTree instead, which every backend reaches
+// because it is the only way this package starts a runtime process.
func configureProcessGroup(cmd *exec.Cmd) {}
// ownedProcessTree is the Windows equivalent of a Unix process group: a Job
@@ -78,8 +78,9 @@ type jobObjectBasicAccountingInformation struct {
}
// startOwnedProcessTree starts cmd and takes ownership of every process it goes
-// on to create. Backends that need whole-tree cleanup call this instead of
-// cmd.Start.
+// on to create. It is the only way this package starts a runtime process;
+// TestOnlyOwnedProcessTreesAreStarted keeps a new backend from reaching for
+// cmd.Start and quietly reintroducing GH #7522.
//
// The child is created suspended and assigned to a Job Object before it runs.
// That ordering is the whole point: Windows grants membership only to processes
@@ -107,8 +108,15 @@ func startOwnedProcessTree(cmd *exec.Cmd, logger *slog.Logger) error {
}
if err := ownProcessTree(cmd); err != nil && logger != nil {
- logger.Warn("could not take ownership of the agent process tree; descendant cleanup will be best-effort",
- "error", err, "pid", cmd.Process.Pid)
+ // Deliberately fail open. Failing the launch instead would take a host
+ // down entirely rather than degrade it, and the realistic causes are
+ // environmental — an outer job that forbids assignment, or a hardened
+ // policy denying PROCESS_SET_QUOTA — not per-task. The consequence is
+ // named in the message because it is the only signal an operator gets
+ // that cancellation on this host is back to killing the leader alone.
+ logger.Warn("could not take ownership of the agent process tree; cancelling or timing out this "+
+ "process will kill only the direct child and can leave its descendants running",
+ "error", err, "pid", cmd.Process.Pid, "executable", cmd.Path)
}
if err := resumeProcess(cmd.Process.Pid); err != nil {
diff --git a/server/pkg/agent/proc_windows_test.go b/server/pkg/agent/proc_windows_test.go
index 391d188e46..b0e4c7fece 100644
--- a/server/pkg/agent/proc_windows_test.go
+++ b/server/pkg/agent/proc_windows_test.go
@@ -127,6 +127,85 @@ func TestStartOwnedProcessTreeCapturesImmediateDescendants(t *testing.T) {
}
}
+// TestProbeOutputOwnsItsProcessTree is the Windows regression for the probe
+// path in GH #7522. cmd.Output() calls Start itself, so a probe written with it
+// never reaches startOwnedProcessTree and owns nothing here — and on Windows
+// the direct child of a `--version` probe is typically the npm shim, with the
+// real CLI already a grandchild. outputOwned has to put both in the job and
+// take both down when the probe's context is cancelled.
+func TestProbeOutputOwnsItsProcessTree(t *testing.T) {
+ exePath, pidPath := buildDescendantSpawner(t)
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ cmd := NewCommand(exePath, nil).exec(ctx, "spawn")
+ cmd.Env = append(os.Environ(), "DESCENDANT_PID_FILE="+pidPath)
+ hideAgentWindow(cmd)
+ // The grandchild inherits the stdout pipe, so without this a wedged
+ // descendant would hold Wait open past the cancellation — the exact stall
+ // detectCLIVersion documents.
+ cmd.WaitDelay = 5 * time.Second
+
+ done := make(chan struct{})
+ go func() {
+ _, _ = outputOwned(cmd, slog.New(slog.NewTextHandler(io.Discard, nil)))
+ close(done)
+ }()
+
+ descendantPid := waitForDescendantPid(t, pidPath)
+ if !processStillRunning(descendantPid) {
+ t.Fatalf("descendant %d was not running; the test cannot prove anything", descendantPid)
+ }
+ if total := jobTotalProcesses(t, cmd); total < 2 {
+ t.Fatalf("job accounted for %d processes, want the probe and its descendant; the descendant escaped the job", total)
+ }
+
+ cancel()
+ select {
+ case <-done:
+ case <-time.After(30 * time.Second):
+ t.Fatal("outputOwned never returned after the probe was cancelled")
+ }
+ if processStillRunning(descendantPid) {
+ t.Fatalf("descendant %d survived cancellation of the probe that spawned it", descendantPid)
+ }
+}
+
+// TestProbeReturnsWhenLeaderExitsHoldingPipes is the normal-exit counterpart to
+// the test above: nobody cancels anything here.
+//
+// The spawner leaves a descendant holding the inherited stdout/stderr write
+// ends and its leader exits. cmd.Wait cannot return until those close, and on
+// Windows the thing that closes them is the Job Object going away — which is
+// the release that runs after Wait. Without a bound the probe waits for its own
+// cleanup forever, and checkOpenclawVersion runs before any task timeout
+// exists, so the task would hang until a human cancelled it.
+func TestProbeReturnsWhenLeaderExitsHoldingPipes(t *testing.T) {
+ exePath, pidPath := buildDescendantSpawner(t)
+
+ cmd := NewCommand(exePath, nil).exec(context.Background(), "spawn-and-exit")
+ cmd.Env = append(os.Environ(), "DESCENDANT_PID_FILE="+pidPath)
+ hideAgentWindow(cmd)
+
+ done := make(chan struct{})
+ go func() {
+ _, _ = outputOwned(cmd, slog.New(slog.NewTextHandler(io.Discard, nil)))
+ close(done)
+ }()
+
+ descendantPid := waitForDescendantPid(t, pidPath)
+ select {
+ case <-done:
+ case <-time.After(30 * time.Second):
+ t.Fatal("outputOwned never returned: the leader exited, but Wait is still waiting for a pipe " +
+ "that only releaseProcessGroup can close, and releaseProcessGroup runs after Wait")
+ }
+ if processStillRunning(descendantPid) {
+ t.Fatalf("descendant %d outlived the probe that spawned it", descendantPid)
+ }
+}
+
// TestWaitProcessGroupGoneWithoutOwnershipReportsUnconfirmed covers the
// degraded path: a command started with a plain Start owns no job, so there is
// nothing to observe, and callers must read that as "cleanup unconfirmed"
@@ -211,8 +290,13 @@ import (
func main() {
if len(os.Args) > 1 && os.Args[1] == "descendant" { time.Sleep(10*time.Minute); return }
child := exec.Command(os.Args[0], "descendant")
+ // Inherit stdio: the descendant holding the parent's pipes open after the
+ // parent exits is what "spawn-and-exit" exists to reproduce.
+ child.Stdout = os.Stdout
+ child.Stderr = os.Stderr
if err := child.Start(); err != nil { panic(err) }
if err := os.WriteFile(os.Getenv("DESCENDANT_PID_FILE"), []byte(fmt.Sprint(child.Process.Pid)), 0600); err != nil { panic(err) }
+ if len(os.Args) > 1 && os.Args[1] == "spawn-and-exit" { return }
time.Sleep(10*time.Minute)
}`
if err := os.WriteFile(sourcePath, []byte(source), 0o600); err != nil {
diff --git a/server/pkg/agent/qoder.go b/server/pkg/agent/qoder.go
index aab6f49380..eed7584daf 100644
--- a/server/pkg/agent/qoder.go
+++ b/server/pkg/agent/qoder.go
@@ -131,7 +131,7 @@ func (b *qoderBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
return nil, fmt.Errorf("qoder stderr pipe: %w", err)
}
- if err := cmd.Start(); err != nil {
+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
cancel()
return nil, fmt.Errorf("start qoder: %w", err)
}
@@ -213,6 +213,7 @@ func (b *qoderBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
defer func() {
stdin.Close()
_ = cmd.Wait()
+ releaseProcessGroup(cmd)
}()
startTime := time.Now()
diff --git a/server/pkg/agent/qwen.go b/server/pkg/agent/qwen.go
index ec17899134..6faf4b1636 100644
--- a/server/pkg/agent/qwen.go
+++ b/server/pkg/agent/qwen.go
@@ -134,7 +134,7 @@ func (b *qwenBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
closeStdin := func() { closeStdinOnce.Do(func() { _ = stdin.Close() }) }
stderrBuf := newStderrTail(newLogWriter(b.cfg.Logger, "[qwen:stderr] "), agentStderrTailBytes)
cmd.Stderr = stderrBuf
- if err := cmd.Start(); err != nil {
+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
closeStdin()
cancel()
return nil, fmt.Errorf("start qwen: %w", err)
@@ -197,6 +197,7 @@ func (b *qwenBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
_ = stdout.Close()
}
exitErr := cmd.Wait()
+ releaseProcessGroup(cmd)
duration := time.Since(started)
// Wait has already closed the stdin pipe, so a prompt write still
diff --git a/server/pkg/agent/qwenpaw.go b/server/pkg/agent/qwenpaw.go
index 2a8896e668..329b80d253 100644
--- a/server/pkg/agent/qwenpaw.go
+++ b/server/pkg/agent/qwenpaw.go
@@ -112,7 +112,7 @@ func (b *qwenpawBackend) Execute(ctx context.Context, prompt string, opts ExecOp
return nil, fmt.Errorf("qwenpaw stderr pipe: %w", err)
}
- if err := cmd.Start(); err != nil {
+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
cancel()
return nil, fmt.Errorf("start qwenpaw: %w", err)
}
@@ -179,6 +179,7 @@ func (b *qwenpawBackend) Execute(ctx context.Context, prompt string, opts ExecOp
defer func() {
stdin.Close()
_ = cmd.Wait()
+ releaseProcessGroup(cmd)
}()
startTime := time.Now()
diff --git a/server/pkg/agent/reasonix.go b/server/pkg/agent/reasonix.go
index 129915ad8a..880621ffdd 100644
--- a/server/pkg/agent/reasonix.go
+++ b/server/pkg/agent/reasonix.go
@@ -119,7 +119,7 @@ func (b *reasonixBackend) Execute(ctx context.Context, prompt string, opts ExecO
return nil, fmt.Errorf("reasonix stderr pipe: %w", err)
}
- if err := cmd.Start(); err != nil {
+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
cancel()
return nil, fmt.Errorf("start reasonix: %w", err)
}
@@ -235,6 +235,7 @@ func (b *reasonixBackend) Execute(ctx context.Context, prompt string, opts ExecO
defer func() {
stdin.Close()
_ = cmd.Wait()
+ releaseProcessGroup(cmd)
}()
startTime := time.Now()
diff --git a/server/pkg/agent/thinking.go b/server/pkg/agent/thinking.go
index e5287887c9..c313325b80 100644
--- a/server/pkg/agent/thinking.go
+++ b/server/pkg/agent/thinking.go
@@ -177,7 +177,7 @@ func loadClaudeThinkingByModel(ctx context.Context, cmd Command) map[string]*Mod
func claudeEffortSuperset(ctx context.Context, runtimeCmd Command) []string {
cmd := runtimeCmd.exec(ctx, "--help")
hideAgentWindow(cmd)
- out, err := cmd.CombinedOutput()
+ out, err := combinedOutputOwned(cmd, runtimeCmd.logger)
if err != nil {
return append([]string(nil), claudeStaticEffortFallback...)
}
@@ -358,7 +358,7 @@ var codexDebugModelsArgs = []string{"debug", "models", "--bundled"}
func runCodexDebugModels(ctx context.Context, runtimeCmd Command) ([]byte, error) {
cmd := runtimeCmd.exec(ctx, codexDebugModelsArgs...)
hideAgentWindow(cmd)
- return cmd.Output()
+ return outputOwned(cmd, runtimeCmd.logger)
}
// parseCodexModelCatalog projects the CLI's raw catalog into the daemon wire
diff --git a/server/pkg/agent/traecli.go b/server/pkg/agent/traecli.go
index 1e33062adf..8c437ebaca 100644
--- a/server/pkg/agent/traecli.go
+++ b/server/pkg/agent/traecli.go
@@ -143,7 +143,7 @@ func (b *traecliBackend) Execute(ctx context.Context, prompt string, opts ExecOp
return nil, fmt.Errorf("traecli stderr pipe: %w", err)
}
- if err := cmd.Start(); err != nil {
+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
cancel()
return nil, fmt.Errorf("start traecli: %w", err)
}
@@ -225,6 +225,7 @@ func (b *traecliBackend) Execute(ctx context.Context, prompt string, opts ExecOp
defer func() {
stdin.Close()
_ = cmd.Wait()
+ releaseProcessGroup(cmd)
}()
startTime := time.Now()
diff --git a/server/pkg/agent/zeroclaw.go b/server/pkg/agent/zeroclaw.go
index 9f5e2b5465..9efa9a5558 100644
--- a/server/pkg/agent/zeroclaw.go
+++ b/server/pkg/agent/zeroclaw.go
@@ -277,7 +277,7 @@ func (b *zeroclawBackend) Execute(ctx context.Context, prompt string, opts ExecO
return nil, fmt.Errorf("zeroclaw stderr pipe: %w", err)
}
- if err := cmd.Start(); err != nil {
+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
cancel()
return nil, fmt.Errorf("start zeroclaw: %w", err)
}
@@ -369,6 +369,7 @@ func (b *zeroclawBackend) Execute(ctx context.Context, prompt string, opts ExecO
defer func() {
stdin.Close()
_ = cmd.Wait()
+ releaseProcessGroup(cmd)
}()
startTime := time.Now()