Files
pipelines/internal/cli/harness.go
T
alan 914345cb31 Move harness profiles between host and Docker and stop silent draft retargeting
Native installs left Docker-era harness profiles in harnesses.json, so every
authoring launch failed trying to reach a Docker service, and a retained draft
bound to the old Docker server was silently projected onto the configured one.

- harness: add Profile.Mode and VerifyDockerLink as the single mode/verification
  helpers. `harness setup --host` configures or converts a host profile and
  clears docker_directory; reconfiguring a Docker-linked profile re-verifies the
  recorded directory still owns compose.yaml and fails naming it instead of
  saving a link that cannot launch. Setup's summary and `harness list` (via the
  new List/ListView shape) report the resulting mode and, for Docker, the
  directory, without changing the stored Config schema.
- setup-native.py: after build/install-skill it writes host (no docker_directory)
  profiles for the detected harnesses, defaulting to the detected OpenCode profile
  rather than a stale pi default, taking models from --model or the existing valid
  profile and never inventing one; it clears a stale Docker link and preserves
  unrelated keys/profiles. Detection-only: no harness install, upgrade or download.
- draft: add Draft.Resolve, the shared mismatch helper, which projects a draft
  onto the configured server and returns a dual-URL notice. CLI validate/submit
  and the TUI draft browser use it so a foreign draft is never silently
  retargeted; the TUI pre-wraps the notice to the panel width.
- Tests cover the Docker->host and host->host transitions, the missing-directory
  failure, installer write/migration (Python), and the CLI/TUI notice, using the
  real config file path in a temp dir.
- Update help text, README, docs and the packaged authoring skill reference to
  describe host as the default and the Docker-linked case.
2026-10-15 19:53:10 +01:00

333 lines
10 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" {
list, err := harness.List()
if err != nil {
return err
}
return a.output(list)
}
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 := harness.VerifyDockerLink(absolute); 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")
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
}
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
}