From b81d3e1a47b6da1b971c62cab7d5b7ddeae06d98 Mon Sep 17 00:00:00 2001 From: Dinesh Pandiyan Date: Fri, 4 Dec 2026 12:05:11 +1100 Subject: [PATCH] fix: find harness CLIs from service environments --- docs/harnesses.md | 5 + docs/runtime.md | 6 + docs/service.md | 11 +- server/internal/claudecode/cli.go | 93 ++++---- server/internal/claudecodesetup/connector.go | 2 +- server/internal/claudecodesetup/facts.go | 8 +- server/internal/claudecodesetup/module.go | 3 - server/internal/claudecodesetup/setup.go | 41 +++- server/internal/claudecodesetup/setup_test.go | 85 ++++++++ server/internal/codex/daemon.go | 17 +- server/internal/codexsetup/connector.go | 4 +- server/internal/codexsetup/setup.go | 38 +++- server/internal/codexsetup/setup_test.go | 78 +++++++ server/internal/harness/module.go | 19 +- server/internal/serve/localmachine.go | 4 +- server/internal/serve/serve_test.go | 1 + server/internal/t3setup/autopair.go | 73 +++---- server/internal/t3setup/export_test.go | 4 - server/internal/t3setup/module.go | 2 +- server/internal/t3setup/module_test.go | 59 ++++++ server/internal/t3setup/t3setup_test.go | 20 +- server/internal/toolpath/shell_other.go | 13 ++ server/internal/toolpath/shell_unix.go | 125 +++++++++++ server/internal/toolpath/shell_unix_test.go | 128 +++++++++++ server/internal/toolpath/toolpath.go | 191 +++++++++++++++++ server/internal/toolpath/toolpath_test.go | 198 ++++++++++++++++++ server/internal/worker/integration_test.go | 1 + server/internal/workersetup/claude_test.go | 20 +- server/internal/workersetup/workersetup.go | 11 +- 29 files changed, 1094 insertions(+), 166 deletions(-) delete mode 100644 server/internal/t3setup/export_test.go create mode 100644 server/internal/toolpath/shell_other.go create mode 100644 server/internal/toolpath/shell_unix.go create mode 100644 server/internal/toolpath/shell_unix_test.go create mode 100644 server/internal/toolpath/toolpath.go create mode 100644 server/internal/toolpath/toolpath_test.go diff --git a/docs/harnesses.md b/docs/harnesses.md index a0fd8d38..23adf14b 100644 --- a/docs/harnesses.md +++ b/docs/harnesses.md @@ -78,6 +78,11 @@ environment and executable lookup, logging, test overrides and a change callback. The local placement can atomically save settings with a secret when `SaveSettingsWithSecret` is supplied. +For a local CLI, use `Ports.ToolsOrProcess()` to resolve the executable +and build the child process's `PATH`. The server and each worker cache +their own login-shell lookup. An explicit setup check or connect can call +`Refresh` after a missing executable to pick up shell configuration changes. + | Placement | Composition and call sites | | --- | --- | | Local | [`serve/localmachine.go`](../server/internal/serve/localmachine.go) composes the modules that the profile allows over machine-scoped store ports and installs into `machine.Local`. Connector and adapter calls are in process. [`observe.Service.Run`](../server/internal/observe/placement.go) starts the local observer. | diff --git a/docs/runtime.md b/docs/runtime.md index 11288cf9..56959692 100644 --- a/docs/runtime.md +++ b/docs/runtime.md @@ -826,4 +826,10 @@ in Claude Code, and the setup status says why. ## Codex connection +When Stage starts from a GUI or service manager, its initial `PATH` can +omit package-manager installations. On the machine that hosts Codex, Stage +searches its process `PATH`, the user's login-shell `PATH`, then common +install directories. A daemon started by Stage inherits that combined +`PATH` with the selected CLI's directory first, so a pnpm shim can run Node. + Codex is hosted ([ADR 0006](adr/0006-codex-app-server-harness.md)): the server talks to the Codex app-server daemon on this machine, over WebSocket on the daemon's unix control socket (`codex app-server daemon version` reports its path). Connect (Settings or `stage harness codex run connect`) starts the daemon when it is down, reads the Codex login and connects the Codex home as the connection. Stage starts the daemon on demand (at most once every 30 s) and never stops, restarts or updates it: it outlives Stage, keeps running turns across Stage restarts and serves `codex resume` and Codex Desktop. The CLI runs with the server's environment minus caller session variables (`CODEX_THREAD_ID`, `STAGE_CALLER_SESSION`, Claude and T3 session variables), so its threads are never attributed to the server's own caller. The module’s settings keep the CLI path (`stage harness codex set binary=PATH`; empty: `codex` on PATH) and whether this machine connected, so a restart reinstalls the adapter without contacting the daemon until first use. Stage stores no Codex credentials: log in with `codex login`. `stage harness codex disconnect` stops tracking; the daemon and its threads stay. On a worker that allows local harnesses the same setup runs on the worker's machine (its `codex`, login and daemon), with that machine's public settings kept on the main server (`setup.settings.get`/`save`, [execution.md](execution.md#remote-machines)); no Codex credentials cross the channel, and the worker never stops its daemon either. diff --git a/docs/service.md b/docs/service.md index c3b4f4bf..ad99b9e7 100644 --- a/docs/service.md +++ b/docs/service.md @@ -185,9 +185,14 @@ template (`STAGE_LISTEN=unix`) and never overwrites it. Apply edits with `stage.db`. A local connection (`stage harness opencode run connect-local`) reads the OpenCode registration file under the service's `XDG_STATE_HOME` (else `~/.local/state`) each time. -- Codex: no credentials in `stage.db`. The daemon uses the Codex login under - the service's `CODEX_HOME` (else `~/.codex`); `codex` must be on the - service's `PATH`, or set its path (`stage harness codex set binary=PATH`). +- The Codex daemon manages its own credentials and uses the login for the + service's `CODEX_HOME` (default `~/.codex`). To select a specific executable, use + `stage harness codex set binary=/absolute/path/to/codex`. +- Codex, Claude Code and T3 CLI lookup starts with the service's `PATH`, + then searches the user's interactive login-shell `PATH` and common install + directories, including `~/Library/pnpm/bin` on macOS. Local workers use + their own machine's paths. Stage passes the tool directories to the CLIs + it launches so package-manager shims can also find their runtimes. - `stage service start` validates the file before starting, so a bad file is an error there (exit 7) instead of a restart loop. diff --git a/server/internal/claudecode/cli.go b/server/internal/claudecode/cli.go index d4eedda7..57ea64d1 100644 --- a/server/internal/claudecode/cli.go +++ b/server/internal/claudecode/cli.go @@ -13,6 +13,8 @@ import ( "strings" "sync" "time" + + "github.com/flexdinesh/stage/server/internal/toolpath" ) // CLI runs the claude executable for Stage: in a cleaned environment, and a @@ -29,6 +31,9 @@ type CLI struct { Scope bool // Home is the user's home ("" : os.UserHomeDir). Home string + // Tools supplies the PATH claude runs with, after Environ's (nil: the + // process PATH plus toolpath.Dirs(Home)). + Tools toolpath.Tools } // Result is one finished run. @@ -124,72 +129,60 @@ func (c *CLI) env() []string { } out = append(out, kv) } - return append(out, "PATH="+widenPath(path, c.home())) + // A background session inherits the environment of the launch that + // started Claude's daemon, so it gets the user's PATH too. + return append(out, "PATH="+toolpath.Merge(filepath.Dir(c.Bin), path, c.tools().PATH(), legacyBinDir(c.home()))) } -func (c *CLI) home() string { - if c.Home != "" { - return c.Home +func (c *CLI) tools() toolpath.Tools { + if c.Tools != nil { + return c.Tools } - h, _ := os.UserHomeDir() - return h + r := toolpath.Process() + r.Home = c.Home + return r } -// ToolDirs are where installers put claude and the tools its sessions run -// when a service manager's PATH lacks them; searched after PATH. -func ToolDirs(home string) []string { - var dirs []string - if home != "" { - for _, d := range []string{".local/bin", ".claude/local", ".npm-global/bin", ".bun/bin", ".volta/bin", ".local/share/pnpm"} { - dirs = append(dirs, filepath.Join(home, d)) - } +func (c *CLI) home() string { + if c.Home != "" { + return c.Home } - return append(dirs, "/usr/local/bin", "/opt/homebrew/bin", "/usr/bin", "/bin") + home, _ := os.UserHomeDir() + return home } -// widenPath appends the tool dirs missing from path: a background session -// inherits the environment of the launch that started Claude's daemon. -func widenPath(path, home string) string { - parts := filepath.SplitList(path) - for _, d := range ToolDirs(home) { - if !slices.Contains(parts, d) { - parts = append(parts, d) - } - } - return strings.Join(parts, string(os.PathListSeparator)) +// legacyBinDir is the original Claude Code installer's private tool directory. +func legacyBinDir(home string) string { + return filepath.Join(home, ".claude", "local") } -// Find resolves the claude command: bin (a name or path) when set, else -// claude on PATH, else in the tool dirs. "" when none is executable. +// Find resolves the configured command, or claude followed by its legacy +// installation when no command was configured. func Find(bin, home string, lookPath func(string) (string, error)) string { if lookPath == nil { - lookPath = exec.LookPath + r := toolpath.Process() + r.Home = home + lookPath = r.LookPath } - if bin = strings.TrimSpace(bin); bin != "" { - if strings.HasPrefix(bin, "~/") && home != "" { - bin = filepath.Join(home, bin[2:]) - } - p, err := lookPath(bin) - if err != nil { - return "" - } - if abs, err := filepath.Abs(p); err == nil { - return abs - } - return p + name := strings.TrimSpace(bin) + if name == "" { + name = "claude" } - if p, err := lookPath("claude"); err == nil { - if abs, err := filepath.Abs(p); err == nil { - return abs - } - return p + if strings.HasPrefix(name, "~/") && home != "" { + name = filepath.Join(home, name[2:]) } - for _, d := range ToolDirs(home) { - if p, err := lookPath(filepath.Join(d, "claude")); err == nil { - return p - } + p, err := lookPath(name) + if err != nil && name == "claude" && home != "" { + p, err = lookPath(filepath.Join(legacyBinDir(home), name)) + } + if err != nil { + return "" + } + abs, err := filepath.Abs(p) + if err != nil { + return p } - return "" + return abs } var ( diff --git a/server/internal/claudecodesetup/connector.go b/server/internal/claudecodesetup/connector.go index 4f4c1c2b..0a610050 100644 --- a/server/internal/claudecodesetup/connector.go +++ b/server/internal/claudecodesetup/connector.go @@ -39,7 +39,7 @@ func (c *Connector) Run(ctx context.Context, action string, input json.RawMessag } if action == claudecode.ActionCheck { c.svc.probed.Forget() // an explicit check probes the facts again - return c.svc.Status(ctx, true).CheckResult(), nil + return c.svc.status(ctx, true, true).CheckResult(), nil } res, err := c.svc.Connect(ctx) if err == nil { diff --git a/server/internal/claudecodesetup/facts.go b/server/internal/claudecodesetup/facts.go index d8970be1..f4e352d9 100644 --- a/server/internal/claudecodesetup/facts.go +++ b/server/internal/claudecodesetup/facts.go @@ -15,12 +15,8 @@ import ( // younger than harness.FactsTTL. The channel gets one result; a failed or // slow probe is a fact, never a status error (s.mu held; the probe itself // takes no Service lock). -func (s *Service) probeExtras(ctx context.Context) <-chan harness.Probed { - if !s.summary().Configured { - return nil - } - bin := s.find() - if bin == "" { +func (s *Service) probeExtras(ctx context.Context, bin string) <-chan harness.Probed { + if bin == "" || !s.summary().Configured { return nil } cli, home, timeout, setup := s.cli(bin), s.opts.Home, s.opts.MCPTimeout, s.ports.CLIName()+" setup mcp --claude" diff --git a/server/internal/claudecodesetup/module.go b/server/internal/claudecodesetup/module.go index 49cdddab..c34c04e5 100644 --- a/server/internal/claudecodesetup/module.go +++ b/server/internal/claudecodesetup/module.go @@ -30,9 +30,6 @@ func compose(ctx context.Context, p harness.Ports) (harness.Composition, error) default: o.Scope = claudecode.ScopeAvailable() } - if o.LookPath == nil { - o.LookPath = p.LookupPath - } if o.StateDir == "" && p.DataDir != "" { o.StateDir = filepath.Join(p.DataDir, "claude") } diff --git a/server/internal/claudecodesetup/setup.go b/server/internal/claudecodesetup/setup.go index 22811355..e931262c 100644 --- a/server/internal/claudecodesetup/setup.go +++ b/server/internal/claudecodesetup/setup.go @@ -22,6 +22,7 @@ import ( "github.com/flexdinesh/stage/server/internal/execution" "github.com/flexdinesh/stage/server/internal/harness" "github.com/flexdinesh/stage/server/internal/machine" + "github.com/flexdinesh/stage/server/internal/toolpath" ) // Error codes (409 body "code"). @@ -56,7 +57,7 @@ type Options struct { Home string // Environ is the environment passed on to claude (nil: os.Environ()). Environ []string - // LookPath resolves the command (nil: exec.LookPath). + // LookPath overrides the machine tool lookup in tests. LookPath func(string) (string, error) // Scope runs background launches in their own systemd scope // (claudecode.ScopeAvailable). @@ -133,6 +134,11 @@ func New(ctx context.Context, p Ports, o Options) (*Service, error) { if o.Home == "" { o.Home, _ = os.UserHomeDir() } + if p.Tools == nil { + tools := toolpath.Process() + tools.Home = o.Home + p.Tools = tools + } if o.CheckTimeout == 0 { o.CheckTimeout = checkTimeout } @@ -162,7 +168,7 @@ func New(ctx context.Context, p Ports, o Options) (*Service, error) { } s := &Service{ports: p, opts: o, log: o.Logger, saved: saved, id: id, life: ctx} if id != 0 && !saved.Disconnected { - if bin := s.find(); bin != "" { + if bin := s.find(false); bin != "" { s.install(bin, saved.ConfigDir) } else { s.state, s.reason = StateNotFound, s.notFound() @@ -171,12 +177,20 @@ func New(ctx context.Context, p Ports, o Options) (*Service, error) { return s, nil } -func (s *Service) find() string { - return claudecode.Find(s.saved.Binary, s.opts.Home, s.opts.LookPath) +func (s *Service) find(refresh bool) string { + if s.opts.LookPath != nil { + return claudecode.Find(s.saved.Binary, s.opts.Home, s.opts.LookPath) + } + p := claudecode.Find(s.saved.Binary, s.opts.Home, s.ports.Tools.LookPath) + if p == "" && refresh { + s.ports.Tools.Refresh() + p = claudecode.Find(s.saved.Binary, s.opts.Home, s.ports.Tools.LookPath) + } + return p } func (s *Service) cli(bin string) *claudecode.CLI { - return &claudecode.CLI{Bin: bin, Home: s.opts.Home, Environ: s.opts.Environ, Scope: s.opts.Scope} + return &claudecode.CLI{Bin: bin, Home: s.opts.Home, Environ: s.opts.Environ, Scope: s.opts.Scope, Tools: s.ports.Tools} } // install puts the adapter for bin on the connection (s.mu held or setup). @@ -267,9 +281,8 @@ func (s *Service) notFound() string { // check runs the CLI checks: the command, its version and its login. It // returns the state, a reason for anything but connected-ready, and the // auth status. -func (s *Service) check(ctx context.Context) (string, string, Details, claudecode.Auth) { +func (s *Service) check(ctx context.Context, bin string) (string, string, Details, claudecode.Auth) { d := Details{Scope: s.opts.Scope} - bin := s.find() if bin == "" { return StateNotFound, s.notFound(), d, claudecode.Auth{} } @@ -320,7 +333,7 @@ func label(configDir, home string) string { func (s *Service) Connect(ctx context.Context) (harness.Result, error) { s.mu.Lock() defer s.mu.Unlock() - state, reason, d, au := s.check(ctx) + state, reason, d, au := s.check(ctx, s.find(true)) s.checked, s.details = true, d if state != "" { s.state, s.reason = state, reason @@ -393,7 +406,7 @@ func (s *Service) Configure(ctx context.Context, raw json.RawMessage) error { s.saved, s.checked = next, false s.probed.Forget() if s.active || (s.id != 0 && !s.saved.Disconnected) { - if bin := s.find(); bin != "" { + if bin := s.find(false); bin != "" { s.install(bin, s.saved.ConfigDir) } else { s.uninstall() @@ -423,11 +436,17 @@ func (s *Service) Summary() harness.Summary { // Status reports the setup; refresh (or the first call) runs the CLI // checks, bounded. func (s *Service) Status(ctx context.Context, refresh bool) harness.Status { + return s.status(ctx, refresh, false) +} + +// rescan retries a missing executable on an explicit check. +func (s *Service) status(ctx context.Context, refresh, rescan bool) harness.Status { s.mu.Lock() defer s.mu.Unlock() if refresh || !s.checked { - probe := s.probeExtras(ctx) - state, reason, d, au := s.check(ctx) + bin := s.find(rescan) + probe := s.probeExtras(ctx, bin) + state, reason, d, au := s.check(ctx, bin) s.checked, s.details = true, d switch { case state != "": diff --git a/server/internal/claudecodesetup/setup_test.go b/server/internal/claudecodesetup/setup_test.go index 803d6c8d..15bcd930 100644 --- a/server/internal/claudecodesetup/setup_test.go +++ b/server/internal/claudecodesetup/setup_test.go @@ -125,6 +125,91 @@ func TestConnectDisconnectAndRestart(t *testing.T) { } } +func TestLegacyInstallerLookupAndChildPATH(t *testing.T) { + e := newEnv(t) + ctx := t.Context() + dir := filepath.Join(e.f.Home, ".claude", "local") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + bin := filepath.Join(dir, "claude") + if err := os.Symlink(e.f.Bin, bin); err != nil { + t.Fatal(err) + } + e.opts.LookPath = func(name string) (string, error) { + if name == bin || name == e.f.Bin { + return name, nil + } + return "", os.ErrNotExist + } + if err := e.saveBinary(ctx, ""); err != nil { + t.Fatal(err) + } + svc := e.service(t) + if d := svc.Status(ctx, true).Details.(claudecodesetup.Details); d.Binary != bin || d.Version == "" { + t.Fatalf("legacy installation: %+v", d) + } + // A separately configured executable also gets the legacy tool directory. + if err := svc.Configure(ctx, []byte(`{"binary":"`+e.f.Bin+`"}`)); err != nil { + t.Fatal(err) + } + if _, err := svc.Connect(ctx); err != nil { + t.Fatal(err) + } + calls := e.f.Read().Calls + if path := calls[len(calls)-1].Env["PATH"]; !slices.Contains(filepath.SplitList(path), dir) { + t.Fatalf("Claude PATH %q missing %q", path, dir) + } +} + +// installingClaude models a shell PATH that changes after setup's first lookup. +type installingClaude struct { + bin string + refreshes int +} + +func (i *installingClaude) LookPath(name string) (string, error) { + if name == "claude" && i.refreshes > 0 { + return i.bin, nil + } + return "", os.ErrNotExist +} +func (i *installingClaude) PATH() string { return filepath.Dir(i.bin) } +func (i *installingClaude) Refresh() { i.refreshes++ } + +func TestCheckAndConnectRefreshMissingClaude(t *testing.T) { + for _, action := range []string{claudecode.ActionCheck, claudecode.ActionConnect} { + t.Run(action, func(t *testing.T) { + e := newEnv(t) + ctx := t.Context() + if err := e.saveBinary(ctx, ""); err != nil { + t.Fatal(err) + } + tools := &installingClaude{bin: e.f.Bin} + e.opts.LookPath = nil + built, err := claudecodesetup.Module.Compose(ctx, harness.Ports{ + Settings: e.ports.Settings(), Identity: e.ports, Install: e.local.Install, + Tools: tools, Overrides: map[string]any{claudecode.Kind: e.opts}, + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(built.Close) + st, err := built.Connector.Status(ctx, false) + if err != nil || st.State != claudecodesetup.StateNotFound || tools.refreshes != 0 { + t.Fatalf("initial status %+v, refreshes %d, error %v", st, tools.refreshes, err) + } + if _, err := built.Connector.Run(ctx, action, nil); err != nil { + t.Fatal(err) + } + st, err = built.Connector.Status(ctx, false) + if err != nil || st.Details.(claudecodesetup.Details).Binary != e.f.Bin || tools.refreshes != 1 { + t.Fatalf("after %s: %+v, refreshes %d, error %v", action, st, tools.refreshes, err) + } + }) + } +} + // Each failed check says what to do; none creates a connection. func TestConnectFailures(t *testing.T) { e := newEnv(t) diff --git a/server/internal/codex/daemon.go b/server/internal/codex/daemon.go index 751e5a43..29f533ff 100644 --- a/server/internal/codex/daemon.go +++ b/server/internal/codex/daemon.go @@ -8,8 +8,11 @@ import ( "fmt" "os" "os/exec" + "path/filepath" "strings" "time" + + "github.com/flexdinesh/stage/server/internal/toolpath" ) // DaemonInfo is what `codex app-server daemon version` (and `start`) @@ -48,12 +51,14 @@ var ErrNotInstalled = errors.New("codex CLI not found") // commandTimeout bounds one daemon command. const commandTimeout = 20 * time.Second -// CLI runs Binary ("" = codex on PATH) with Stage's environment minus the -// variables that would tie the daemon to another session (Environ). +// CLI runs Binary (default "codex") with the machine's tool PATH. +// Environ removes caller session IDs before the daemon inherits it. type CLI struct { Binary string // Env is the base environment (nil: os.Environ()). Env []string + // Tools resolves Binary and the PATH (nil: toolpath.Process()). + Tools toolpath.Tools } // Path is the binary CLI runs. @@ -75,7 +80,11 @@ func (c CLI) Start(ctx context.Context) (DaemonInfo, error) { func (c CLI) run(ctx context.Context, verb string) (DaemonInfo, error) { ctx, cancel := context.WithTimeout(ctx, commandTimeout) defer cancel() - path, err := exec.LookPath(c.Path()) + tools := c.Tools + if tools == nil { + tools = toolpath.Process() + } + path, err := tools.LookPath(c.Path()) if err != nil { return DaemonInfo{}, fmt.Errorf("%w: %s", ErrNotInstalled, c.Path()) } @@ -84,7 +93,7 @@ func (c CLI) run(ctx context.Context, verb string) (DaemonInfo, error) { if env == nil { env = os.Environ() } - cmd.Env = Environ(env) + cmd.Env = toolpath.Env(Environ(env), tools.PATH(), filepath.Dir(path)) var stdout, stderr bytes.Buffer cmd.Stdout, cmd.Stderr = &stdout, &stderr runErr := cmd.Run() diff --git a/server/internal/codexsetup/connector.go b/server/internal/codexsetup/connector.go index cce7c4e8..f65200d5 100644 --- a/server/internal/codexsetup/connector.go +++ b/server/internal/codexsetup/connector.go @@ -141,8 +141,8 @@ func (c *Connector) Run(ctx context.Context, action string, input json.RawMessag } } if action == codex.ActionCheck { - c.svc.probed.Forget() // an explicit check probes the facts again - status, err := c.Status(ctx, true) + c.svc.recheck(ctx) + status, err := c.Status(ctx, false) return status.CheckResult(), err } res, err := c.svc.Connect(ctx) diff --git a/server/internal/codexsetup/setup.go b/server/internal/codexsetup/setup.go index 512602a6..1ef5e037 100644 --- a/server/internal/codexsetup/setup.go +++ b/server/internal/codexsetup/setup.go @@ -91,8 +91,10 @@ type Service struct { // New loads the machine's setup and, when it was connected, installs the // adapter on its active connection (the daemon starts on first use). func New(ctx context.Context, opts Options) (*Service, error) { + tools := opts.ToolsOrProcess() + opts.Tools = tools if opts.Daemon == nil { - opts.Daemon = func(binary string) codex.Daemon { return codex.CLI{Binary: binary} } + opts.Daemon = func(binary string) codex.Daemon { return codex.CLI{Binary: binary, Tools: tools} } } if opts.Logger == nil { opts.Logger = slog.Default() @@ -135,7 +137,7 @@ func (s *Service) Connect(ctx context.Context) (harness.Result, error) { s.mu.Lock() defer s.mu.Unlock() client := s.newClient(s.saved.Binary) - p, err := client.Probe(ctx) + p, err := s.probe(ctx, client, true) if err != nil { client.Close() s.fail(err) @@ -247,18 +249,31 @@ func (s *Service) Status(ctx context.Context, refresh bool) (string, string, Det s.mu.Lock() defer s.mu.Unlock() if refresh || s.checked.IsZero() || time.Since(s.checked) > statusTTL { - s.check(ctx) + s.check(ctx, false) } return s.state, s.reason, s.details } -// check refreshes the state (s.mu held). -func (s *Service) check(ctx context.Context) { +// recheck handles an explicit check. Polls keep the cached shell PATH. +func (s *Service) recheck(ctx context.Context) { + s.mu.Lock() + defer s.mu.Unlock() + s.probed.Forget() + s.check(ctx, true) +} + +// check refreshes the state with s.mu held. +func (s *Service) check(ctx context.Context, rescan bool) { now := time.Now().UTC() - s.checked, s.details.CheckedAt = now, &now + s.details.CheckedAt = &now + defer func() { s.checked = time.Now() }() if !s.active { s.state, s.reason, s.details.Fix = StateNotConnected, "", "" info, err := s.opts.Daemon(s.saved.Binary).Version(ctx) + if rescan && errors.Is(err, codex.ErrNotInstalled) { + s.opts.Tools.Refresh() + info, err = s.opts.Daemon(s.saved.Binary).Version(ctx) + } switch { case errors.Is(err, codex.ErrNotInstalled): s.state, s.reason = StateNotInstalled, codex.Problem(err) @@ -276,7 +291,7 @@ func (s *Service) check(ctx context.Context) { } return } - p, err := s.client.Probe(ctx) + p, err := s.probe(ctx, s.client, rescan) if err != nil { s.fail(err) return @@ -289,6 +304,15 @@ func (s *Service) check(ctx context.Context) { s.state, s.reason, s.details.Fix = StateConnected, "", "" } +func (s *Service) probe(ctx context.Context, client *codex.Client, rescan bool) (codex.Probe, error) { + p, err := client.Probe(ctx) + if rescan && errors.Is(err, codex.ErrNotInstalled) { + s.opts.Tools.Refresh() + return client.Probe(ctx) + } + return p, err +} + // preview reads the account through a running daemon without connecting // Stage to it (s.mu held). The daemon is never started here. func (s *Service) preview(ctx context.Context, info codex.DaemonInfo) { diff --git a/server/internal/codexsetup/setup_test.go b/server/internal/codexsetup/setup_test.go index 664edb36..c65fc075 100644 --- a/server/internal/codexsetup/setup_test.go +++ b/server/internal/codexsetup/setup_test.go @@ -4,6 +4,9 @@ import ( "context" "encoding/json" "errors" + "os" + "os/exec" + "path/filepath" "slices" "testing" @@ -15,6 +18,7 @@ import ( "github.com/flexdinesh/stage/server/internal/execution" "github.com/flexdinesh/stage/server/internal/harness" "github.com/flexdinesh/stage/server/internal/machine" + "github.com/flexdinesh/stage/server/internal/toolpath" ) type rig struct { @@ -187,6 +191,80 @@ func TestStatusReportsAStoppedDaemonWithItsFix(t *testing.T) { } } +// A stale shell PATH first misses the CLI. Refresh makes the real resolver +// available so the retry exercises executable lookup and the child process. +type stalePath struct { + *toolpath.Resolver + refreshed bool +} + +func (p *stalePath) LookPath(file string) (string, error) { + if !p.refreshed { + return "", exec.ErrNotFound + } + return p.Resolver.LookPath(file) +} + +func (p *stalePath) Refresh() { p.refreshed = true } + +func TestSetupFindsPnpmCodexAndItsRuntime(t *testing.T) { + r := newRig(t) + home := t.TempDir() + binDir := filepath.Join(home, "Library", "pnpm", "bin") + if err := os.MkdirAll(binDir, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(binDir, "codex"), []byte("#!/bin/sh\nexec node \"$@\"\n"), 0o700); err != nil { + t.Fatal(err) + } + // The shim needs node from the login shell. The runtime also verifies + // that a tool in the shim's directory is visible and caller IDs are gone. + nodeDir := t.TempDir() + node := `#!/bin/sh +set -eu +[ "$(command -v codex)" = "$HOME/Library/pnpm/bin/codex" ] +[ -z "${CODEX_THREAD_ID-}" ] +case "$*" in + "app-server daemon version") echo '{"status":"stopped","cliVersion":"pnpm-test"}' ;; + "app-server daemon start") printf '{"status":"started","socketPath":"%s"}\n' "$TEST_CODEX_SOCKET" ;; + *) exit 1 ;; +esac +` + if err := os.WriteFile(filepath.Join(nodeDir, "node"), []byte(node), 0o700); err != nil { + t.Fatal(err) + } + t.Setenv("HOME", home) + t.Setenv("PATH", t.TempDir()) + t.Setenv("CODEX_THREAD_ID", "stage-caller") + t.Setenv("TEST_CODEX_SOCKET", r.srv.Path) + tools := &stalePath{Resolver: &toolpath.Resolver{Home: home, Probe: func(context.Context) (string, error) { + return nodeDir, nil + }}} + composed, err := codexsetup.Module.Compose(t.Context(), harness.Ports{ + Settings: r.ports.Settings(), Identity: r.ports, Install: r.local.Install, Tools: tools, + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(composed.Close) + c := composed.Connector + st, err := c.Status(t.Context(), true) + if err != nil || st.State != codexsetup.StateNotInstalled || tools.refreshed { + t.Fatalf("passive status %+v, refresh %v, err %v", st, tools.refreshed, err) + } + if _, err := c.Run(t.Context(), codex.ActionCheck, nil); err != nil { + t.Fatal(err) + } + st, err = c.Status(t.Context(), false) + if err != nil || st.State != codexsetup.StateNotConnected || details(t, st).CLIVersion != "pnpm-test" { + t.Fatalf("recheck %+v, err %v", st, err) + } + tools.refreshed = false + if _, err := c.Run(t.Context(), codex.ActionConnect, nil); err != nil || !c.Summary(t.Context()).Connected { + t.Fatalf("connect through pnpm shim: %v", err) + } +} + type failing struct{ d *codextest.Daemon } func (f failing) Version(ctx context.Context) (codex.DaemonInfo, error) { return f.d.Version(ctx) } diff --git a/server/internal/harness/module.go b/server/internal/harness/module.go index 8fe2331b..1b8a89e4 100644 --- a/server/internal/harness/module.go +++ b/server/internal/harness/module.go @@ -6,6 +6,7 @@ import ( "log/slog" "github.com/flexdinesh/stage/server/internal/execution" + "github.com/flexdinesh/stage/server/internal/toolpath" ) // Module composes one harness on the machine that runs it. Its settings @@ -78,7 +79,7 @@ type WorkspaceEvidence struct { Workspace string `json:"workspace"` } -// Ports are bound to the machine before Compose runs. Getenv and LookupPath +// Ports are bound to the machine before Compose runs. Getenv and Tools // refer to that process. Overrides supply machine-local test dependencies. type Ports struct { Settings Settings @@ -93,10 +94,20 @@ type Ports struct { Profile Profile Logger *slog.Logger Getenv func(string) string - LookupPath func(string) (string, error) - Overrides map[string]any - OnChanged func() + // Tools finds harness CLIs and the PATH their processes get (nil: + // toolpath.Process, see ToolsOrProcess). + Tools toolpath.Tools + Overrides map[string]any + OnChanged func() // CLI is the Stage CLI on this machine's PATH, named in fix commands // ("": DefaultCLI; see CLIName). CLI string } + +// ToolsOrProcess is Tools, or the process PATH plus toolpath.Dirs when unset. +func (p Ports) ToolsOrProcess() toolpath.Tools { + if p.Tools != nil { + return p.Tools + } + return toolpath.Process() +} diff --git a/server/internal/serve/localmachine.go b/server/internal/serve/localmachine.go index 859d7951..c416ae1f 100644 --- a/server/internal/serve/localmachine.go +++ b/server/internal/serve/localmachine.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "log/slog" - "os/exec" "github.com/flexdinesh/stage/server/internal/config" "github.com/flexdinesh/stage/server/internal/db" @@ -12,6 +11,7 @@ import ( "github.com/flexdinesh/stage/server/internal/harnesses" "github.com/flexdinesh/stage/server/internal/machine" "github.com/flexdinesh/stage/server/internal/remote" + "github.com/flexdinesh/stage/server/internal/toolpath" ) type localMachine struct { @@ -25,7 +25,7 @@ func (m *localMachine) compose(ctx context.Context, store *db.Store, cfg config. Settings: p.Settings(), Secrets: p.Secrets(), Identity: p, Install: m.Install, SaveSettingsWithSecret: p.SaveSettingsWithSecret, SetLastError: p.SetLastError, DataDir: cfg.DataDir, Profile: m.Profile(), Logger: logger, Getenv: cfg.Getenv, - LookupPath: exec.LookPath, Overrides: overrides, OnChanged: changed, CLI: cli, + Tools: &toolpath.Resolver{Getenv: cfg.Getenv}, Overrides: overrides, OnChanged: changed, CLI: cli, } for _, module := range harnesses.Modules() { d := module.Descriptor diff --git a/server/internal/serve/serve_test.go b/server/internal/serve/serve_test.go index 07afb700..10a98886 100644 --- a/server/internal/serve/serve_test.go +++ b/server/internal/serve/serve_test.go @@ -58,6 +58,7 @@ func isolate(t *testing.T) string { t.Fatal(err) } t.Setenv("HOME", home) + t.Setenv("SHELL", "/bin/sh") t.Setenv("XDG_DATA_HOME", "") rt := filepath.Join(short, "rt") if err := os.Mkdir(rt, 0o700); err != nil { diff --git a/server/internal/t3setup/autopair.go b/server/internal/t3setup/autopair.go index ecd212b0..61448330 100644 --- a/server/internal/t3setup/autopair.go +++ b/server/internal/t3setup/autopair.go @@ -15,6 +15,7 @@ import ( "github.com/flexdinesh/stage/server/internal/db" "github.com/flexdinesh/stage/server/internal/t3" + "github.com/flexdinesh/stage/server/internal/toolpath" ) // Why auto-pair is unavailable. @@ -46,19 +47,17 @@ type LocalCLI struct { Bin string // Exec runs the CLI; nil = os/exec. Exec Runner - // LookPath resolves a command name or path to an executable; nil = - // exec.LookPath. + // Tools finds the CLI and supplies its process PATH. + Tools toolpath.Tools + // LookPath overrides the machine tool lookup in tests. LookPath func(file string) (string, error) - // Home is the user's home for the CLI search; "" = os.UserHomeDir. - Home string } -// Run runs bin with args. -func (l *LocalCLI) Run(ctx context.Context, bin string, args []string) ([]byte, error) { - if l.Exec == nil { - return execRunner(ctx, bin, args) +func (l *LocalCLI) tools() toolpath.Tools { + if l.Tools != nil { + return l.Tools } - return l.Exec(ctx, bin, args) + return toolpath.Process() } // AutoPair is whether the auto-pair setup action can work. @@ -99,45 +98,21 @@ func IsLoopbackURL(u string) bool { return ip != nil && ip.IsLoopback() } -// cliDirs are where installers put the t3 CLI when it is not on the -// server's PATH (a service manager's PATH is minimal). -func cliDirs(home string) []string { - var dirs []string - if home != "" { - for _, d := range []string{".local/bin", ".bun/bin", ".local/share/pnpm", ".npm-global/bin", ".volta/bin"} { - dirs = append(dirs, filepath.Join(home, d)) - } - } - return append(dirs, "/usr/local/bin", "/opt/homebrew/bin") -} - -// FindCLI is the t3 CLI: Bin (only it, when set), else PATH, else the -// usual install dirs. "" when none. +// FindCLI resolves T3_BIN when set, or t3 on the machine's PATH. func (l *LocalCLI) FindCLI() string { + name := l.Bin + if name == "" { + name = "t3" + } look := l.LookPath if look == nil { - look = execLookPath - } - if l.Bin != "" { - p, err := look(l.Bin) - if err != nil { - return "" - } - return p + look = l.tools().LookPath } - if p, err := look("t3"); err == nil { - return p - } - home := l.Home - if home == "" { - home, _ = os.UserHomeDir() - } - for _, d := range cliDirs(home) { - if p, err := look(filepath.Join(d, "t3")); err == nil { - return p - } + path, err := look(name) + if err != nil { + return "" } - return "" + return path } // PairingArgs are the `t3` arguments that mint a pairing code for stage. @@ -189,13 +164,13 @@ func unavailableMessage(reason, t3URL string) string { return "auto-pair needs the t3 CLI, which was not found on this machine (set T3_BIN); pair with a code from `t3 pair`" } -func execLookPath(file string) (string, error) { return exec.LookPath(file) } - -// execRunner runs the CLI with its own directory first on PATH (script -// shims find their runtime next to them). -func execRunner(ctx context.Context, bin string, args []string) ([]byte, error) { +// Run puts the CLI directory first on PATH so script shims find sibling runtimes. +func (l *LocalCLI) Run(ctx context.Context, bin string, args []string) ([]byte, error) { + if l.Exec != nil { + return l.Exec(ctx, bin, args) + } cmd := exec.CommandContext(ctx, bin, args...) - cmd.Env = append(os.Environ(), "PATH="+filepath.Dir(bin)+string(os.PathListSeparator)+os.Getenv("PATH")) + cmd.Env = toolpath.Env(os.Environ(), l.tools().PATH(), filepath.Dir(bin)) var stdout, stderr bytes.Buffer cmd.Stdout, cmd.Stderr = &stdout, &stderr if err := cmd.Run(); err != nil { diff --git a/server/internal/t3setup/export_test.go b/server/internal/t3setup/export_test.go deleted file mode 100644 index 2b2eff52..00000000 --- a/server/internal/t3setup/export_test.go +++ /dev/null @@ -1,4 +0,0 @@ -package t3setup - -// ExecRunner exposes execRunner to the external tests. -var ExecRunner = execRunner diff --git a/server/internal/t3setup/module.go b/server/internal/t3setup/module.go index 7c520e47..76e1393c 100644 --- a/server/internal/t3setup/module.go +++ b/server/internal/t3setup/module.go @@ -96,7 +96,7 @@ func compose(ctx context.Context, p harness.Ports) (harness.Composition, error) setup := New(Options{ Settings: p.Settings, Secrets: p.Secrets, Identity: p.Identity, Client: client, Endpoint: endpoint, AdminToken: admin, ClientName: clientName, - Fake: IsFake(client), Local: &LocalCLI{Bin: getenv(envBin), LookPath: p.LookupPath}, + Fake: IsFake(client), Local: &LocalCLI{Bin: getenv(envBin), Tools: p.ToolsOrProcess()}, Logger: logger, OnPaired: p.OnChanged, OnSwitched: func(sw harness.Switch) { install(sw.Old, sw.New) }, }) diff --git a/server/internal/t3setup/module_test.go b/server/internal/t3setup/module_test.go index 29ecbae6..ed7516a7 100644 --- a/server/internal/t3setup/module_test.go +++ b/server/internal/t3setup/module_test.go @@ -1,10 +1,13 @@ package t3setup_test import ( + "context" "encoding/json" "log/slog" "net/http" "net/http/httptest" + "os" + "path/filepath" "strings" "testing" "time" @@ -16,6 +19,7 @@ import ( "github.com/flexdinesh/stage/server/internal/machine" "github.com/flexdinesh/stage/server/internal/t3" "github.com/flexdinesh/stage/server/internal/t3setup" + "github.com/flexdinesh/stage/server/internal/toolpath" ) func TestModuleInstallsOnFirstPairing(t *testing.T) { @@ -51,6 +55,61 @@ func TestModuleInstallsOnFirstPairing(t *testing.T) { } } +func TestModuleAutoPairFindsCLIAndRuntimeAfterInstall(t *testing.T) { + ctx := t.Context() + store := db.NewStore(testDB.Fresh(t)) + p := machine.NewStorePorts(store.OnMachine(db.LocalMachine), harness.MustRegistry(t3setup.Module.Descriptor)) + cliDir, runtimeDir := t.TempDir(), t.TempDir() + tools := &toolpath.Resolver{ + Getenv: func(string) string { return "" }, + Probe: func(context.Context) (string, error) { return toolpath.Merge(cliDir, runtimeDir), nil }, + } + fake := &client{Fake: t3.NewFake()} + fake.SetProbe(reachable("env-a")) + // Expose only the client methods so auto-pair runs the real local CLI. + upstream := struct{ t3.Client }{fake} + built, err := t3setup.Module.Compose(ctx, harness.Ports{ + Settings: p.Settings(), Identity: p, Secrets: p.Secrets(), + Overrides: map[string]any{t3.Kind: upstream}, Tools: tools, + Getenv: func(key string) string { + if key == "T3_BIN" { + return "test-t3" + } + return "" + }, + Install: func(_, _ int64, _ execution.Adapter) {}, + }) + if err != nil { + t.Fatal(err) + } + st, err := built.Connector.Status(ctx, true) + if err != nil { + t.Fatal(err) + } + if ap := st.Details.(t3setup.Details).AutoPair; ap.Available || ap.Reason == nil || *ap.Reason != t3setup.ReasonCLINotFound { + t.Fatalf("before installation: %+v", ap) + } + if err := os.WriteFile(filepath.Join(cliDir, "test-t3"), []byte("#!/bin/sh\nexec t3-test-runtime\n"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(runtimeDir, "t3-test-runtime"), []byte("#!/bin/sh\necho '{\"credential\":\"CODE\"}'\n"), 0o755); err != nil { + t.Fatal(err) + } + st, err = built.Connector.Status(ctx, false) + if err != nil { + t.Fatal(err) + } + if !st.Details.(t3setup.Details).AutoPair.Available { + t.Fatal("auto-pair unavailable after CLI installation") + } + if _, err := built.Connector.Run(ctx, t3.ActionAutoPair, nil); err != nil { + t.Fatal(err) + } + if len(fake.Pairs) != 1 || fake.Pairs[0] != "CODE" { + t.Fatalf("redeemed pairing codes: %v", fake.Pairs) + } +} + func TestModuleRestoresAndClearsSettingsAndSecrets(t *testing.T) { ctx := t.Context() store := db.NewStore(testDB.Reset(t)) diff --git a/server/internal/t3setup/t3setup_test.go b/server/internal/t3setup/t3setup_test.go index 2a388cca..f67dfdfa 100644 --- a/server/internal/t3setup/t3setup_test.go +++ b/server/internal/t3setup/t3setup_test.go @@ -105,8 +105,7 @@ func newEnv(t *testing.T, bin string, fake bool) *env { OnSwitched: func(sw harness.Switch) { e.switches = append(e.switches, sw) }, Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), Local: &t3setup.LocalCLI{ - Bin: bin, - Home: "/home/u", + Bin: bin, Exec: func(_ context.Context, bin string, args []string) ([]byte, error) { e.runs = append(e.runs, append([]string{bin}, args...)) return e.runOut, e.runErr @@ -247,11 +246,9 @@ func TestAutoPairAvailability(t *testing.T) { if ok, r := reason(e); ok || r != "cli_not_found" { t.Fatalf("no cli: %v %q", ok, r) } - for _, p := range []string{"/home/u/.bun/bin/t3", "/opt/homebrew/bin/t3", "t3"} { - e.paths = map[string]bool{p: true} - if ok, r := reason(e); !ok || r != "" { - t.Fatalf("cli at %s: %v %q", p, ok, r) - } + e.paths["t3"] = true + if ok, r := reason(e); !ok || r != "" { + t.Fatalf("t3 on PATH: %v %q", ok, r) } // T3_BIN is the only candidate when set. @@ -269,12 +266,12 @@ func TestAutoPairAvailability(t *testing.T) { func TestAutoPairMintsAndRedeems(t *testing.T) { ctx := context.Background() e := newEnv(t, "", false) - e.paths["/home/u/.local/bin/t3"] = true + e.paths["t3"] = true e.runOut = []byte(`{"id":"p1","credential":"PAIR-123","label":"stage mcp","scopes":["orchestration:read"],"expiresAt":"2026-11-17T10:05:00Z"}` + "\n") if _, err := e.svc.AutoPair(ctx); err != nil { t.Fatal(err) } - want := []string{"/home/u/.local/bin/t3", "auth", "pairing", "create", "--json", "--label", "stage mcp", "--ttl", "5m", + want := []string{"/usr/bin/t3", "auth", "pairing", "create", "--json", "--label", "stage mcp", "--ttl", "5m", "--scope", "orchestration:read", "--scope", "orchestration:operate", "--scope", "settings:write", "--scope", "source-control:write"} if len(e.runs) != 1 || !slices.Equal(e.runs[0], want) { t.Fatalf("ran %q", e.runs) @@ -634,11 +631,12 @@ func TestExecRunnerReportsStderr(t *testing.T) { if err := os.WriteFile(bin, []byte(script), 0o755); err != nil { t.Fatal(err) } - out, err := t3setup.ExecRunner(context.Background(), bin, []string{"ok"}) + cli := &t3setup.LocalCLI{} + out, err := cli.Run(context.Background(), bin, []string{"ok"}) if err != nil || strings.TrimSpace(string(out)) != `{"credential":"C"}` { t.Fatalf("ok: %q %v", out, err) } - if _, err := t3setup.ExecRunner(context.Background(), bin, []string{"fail"}); err == nil || !strings.Contains(err.Error(), "exit status 3: boom") { + if _, err := cli.Run(context.Background(), bin, []string{"fail"}); err == nil || !strings.Contains(err.Error(), "exit status 3: boom") { t.Fatalf("fail: %v", err) } } diff --git a/server/internal/toolpath/shell_other.go b/server/internal/toolpath/shell_other.go new file mode 100644 index 00000000..f7c7684b --- /dev/null +++ b/server/internal/toolpath/shell_other.go @@ -0,0 +1,13 @@ +//go:build !unix + +package toolpath + +import ( + "context" + "errors" +) + +// LoginShell is unavailable off Unix: the process PATH and Dirs apply. +func LoginShell(context.Context, func(string) string) (string, error) { + return "", errors.New("login shell PATH is read on Unix only") +} diff --git a/server/internal/toolpath/shell_unix.go b/server/internal/toolpath/shell_unix.go new file mode 100644 index 00000000..c824cbce --- /dev/null +++ b/server/internal/toolpath/shell_unix.go @@ -0,0 +1,125 @@ +//go:build unix + +package toolpath + +import ( + "bufio" + "context" + "errors" + "io" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" + "syscall" +) + +// LoginShell reads PATH after the user's interactive login startup files run. +func LoginShell(ctx context.Context, getenv func(string) string) (string, error) { + ctx, cancel := context.WithTimeout(ctx, ProbeTimeout) + defer cancel() + shell := getenv("SHELL") + if !filepath.IsAbs(shell) { + if runtime.GOOS == "darwin" { + shell = darwinShell(ctx, "/usr/bin/id", "/usr/bin/dscl") + } else { + shell = passwdShell() + } + } + // sh sees the exported PATH even in fish, where the shell variable is + // a list. NULs separate the record from login and logout messages. + cmd := exec.CommandContext(ctx, shell, "-ilc", `/bin/sh -c 'printf "\0`+marker+`\0%s\0" "$PATH"'`) + path, err := probeOutput(ctx, cmd, 0) + if err != nil { + return "", err + } + if path == "" { + return "", errors.New("login shell printed no PATH") + } + return path, nil +} + +const marker = "__STAGE_TOOLPATH__" + +// probeOutput reads one bounded stdout record: a line for account commands +// or a marked, NUL-terminated PATH for the shell. +func probeOutput(ctx context.Context, cmd *exec.Cmd, delimiter byte) (string, error) { + r, err := cmd.StdoutPipe() + if err != nil { + return "", err + } + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + cmd.Cancel = func() error { return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) } + if err := cmd.Start(); err != nil { + return "", err + } + + stop := context.AfterFunc(ctx, func() { r.Close() }) + record, readErr := readRecord(bufio.NewReader(r), delimiter) + // Logout hooks can write more than a pipe's capacity. Wait closes the + // pipe after the shell exits even if a background job inherited it. + go func() { _, _ = io.Copy(io.Discard, r) }() + err = cmd.Wait() + stop() + if ctx.Err() != nil { + return "", ctx.Err() + } + if err != nil { + return "", err + } + return record, readErr +} + +func readRecord(r *bufio.Reader, delimiter byte) (string, error) { + if delimiter == 0 { + for { + field, err := r.ReadSlice(0) + if err != nil && err != bufio.ErrBufferFull { + return "", err + } + if string(field) == marker+"\x00" { + break + } + } + } + const maxOutput = 1 << 20 + record, err := bufio.NewReader(io.LimitReader(r, maxOutput)).ReadString(delimiter) + if err != nil { + return "", err + } + return record[:len(record)-1], nil +} + +func darwinShell(ctx context.Context, id, dscl string) string { + const fallback = "/bin/zsh" + name, err := probeOutput(ctx, exec.CommandContext(ctx, id, "-un"), '\n') + if err != nil { + return fallback + } + cmd := exec.CommandContext(ctx, dscl, ".", "-read", "/Users/"+strings.TrimSpace(name), "UserShell") + out, err := probeOutput(ctx, cmd, '\n') + shell, ok := strings.CutPrefix(out, "UserShell:") + shell = strings.TrimSpace(shell) + if err == nil && ok && filepath.IsAbs(shell) { + return shell + } + return fallback +} + +func passwdShell() string { + f, err := os.Open("/etc/passwd") + if err == nil { + defer f.Close() + uid := strconv.Itoa(os.Getuid()) + sc := bufio.NewScanner(f) + for sc.Scan() { + fields := strings.Split(sc.Text(), ":") + if len(fields) == 7 && fields[2] == uid && filepath.IsAbs(fields[6]) { + return fields[6] + } + } + } + return "/bin/sh" +} diff --git a/server/internal/toolpath/shell_unix_test.go b/server/internal/toolpath/shell_unix_test.go new file mode 100644 index 00000000..6286d9bb --- /dev/null +++ b/server/internal/toolpath/shell_unix_test.go @@ -0,0 +1,128 @@ +//go:build unix + +package toolpath + +import ( + "context" + "errors" + "io" + "os" + "path/filepath" + "syscall" + "testing" + "time" +) + +func TestLoginShellNoisyStartup(t *testing.T) { + dir := t.TempDir() + // Exercise the actual shell command with no system tools on PATH. + path := filepath.Join(dir, "package manager bin ") + ":" + filepath.Join(dir, "with\nnewline") + t.Setenv("TOOLPATH_TEST_PATH", path) + shell := writeTool(t, filepath.Join(dir, "login shell"), `#!/bin/sh +[ "$1" = -ilc ] || exit 2 +exec 3>&- +printf 'noise\0' +printf '%8192s' noise +printf 'rc banner without a newline' +echo 'rc warning' >&2 +export PATH="$TOOLPATH_TEST_PATH" +eval "$2" +printf '%131072s' 'logout noise' +`) + t.Setenv("SHELL", shell) + got, err := LoginShell(t.Context(), os.Getenv) + if got != path || err != nil { + t.Fatalf("LoginShell = %q, %v; want %q", got, err, path) + } +} + +func TestLoginShellLeavesSuccessfulStartupJobRunning(t *testing.T) { + dir := t.TempDir() + done := filepath.Join(dir, "done") + t.Setenv("TOOLPATH_TEST_DONE", done) + t.Setenv("SHELL", writeTool(t, filepath.Join(dir, "shell"), `#!/bin/sh +(/bin/sleep 0.2; echo done > "$TOOLPATH_TEST_DONE") & +eval "$2" +`)) + if _, err := LoginShell(t.Context(), os.Getenv); err != nil { + t.Fatal(err) + } + for deadline := time.Now().Add(3 * time.Second); ; { + if _, err := os.Stat(done); err == nil { + return + } + if time.Now().After(deadline) { + t.Fatal("background job did not finish") + } + time.Sleep(10 * time.Millisecond) + } +} + +func TestDarwinAccountShell(t *testing.T) { + dir := t.TempDir() + id := writeTool(t, filepath.Join(dir, "id"), "#!/bin/sh\n[ \"$1\" = -un ] && echo example\n") + dscl := writeTool(t, filepath.Join(dir, "dscl"), `#!/bin/sh +[ "$*" = ". -read /Users/example UserShell" ] || exit 2 +echo "$TOOLPATH_TEST_DSCL" +`) + for _, tc := range []struct{ output, want string }{ + {"UserShell: /opt/fish", "/opt/fish"}, + {"UserShell: ", "/bin/zsh"}, + {"Unexpected attribute: /opt/fish", "/bin/zsh"}, + } { + t.Setenv("TOOLPATH_TEST_DSCL", tc.output) + if got := darwinShell(t.Context(), id, dscl); got != tc.want { + t.Errorf("dscl returned %q, shell = %q; want %q", tc.output, got, tc.want) + } + } + if got := darwinShell(t.Context(), id, filepath.Join(dir, "missing")); got != "/bin/zsh" { + t.Fatalf("missing dscl fallback = %q", got) + } +} + +func TestProbeDeadlineKillsChildren(t *testing.T) { + for _, command := range []string{"shell", "dscl"} { + t.Run(command, func(t *testing.T) { + dir := t.TempDir() + fifo := filepath.Join(dir, "child-fd") + if err := syscall.Mkfifo(fifo, 0600); err != nil { + t.Fatal(err) + } + pipe, err := os.OpenFile(fifo, os.O_RDONLY|syscall.O_NONBLOCK, 0) + if err != nil { + t.Fatal(err) + } + defer pipe.Close() + t.Setenv("TOOLPATH_TEST_FIFO", fifo) + helper := writeTool(t, filepath.Join(dir, "hanging"), `#!/bin/sh +exec 4>"$TOOLPATH_TEST_FIFO" +/bin/sleep 10 & +echo started >&4 +wait +`) + id := writeTool(t, filepath.Join(dir, "id"), "#!/bin/sh\necho example\n") + t.Setenv("SHELL", helper) + ctx, cancel := context.WithTimeout(t.Context(), 500*time.Millisecond) + defer cancel() + start := time.Now() + if command == "shell" { + if _, err := LoginShell(ctx, os.Getenv); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("LoginShell error = %v", err) + } + } else if got := darwinShell(ctx, id, helper); got != "/bin/zsh" { + t.Fatalf("dscl timeout fallback = %q", got) + } + if elapsed := time.Since(start); elapsed > 3*time.Second { + t.Fatalf("probe exceeded deadline by %s", elapsed-500*time.Millisecond) + } + // The child inherited fd 4. EOF proves it released that fd. + if err := pipe.SetReadDeadline(time.Now().Add(time.Second)); err != nil { + t.Fatal(err) + } + got, err := io.ReadAll(pipe) + if err != nil || string(got) != "started\n" { + t.Fatalf("child pipe = %q, %v; expected startup then EOF", got, err) + } + }) + } +} diff --git a/server/internal/toolpath/toolpath.go b/server/internal/toolpath/toolpath.go new file mode 100644 index 00000000..2cf9b1d8 --- /dev/null +++ b/server/internal/toolpath/toolpath.go @@ -0,0 +1,191 @@ +// Package toolpath finds the CLIs harnesses run and the PATH their +// processes get. A service manager (launchd, systemd) or a GUI launch starts +// Stage with a minimal PATH, so the user's tools (pnpm, mise, nvm, Homebrew) +// are found through the login shell's PATH and the usual install dirs. +package toolpath + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "time" +) + +// Tools finds harness CLIs and the PATH their processes run with. +type Tools interface { + // LookPath resolves a command name, absolute path or ~/ path to an + // executable, searching PATH. + LookPath(file string) (string, error) + // PATH is the process PATH, then the login shell's, then Dirs. + PATH() string + // Refresh re-reads the login shell's PATH (rate limited), so a CLI + // installed after Stage started is found without a restart. + Refresh() +} + +// ProbeTimeout bounds one login-shell PATH read. +const ProbeTimeout = 3 * time.Second + +// MinRefresh is the shortest interval between two login-shell reads. +const MinRefresh = 5 * time.Second + +// Resolver is Tools for this process. The login shell is read on first +// use and cached. A failed refresh keeps the last successful shell PATH. +type Resolver struct { + // Getenv reads the environment (nil: os.Getenv). + Getenv func(string) string + // Home overrides HOME for installer directories and ~/ paths. + Home string + // Probe reads the login shell's PATH (nil: LoginShell). + Probe func(ctx context.Context) (string, error) + + mu sync.Mutex + shell string + at time.Time +} + +// Process is a Resolver that never runs a shell: the process PATH plus +// Dirs (tests and callers without a machine). +func Process() *Resolver { + return &Resolver{Probe: func(context.Context) (string, error) { return "", nil }} +} + +func (r *Resolver) getenv(k string) string { + if r.Getenv != nil { + return r.Getenv(k) + } + return os.Getenv(k) +} + +func (r *Resolver) home() string { + if r.Home != "" { + return r.Home + } + return r.getenv("HOME") +} + +// PATH implements Tools. +func (r *Resolver) PATH() string { + return Merge(r.getenv("PATH"), r.shellPath(), strings.Join(Dirs(r.home()), string(os.PathListSeparator))) +} + +// Refresh implements Tools. +func (r *Resolver) Refresh() { + r.mu.Lock() + defer r.mu.Unlock() + if time.Since(r.at) < MinRefresh { + return + } + r.probe() +} + +func (r *Resolver) shellPath() string { + r.mu.Lock() + defer r.mu.Unlock() + if r.at.IsZero() { + r.probe() + } + return r.shell +} + +// probe reads the shell PATH; r.mu is held. +func (r *Resolver) probe() { + probe := r.Probe + if probe == nil { + probe = func(ctx context.Context) (string, error) { return LoginShell(ctx, r.getenv) } + } + ctx, cancel := context.WithTimeout(context.Background(), ProbeTimeout) + defer cancel() + p, err := probe(ctx) + if err == nil && ctx.Err() == nil { + r.shell = p + } + r.at = time.Now() +} + +// LookPath implements Tools. +func (r *Resolver) LookPath(file string) (string, error) { + file = strings.TrimSpace(file) + if file == "" { + return "", &exec.Error{Name: file, Err: exec.ErrNotFound} + } + if strings.HasPrefix(file, "~/") { + home := r.home() + if !filepath.IsAbs(home) { + return "", &exec.Error{Name: file, Err: exec.ErrNotFound} + } + file = filepath.Join(home, file[2:]) + } + if strings.ContainsRune(file, filepath.Separator) { + if !executable(file) { + return "", &exec.Error{Name: file, Err: exec.ErrNotFound} + } + return filepath.Abs(file) + } + for _, d := range filepath.SplitList(r.PATH()) { + if p := filepath.Join(d, file); executable(p) { + return p, nil + } + } + return "", &exec.Error{Name: file, Err: exec.ErrNotFound} +} + +func executable(p string) bool { + // p always contains a separator, so LookPath checks effective execute + // access without searching the process PATH. + resolved, err := exec.LookPath(p) + if err != nil { + return false + } + st, err := os.Stat(resolved) + return err == nil && st.Mode().IsRegular() +} + +// Dirs are where installers put CLIs and runtimes when the PATH lacks +// them; searched after the process and login-shell PATH. +func Dirs(home string) []string { + var dirs []string + if home != "" { + for _, d := range []string{ + ".local/bin", ".npm-global/bin", ".bun/bin", ".volta/bin", + ".local/share/pnpm", ".local/share/pnpm/bin", "Library/pnpm", "Library/pnpm/bin", + ".local/share/mise/shims", + } { + dirs = append(dirs, filepath.Join(home, d)) + } + } + return append(dirs, "/usr/local/bin", "/opt/homebrew/bin", "/usr/bin", "/bin") +} + +// Merge joins PATH lists in order, dropping empty, relative and repeated +// entries. +func Merge(lists ...string) string { + var out []string + seen := make(map[string]bool) + for _, l := range lists { + for _, d := range filepath.SplitList(l) { + if !filepath.IsAbs(d) || seen[d] { + continue + } + out = append(out, d) + seen[d] = true + } + } + return strings.Join(out, string(os.PathListSeparator)) +} + +// Env is env with PATH replaced by binDir (when set: a script shim finds +// the runtime installed next to it) and then path. +func Env(env []string, path, binDir string) []string { + out := make([]string, 0, len(env)+1) + for _, kv := range env { + if k, _, _ := strings.Cut(kv, "="); k == "PATH" { + continue + } + out = append(out, kv) + } + return append(out, "PATH="+Merge(binDir, path)) +} diff --git a/server/internal/toolpath/toolpath_test.go b/server/internal/toolpath/toolpath_test.go new file mode 100644 index 00000000..5f42a44d --- /dev/null +++ b/server/internal/toolpath/toolpath_test.go @@ -0,0 +1,198 @@ +//go:build unix + +package toolpath + +import ( + "context" + "errors" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +func writeTool(t *testing.T, path, contents string) string { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(contents), 0700); err != nil { + t.Fatal(err) + } + return path +} + +func TestInstallerFallback(t *testing.T) { + for _, dir := range []string{".local/share/pnpm", ".local/share/pnpm/bin", "Library/pnpm", "Library/pnpm/bin", ".local/share/mise/shims"} { + t.Run(dir, func(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("PATH", t.TempDir()) + want := writeTool(t, filepath.Join(os.Getenv("HOME"), dir, "stage-test-tool"), "") + r := &Resolver{Probe: func(context.Context) (string, error) { + return "", errors.New("shell unavailable") + }} + path, err := r.LookPath("stage-test-tool") + if err != nil || path != want { + t.Fatalf("LookPath = %q, %v; want %q", path, err, want) + } + }) + } +} + +func TestLookPathPrecedence(t *testing.T) { + process, shell, home := t.TempDir(), t.TempDir(), t.TempDir() + t.Setenv("PATH", process) + t.Setenv("HOME", home) + calls := 0 + r := &Resolver{Probe: func(context.Context) (string, error) { + calls++ + return shell, nil + }} + dirs := []string{process, shell, filepath.Join(home, ".local/bin")} + for _, dir := range dirs { + writeTool(t, filepath.Join(dir, "stage-test-tool"), "") + } + for _, dir := range dirs { + want := filepath.Join(dir, "stage-test-tool") + got, err := r.LookPath("stage-test-tool") + if err != nil || got != want { + t.Fatalf("LookPath = %q, %v; want %q", got, err, want) + } + if err := os.Remove(want); err != nil { + t.Fatal(err) + } + } + if _, err := r.LookPath("stage-test-tool"); !errors.Is(err, exec.ErrNotFound) { + t.Fatalf("after removal, LookPath error = %v", err) + } + if calls != 1 { + t.Fatalf("lookup probed shell %d times", calls) + } +} + +func TestRefresh(t *testing.T) { + t.Setenv("PATH", "") + t.Setenv("HOME", t.TempDir()) + calls := 0 + r := &Resolver{Probe: func(ctx context.Context) (string, error) { + if _, ok := ctx.Deadline(); !ok { + t.Fatal("probe has no deadline") + } + calls++ + if calls == 2 { + return "/partial", errors.New("temporary failure") + } + if calls == 3 { + return "/new", nil + } + return "/old", nil + }} + for _, tc := range []struct { + expire bool + calls int + first string + }{ + {false, 1, "/old"}, {false, 1, "/old"}, + {true, 2, "/old"}, {false, 2, "/old"}, + {true, 3, "/new"}, + } { + if tc.expire { + r.at = time.Now().Add(-MinRefresh) + } + r.Refresh() + if first := filepath.SplitList(r.PATH())[0]; first != tc.first || calls != tc.calls { + t.Fatalf("first PATH entry = %q after %d probes, want %q after %d", first, calls, tc.first, tc.calls) + } + } +} + +func TestConcurrentFirstUseAndRefresh(t *testing.T) { + shell := t.TempDir() + var calls atomic.Int32 + release := make(chan struct{}) + r := &Resolver{Probe: func(context.Context) (string, error) { + calls.Add(1) + <-release + return shell, nil + }} + const readers = 20 + var ready, finished sync.WaitGroup + ready.Add(readers) + for i := range readers { + finished.Go(func() { + ready.Done() + if i%2 == 0 { + r.Refresh() + } + if !slices.Contains(filepath.SplitList(r.PATH()), shell) { + t.Error("concurrent reader missed login PATH") + } + }) + } + ready.Wait() + close(release) + finished.Wait() + if got := calls.Load(); got != 1 { + t.Fatalf("concurrent first use ran %d probes", got) + } +} + +func TestExplicitPath(t *testing.T) { + home := t.TempDir() + t.Chdir(home) + r := &Resolver{Home: home, Probe: func(context.Context) (string, error) { + t.Fatal("explicit path invoked shell") + return "", nil + }} + want := writeTool(t, filepath.Join(home, "my tools", "example"), "") + for _, name := range []string{want, "~/my tools/example", "./my tools/example"} { + if got, err := r.LookPath(name); got != want || err != nil { + t.Errorf("LookPath(%q) = %q, %v; want %q", name, got, err, want) + } + } + if err := os.Chmod(want, 0600); err != nil { + t.Fatal(err) + } + for _, name := range []string{"", home, want, "~/missing"} { + if _, err := r.LookPath(name); !errors.Is(err, exec.ErrNotFound) { + t.Errorf("LookPath(%q) error = %v", name, err) + } + } +} + +func TestEffectiveExecuteAccess(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root may execute owner-inaccessible files") + } + first, second := t.TempDir(), t.TempDir() + t.Setenv("PATH", first+":"+second) + path := writeTool(t, filepath.Join(first, "stage-test-tool"), "") + if err := os.Chmod(path, 0601); err != nil { + t.Fatal(err) + } + want := writeTool(t, filepath.Join(second, "stage-test-tool"), "") + if got, err := Process().LookPath("stage-test-tool"); got != want || err != nil { + t.Fatalf("LookPath = %q, %v; want %q", got, err, want) + } +} + +func TestEnv(t *testing.T) { + env := []string{"PATH=/old", "OTHER=a=b", "PATH_BACKUP=keep", "PATH=/other"} + before := slices.Clone(env) + path := strings.Join([]string{"/process", ".", "", "/shim", "/process", "/with spaces"}, ":") + for dir, wantPath := range map[string]string{ + "/shim": "/shim:/process:/with spaces", + "": "/process:/shim:/with spaces", + } { + got := Env(env, path, dir) + want := []string{"OTHER=a=b", "PATH_BACKUP=keep", "PATH=" + wantPath} + if !slices.Equal(got, want) || !slices.Equal(env, before) { + t.Errorf("Env(%q) = %q, input = %q; want %q", dir, got, env, want) + } + } +} diff --git a/server/internal/worker/integration_test.go b/server/internal/worker/integration_test.go index fe447f52..8a82c389 100644 --- a/server/internal/worker/integration_test.go +++ b/server/internal/worker/integration_test.go @@ -42,6 +42,7 @@ func isolate(t *testing.T) string { } t.Cleanup(func() { _ = os.RemoveAll(short) }) t.Setenv("HOME", t.TempDir()) + t.Setenv("SHELL", "/bin/sh") t.Setenv("XDG_DATA_HOME", "") t.Setenv("XDG_CONFIG_HOME", "") t.Setenv("STAGE_DATA_DIR", "") diff --git a/server/internal/workersetup/claude_test.go b/server/internal/workersetup/claude_test.go index 13659124..271177a4 100644 --- a/server/internal/workersetup/claude_test.go +++ b/server/internal/workersetup/claude_test.go @@ -4,6 +4,8 @@ import ( "encoding/json" "errors" "os" + "path/filepath" + "slices" "strings" "testing" "time" @@ -42,7 +44,11 @@ var localHarnesses = harness.Profile{Kind: harness.ProfileServer, LocalProcesses // reported by Claude. Disconnect is recorded on the main server too. func TestRemoteClaudeConnectsAndRunsATaskOverTheChannel(t *testing.T) { f := claudetest.New(t) - r := newRigWith(t, map[string]string{}, rigOptions{profile: localHarnesses, claude: claudeOptions(f)}) + runtimeDir := t.TempDir() + opts := claudeOptions(f) + opts.LookPath = nil + env := map[string]string{"SHELL": "/bin/false", "PATH": strings.Join([]string{filepath.Dir(f.Bin), runtimeDir}, string(os.PathListSeparator))} + r := newRigWith(t, env, rigOptions{profile: localHarnesses, claude: opts}) ctx := t.Context() m := r.machine() if a := m.Allows(claudecode.Descriptor); !a.Available { @@ -56,7 +62,7 @@ func TestRemoteClaudeConnectsAndRunsATaskOverTheChannel(t *testing.T) { t.Fatal("the connectors index left out Claude Code") } c := r.connector(claudecode.Kind) - if _, err := c.Configure(ctx, json.RawMessage(`{"binary":"`+f.Bin+`"}`)); err != nil { + if _, err := c.Configure(ctx, json.RawMessage(`{"binary":"claude"}`)); err != nil { t.Fatal(err) } if _, err := c.Run(ctx, claudecode.ActionConnect, nil); err != nil { @@ -70,7 +76,7 @@ func TestRemoteClaudeConnectsAndRunsATaskOverTheChannel(t *testing.T) { t.Fatalf("connected the local machine: %d", local) } saved := savedSettings[claudecodesetup.SetupSettings](r, r.id, claudecode.Kind) - if saved.Binary != f.Bin || saved.ConfigDir != f.ConfigDir() || saved.Disconnected { + if saved.Binary != "claude" || saved.ConfigDir != f.ConfigDir() || saved.Disconnected { t.Fatalf("main server record %+v", saved) } if creds, err := os.ReadFile(worker.NewCredentialStore(r.cfgPath).Path()); err == nil && strings.Contains(string(creds), claudecode.Kind) { @@ -98,8 +104,12 @@ func TestRemoteClaudeConnectsAndRunsATaskOverTheChannel(t *testing.T) { if err != nil || got.State != db.StateRunning || got.Session == nil { t.Fatalf("start %+v %v", got, err) } - if n := len(f.Launches()); n != 1 { - t.Fatalf("launches %d", n) + launches := f.Launches() + if len(launches) != 1 { + t.Fatalf("launches %d", len(launches)) + } + if path := launches[0].Env["PATH"]; !slices.Contains(filepath.SplitList(path), runtimeDir) { + t.Fatalf("worker launch PATH %q missing %q", path, runtimeDir) } o, err := r.store.Observation(ctx, *got.Session) if err != nil || !strings.HasPrefix(o.Links.Command, "claude attach ") { diff --git a/server/internal/workersetup/workersetup.go b/server/internal/workersetup/workersetup.go index 4ac2dbd6..42bdeee1 100644 --- a/server/internal/workersetup/workersetup.go +++ b/server/internal/workersetup/workersetup.go @@ -9,7 +9,6 @@ import ( "fmt" "log/slog" "os" - "os/exec" "slices" "strings" "sync" @@ -22,6 +21,7 @@ import ( "github.com/flexdinesh/stage/server/internal/harnesses" "github.com/flexdinesh/stage/server/internal/machine" "github.com/flexdinesh/stage/server/internal/remote" + "github.com/flexdinesh/stage/server/internal/toolpath" "github.com/flexdinesh/stage/server/internal/workerchan" ) @@ -43,6 +43,8 @@ type Options struct { type Setup struct { o Options log *slog.Logger + // All local harnesses on the worker share the cached login-shell PATH. + tools *toolpath.Resolver mu sync.Mutex composed map[string]*installed @@ -69,7 +71,10 @@ func Attach(o Options) *Setup { if o.Getenv == nil { o.Getenv = os.Getenv } - s := &Setup{o: o, log: o.Logger.With("component", "workersetup"), composed: map[string]*installed{}} + s := &Setup{ + o: o, log: o.Logger.With("component", "workersetup"), + tools: &toolpath.Resolver{Getenv: o.Getenv}, composed: map[string]*installed{}, + } var removed []string for _, key := range harnesses.Env().Removed { if o.Getenv(key) != "" { @@ -179,7 +184,7 @@ func (s *Setup) install(ctx context.Context, mod harness.Module, input remote.Se Settings: ports, Secrets: ports.Creds, Identity: ports, SetLastError: ports.SetLastError, Install: func(old, next int64, a execution.Adapter) { state.install(local, old, next, a) }, OnChanged: s.o.Host.Notify, Profile: local.Profile(), - DataDir: s.o.StateDir, Logger: s.log, Getenv: s.o.Getenv, LookupPath: exec.LookPath, Overrides: s.o.Overrides, CLI: s.o.CLI, + DataDir: s.o.StateDir, Logger: s.log, Getenv: s.o.Getenv, Tools: s.tools, Overrides: s.o.Overrides, CLI: s.o.CLI, } if offline { cached := cachedPorts{input}