Merge: one way to set up harnesses (pipelines harness setup)

This commit is contained in:
2026-11-02 16:14:50 +00:00
23 changed files with 1033 additions and 222 deletions
@@ -28,7 +28,11 @@ propagation; container profiles have no `DockerDirectory` and cannot recurse, an
explicit native profiles keep the host path. The picker uses a true `x/term` TTY
check, so `/dev/null` and pipes fail fast instead of hanging.
`pipelines harness setup opencode|pi --login --default` runs a styled onboarding
`pipelines harness setup <claude|codex|opencode|pi>` is the single setup path on
native and Docker installations: it checks the CLI is reachable from the server
(printing the install command when missing), signs in only when needed (`--login`
forces it) and verifies with the server's own check. Claude Code and Codex have
no models to pick. For OpenCode/Pi it runs a styled onboarding
wizard (bold title, verified Docker harness versions) and selects separate
harness and new-pipeline models using type-to-filter fuzzy pickers, not numbered
prompts. Each picker itself shows its numbered step with the title and purpose
@@ -39,14 +43,14 @@ and Esc cancels. The saved value is preselected and marked `(current)`; the wind
follows the active row on narrow terminals and the heading, selected row and
no-match state stay within the real terminal height.
Automation: `--model PROVIDER/MODEL --pipeline-model PROVIDER/MODEL`.
`harness default [opencode|pi]` switches defaults; `harness list` prints settings.
`harness default [opencode|pi]` switches defaults; `harness list` shows installed /
signed-in / configured / default status for all four (`--json` adds profiles).
Setup reads catalogs/login state without inference. Changing defaults never
rewrites published definitions or retained drafts. Canceling or failing either
picker leaves saved preferences byte-identical. Non-terminal automation with a
missing model fails clearly instead of starting a picker.
`./install --opencode` / `./install --pi` reopen login and selection. With an
existing Docker setup, they configure inside its container and link the host
On an existing Docker setup, `pipelines harness setup opencode|pi` configures inside its container and link the host
launcher without restarting/deploying services. They resolve and verify the current
OpenCode V2 release from the single documented complete
`GET .../git/matching-refs/tags/v2` response (a bounded complete array with no
@@ -63,8 +67,7 @@ stay authoritative and a dirty source still rebuilds. If discovery, digest
resolution or completeness cannot be established they stop with an error (keeping
the last verified Dockerfile fallback pins); they never guess, fall back to a host
runtime or install a stale pin.
Without a Docker installation, `./install --opencode`/`--pi` stop and require an
existing Docker setup; the native installation reuses the host OpenCode
(`./install --opencode`/`--pi` were removed and only point to that command.) The native installation reuses the host OpenCode
configuration, writes **host** (non-Docker) profiles for the harnesses it detects
into XDG config home's `pipelines/harnesses.json`, and clears a stale Docker link
so a Docker-era profile is not left Docker-linked. It never installs, upgrades or
@@ -51,7 +51,7 @@ parallel/distributed task engine or a guarantee that model reports are correct.
source identity labels already match; a dirty source always invokes the Docker
build and relies on layer caching. A model/login-only reconfiguration compares only
the verified release image identity, so a changed source alone does not rebuild.
`./install --opencode|--pi` reconfigures inside the existing container and
`pipelines harness setup opencode|pi` reconfigures inside the existing container and
refuses an image that does not match; it does not rebuild or restart services (an
explicit ordinary `./install` does when the user asks).
+24
View File
@@ -67,6 +67,30 @@ func (a *authEnv) resolve(ctx context.Context, binary string, base []string) []s
return append(append([]string{}, base...), a.extra...)
}
// SignedIn reports whether Claude Code started with env is signed in, trying
// the same sources the server uses for the processes it starts: the default
// login, then the login file in ConfigDir, then the private service token. The
// second result names the source that worked.
func SignedIn(ctx context.Context, binary string, env []string) (bool, string) {
if cliLoggedIn(ctx, binary, env) {
return true, "Claude Code login"
}
if dir := ConfigDir(); dir != "" && !hasEnv(env, secureStorageEnvKey) && !hasEnv(env, "CLAUDE_CONFIG_DIR") {
if cliLoggedIn(ctx, binary, append(append([]string{}, env...), secureStorageEnvKey+"="+dir)) {
return true, "login file in " + dir
}
}
if HasServiceToken() && !hasEnv(env, "CLAUDE_CODE_OAUTH_TOKEN") {
if cliLoggedIn(ctx, binary, withServiceToken(append([]string{}, env...))) {
return true, "service token " + serviceTokenPath()
}
}
return false, ""
}
// ServiceTokenPath is the token file the server reads.
func ServiceTokenPath() string { return serviceTokenPath() }
func hasEnv(env []string, key string) bool {
for _, item := range env {
if strings.HasPrefix(item, key+"=") {
+4
View File
@@ -20,6 +20,7 @@ import (
"git.a-wan.net/alan/pipelines/internal/client"
"git.a-wan.net/alan/pipelines/internal/draft"
"git.a-wan.net/alan/pipelines/internal/harness"
"git.a-wan.net/alan/pipelines/internal/installation"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/runinspect"
@@ -32,6 +33,9 @@ import (
type App struct {
Out, Err io.Writer
In io.Reader
// Install is the native installation manifest this CLI belongs to, or nil
// (Docker installation, or a development/Go-installed CLI).
Install *installation.Config
}
type options struct {
outputFormat string
+1 -1
View File
@@ -64,7 +64,7 @@ var notes = map[string]string{
}
var serviceHelp = map[string]string{
"harness": "pipelines harness launches the configured default. harness setup opencode|pi offers fuzzy model selection; --host configures a native host harness and clears any Docker link, --login reopens login, --default chooses the default harness, --model and --pipeline-model set separate defaults explicitly. harness list prints non-secret settings, including each profile's launch mode. Only configured harnesses are offered.",
"harness": "pipelines harness launches the configured default (opencode or pi). harness setup <claude|codex|opencode|pi> is the one way to set up a harness on a native or Docker installation: it checks the CLI is installed where the server finds it (printing the install command when missing), signs in with the harness's own login when needed (--login forces it), picks OpenCode/Pi models with fuzzy selection (--model, --pipeline-model, --default), and verifies with the server's own check. harness list shows installed, signed-in, configured and default status for all four (--json adds the profiles).",
"skill": "pipelines skill install installs/updates the bundled workflow skill in OpenCode and detected Claude Code skill roots without changing login/config or user-modified skills. ./install includes this step.",
"service": "Configure per-user OS autostart: pipelines service enable. Runs use the directory you invoke pipelines run from. Use --print to preview, service status to inspect, and service disable before uninstalling. Linux uses systemd; macOS uses launchd. No sudo.",
"serve": "Run the native server in the foreground. Its flags are documented by pipelines serve --help. Installation never starts it automatically.",
+2 -158
View File
@@ -17,11 +17,7 @@ import (
func (a App) harness(ctx context.Context, args []string) error {
if len(args) > 0 && args[0] == "list" {
list, err := harness.List()
if err != nil {
return err
}
return a.output(list)
return a.harnessList(ctx, args[1:])
}
if len(args) > 0 && args[0] == "default" {
c, err := harness.Load()
@@ -81,159 +77,7 @@ func (a App) harness(ctx context.Context, args []string) error {
return harness.Save(c)
}
if len(args) > 0 && args[0] == "setup" {
f := flag.NewFlagSet("harness setup", flag.ContinueOnError)
f.SetOutput(a.Err)
model := f.String("model", "", "Interactive harness default provider/model")
pipelineModel := f.String("pipeline-model", "", "New pipeline stage default provider/model")
executable := f.String("executable", "", "Harness executable (defaults to its name)")
login := f.Bool("login", false, "Open the harness login without deleting credentials")
makeDefault := f.Bool("default", false, "Use this harness by default")
host := f.Bool("host", false, "Configure a native host harness and clear any Docker link")
versions := f.String("versions", "", "Verified Docker harness versions to display (from the in-image probe)")
if err := parse(f, args[1:]); err != nil {
return err
}
if len(f.Args()) > 1 {
return fmt.Errorf("usage: pipelines harness setup [opencode|pi] [--login] [--host] [--model P/M] [--pipeline-model P/M] [--default]")
}
name := ""
if len(f.Args()) == 1 {
name = f.Args()[0]
} else {
var available []string
for _, name := range []string{"opencode", "pi"} {
if _, err := exec.LookPath(name); err == nil {
available = append(available, name)
}
}
var err error
name, err = harness.Select(ctx, "Harness to configure", available, a.In, a.Err)
if err != nil {
return err
}
}
if name != "opencode" && name != "pi" {
return fmt.Errorf("supported harnesses: opencode, pi")
}
if *executable == "" {
*executable = name
}
if strings.ContainsRune(*executable, os.PathSeparator) {
absolute, pathErr := filepath.Abs(*executable)
if pathErr != nil {
return pathErr
}
*executable = absolute
}
if _, err := exec.LookPath(*executable); err != nil {
return fmt.Errorf("install %s before configuring it: %w", name, err)
}
c, err := harness.Load()
if err != nil {
return err
}
existing, exists := c.Profiles[name]
// A profile can move between Docker and host. Without an explicit
// --host selection a Docker-linked profile is only reconfigured when its
// recorded installation is still verifiable; otherwise setup fails
// naming the directory instead of saving a link that cannot launch.
if !*host && 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(*versions)
if *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()
}
// 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` is a documented Pi 1.1.0 flag
// that keeps Pipelines' header/handoff visible above Pi's interface
// instead of the default fullscreen clear. Never inject a coding/task
// prompt or scripted keystrokes.
loginArgs := []string{"auth", "login"}
if name == "pi" {
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 = a.In
cmd.Stdout = a.Out
cmd.Stderr = a.Err
if err := cmd.Run(); err != nil {
return fmt.Errorf("%s login did not complete: %w", name, err)
}
}
readCtx, cancel := context.WithTimeout(ctx, 60*time.Second)
defer cancel()
models, err := harnessModels(readCtx, name, *executable)
if err != nil {
return err
}
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: c.Profiles[name].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: c.Profiles[name].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 := c.Profiles[name]
profile.Executable, profile.Model, profile.PipelineModel = *executable, *model, *pipelineModel
if *host {
profile.DockerDirectory = ""
}
c.Profiles[name] = profile
if *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())
return nil
return a.harnessSetup(ctx, args[1:])
}
name := ""
if len(args) > 0 && (args[0] == "opencode" || args[0] == "pi") {
+618
View File
@@ -0,0 +1,618 @@
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 <claude|codex|opencode|pi> [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 <claude|codex|opencode|pi> [--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 <claude|codex|opencode|pi>")
return nil
}
+209
View File
@@ -0,0 +1,209 @@
package cli
import (
"bytes"
"context"
"encoding/json"
"net"
"os"
"path/filepath"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/installation"
)
// isolateHarnesses gives a test an empty PATH directory of fake harnesses and
// a private HOME, so no real harness, login, config or socket is reachable.
func isolateHarnesses(t *testing.T) (root, bin string) {
t.Helper()
root = t.TempDir()
bin = filepath.Join(root, "bin")
if err := os.Mkdir(bin, 0700); err != nil {
t.Fatal(err)
}
t.Setenv("HOME", root)
t.Setenv("PATH", bin)
t.Setenv("FIXTURE", root)
t.Setenv("PIPELINES_HARNESS_CONFIG", filepath.Join(root, "harnesses.json"))
t.Setenv("PIPELINES_CLAUDE", "")
t.Setenv("PIPELINES_OPENCODE", "")
t.Setenv("PIPELINES_CLAUDE_TOKEN_FILE", filepath.Join(root, "no-token"))
t.Setenv("CLAUDE_CONFIG_DIR", filepath.Join(root, ".claude"))
t.Setenv("CODEX_HOME", filepath.Join(root, "codex"))
previous := harnessFallbackDirs
harnessFallbackDirs = func() []string { return nil }
t.Cleanup(func() { harnessFallbackDirs = previous })
return root, bin
}
func fakeHarness(t *testing.T, bin, name, body string) string {
t.Helper()
path := filepath.Join(bin, name)
if err := os.WriteFile(path, []byte("#!/bin/sh\n"+body), 0700); err != nil {
t.Fatal(err)
}
return path
}
func runHarness(t *testing.T, app App, args ...string) (string, error) {
t.Helper()
var out bytes.Buffer
app.In, app.Out, app.Err = bytes.NewBuffer(nil), &out, &out
err := app.Run(context.Background(), append([]string{"harness"}, args...))
return out.String(), err
}
func TestHarnessSetupMissingCLIPrintsInstallCommand(t *testing.T) {
isolateHarnesses(t)
for _, name := range harnessNames {
_, err := runHarness(t, App{}, "setup", name)
if err == nil || !strings.Contains(err.Error(), harnessInstallCommand(name)) || !strings.Contains(err.Error(), "pipelines harness setup "+name) {
t.Fatalf("%s: missing CLI error = %v", name, err)
}
}
}
func TestHarnessSetupUsesTheServerPath(t *testing.T) {
root, bin := isolateHarnesses(t)
fakeHarness(t, bin, "claude", "echo '{\"loggedIn\":true}'\n")
servicePath := filepath.Join(root, "service-bin")
_, err := runHarness(t, App{Install: &installation.Config{Path: servicePath}}, "setup", "claude")
if err == nil || !strings.Contains(err.Error(), "not on the PATH the Pipelines server runs with") {
t.Fatalf("shell-only claude error = %v", err)
}
if _, err := runHarness(t, App{Install: &installation.Config{Path: bin}}, "setup", "claude"); err != nil {
t.Fatalf("claude on the server PATH: %v", err)
}
}
func TestHarnessSetupClaudeSignedInSkipsLogin(t *testing.T) {
root, bin := isolateHarnesses(t)
fakeHarness(t, bin, "claude", "case \"$*\" in\n'auth status') echo '{\"loggedIn\":true}' ;;\n*) echo \"$*\" >> \"$FIXTURE/claude-calls\"; exit 1 ;;\nesac\n")
out, err := runHarness(t, App{}, "setup", "claude")
if err != nil {
t.Fatal(err, out)
}
for _, want := range []string{"skipping login", "Verified: Claude Code is signed in", "every 10 s; no restart needed"} {
if !strings.Contains(out, want) {
t.Fatalf("missing %q:\n%s", want, out)
}
}
if _, err := os.Stat(filepath.Join(root, "claude-calls")); !os.IsNotExist(err) {
t.Fatal("a signed-in Claude Code was asked to log in")
}
if _, err := runHarness(t, App{}, "setup", "claude", "--model", "a/b"); err == nil {
t.Fatal("--model accepted for Claude Code")
}
}
func TestHarnessSetupClaudeRunsLoginWhenSignedOut(t *testing.T) {
root, bin := isolateHarnesses(t)
fakeHarness(t, bin, "claude", "case \"$*\" in\n'auth status') if [ -f \"$FIXTURE/logged\" ]; then echo '{\"loggedIn\":true}'; else echo '{\"loggedIn\":false}'; exit 1; fi ;;\n'auth login') : > \"$FIXTURE/logged\" ;;\n*) exit 91 ;;\nesac\n")
out, err := runHarness(t, App{}, "setup", "claude")
if err != nil {
t.Fatal(err, out)
}
if _, err := os.Stat(filepath.Join(root, "logged")); err != nil || !strings.Contains(out, "claude auth login") || !strings.Contains(out, "Verified") {
t.Fatalf("login not invoked:\n%s", out)
}
}
func TestHarnessSetupCodexLoginAndSocket(t *testing.T) {
root, bin := isolateHarnesses(t)
fakeHarness(t, bin, "codex", "case \"$*\" in\n'login status') [ -f \"$FIXTURE/logged\" ] ;;\nlogin) : > \"$FIXTURE/logged\" ;;\n*) exit 91 ;;\nesac\n")
out, err := runHarness(t, App{}, "setup", "codex")
if _, statErr := os.Stat(filepath.Join(root, "logged")); statErr != nil || !strings.Contains(out, "codex login") {
t.Fatalf("codex login not invoked:\n%s", out)
}
if err == nil || !strings.Contains(err.Error(), "app-server-control.sock") || !strings.Contains(err.Error(), "Open the Codex app") {
t.Fatalf("missing socket error = %v", err)
}
// Unix socket paths are length-limited; keep CODEX_HOME short.
home, err := os.MkdirTemp("/tmp", "cx")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(home) })
t.Setenv("CODEX_HOME", home)
if err := os.Mkdir(filepath.Join(home, "app-server-control"), 0700); err != nil {
t.Fatal(err)
}
listener, err := net.Listen("unix", filepath.Join(home, "app-server-control", "app-server-control.sock"))
if err != nil {
t.Fatal(err)
}
defer listener.Close()
out, err = runHarness(t, App{}, "setup", "codex")
if err != nil || !strings.Contains(out, "skipping login") || !strings.Contains(out, "socket") || !strings.Contains(out, "no restart needed") {
t.Fatalf("codex with socket: %v\n%s", err, out)
}
}
func TestHarnessSetupOpenCodeLogsInWhenNoProviderIsConnected(t *testing.T) {
root, bin := isolateHarnesses(t)
fakeHarness(t, bin, "opencode", "case \"$*\" in\n'api get /api/integration') echo '{}' ;;\nmodels) printf '%s\\n' fixture/harness fixture/stages ;;\n'auth list --format json') if [ -f \"$FIXTURE/logged\" ]; then echo '[{\"id\":\"fixture\",\"connections\":[{}]}]'; else echo '[]'; fi ;;\n'auth login') : > \"$FIXTURE/logged\" ;;\n*) exit 91 ;;\nesac\n")
out, err := runHarness(t, App{}, "setup", "opencode", "--model", "fixture/harness", "--pipeline-model", "fixture/stages")
if err != nil {
t.Fatal(err, out)
}
if _, err := os.Stat(filepath.Join(root, "logged")); err != nil {
t.Fatalf("OpenCode login not invoked:\n%s", out)
}
for _, want := range []string{"opening the OpenCode sign-in", "Configuration complete", "Verified: OpenCode lists both models", "no restart needed"} {
if !strings.Contains(out, want) {
t.Fatalf("missing %q:\n%s", want, out)
}
}
// Signed in now: a second setup skips the login.
out, err = runHarness(t, App{}, "setup", "opencode", "--model", "fixture/harness", "--pipeline-model", "fixture/stages")
if err != nil || !strings.Contains(out, "skipping login") {
t.Fatalf("signed-in OpenCode: %v\n%s", err, out)
}
}
func TestHarnessListShowsAllFour(t *testing.T) {
root, bin := isolateHarnesses(t)
fakeHarness(t, bin, "claude", "echo '{\"loggedIn\":true}'\n")
opencode := fakeHarness(t, bin, "opencode", "case \"$*\" in\n'api get /api/integration') echo '{}' ;;\nmodels) printf '%s\\n' fixture/harness fixture/stages ;;\n'auth list --format json') echo '[{\"id\":\"fixture\",\"connections\":[{}]}]' ;;\n*) exit 91 ;;\nesac\n")
writeHarnessConfig(t, filepath.Join(root, "harnesses.json"), `{"default":"opencode","profiles":{"opencode":{"executable":"`+opencode+`","model":"fixture/harness","pipeline_model":"fixture/stages"}}}`)
out, err := runHarness(t, App{}, "list")
if err != nil {
t.Fatal(err)
}
lines := map[string]string{}
for _, line := range strings.Split(out, "\n") {
if fields := strings.Fields(line); len(fields) > 0 {
lines[fields[0]] = strings.Join(fields, " ")
}
}
for name, want := range map[string]string{
"claude": "claude yes yes yes -",
"codex": "codex no - no -",
"opencode": "opencode yes yes yes yes model fixture/harness",
"pi": "pi no - no -",
} {
if !strings.HasPrefix(lines[name], want) {
t.Fatalf("%s row = %q, want prefix %q\n%s", name, lines[name], want, out)
}
}
out, err = runHarness(t, App{}, "list", "--json")
if err != nil {
t.Fatal(err)
}
var view struct {
Default string `json:"default"`
Harnesses []harnessStatus `json:"harnesses"`
}
if err := json.Unmarshal([]byte(out), &view); err != nil || view.Default != "opencode" || len(view.Harnesses) != 4 {
t.Fatalf("list --json = %v\n%s", err, out)
}
}
func TestHarnessSetupHelpHidesCompatibilityFlags(t *testing.T) {
isolateHarnesses(t)
out, err := runHarness(t, App{}, "setup", "--help")
if err != nil || !strings.Contains(out, "pipelines harness setup <claude|codex|opencode|pi>") || strings.Contains(out, "--host") || strings.Contains(out, "--versions") {
t.Fatalf("help: %v\n%s", err, out)
}
}
+3 -1
View File
@@ -47,7 +47,9 @@ MAINTAIN
SERVER / INTERFACE
harness [opencode|pi] Launch the configured default harness in this directory
harness setup opencode|pi Login/select separate harness and new-pipeline defaults
harness setup <claude|codex|opencode|pi>
Install check, sign-in, models and verify for one harness
harness list Installed / signed-in / configured / default for all four
tui Open the dashboard (default with no command)
serve Start native server in the foreground (Ctrl+C stops it)
service enable Configure user autostart
+2 -2
View File
@@ -54,10 +54,10 @@ func (p Profile) Mode() string {
// is reconfigured or reported as usable, so a stale link is never silently kept.
func VerifyDockerLink(directory string) error {
if directory == "" {
return fmt.Errorf("no Docker installation directory is recorded; run pipelines harness setup <opencode|pi> --host for a native harness")
return fmt.Errorf("no Docker installation directory is recorded; run pipelines harness setup <opencode|pi> on the native installation")
}
if _, err := os.Stat(filepath.Join(directory, "compose.yaml")); err != nil {
return fmt.Errorf("recorded Docker installation %s is no longer usable: %w; relink with pipelines harness link <opencode|pi> --docker-directory <checkout>, or switch to a host harness with pipelines harness setup <opencode|pi> --host", directory, err)
return fmt.Errorf("recorded Docker installation %s is no longer usable: %w; relink with pipelines harness link <opencode|pi> --docker-directory <checkout>, or rerun pipelines harness setup <opencode|pi> from the native installation", directory, err)
}
return nil
}
+4
View File
@@ -80,6 +80,10 @@ func DisplayName(name string) string {
return "OpenCode"
case "pi":
return "Pi"
case "claude":
return "Claude Code"
case "codex":
return "Codex"
default:
return name
}