Skip to content

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

Go

MUL-8571 ZIC-396 fix(hermes): own Windows task gateways without breakaway (#9963)

ZIcee437b11a718d
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index b42022c95d..b852f33b87 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -602,6 +602,10 @@ jobs:
# -v makes RUN/PASS evidence explicit in CI logs.
run: go test ./pkg/agent -v -run '^(TestStartOwnedProcessTreeCapturesImmediateDescendants|TestStartOwnedProcessTreeLeavesNoSuspendedChild|TestWaitProcessGroupGoneWithoutOwnershipReportsUnconfirmed|TestCodexInitializeRetrySupportedWithOwnedProcessTree|TestCodexWindowsDescendantsDieWithTheOwnedProcessTree|TestCodeArtsWindowsCancellationTerminatesDescendants)$' -count=1 -timeout=5m
+ - name: Test Windows Hermes gateway ownership and reservation
+ working-directory: server
+ run: go test ./pkg/agent -v -run '^(TestHermesGatewayWindowsCleanupOwnsDescendants|TestHermesGatewayReservation)$' -count=1 -timeout=5m
+
- name: Test bounded CLI output collection on Windows
working-directory: server
# MUL-5467: RunCollect / RunCollectQuiet own the pipes as well as the
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.md
index cdae2118f8..0d2a08b3c1 100644
--- a/CLI_AND_DAEMON.md
+++ b/CLI_AND_DAEMON.md
@@ -463,6 +463,13 @@ The daemon launches MiniMax Code as `mcode acp`, writes the task brief to `AGENT
#### Hermes agent memory
+On Windows, detected Hermes versions 0.22 and later use a daemon-owned foreground
+gateway for each isolated task home. The daemon waits for its startup reservation
+before launching ACP, which performs the readiness handshake. The gateway and its
+tool descendants remain in a Windows job object and are terminated on task cleanup
+or cancellation; agent jobs do not permit breakaway. Other platforms and older or
+unrecognized Hermes versions retain their existing ACP startup behavior.
+
Hermes discovers skills only from its own home, so binding Multica skills to a Hermes agent makes the daemon build a per-task `HERMES_HOME` overlay for that agent. The agent's long-term memory (`memories/`) does **not** live inside that task-scoped overlay: it is linked to a persistent store at
```
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index f7c233548a..781390ce20 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -8830,6 +8830,11 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
if err := agent.StopHermesTaskGateway(backendConfig, env.HermesHome); err != nil {
return TaskResult{}, err
}
+ stopGateway, err := agent.StartHermesTaskGateway(ctx, backendConfig, env.HermesHome)
+ if err != nil {
+ return TaskResult{}, err
+ }
+ defer stopGateway()
defer func() {
if err := agent.StopHermesTaskGateway(backendConfig, env.HermesHome); err != nil {
d.logger.Warn("failed to stop task Hermes gateway", "home", env.HermesHome, "error", err)
diff --git a/server/pkg/agent/hermes_gateway.go b/server/pkg/agent/hermes_gateway.go
index bfc1805a55..05f3711943 100644
--- a/server/pkg/agent/hermes_gateway.go
+++ b/server/pkg/agent/hermes_gateway.go
@@ -7,10 +7,84 @@ import (
"os"
"os/exec"
"path/filepath"
+ "runtime"
"strings"
+ "sync"
+ "syscall"
"time"
)
+// StartHermesTaskGateway owns the foreground gateway for a Windows task home.
+// ACP's detached auto-start requires breakaway, which would let tool processes
+// escape our kill-on-close job. A foreground owner needs no such exception.
+// The caller must first retire any previous owner with StopHermesTaskGateway.
+func StartHermesTaskGateway(ctx context.Context, cfg Config, home string) (func(), error) {
+ version, err := parseSemver(cfg.CLIVersion)
+ if runtime.GOOS != "windows" || home == "" || cfg.Env["HERMES_HOME"] != home ||
+ err != nil || version.lessThan(semver{Minor: 22}) {
+ return func() {}, nil
+ }
+ return startHermesTaskGateway(ctx, cfg, home, hermesGatewayReserved)
+}
+
+func startHermesTaskGateway(ctx context.Context, cfg Config, home string, reserved func(string) (bool, error)) (func(), error) {
+ runCtx, cancel := context.WithCancel(ctx)
+ cmd := cfg.commandAt(cfg.ExecutablePath).exec(runCtx, "--profile", "default", "gateway", "run", "--quiet", "--external-supervisor")
+ hideAgentWindow(cmd)
+ cmd.Env = buildEnv(cfg.Env)
+ cmd.Env = append(cmd.Env, "HERMES_DISABLE_LAZY_INSTALLS=1", "PYTHONIOENCODING=utf-8", "HERMES_GATEWAY_DETACHED=1")
+ cmd.WaitDelay = 2 * time.Second
+ cmd.Cancel = func() error {
+ signalProcessGroup(cmd, syscall.SIGKILL)
+ return nil
+ }
+ // Keep gateway output out of ACP's protocol and avoid retaining unredacted
+ // startup output in task errors. Hermes writes diagnostics in the task home.
+ if err := startOwnedProcessTree(cmd, cfg.Logger); err != nil {
+ cancel()
+ return nil, fmt.Errorf("start task Hermes gateway: %w", err)
+ }
+ done := make(chan struct{})
+ var waitErr error
+ go func() {
+ waitErr = cmd.Wait()
+ signalProcessGroup(cmd, syscall.SIGKILL)
+ releaseProcessGroup(cmd)
+ close(done)
+ }()
+ var once sync.Once
+ stop := func() { once.Do(func() { cancel(); <-done }) }
+ fail := func(err error) (func(), error) {
+ stop()
+ return nil, fmt.Errorf("start task Hermes gateway: %w", err)
+ }
+ startup, finish := context.WithTimeout(ctx, 60*time.Second)
+ defer finish()
+ tick := time.NewTicker(50 * time.Millisecond)
+ defer tick.Stop()
+ for {
+ select {
+ case <-startup.Done():
+ return fail(startup.Err())
+ case <-done:
+ if waitErr == nil {
+ waitErr = errors.New("gateway exited before reserving its task home")
+ }
+ return fail(waitErr)
+ case <-tick.C:
+ owned, err := reserved(home)
+ if err != nil {
+ return fail(err)
+ }
+ if owned {
+ // This is a startup reservation, not readiness. ACP performs the
+ // authenticated readiness handshake and waits for this owner.
+ return stop, nil
+ }
+ }
+ }
+}
+
// StopHermesTaskGateway retires the gateway of a daemon-created Hermes home.
// Gateway-backed ACP detaches its execution owner from the stdio process; it
// must exit before the next task inherits this conversation's home, otherwise
diff --git a/server/pkg/agent/hermes_gateway_other.go b/server/pkg/agent/hermes_gateway_other.go
new file mode 100644
index 0000000000..bd38f3831a
--- /dev/null
+++ b/server/pkg/agent/hermes_gateway_other.go
@@ -0,0 +1,5 @@
+//go:build !windows
+
+package agent
+
+func hermesGatewayReserved(string) (bool, error) { return false, nil }
diff --git a/server/pkg/agent/hermes_gateway_test.go b/server/pkg/agent/hermes_gateway_test.go
new file mode 100644
index 0000000000..a16463db1c
--- /dev/null
+++ b/server/pkg/agent/hermes_gateway_test.go
@@ -0,0 +1,30 @@
+package agent
+
+import (
+ "context"
+ "path/filepath"
+ "testing"
+)
+
+func TestStartHermesTaskGatewayScope(t *testing.T) {
+ home := t.TempDir()
+ for _, tc := range []struct {
+ name, version, envHome, home string
+ }{
+ {"older ACP", "0.20.6", home, home},
+ {"unknown version", "unknown", home, home},
+ {"no overlay", "0.22.6", "", ""},
+ {"different home", "0.22.6", home, filepath.Join(home, "other")},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ stop, err := StartHermesTaskGateway(context.Background(), Config{
+ ExecutablePath: filepath.Join(home, "must-not-run"), CLIVersion: tc.version,
+ Env: map[string]string{"HERMES_HOME": tc.envHome},
+ }, tc.home)
+ if err != nil {
+ t.Fatal(err)
+ }
+ stop()
+ })
+ }
+}
diff --git a/server/pkg/agent/hermes_gateway_unix_test.go b/server/pkg/agent/hermes_gateway_unix_test.go
index 7602849665..52b4f8e080 100644
--- a/server/pkg/agent/hermes_gateway_unix_test.go
+++ b/server/pkg/agent/hermes_gateway_unix_test.go
@@ -3,13 +3,66 @@
package agent
import (
+ "context"
+ "errors"
"log/slog"
"os"
"path/filepath"
"strings"
"testing"
+ "time"
)
+func TestStartHermesTaskGatewayLifecycle(t *testing.T) {
+ for _, mode := range []string{"ready", "cancel startup", "cancel running", "exit", "probe error"} {
+ t.Run(mode, func(t *testing.T) {
+ home := t.TempDir()
+ path, record := filepath.Join(home, "hermes"), filepath.Join(home, "invocation")
+ writeTestExecutable(t, path, []byte("#!/bin/sh\nprintf '%s\\n' \"$@\" \"$HERMES_HOME\" \"$PYTHONIOENCODING\" \"$HERMES_GATEWAY_DETACHED\" > \"$RECORD\"\nif [ \"$MODE\" = exit ]; then exit 7; fi\nexec sleep 60\n"))
+ cfg := Config{ExecutablePath: path, LaunchPrefix: []string{"wrapped"}, Logger: slog.Default(),
+ Env: map[string]string{"HERMES_HOME": home, "RECORD": record, "MODE": mode, "PYTHONIOENCODING": "ascii", "HERMES_GATEWAY_DETACHED": "0"}}
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ stop, err := startHermesTaskGateway(ctx, cfg, home, func(string) (bool, error) {
+ if _, err := os.Stat(record); err != nil {
+ return false, nil
+ }
+ switch mode {
+ case "cancel startup":
+ cancel()
+ return false, nil
+ case "probe error":
+ return false, errors.New("probe failed")
+ case "exit":
+ return false, nil
+ }
+ return true, nil
+ })
+ if mode == "ready" || mode == "cancel running" {
+ if err != nil {
+ t.Fatal(err)
+ }
+ if mode == "cancel running" {
+ cancel()
+ }
+ stop()
+ stop() // Deferred cleanup may follow cancellation.
+ } else if err == nil {
+ stop()
+ t.Fatal("expected startup failure")
+ }
+ got, readErr := os.ReadFile(record)
+ if readErr != nil {
+ t.Fatal(readErr)
+ }
+ want := "wrapped\n--profile\ndefault\ngateway\nrun\n--quiet\n--external-supervisor\n" + home + "\nutf-8\n1\n"
+ if string(got) != want {
+ t.Fatalf("invocation = %q, want %q", got, want)
+ }
+ })
+ }
+}
+
func TestStopHermesTaskGateway(t *testing.T) {
home, tools := t.TempDir(), t.TempDir()
record := filepath.Join(tools, "invocation")
diff --git a/server/pkg/agent/hermes_gateway_windows.go b/server/pkg/agent/hermes_gateway_windows.go
new file mode 100644
index 0000000000..7aa7693d26
--- /dev/null
+++ b/server/pkg/agent/hermes_gateway_windows.go
@@ -0,0 +1,42 @@
+//go:build windows
+
+package agent
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+
+ "golang.org/x/sys/windows"
+)
+
+// Hermes gateway.status reserves one byte at 1 MiB on Windows. Probe the
+// reservation rather than the PID record: stale records survive a killed job,
+// and the reservation precedes control endpoint publication in Hermes 0.22.
+func hermesGatewayReserved(home string) (bool, error) {
+ path := filepath.Join(home, "gateway.lock")
+ info, err := os.Lstat(path)
+ if os.IsNotExist(err) {
+ return false, nil
+ }
+ if err != nil {
+ return false, err
+ }
+ if !info.Mode().IsRegular() {
+ return false, errors.New("refusing non-local Hermes gateway lock")
+ }
+ f, err := os.OpenFile(path, os.O_RDWR, 0)
+ if err != nil {
+ return false, err
+ }
+ defer f.Close()
+ position := windows.Overlapped{Offset: 1024 * 1024}
+ err = windows.LockFileEx(windows.Handle(f.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &position)
+ if errors.Is(err, windows.ERROR_LOCK_VIOLATION) {
+ return true, nil
+ }
+ if err != nil {
+ return false, err
+ }
+ return false, windows.UnlockFileEx(windows.Handle(f.Fd()), 0, 1, 0, &position)
+}
diff --git a/server/pkg/agent/hermes_gateway_windows_test.go b/server/pkg/agent/hermes_gateway_windows_test.go
new file mode 100644
index 0000000000..e7f7bee40b
--- /dev/null
+++ b/server/pkg/agent/hermes_gateway_windows_test.go
@@ -0,0 +1,124 @@
+//go:build windows
+
+package agent
+
+import (
+ "context"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "testing"
+ "time"
+
+ "golang.org/x/sys/windows"
+)
+
+func TestHermesGatewayProcessHelper(t *testing.T) {
+ mode := os.Getenv("MULTICA_TEST_GATEWAY_HELPER")
+ if mode == "" {
+ return
+ }
+ if mode == "child" {
+ time.Sleep(time.Minute)
+ os.Exit(0)
+ }
+ if os.Getenv("PYTHONIOENCODING") != "utf-8" || os.Getenv("HERMES_GATEWAY_DETACHED") != "1" {
+ t.Fatal("gateway launch environment does not match the Windows contract")
+ }
+ exe, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ child := exec.Command(exe, "-test.run=^TestHermesGatewayProcessHelper$")
+ child.Env = append(os.Environ(), "MULTICA_TEST_GATEWAY_HELPER=child")
+ if err := child.Start(); err != nil {
+ t.Fatal(err)
+ }
+ defer child.Process.Kill()
+ home := os.Getenv("HERMES_HOME")
+ if err := os.WriteFile(filepath.Join(home, "child.pid"), []byte(strconv.Itoa(child.Process.Pid)), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ f, err := os.OpenFile(filepath.Join(home, "gateway.lock"), os.O_CREATE|os.O_RDWR, 0o600)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Close()
+ position := windows.Overlapped{Offset: 1024 * 1024}
+ if err := windows.LockFileEx(windows.Handle(f.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, &position); err != nil {
+ t.Fatal(err)
+ }
+ time.Sleep(time.Minute)
+}
+
+func TestHermesGatewayWindowsCleanupOwnsDescendants(t *testing.T) {
+ for _, cancelled := range []bool{false, true} {
+ t.Run(strconv.FormatBool(cancelled), func(t *testing.T) {
+ home := t.TempDir()
+ exe, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ stop, err := StartHermesTaskGateway(ctx, Config{
+ ExecutablePath: exe, LaunchPrefix: []string{"-test.run=^TestHermesGatewayProcessHelper$", "--"},
+ CLIVersion: "0.22.6", Env: map[string]string{"HERMES_HOME": home, "MULTICA_TEST_GATEWAY_HELPER": "owner"},
+ }, home)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer stop()
+ pid := waitForDescendantPid(t, filepath.Join(home, "child.pid"))
+ if !processStillRunning(pid) {
+ t.Fatal("gateway descendant did not start")
+ }
+ if cancelled {
+ cancel()
+ }
+ stop()
+ deadline := time.Now().Add(5 * time.Second)
+ for processStillRunning(pid) && time.Now().Before(deadline) {
+ time.Sleep(10 * time.Millisecond)
+ }
+ if processStillRunning(pid) {
+ t.Fatal("gateway descendant survived cleanup")
+ }
+ if owned, err := hermesGatewayReserved(home); err != nil || owned {
+ t.Fatalf("gateway reservation survived cleanup: %v, %v", owned, err)
+ }
+ })
+ }
+}
+
+func TestHermesGatewayReservation(t *testing.T) {
+ home := t.TempDir()
+ check := func(want bool) {
+ t.Helper()
+ got, err := hermesGatewayReserved(home)
+ if err != nil || got != want {
+ t.Fatalf("reserved = %v, %v; want %v", got, err, want)
+ }
+ }
+ check(false)
+ f, err := os.OpenFile(filepath.Join(home, "gateway.lock"), os.O_CREATE|os.O_RDWR, 0o600)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Close()
+ // A stale PID record is not a live reservation.
+ if _, err := f.WriteString(`{"pid":1234}`); err != nil {
+ t.Fatal(err)
+ }
+ check(false)
+ position := windows.Overlapped{Offset: 1024 * 1024}
+ if err := windows.LockFileEx(windows.Handle(f.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &position); err != nil {
+ t.Fatal(err)
+ }
+ check(true)
+ if err := windows.UnlockFileEx(windows.Handle(f.Fd()), 0, 1, 0, &position); err != nil {
+ t.Fatal(err)
+ }
+ check(false)
+}