Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/harnesses.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
6 changes: 6 additions & 0 deletions docs/runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
11 changes: 8 additions & 3 deletions docs/service.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
93 changes: 43 additions & 50 deletions server/internal/claudecode/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -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 (
Expand Down
2 changes: 1 addition & 1 deletion server/internal/claudecodesetup/connector.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
8 changes: 2 additions & 6 deletions server/internal/claudecodesetup/facts.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
3 changes: 0 additions & 3 deletions server/internal/claudecodesetup/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
Expand Down
41 changes: 30 additions & 11 deletions server/internal/claudecodesetup/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -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").
Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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()
Expand All @@ -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).
Expand Down Expand Up @@ -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{}
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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 != "":
Expand Down
Loading