package cli import ( "context" "errors" "flag" "fmt" "os" "os/exec" "path/filepath" "strings" "text/tabwriter" "time" "git.a-wan.net/alan/pipelines/internal/claude" "git.a-wan.net/alan/pipelines/internal/codex" "git.a-wan.net/alan/pipelines/internal/harness" ) // harnessNames is every harness `pipelines harness setup` and `list` handle. var harnessNames = []string{"claude", "codex", "opencode", "pi"} const harnessSetupUsage = `Usage: pipelines harness setup [options] Set up one agent harness for this Pipelines installation (native or Docker, detected from the installation). Steps: 1. check the harness CLI is installed where the server finds it (prints the install command and stops when it is missing) 2. sign in with the harness's own login when not signed in 3. OpenCode/Pi: pick the interactive and new-pipeline default models (Claude Code and Codex models are chosen per chat in the app) 4. verify with the server's own check and report whether a restart is needed Options: --login sign in again even when already signed in --model P/M OpenCode/Pi interactive (authoring/debug) model --pipeline-model P/M OpenCode/Pi default model for new pipeline stages --default make this OpenCode/Pi harness the default for new/edit/debug --executable PATH OpenCode/Pi executable (default: found on the server's PATH) See also: pipelines harness list ` // harnessFallbackDirs are per-user install locations a login service PATH may // lack; the server looks there too (see claude.BinaryPath and OpenCode // discovery). A variable so tests never find a real harness on this machine. var harnessFallbackDirs = func() []string { dirs := []string{"/opt/homebrew/bin", "/usr/local/bin", "/usr/bin"} if home, err := os.UserHomeDir(); err == nil { dirs = append([]string{filepath.Join(home, ".local", "bin")}, dirs...) } return dirs } // harnessInstallCommand is the documented install command for each harness. func harnessInstallCommand(name string) string { switch name { case "opencode": return "curl -fsSL https://opencode.ai/install | bash" case "pi": return "npm install --global @earendil-works/pi-coding-agent" case "claude": return "curl -fsSL https://claude.ai/install.sh | bash" case "codex": return "npm install --global @openai/codex" } return "" } // setupEnvironment is where the harness has to work: the server's PATH on a // native installation, or the Docker checkout that owns the container. type setupEnvironment struct { docker string // Docker installation checkout, "" for native path string // PATH the server runs with native bool // a native installation manifest was found } func (a App) detectSetupEnvironment(host bool, c harness.Config) setupEnvironment { if a.Install != nil { path := a.Install.Path if path == "" { path = os.Getenv("PATH") } return setupEnvironment{path: path, native: true} } if !host && !inContainer() { for _, name := range []string{c.Default, "opencode", "pi"} { if p, ok := c.Profiles[name]; ok && dockerInstallation(p.DockerDirectory) { return setupEnvironment{docker: p.DockerDirectory} } } if wd, err := os.Getwd(); err == nil && dockerInstallation(wd) { return setupEnvironment{docker: wd} } } return setupEnvironment{path: os.Getenv("PATH")} } // dockerInstallation reports a configured `./install --docker` checkout, the // same test scripts/setup-harness.py applies. func dockerInstallation(dir string) bool { if dir == "" { return false } if _, err := os.Stat(filepath.Join(dir, "compose.yaml")); err != nil { return false } data, err := os.ReadFile(filepath.Join(dir, ".env")) return err == nil && strings.Contains(string(data), "PIPELINES_HOST_REPOSITORY=") } func inContainer() bool { _, err := os.Stat("/.dockerenv") return err == nil } func executableFile(path string) bool { info, err := os.Stat(path) return err == nil && info.Mode().IsRegular() && info.Mode().Perm()&0111 != 0 } func lookPathIn(name, pathList string) string { if strings.ContainsRune(name, os.PathSeparator) { if absolute, err := filepath.Abs(name); err == nil && executableFile(absolute) { return absolute } return "" } for _, dir := range filepath.SplitList(pathList) { if dir == "" { continue } if candidate := filepath.Join(dir, name); executableFile(candidate) { return candidate } } return "" } // findHarness resolves a harness executable the way the server would: its // override variable, the configured profile, the server's PATH, then the // per-user install locations. func findHarness(name string, env setupEnvironment, profile harness.Profile) string { var candidates []string switch name { case "claude": candidates = append(candidates, strings.TrimSpace(os.Getenv("PIPELINES_CLAUDE"))) case "opencode": candidates = append(candidates, strings.TrimSpace(os.Getenv("PIPELINES_OPENCODE"))) } if profile.DockerDirectory == "" { candidates = append(candidates, profile.Executable) } for _, candidate := range candidates { if candidate == "" { continue } if path := lookPathIn(candidate, env.path); path != "" { return path } } if path := lookPathIn(name, env.path); path != "" { return path } return lookPathIn(name, strings.Join(harnessFallbackDirs(), string(os.PathListSeparator))) } // missingHarness is the clear stop when a harness CLI cannot be found. func missingHarness(name string, env setupEnvironment) error { display := harness.DisplayName(name) if shell, err := exec.LookPath(name); err == nil && env.path != os.Getenv("PATH") { return fmt.Errorf("%s is on this shell's PATH (%s) but not on the PATH the Pipelines server runs with.\nRerun ./install from this shell so the server records it, then rerun: pipelines harness setup %s", display, shell, name) } return fmt.Errorf("%s is not installed where the Pipelines server can find it.\nInstall it: %s\nThen rerun: pipelines harness setup %s", display, harnessInstallCommand(name), name) } // serviceEnviron is this process's environment with the server's PATH. func serviceEnviron(path string) []string { var env []string for _, item := range os.Environ() { if !strings.HasPrefix(item, "PATH=") { env = append(env, item) } } return append(env, "PATH="+path) } func (a App) interactive(ctx context.Context, env []string, executable string, args ...string) error { cmd := exec.CommandContext(ctx, executable, args...) cmd.Env = env cmd.Stdin, cmd.Stdout, cmd.Stderr = a.In, a.Out, a.Err return cmd.Run() } func codexSignedIn(ctx context.Context, executable string, env []string) bool { ctx, cancel := context.WithTimeout(ctx, 20*time.Second) defer cancel() cmd := exec.CommandContext(ctx, executable, "login", "status") cmd.Env = env return cmd.Run() == nil } func (a App) harnessSetup(ctx context.Context, args []string) error { f := flag.NewFlagSet("harness setup", flag.ContinueOnError) f.SetOutput(a.Err) f.Usage = func() { fmt.Fprint(a.Out, harnessSetupUsage) } model := f.String("model", "", "") pipelineModel := f.String("pipeline-model", "", "") executable := f.String("executable", "", "") login := f.Bool("login", false, "") makeDefault := f.Bool("default", false, "") // --host is a hidden compatibility alias: it forces the native host mode a // native installation selects anyway. --versions is passed by the Docker // installer from its in-image probe. host := f.Bool("host", false, "") versions := f.String("versions", "", "") if err := parse(f, args); err != nil { if errors.Is(err, flag.ErrHelp) { return nil } return err } if len(f.Args()) > 1 { return fmt.Errorf("usage: pipelines harness setup [--login] [--model P/M] [--pipeline-model P/M] [--default]") } name := "" if len(f.Args()) == 1 { name = f.Args()[0] } else { var err error if name, err = harness.Select(ctx, "Harness to set up", harnessNames, a.In, a.Err); err != nil { return err } } known := false for _, n := range harnessNames { known = known || n == name } if !known { return fmt.Errorf("unknown harness %q; supported harnesses: claude, codex, opencode, pi", name) } chat := name == "claude" || name == "codex" if chat && (*model != "" || *pipelineModel != "" || *makeDefault || *executable != "") { return fmt.Errorf("--model, --pipeline-model, --default and --executable apply to opencode and pi; %s models are chosen per chat in the app", harness.DisplayName(name)) } c, err := harness.Load() if err != nil { return err } env := a.detectSetupEnvironment(*host, c) if env.docker != "" { if chat { return fmt.Errorf("%s chat needs a native installation; this is a Docker installation (%s), which runs OpenCode and Pi only", harness.DisplayName(name), env.docker) } forward := []string{name} if *login { forward = append(forward, "--login") } if *model != "" { forward = append(forward, "--model", *model) } if *pipelineModel != "" { forward = append(forward, "--pipeline-model", *pipelineModel) } if *makeDefault { forward = append(forward, "--default") } python, err := exec.LookPath("python3") if err != nil { return fmt.Errorf("Python 3 is required to set up a harness in the Docker installation: %w", err) } fmt.Fprintf(a.Out, "Docker installation (%s): setting up %s inside the container.\n", env.docker, harness.DisplayName(name)) cmd := exec.CommandContext(ctx, python, append([]string{filepath.Join(env.docker, "scripts", "setup-harness.py")}, forward...)...) cmd.Dir = env.docker cmd.Stdin, cmd.Stdout, cmd.Stderr = a.In, a.Out, a.Err return cmd.Run() } switch name { case "claude": return a.setupClaude(ctx, env, *login) case "codex": return a.setupCodex(ctx, env, *login) } return a.setupProfileHarness(ctx, name, env, c, profileSetup{ model: *model, pipelineModel: *pipelineModel, executable: *executable, login: *login, makeDefault: *makeDefault, host: *host, versions: *versions, }) } func (a App) setupClaude(ctx context.Context, env setupEnvironment, login bool) error { binary := findHarness("claude", env, harness.Profile{}) if binary == "" { return missingHarness("claude", env) } fmt.Fprintf(a.Out, "Claude Code: %s\n", binary) environ := serviceEnviron(env.path) signed, how := claude.SignedIn(ctx, binary, environ) if signed && !login { fmt.Fprintf(a.Out, "Signed in (%s); skipping login. Use --login to sign in again.\n", how) } else { fmt.Fprintln(a.Out, "Opening the Claude Code sign-in (claude auth login).") if err := a.interactive(ctx, environ, binary, "auth", "login"); err != nil { return fmt.Errorf("Claude Code login did not complete: %w", err) } signed, how = claude.SignedIn(ctx, binary, environ) } if !signed { return fmt.Errorf("Claude Code is still not signed in for the server. For a login that does not depend on the keychain, run `claude setup-token` and save the token as an owner-only file at %s (install -m 600 /dev/null %s), then rerun: pipelines harness setup claude", claude.ServiceTokenPath(), claude.ServiceTokenPath()) } fmt.Fprintln(a.Out, "Models: chosen per chat in the app's model picker; nothing to set here.") fmt.Fprintf(a.Out, "Verified: Claude Code is signed in (%s), using the server's own `claude auth status` check.\n", how) fmt.Fprintln(a.Out, "Server: the running server looks for Claude Code every 10 s; no restart needed.") return nil } func (a App) setupCodex(ctx context.Context, env setupEnvironment, login bool) error { socket := codex.DefaultSocketPath() binary := findHarness("codex", env, harness.Profile{}) if binary == "" { if codex.Available() { fmt.Fprintf(a.Out, "Codex CLI not found, but the Codex App Server is running (%s); its sign-in is managed by the Codex app.\n", socket) fmt.Fprintln(a.Out, "Server: the running server attaches to that socket within 10 s; no restart needed.") return nil } return missingHarness("codex", env) } fmt.Fprintf(a.Out, "Codex: %s\n", binary) environ := serviceEnviron(env.path) signed := codexSignedIn(ctx, binary, environ) if signed && !login { fmt.Fprintln(a.Out, "Signed in (codex login status); skipping login. Use --login to sign in again.") } else { fmt.Fprintln(a.Out, "Opening the Codex sign-in (codex login).") if err := a.interactive(ctx, environ, binary, "login"); err != nil { return fmt.Errorf("Codex login did not complete: %w", err) } signed = codexSignedIn(ctx, binary, environ) } if !signed { return fmt.Errorf("Codex is still not signed in (codex login status); run `codex login` and rerun: pipelines harness setup codex") } fmt.Fprintln(a.Out, "Models: chosen per chat in the app's model picker; nothing to set here.") if !codex.Available() { return fmt.Errorf("Codex is signed in, but its App Server control socket %s does not exist. Open the Codex app (it provides the socket); the running server checks every 10 s and attaches without a restart", socket) } fmt.Fprintf(a.Out, "Verified: Codex App Server socket %s is present (the server's own check).\n", socket) fmt.Fprintln(a.Out, "Server: the running server re-checks Codex every 10 s; no restart needed.") return nil } type profileSetup struct { model, pipelineModel, executable, versions string login, makeDefault, host bool } // profileLogin runs the harness's own sign-in. Pi has no standalone `auth // login`: open a fresh, no-context, extension-free, no-prompt, no-tools session // and let the user run /login there. `--tui-mode regular` keeps Pipelines' // header/handoff visible above Pi's interface. Never inject a coding/task // prompt or scripted keystrokes. func (a App) profileLogin(ctx context.Context, name, executable string, onboarding harness.Onboarding) error { loginArgs := []string{"auth", "login"} switch name { case "opencode": warm, cancel := context.WithTimeout(ctx, 30*time.Second) _, warmErr := exec.CommandContext(warm, executable, "api", "get", "/api/integration").Output() cancel() if warmErr != nil { return fmt.Errorf("OpenCode provider discovery failed before login: %w", warmErr) } case "pi": onboarding.AuthHandoff() loginArgs = []string{"--tui-mode", "regular", "--no-extensions", "--no-skills", "--no-context-files", "--no-prompt-templates", "--no-tools"} } cmd := exec.CommandContext(ctx, executable, loginArgs...) cmd.Stdin, cmd.Stdout, cmd.Stderr = a.In, a.Out, a.Err if err := cmd.Run(); err != nil { return fmt.Errorf("%s login did not complete: %w", name, err) } return nil } func (a App) setupProfileHarness(ctx context.Context, name string, env setupEnvironment, c harness.Config, o profileSetup) error { existing, exists := c.Profiles[name] executable := "" if o.executable != "" { if executable = lookPathIn(o.executable, env.path); executable == "" { if path, err := exec.LookPath(o.executable); err == nil { executable, _ = filepath.Abs(path) } } if executable == "" { return fmt.Errorf("%s executable %s was not found", harness.DisplayName(name), o.executable) } } else if executable = findHarness(name, env, existing); executable == "" { return missingHarness(name, env) } // A Docker-linked profile is only reconfigured on the host when its // recorded installation is still verifiable; a native installation or // --host replaces the link with the host profile instead. native := o.host || env.native if !native && exists && existing.DockerDirectory != "" { if err := harness.VerifyDockerLink(existing.DockerDirectory); err != nil { return err } } onboarding := harness.NewOnboarding(a.Out) action := "Configure" if exists { action = "Reconfigure" } onboarding.Header(name, action) onboarding.Versions(o.versions) fmt.Fprintf(a.Out, "%s: %s\n", harness.DisplayName(name), executable) readCtx, cancel := context.WithTimeout(ctx, 60*time.Second) defer cancel() models, err := harnessModels(readCtx, name, executable) if err != nil { return err } loggedIn := false if o.login || len(models) == 0 { if !o.login { fmt.Fprintf(a.Out, "No signed-in %s provider lists any models; opening the %s sign-in.\n", harness.DisplayName(name), harness.DisplayName(name)) } if err := a.profileLogin(ctx, name, executable, onboarding); err != nil { return err } loggedIn = true if models, err = harnessModels(readCtx, name, executable); err != nil { return err } if len(models) == 0 { return fmt.Errorf("%s still lists no models from a signed-in provider; sign in with `pipelines harness setup %s --login`", harness.DisplayName(name), name) } } else { fmt.Fprintf(a.Out, "Signed in (%d models available); skipping login. Use --login to sign in again.\n", len(models)) } model, pipelineModel := o.model, o.pipelineModel if model == "" { model, err = harness.Pick(ctx, harness.Selection{ Step: "Step 1 of 2", Title: "Choose the interactive " + harness.DisplayName(name) + " model", Purpose: "Used when you open " + harness.DisplayName(name) + " for authoring and debugging sessions. It is stored separately from the new-pipeline-stage model.", Options: models, Current: existing.Model, }, a.In, a.Err) if err != nil { return err } } if pipelineModel == "" { pipelineModel, err = harness.Pick(ctx, harness.Selection{ Step: "Step 2 of 2", Title: "Choose the default model for new " + harness.DisplayName(name) + " pipelines", Purpose: "Used by model stages in new pipelines and starters. It never rewrites published workflows or existing drafts.", Options: models, Current: existing.PipelineModel, }, a.In, a.Err) if err != nil { return err } } available := func(value string) bool { for _, m := range models { if m == value { return true } } return false } if !harness.ValidModel(model) || !harness.ValidModel(pipelineModel) || !available(model) || !available(pipelineModel) { return fmt.Errorf("choose exact model IDs from %s's available catalog; defaults unchanged", name) } profile := existing profile.Executable, profile.Model, profile.PipelineModel = executable, model, pipelineModel if native { profile.DockerDirectory = "" } c.Profiles[name] = profile if o.makeDefault || c.Default == "" { c.Default = name } if err = harness.Save(c); err != nil { return err } onboarding.Summary(name, model, pipelineModel, c.Default, c.Profiles[name].Mode()) check := "pipelines provider-check --model " + pipelineModel if name == "pi" { check = "pipelines provider-check --harness pi --model " + pipelineModel } fmt.Fprintf(a.Out, "Verified: %s lists both models from a signed-in provider (live check, may cost: %s).\n", harness.DisplayName(name), check) fmt.Fprintln(a.Out, "Server: new runs and sessions read these profiles when they start; no restart needed.") if loggedIn && name == "opencode" && env.native { fmt.Fprintln(a.Out, "If the app's OpenCode chat does not offer the newly signed-in provider, run `pipelines restart` when no runs are active.") } return nil } // harnessStatus is one row of `pipelines harness list`. type harnessStatus struct { Name string `json:"name"` Installed bool `json:"installed"` Executable string `json:"executable,omitempty"` SignedIn bool `json:"signed_in"` Configured bool `json:"configured"` Default bool `json:"default"` Detail string `json:"detail"` Docker bool `json:"docker,omitempty"` } func harnessStatuses(ctx context.Context, env setupEnvironment, c harness.Config) []harnessStatus { var rows []harnessStatus for _, name := range harnessNames { profile, configured := c.Profiles[name] row := harnessStatus{Name: name, Default: c.Default == name} if configured && profile.DockerDirectory != "" { row.Installed, row.SignedIn, row.Configured, row.Docker = true, true, true, true row.Detail = "model " + profile.Model + " · new pipelines " + profile.PipelineModel + " · " + profile.Mode() rows = append(rows, row) continue } row.Executable = findHarness(name, env, profile) row.Installed = row.Executable != "" check, cancel := context.WithTimeout(ctx, 20*time.Second) environ := serviceEnviron(env.path) switch name { case "claude": if row.Installed { row.SignedIn, _ = claude.SignedIn(check, row.Executable, environ) } row.Configured = row.SignedIn row.Detail = "chat; models chosen per chat" case "codex": if row.Installed { row.SignedIn = codexSignedIn(check, row.Executable, environ) } row.Configured = codex.Available() if row.Configured { row.SignedIn = true row.Detail = "chat; Codex App Server attached" } else { row.Detail = "chat; open the Codex app (no App Server socket)" } default: if row.Installed { models, err := harnessModels(check, name, row.Executable) row.SignedIn = err == nil && len(models) > 0 } row.Configured = configured if configured { row.Detail = "model " + profile.Model + " · new pipelines " + profile.PipelineModel } else { row.Detail = "stages; no models chosen" } } cancel() if env.docker != "" && (name == "claude" || name == "codex") { row.Configured = false row.Detail = "not used by a Docker installation" } rows = append(rows, row) } return rows } func (a App) harnessList(ctx context.Context, args []string) error { f := flag.NewFlagSet("harness list", flag.ContinueOnError) f.SetOutput(a.Err) asJSON := f.Bool("json", false, "Print profiles and status as JSON") if err := parse(f, args); err != nil { if errors.Is(err, flag.ErrHelp) { return nil } return err } view, err := harness.List() if err != nil { return err } c, err := harness.Load() if err != nil { return err } rows := harnessStatuses(ctx, a.detectSetupEnvironment(false, c), c) if *asJSON { return a.output(struct { harness.ListView Harnesses []harnessStatus `json:"harnesses"` }{view, rows}) } yes := func(v bool) string { if v { return "yes" } return "no" } w := tabwriter.NewWriter(a.Out, 0, 4, 2, ' ', 0) fmt.Fprintln(w, "HARNESS\tINSTALLED\tSIGNED IN\tCONFIGURED\tDEFAULT\tDETAIL") for _, row := range rows { installed, signed := yes(row.Installed), yes(row.SignedIn) if row.Docker { installed, signed = "in Docker", "in Docker" } else if !row.Installed { signed = "-" } def := "-" if row.Default { def = "yes" } fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n", row.Name, installed, signed, yes(row.Configured), def, row.Detail) } if err := w.Flush(); err != nil { return err } fmt.Fprintln(a.Out, "\nSet one up: pipelines harness setup ") return nil }