Files
pipelines/internal/cli/harness.go
T
alan 05ae530442 Make Pipelines Docker-only with OpenCode and Pi
Install current verified harness releases inside Docker, preserve persistent accounts and settings, and provide separate interactive and pipeline model defaults with terminal onboarding and fuzzy pickers.

Add Docker-aware authoring transport, Pi stage execution, bounded workflow controls, reliable final-result readback and usage settlement, and finite short-lived CLI pipe draining. Keep dated installation evidence and packaged authoring guidance consistent.

Verified with a real Docker installation, both harness stages and interactive authors, the built-in plan/implement/review starter, independent host race/vet checks, installer tests, and packaged skill tests. Generated release receipts stay ignored in clean checkouts.
2026-10-11 23:00:25 +01:00

319 lines
9.7 KiB
Go

package cli
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/author"
"git.a-wan.net/alan/pipelines/internal/harness"
)
func (a App) harness(ctx context.Context, args []string) error {
if len(args) > 0 && args[0] == "list" {
c, err := harness.Load()
if err != nil {
return err
}
return a.output(c)
}
if len(args) > 0 && args[0] == "default" {
c, err := harness.Load()
if err != nil {
return err
}
names, _, err := harness.Choices()
if err != nil {
return err
}
name := ""
if len(args) == 2 {
name = args[1]
} else if len(args) == 1 {
name, err = harness.Select(ctx, "Default harness", names, a.In, a.Err)
if err != nil {
return err
}
} else {
return fmt.Errorf("usage: harness default [opencode|pi]")
}
if _, ok := c.Profiles[name]; !ok {
return fmt.Errorf("harness %q is not configured", name)
}
c.Default = name
return harness.Save(c)
}
if len(args) > 0 && args[0] == "link" {
f := flag.NewFlagSet("harness link", flag.ContinueOnError)
f.SetOutput(a.Err)
directory := f.String("docker-directory", "", "Existing Docker installation checkout")
model := f.String("model", "", "Configured interactive model")
pipelineModel := f.String("pipeline-model", "", "Configured new-pipeline model")
makeDefault := f.Bool("default", false, "Set default harness")
if err := parse(f, args[1:]); err != nil {
return err
}
if len(f.Args()) != 1 || (f.Args()[0] != "pi" && f.Args()[0] != "opencode") || !harness.ValidModel(*model) || !harness.ValidModel(*pipelineModel) {
return fmt.Errorf("harness link requires opencode|pi and exact --model/--pipeline-model")
}
absolute, err := filepath.Abs(*directory)
if err != nil || *directory == "" {
return fmt.Errorf("Docker installation directory is required")
}
if _, err := os.Stat(filepath.Join(absolute, "compose.yaml")); err != nil {
return err
}
c, err := harness.Load()
if err != nil {
return err
}
name := f.Args()[0]
c.Profiles[name] = harness.Profile{Executable: name, Model: *model, PipelineModel: *pipelineModel, DockerDirectory: absolute}
if *makeDefault || c.Default == "" {
c.Default = name
}
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")
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] [--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
}
onboarding := harness.NewOnboarding(a.Out)
action := "Configure"
if _, ok := c.Profiles[name]; ok {
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
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)
return nil
}
name := ""
if len(args) > 0 && (args[0] == "opencode" || args[0] == "pi") {
name = args[0]
args = args[1:]
}
cwd, err := os.Getwd()
if err != nil {
return err
}
skill, err := author.SkillDirectory()
if err != nil {
return err
}
cmd, err := harness.Command(ctx, name, cwd, strings.Join(args, " "), skill)
if err != nil {
return err
}
cmd.Stdin = a.In
cmd.Stdout = a.Out
cmd.Stderr = a.Err
return cmd.Run()
}
func harnessModels(ctx context.Context, name, executable string) ([]string, error) {
if name == "opencode" {
if _, err := exec.CommandContext(ctx, executable, "api", "get", "/api/integration").Output(); err != nil {
return nil, fmt.Errorf("OpenCode provider discovery failed: %w", err)
}
}
args := []string{"models"}
if name == "pi" {
args = []string{"--no-extensions", "--list-models"}
}
data, err := exec.CommandContext(ctx, executable, args...).Output()
if err != nil {
return nil, fmt.Errorf("%s model discovery failed: %w", name, err)
}
if name == "opencode" {
for attempt := 0; len(strings.TrimSpace(string(data))) == 0 && attempt < 2; attempt++ {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(500 * time.Millisecond):
}
data, err = exec.CommandContext(ctx, executable, args...).Output()
if err != nil {
return nil, err
}
}
}
var models []string
seen := map[string]bool{}
for _, line := range strings.Split(string(data), "\n") {
fields := strings.Fields(line)
if len(fields) == 0 {
continue
}
value := fields[0]
if name == "pi" && len(fields) > 1 {
value = fields[0] + "/" + fields[1]
}
if harness.ValidModel(value) && !seen[value] && value != "provider/model" {
seen[value] = true
models = append(models, value)
}
}
if name == "opencode" {
data, err := exec.CommandContext(ctx, executable, "auth", "list", "--format", "json").Output()
if err != nil {
return nil, fmt.Errorf("OpenCode connected-provider discovery failed: %w", err)
}
var accounts []struct {
ID string `json:"id"`
Connections []json.RawMessage `json:"connections"`
}
if err = json.Unmarshal(data, &accounts); err != nil {
return nil, err
}
connected := map[string]bool{}
for _, a := range accounts {
if len(a.Connections) > 0 {
connected[a.ID] = true
}
}
filtered := models[:0]
for _, m := range models {
p, _, _ := strings.Cut(m, "/")
if connected[p] {
filtered = append(filtered, m)
}
}
models = filtered
}
return models, nil
}