Files
pipelines/internal/cli/app.go
T
alan fae1005962 Allow launching runs with whole-run and per-stage model overrides
Add `pipelines run --model PROVIDER/MODEL` and repeatable
`--stage-model STAGE=PROVIDER/MODEL`, resolved with precedence
per-stage > whole-run > the model pinned in the pipeline version.

- A shared pure resolver (`pipeline.ParseModelOverride` /
  `pipeline.EffectiveModels`) owns the precedence and validation: every value
  must be a `provider/model` pair (`stage.ValidModel`), every stage key must
  exist in the pinned graph, an unknown key fails naming the valid keys, and a
  per-stage key that names a non-model stage is refused.
- The server validates against the pinned version before admission (no run row
  is ever inserted for an invalid request), persists `model`/`stage_models` on
  the run and `provider`/`model` on each step, applies the effective pair to a
  clone of the stage definition so the stage and its repair/formatter path share
  it, overlays the returned run graph with the effective pair (presentation
  only), and reuses the recorded overrides on retry.
- The run record echoes the overrides it was launched with and each step records
  the provider/model it actually ran with; the TUI Evidence pane renders that
  effective pair. The pinned pipeline version and `show --version N` are never
  modified.
- CLI help, `docs/cli.md` and the packaged authoring skill references document
  the flags and the precedence. A TUI override picker remains a documented
  follow-up; the CLI is the deliverable.

Tests: pure precedence/validation table tests, store round-trip and
request-key-mismatch plus migration, server admission/application/overlay/retry
with a controlled executor, CLI flag/help/malformed-value tests, and a TUI
evidence test.
2026-10-16 23:33:53 +01:00

1305 lines
43 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package cli
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/author"
"git.a-wan.net/alan/pipelines/internal/buildinfo"
"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/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/runinspect"
"git.a-wan.net/alan/pipelines/internal/stage"
"git.a-wan.net/alan/pipelines/internal/statusview"
"git.a-wan.net/alan/pipelines/internal/tui"
tea "github.com/charmbracelet/bubbletea"
)
type App struct {
Out, Err io.Writer
In io.Reader
}
type options struct {
harness string
url, name, prompt, title, template, workspace, paths, key, opencode, model string
option, feedback string
output string
conflict string
kind string
all bool
json, source, noOpen, yes, allow, createOnly, force, wait bool
version, expected, limit int
timeout, waitTimeout time.Duration
stageModels stageModelFlags
}
// stageModelFlags collects the repeatable --stage-model STAGE=PROVIDER/MODEL
// values. A repeated key is last-wins. It is a flag.Value so the repeatable flag
// needs no dependency (Go stdlib has no slice flag).
type stageModelFlags map[string]string
// String renders the collected overrides for flag's defaults display.
func (s stageModelFlags) String() string {
keys := make([]string, 0, len(s))
for key := range s {
keys = append(keys, key)
}
sort.Strings(keys)
parts := make([]string, 0, len(keys))
for _, key := range keys {
parts = append(parts, key+"="+s[key])
}
return strings.Join(parts, ",")
}
// Set parses one STAGE=PROVIDER/MODEL value and validates the provider/model with
// the shared parser, so a malformed value fails before any run is created.
func (s stageModelFlags) Set(value string) error {
key, model, ok := strings.Cut(value, "=")
key, model = strings.TrimSpace(key), strings.TrimSpace(model)
if !ok || key == "" || model == "" {
return fmt.Errorf("--stage-model requires STAGE=PROVIDER/MODEL")
}
if _, err := pipeline.ParseModelOverride(model); err != nil {
return fmt.Errorf("--stage-model %s: %w", key, err)
}
s[key] = model
return nil
}
func (a App) flags(command string) (*flag.FlagSet, *options) {
o := &options{}
f := flag.NewFlagSet(command, flag.ContinueOnError)
f.SetOutput(a.Err)
f.StringVar(&o.url, "url", envOr("PIPELINES_URL", "ws://127.0.0.1:8080/connect"), "Pipeline server WebSocket URL")
f.BoolVar(&o.json, "json", false, "Machine-readable JSON; no interactive picker/editor")
f.DurationVar(&o.timeout, "timeout", 30*time.Second, "Timeout per server request")
switch command {
case "provider-check":
f.StringVar(&o.harness, "harness", "opencode", "Provider-check harness: opencode or configured pi")
f.StringVar(&o.model, "model", envOr("PIPELINES_DEFAULT_MODEL", ""), "Provider/model to validate with one tool-free generation")
f.BoolVar(&o.yes, "yes", false, "Approve the small validation generation without prompting")
case "new", "edit":
f.StringVar(&o.harness, "harness", "", "Authoring harness: configured opencode/pi, or nvim")
f.BoolVar(&o.yes, "yes", false, "Approve draft creation/editor launch without prompting")
f.StringVar(&o.name, "name", "", "Pipeline name (or edit ID)")
f.StringVar(&o.prompt, "prompt", "", "Request to give the configured harness; omitted asks what to change")
f.BoolVar(&o.noOpen, "no-open", false, "Create the draft without opening the configured harness")
f.StringVar(&o.opencode, "opencode", envOr("PIPELINES_OPENCODE", "opencode"), "Host OpenCode executable")
if command == "new" {
f.StringVar(&o.template, "template", "", "Optional template key; omitted starts a one-stage draft")
}
if command == "edit" {
f.IntVar(&o.version, "version", 0, "Source version (0 = latest)")
}
case "show", "export", "versions":
f.IntVar(&o.version, "version", 0, "Immutable version (0 = latest)")
if command == "export" {
f.StringVar(&o.output, "output", "", "Save selected definitions as a ZIP bundle")
f.BoolVar(&o.all, "all", false, "Export all pipelines without selection")
}
case "import":
f.StringVar(&o.conflict, "on-conflict", "ask", "Different existing definitions: ask, keep, both, or import")
f.BoolVar(&o.all, "all", false, "Select every pipeline in the bundle")
f.BoolVar(&o.yes, "yes", false, "Confirm publication (schedules may activate)")
case "template":
f.BoolVar(&o.source, "source", false, "Print original Markdown instead of metadata")
case "submit":
f.BoolVar(&o.yes, "yes", false, "Confirm publication without an interactive prompt")
f.StringVar(&o.name, "name", "", "Name for an external Markdown file (managed drafts already know their name)")
f.BoolVar(&o.createOnly, "create-only", false, "Reject existing names rather than creating another version")
f.IntVar(&o.expected, "expected-version", 0, "Reject if the latest version changed")
f.BoolVar(&o.force, "force", false, "Explicitly bypass a draft's base-version conflict guard (validation still applies)")
case "run":
f.StringVar(&o.name, "pipeline", "", "Exact registered pipeline name or ID")
f.StringVar(&o.prompt, "prompt", "", "Task prompt; omitted opens a multiline composer")
f.StringVar(&o.title, "title", "", "Explicit run title; default is derived from the prompt")
f.StringVar(&o.workspace, "workspace", "", "Run directory (default: current directory)")
f.BoolVar(&o.yes, "yes", false, "Confirm execution without an interactive prompt")
f.BoolVar(&o.allow, "allow-tools", false, "Compatibility flag; stage-declared tools are enabled automatically")
f.StringVar(&o.paths, "write-paths", "", "Optional narrower edit scope; default is all files in the run directory")
f.StringVar(&o.key, "request-key", "", "Idempotency key (default: generated unique key)")
f.IntVar(&o.version, "version", 0, "Version to run (default: latest)")
f.StringVar(&o.model, "model", "", "Override the model for every stage of this run (PROVIDER/MODEL)")
o.stageModels = stageModelFlags{}
f.Var(o.stageModels, "stage-model", "Override one stage's model; repeatable (STAGE=PROVIDER/MODEL); beats --model")
f.BoolVar(&o.wait, "wait", false, "In JSON mode, wait for a terminal run state")
f.DurationVar(&o.waitTimeout, "wait-timeout", 0, "Client limit for --wait after the run is admitted (0 waits until terminal); separate from per-request --timeout")
case "runs":
f.StringVar(&o.name, "pipeline", "", "Filter by exact pipeline name or ID")
case "search":
f.StringVar(&o.kind, "type", "", "Narrow to one kind: "+strings.Join(protocol.SearchKinds, ", "))
f.IntVar(&o.limit, "limit", 0, "Maximum results (default 50, max 200)")
case "retry":
f.BoolVar(&o.yes, "yes", false, "Confirm retry without an interactive prompt")
f.StringVar(&o.key, "request-key", "", "Idempotency key (default: generated unique key)")
f.BoolVar(&o.wait, "wait", false, "Wait for the new run to finish")
f.DurationVar(&o.waitTimeout, "wait-timeout", 0, "Client limit for --wait (0 waits until the run ends); independent of --timeout")
case "cancel", "draft-delete":
f.BoolVar(&o.yes, "yes", false, "Confirm this action without an interactive prompt")
case "decide":
f.StringVar(&o.option, "option", "", "Option key to choose among the waiting stage's edges (required)")
f.StringVar(&o.feedback, "feedback", "", "Optional free-text feedback recorded with the decision")
case "debug":
f.StringVar(&o.harness, "harness", "", "Debugging harness: configured opencode/pi, or nvim")
f.BoolVar(&o.yes, "yes", false, "Approve opening a debugging session without prompting")
f.StringVar(&o.opencode, "opencode", envOr("PIPELINES_OPENCODE", "opencode"), "Host OpenCode executable")
f.BoolVar(&o.noOpen, "no-open", false, "Print the investigation prompt without launching the configured harness")
}
f.Usage = func() {
fmt.Fprintf(a.Out, "Usage: pipelines %s\n", usage[command])
if note := notes[command]; note != "" {
fmt.Fprintln(a.Out, "\n"+note)
}
fmt.Fprintln(a.Out, "\nOptions:")
f.VisitAll(func(entry *flag.Flag) {
label := "--" + entry.Name
if b, ok := entry.Value.(interface{ IsBoolFlag() bool }); !ok || !b.IsBoolFlag() {
label += " <value>"
}
defaultLabel := ""
if entry.DefValue != "" && entry.DefValue != "false" && entry.DefValue != "0" {
defaultLabel = " (default: " + entry.DefValue + ")"
}
fmt.Fprintf(a.Out, " %-28s %s%s\n", label, entry.Usage, defaultLabel)
})
fmt.Fprintln(a.Out, " --help Show this help")
}
return f, o
}
func envOr(key, value string) string {
if v := os.Getenv(key); v != "" {
return v
}
return value
}
// recordedFeedback returns the feedback the server actually stored for the
// decided step that carries the chosen option, so a repeated (idempotent)
// decision reports the recorded evidence rather than the ignored request text.
func recordedFeedback(detail *protocol.RunDetail, option string) string {
for i := len(detail.Steps) - 1; i >= 0; i-- {
if chosen, feedback := protocol.DecisionEvidence(detail.Steps[i].Output); chosen == option {
return strings.TrimSpace(feedback)
}
}
return ""
}
// parse allows flags before or after positional arguments without reinterpreting values.
func parse(f *flag.FlagSet, args []string) error {
var flags, positionals []string
for i := 0; i < len(args); i++ {
arg := args[i]
if arg == "--" {
positionals = append(positionals, args[i+1:]...)
break
}
if !strings.HasPrefix(arg, "-") || arg == "-" {
positionals = append(positionals, arg)
continue
}
flags = append(flags, arg)
name := strings.SplitN(strings.TrimLeft(arg, "-"), "=", 2)
if len(name) == 2 || name[0] == "help" || name[0] == "h" {
continue
}
entry := f.Lookup(name[0])
if entry == nil {
return fmt.Errorf("unknown option %s; use pipelines help %s", arg, f.Name())
}
if b, ok := entry.Value.(interface{ IsBoolFlag() bool }); ok && b.IsBoolFlag() {
continue
}
if i+1 >= len(args) {
return fmt.Errorf("%s needs a value", arg)
}
i++
flags = append(flags, args[i])
}
return f.Parse(append(flags, positionals...))
}
func (a App) Run(ctx context.Context, args []string) error {
if len(args) > 0 && args[0] == "choose-model" {
return a.chooseModel(ctx, args[1:])
}
if len(args) > 0 && args[0] == "harness" {
return a.harness(ctx, args[1:])
}
if len(args) > 0 && args[0] == "--version" {
args = append([]string{"version"}, args[1:]...)
}
// Global selectors may appear before the command as well as after it.
leading := 0
for leading < len(args) {
parts := strings.SplitN(strings.TrimLeft(args[leading], "-"), "=", 2)
if !strings.HasPrefix(args[leading], "-") || (parts[0] != "url" && parts[0] != "timeout" && parts[0] != "json") {
break
}
leading++
if len(parts) == 1 && parts[0] != "json" {
if leading >= len(args) {
return fmt.Errorf("--%s requires a value", parts[0])
}
leading++
}
}
if leading > 0 {
if leading == len(args) {
return fmt.Errorf("a command is required; use pipelines help")
}
// Harness preferences are local, even when an agent's standard CLI
// prefix includes a server URL. No server mutation occurs here.
if args[leading] == "harness" {
return a.harness(ctx, args[leading+1:])
}
args = append(append([]string{}, args[leading:]...), args[:leading]...)
}
if len(args) == 0 || args[0] == "help" || args[0] == "--help" || args[0] == "-h" {
if len(args) > 1 && args[0] == "help" {
if note, ok := serviceHelp[args[1]]; ok {
fmt.Fprintf(a.Out, "Usage: pipelines %s [options]\n\n%s\n\nService commands require the installed launcher.\n", args[1], note)
return nil
}
if _, ok := usage[args[1]]; !ok {
return fmt.Errorf("unknown application command %q; service help: pipelines <service-command> --help", args[1])
}
f, _ := a.flags(args[1])
f.Usage()
return nil
}
fmt.Fprint(a.Out, help)
return nil
}
command := args[0]
if _, ok := usage[command]; !ok {
return fmt.Errorf("unknown command %q; use pipelines help", command)
}
f, o := a.flags(command)
if err := parse(f, args[1:]); err != nil {
if errors.Is(err, flag.ErrHelp) {
return nil
}
return err
}
if o.timeout <= 0 || o.waitTimeout < 0 || o.version < 0 || o.expected < 0 {
return fmt.Errorf("timeout must be positive, wait-timeout nonnegative, and versions nonnegative")
}
pos := f.Args()
if command == "version" {
if len(pos) != 0 {
return fmt.Errorf("version takes no arguments")
}
build := buildinfo.Current()
if o.json {
return a.output(build)
}
fmt.Fprintf(a.Out, "pipelines %s (commit %s)\n", build.Version, build.Commit)
return nil
}
if command == "provider-check" {
if len(pos) != 0 {
return fmt.Errorf("provider-check takes no positional arguments")
}
override, err := pipeline.ParseModelOverride(o.model)
if err != nil {
return fmt.Errorf("--model requires provider/model")
}
provider, model := override.Provider, override.Model
if err := a.confirmAction("Validate "+o.model+" with one small tool-free generation (provider charges may apply)?", o.yes); err != nil {
return err
}
config, err := harness.Load()
if err != nil {
return err
}
// A Docker-linked profile validates through its existing Compose service
// with the original cwd/model/timeout and -T for machine mode. Container
// profiles have no DockerDirectory, so the inner check cannot recurse.
if profile, ok := config.Profiles[o.harness]; ok && profile.DockerDirectory != "" {
return a.providerCheckDocker(ctx, o, profile)
}
check, cancel := context.WithTimeout(ctx, o.timeout)
defer cancel()
operations := &stage.OperationLog{}
session := ""
var generator stage.ModelGenerator
switch o.harness {
case "opencode":
generator = &stage.OpenCodeClient{Operations: operations, OnGenerationSession: func(id, backend, reference string, active bool) error { session = id; return nil }}
case "pi":
profile, ok := config.Profiles["pi"]
if !ok {
return fmt.Errorf("Pi is not configured on this computer")
}
cwd, err := os.Getwd()
if err != nil {
return err
}
generator = &stage.PiClient{Executable: profile.Executable, Directory: cwd, Tools: []string{}, OnOwnership: func(id, reference string, active bool) error { session = id; return nil }}
default:
return fmt.Errorf("provider-check harness must be opencode or pi")
}
text, err := generator.Generate(check, stage.ModelConfig{Harness: o.harness, Provider: provider, Model: model}, "Provider connection validation only. Do not use tools. Reply with exactly PIPELINES_PROVIDER_OK.")
if err == nil && strings.TrimSpace(text) != "PIPELINES_PROVIDER_OK" {
err = fmt.Errorf("model returned a response but did not complete the validation instruction")
}
result := map[string]any{"healthy": err == nil, "model": o.model, "session_id": session, "failures": operations.Failures}
if err != nil {
result["diagnostic"] = err.Error()
}
if o.json {
if outputErr := a.output(result); outputErr != nil {
return outputErr
}
} else if err == nil {
fmt.Fprintln(a.Out, "Validated", o.model, "· retained session", session)
}
return err
}
if command == "draft-delete" {
if len(pos) != 1 {
return fmt.Errorf("draft-delete requires one retained draft path")
}
if err := a.confirmAction("Delete retained draft "+pos[0]+"?", o.yes); err != nil {
return err
}
if err := draft.Delete(pos[0]); err != nil {
return err
}
if o.json {
return a.output(map[string]any{"deleted": pos[0]})
}
_, err := fmt.Fprintln(a.Out, "Deleted draft:", pos[0])
return err
}
if command != "drafts" && os.Getenv("PIPELINES_URL") == "" {
explicit := false
f.Visit(func(value *flag.Flag) {
if value.Name == "url" {
explicit = true
}
})
if !explicit {
configured, err := client.ConfiguredURL()
if err != nil {
return err
}
if configured != "" {
o.url = configured
}
}
}
if command == "tui" {
if len(pos) > 0 {
return fmt.Errorf("tui takes no arguments")
}
_, err := tea.NewProgram(tui.New(ctx, o.url), tea.WithContext(ctx), tea.WithAltScreen()).Run()
return err
}
if command == "drafts" {
if len(pos) > 0 {
return fmt.Errorf("drafts takes no arguments")
}
items, err := draft.List()
if err != nil {
return err
}
if o.json {
return a.output(items)
}
for _, d := range items {
fmt.Fprintf(a.Out, "%s\t%s\tbase v%d\n", d.Name, d.Path, d.BaseVersion)
}
return nil
}
// Connect only for server operations. Keep each RPC bounded, not the interactive session.
dialCtx, cancel := context.WithTimeout(ctx, o.timeout)
c, err := client.Open(dialCtx, o.url)
cancel()
if err != nil {
if command == "status" && len(pos) == 0 {
s := statusview.Offline(o.url)
if o.json {
if outputErr := a.output(s); outputErr != nil {
return outputErr
}
} else {
fmt.Fprintln(a.Out, strings.Join(statusview.Lines(s), "\n"))
}
return fmt.Errorf("Pipelines server unavailable")
}
return err
}
defer c.Close()
// Report at most one build/protocol warning per invocation on stderr, so
// stdout stays parseable JSON; an unsafe newer server fails the command.
c.Report(func(relationship buildinfo.Relationship) {
if relationship.Message != "" {
a.notice("warning: " + relationship.Message)
}
})
call := func(request protocol.Message) (protocol.Message, error) {
requestCtx, cancel := context.WithTimeout(ctx, o.timeout)
defer cancel()
return c.Call(requestCtx, request)
}
resolve := func(value string) (protocol.PipelineSummary, error) {
r, err := call(protocol.Message{Type: protocol.List})
if err != nil {
return protocol.PipelineSummary{}, err
}
// Names win over IDs so numeric pipeline names remain addressable.
for _, p := range r.Pipelines {
if p.Name == value {
return p, nil
}
}
id, _ := strconv.ParseInt(value, 10, 64)
for _, p := range r.Pipelines {
if p.ID == id && id > 0 {
return p, nil
}
}
return protocol.PipelineSummary{}, fmt.Errorf("pipeline %q not found", value)
}
one := func() (string, error) {
if len(pos) != 1 {
return "", fmt.Errorf("%s requires one argument; use pipelines help %s", command, command)
}
return pos[0], nil
}
switch command {
case "stats":
if len(pos) != 0 {
return fmt.Errorf("stats takes no arguments")
}
response, err := call(protocol.Message{Type: protocol.ListRuns})
if err != nil {
return err
}
if response.Usage == nil {
return fmt.Errorf("server did not return usage statistics; update pipelines-server")
}
if o.json {
return a.output(response.Usage)
}
u := response.Usage
average := "—"
if u.Total > u.Active {
average = time.Duration(u.AverageSeconds * float64(time.Second)).Round(time.Second).String()
}
fmt.Fprintf(a.Out, "Usage · all history\n%d runs · %d succeeded · %d failed · %d canceled · %d interrupted · %d active\nAverage completed duration: %s\n\nPipeline\tRuns\tSucceeded\tFailed\tActive\n", u.Total, u.Succeeded, u.Failed, u.Canceled, u.Interrupted, u.Active, average)
for _, p := range u.Pipelines {
fmt.Fprintf(a.Out, "%s\t%d\t%d\t%d\t%d\n", p.Name, p.Total, p.Succeeded, p.Failed, p.Active)
}
fmt.Fprintln(a.Out, "\nDaily activity (UTC)")
for _, d := range u.Days {
fmt.Fprintf(a.Out, "%s\t%d\n", d.Date, d.Runs)
}
return nil
case "status":
if len(pos) != 0 {
return fmt.Errorf("status takes no arguments")
}
response, err := call(protocol.Message{Type: protocol.GetStatus})
if err != nil {
return err
}
if response.Status == nil {
return fmt.Errorf("server did not return status; update pipelines-server")
}
if o.json {
return a.output(response.Status)
}
_, err = fmt.Fprintln(a.Out, strings.Join(statusview.Lines(response.Status), "\n"))
return err
case "debug":
value, err := one()
if err != nil {
return err
}
id, err := strconv.ParseInt(value, 10, 64)
if err != nil || id <= 0 {
return fmt.Errorf("run ID must be positive")
}
response, err := call(protocol.Message{Type: protocol.GetRun, RunID: id})
if err != nil {
return err
}
if response.RunDetail == nil {
return fmt.Errorf("server did not return run detail")
}
executable, err := os.Executable()
if err != nil {
return err
}
// nvim is a client-side editor: keep the native host prefix. A configured
// harness (including a Docker-linked one) gets the shared Docker-aware prefix.
var prefix string
if o.harness == "nvim" {
prefix, err = harness.CLIPrefix(harness.Profile{}, o.url, executable)
} else {
prefix, err = harness.CLIPrefixFor(o.harness, o.url, executable)
}
if err != nil {
return err
}
debug := runinspect.New(response.RunDetail, prefix)
definition, definitionErr := call(protocol.Message{Type: protocol.GetPipeline, PipelineID: response.RunDetail.PipelineID, Version: response.RunDetail.Version})
if definitionErr != nil {
debug.Prompt += "\nPinned pipeline definition unavailable: " + definitionErr.Error() + "\n"
} else if definition.Detail != nil {
data, _ := json.Marshal(definition.Detail)
debug.Prompt += "\nExact immutable pipeline definition and routing graph:\n" + string(data) + "\n"
}
live, evidenceErr := call(protocol.Message{Type: protocol.GetRunEvidence, RunID: id})
if evidenceErr != nil {
debug.Prompt += "\nServer-side live session evidence unavailable: " + evidenceErr.Error() + "\n"
} else {
data, _ := json.Marshal(live.Evidence)
debug.Prompt += "\nRead-only, bounded and credential-redacted OpenCode session evidence for the latest session-bearing steps, retrieved on the execution computer:\n" + string(data) + "\n"
}
if o.json {
return a.output(debug)
}
if o.noOpen {
_, err := fmt.Fprintln(a.Out, debug.Prompt)
return err
}
if err := a.confirmAction(fmt.Sprintf("Open a fresh debugging session for run #%d?", id), o.yes); err != nil {
return err
}
debug, err = debug.Prepare()
if err != nil {
return fmt.Errorf("retain debugging context: %w", err)
}
if debug.ContextFile != "" {
fmt.Fprintln(a.Out, "Retained debugging context:", debug.ContextFile)
}
var cmd *exec.Cmd
if o.harness == "nvim" {
debug, err = debug.PrepareFile()
if err != nil {
return err
}
cmd = exec.CommandContext(ctx, "nvim", "-R", debug.ContextFile)
} else {
cmd, err = harness.Command(ctx, o.harness, debug.Workspace, debug.Prompt, "")
if err != nil {
return err
}
}
cmd.Stdin = a.In
cmd.Stdout = a.Out
cmd.Stderr = a.Err
return cmd.Run()
case "new", "edit":
return a.author(ctx, command, pos, o, call, resolve)
case "validate", "submit":
path, err := one()
if err != nil {
return err
}
source, err := draft.Read(path)
if err != nil {
return err
}
request := protocol.Message{Type: protocol.Validate, Source: source}
if command == "submit" {
d, metaErr := draft.Load(path)
if metaErr != nil && !os.IsNotExist(metaErr) {
return metaErr
}
origin := d
crossServer := d.Server != "" && d.Server != o.url
d, notice := d.Resolve(o.url)
if notice != "" {
if o.json {
fmt.Fprintln(a.Err, notice)
} else {
fmt.Fprintln(a.Out, notice)
}
}
name := o.name
if name == "" {
name = d.Name
}
if name == "" {
return fmt.Errorf("external draft requires --name")
}
expected := d.BaseVersion
if o.expected > 0 {
expected = o.expected
}
if o.force {
expected = 0
}
createOnly := d.CreateOnly || o.createOnly
// An explicit destination version (or force) permits intentional
// updates from an edit draft; never inherit the origin version.
if crossServer && (o.expected > 0 || o.force) {
createOnly = origin.CreateOnly || o.createOnly
}
request = protocol.Message{Type: protocol.Submit, Name: name, Source: source, CreateOnly: createOnly, ExpectedVersion: expected}
if err := a.confirmAction("Publish "+name+" to "+o.url+" as an immutable version? Included schedules activate on acceptance.", o.yes); err != nil {
return err
}
} else if d, metaErr := draft.Load(path); metaErr == nil {
if _, notice := d.Resolve(o.url); notice != "" {
if o.json {
fmt.Fprintln(a.Err, notice)
} else {
fmt.Fprintln(a.Out, notice)
}
}
}
r, err := call(request)
if err != nil {
return err
}
if o.json {
return a.output(r)
}
if command == "validate" {
fmt.Fprintln(a.Out, "Valid draft (server validation). No changes submitted.")
} else {
fmt.Fprintf(a.Out, "Submitted %s v%d\n", r.Name, r.Version)
if r.Detail != nil && r.Detail.Graph.Settings != nil {
fmt.Fprintln(a.Err, "Schedules are now active for this version.")
}
}
return nil
case "list", "templates", "runs", "ping", "connection":
if len(pos) > 0 {
return fmt.Errorf("%s takes no positional arguments", command)
}
typeName := map[string]string{"list": protocol.List, "templates": protocol.ListTemplates, "runs": protocol.ListRuns, "ping": protocol.Ping, "connection": protocol.List}[command]
r, err := call(protocol.Message{Type: typeName})
if err != nil {
return err
}
if command == "runs" && o.name != "" {
p, err := resolve(o.name)
if err != nil {
return err
}
filtered := []protocol.RunSummary{}
for _, run := range r.Runs {
if run.PipelineID == p.ID {
filtered = append(filtered, run)
}
}
r.Runs = filtered
}
if o.json {
return a.output(r)
}
switch command {
case "list":
for _, p := range r.Pipelines {
fmt.Fprintf(a.Out, "%d\t%s\tv%d\t%d stages\n", p.ID, p.Name, p.Version, p.Stages)
}
case "templates":
for _, t := range r.Templates {
note := ""
if t.Scheduled {
note = " [scheduled]"
}
fmt.Fprintf(a.Out, "%-24s %s%s\n", t.Key, t.Description, note)
}
case "runs":
for _, run := range r.Runs {
fmt.Fprintf(a.Out, "%d\t%s\t%s\tv%d\t%s\n", run.ID, run.Label(), run.Name, run.Version, run.Status)
}
case "ping":
fmt.Fprintln(a.Out, "Connected ·", r.Time)
if r.Build != nil {
fmt.Fprintf(a.Out, "Server: %s (commit %s)\n", r.Build.Version, r.Build.Commit)
} else {
fmt.Fprintln(a.Out, "Server build: unavailable (older server)")
}
build := buildinfo.Current()
fmt.Fprintf(a.Out, "Client: %s (commit %s)\n", build.Version, build.Commit)
if note := identityNote(r); note != "" {
fmt.Fprintln(a.Out, "Note:", note)
}
case "connection":
fmt.Fprintln(a.Out, "Server:", o.url)
for _, n := range r.NotificationEndpoints {
fmt.Fprintf(a.Out, "ntfy: %s · topic %s\n", n.ServerURL, n.Topic)
}
if note := identityNote(r); note != "" {
fmt.Fprintln(a.Out, "Note:", note)
}
}
return nil
case "export":
if len(f.Args()) != 1 || o.output != "" || o.all {
return a.exportBundle(ctx, o, f.Args(), call, resolve)
}
value, err := one()
if err != nil {
return err
}
p, err := resolve(value)
if err != nil {
return err
}
r, err := call(protocol.Message{Type: protocol.GetPipeline, PipelineID: p.ID, Version: o.version})
if err != nil {
return err
}
if r.Detail == nil {
return fmt.Errorf("missing pipeline detail")
}
_, err = fmt.Fprint(a.Out, r.Detail.Source)
return err
case "import":
return a.importBundle(ctx, o, f.Args(), call)
case "search":
query := strings.Join(pos, " ")
if strings.TrimSpace(query) == "" {
return fmt.Errorf("search requires a query; use pipelines help search")
}
r, err := call(protocol.Message{Type: protocol.Search, Search: &protocol.SearchRequest{Query: query, Kind: o.kind, Limit: o.limit}})
if err != nil {
return err
}
if r.SearchResults == nil {
return fmt.Errorf("server did not return search results; update pipelines-server")
}
if o.json {
return a.output(r.SearchResults)
}
if len(r.SearchResults.Results) == 0 {
fmt.Fprintln(a.Out, "No matches")
}
for _, hit := range r.SearchResults.Results {
// The shared Label renders every kind; the CLI additionally shows a
// text-field hit's snippet, which the TUI marks on its own line.
label := hit.Label()
if hit.Field != nil {
label += ": " + hit.Field.Snippet
}
fmt.Fprintf(a.Out, "%s\t%s\t%d\t%s\t%s\n", hit.Kind, hit.Target, hit.Score, hit.MatchedField, label)
}
if r.SearchResults.Truncated {
fmt.Fprintf(a.Err, "Results truncated (cap %d, scan bound %d bytes)\n", r.SearchResults.Cap, r.SearchResults.ScanBoundBytes)
}
return nil
case "show", "versions":
value, err := one()
if err != nil {
return err
}
p, err := resolve(value)
if err != nil {
return err
}
r, err := call(protocol.Message{Type: protocol.GetPipeline, PipelineID: p.ID, Version: o.version})
if err != nil {
return err
}
if r.Detail == nil {
return fmt.Errorf("missing pipeline detail")
}
if command == "versions" {
if o.json {
return a.output(r.Detail.Versions)
}
for _, v := range r.Detail.Versions {
fmt.Fprintf(a.Out, "v%d\t%d stages\t%s\n", v.Version, v.Stages, v.CreatedAt)
}
return nil
}
return a.output(r.Detail)
case "template":
key, err := one()
if err != nil {
return err
}
r, err := call(protocol.Message{Type: protocol.ListTemplates})
if err != nil {
return err
}
for _, t := range r.Templates {
if t.Key == key {
if o.source {
_, err = fmt.Fprint(a.Out, t.Source)
return err
}
return a.output(t)
}
}
return fmt.Errorf("template %q not found", key)
case "inspect", "cancel", "retry":
value, err := one()
if err != nil {
return err
}
id, err := strconv.ParseInt(value, 10, 64)
if err != nil || id <= 0 {
return fmt.Errorf("run ID must be positive")
}
typeName := protocol.GetRun
if command == "cancel" {
if err := a.confirmAction(fmt.Sprintf("Cancel run #%d? Previous side effects are not undone.", id), o.yes); err != nil {
return err
}
typeName = protocol.CancelRun
}
key := ""
if command == "retry" {
if err := a.confirmAction(fmt.Sprintf("Retry failed run #%d as a fresh run? Reuses original input/directory; side effects may repeat.", id), o.yes); err != nil {
return err
}
typeName = protocol.RetryRun
key = o.key
if key == "" {
key = fmt.Sprintf("retry-%d-%d", os.Getpid(), time.Now().UnixNano())
}
}
r, err := call(protocol.Message{Type: typeName, RunID: id, RequestKey: key})
if err != nil {
return err
}
if command == "retry" {
return a.finishRun(ctx, r, o, call)
}
return a.output(r.RunDetail)
case "decide":
if len(pos) < 1 || len(pos) > 2 {
return fmt.Errorf("decide requires a run ID and an optional stage key")
}
id, err := strconv.ParseInt(pos[0], 10, 64)
if err != nil || id <= 0 {
return fmt.Errorf("run ID must be positive")
}
option := strings.TrimSpace(o.option)
if option == "" {
return fmt.Errorf("decide requires --option KEY")
}
stageKey := ""
if len(pos) == 2 {
stageKey = pos[1]
}
r, err := call(protocol.Message{Type: protocol.DecideRun, RunID: id, Stage: stageKey, Option: option, Feedback: o.feedback})
if err != nil {
return err
}
if r.RunDetail == nil {
return fmt.Errorf("server did not return run detail")
}
if o.json {
return a.output(r.RunDetail)
}
line := fmt.Sprintf("Decided run #%d: %s · %s", r.RunDetail.ID, option, r.RunDetail.Status)
if feedback := recordedFeedback(r.RunDetail, option); feedback != "" {
line += " · feedback: " + feedback
}
_, err = fmt.Fprintln(a.Out, line)
return err
case "title":
if len(pos) != 2 {
return fmt.Errorf("title requires a run ID and a title")
}
id, err := strconv.ParseInt(pos[0], 10, 64)
if err != nil || id <= 0 {
return fmt.Errorf("run ID must be positive")
}
r, err := call(protocol.Message{Type: protocol.SetRunTitle, RunID: id, Title: pos[1]})
if err != nil {
return err
}
if r.RunDetail == nil {
return fmt.Errorf("server did not return run detail")
}
if o.json {
return a.output(r.RunDetail)
}
_, err = fmt.Fprintf(a.Out, "Renamed run #%d to %s\n", r.RunDetail.ID, r.RunDetail.Label())
return err
case "rpc":
path, err := one()
if err != nil {
return err
}
reader := a.In
if path != "-" {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
reader = f
}
data, err := io.ReadAll(io.LimitReader(reader, (2<<20)+1))
if err != nil {
return err
}
if len(data) > 2<<20 {
return fmt.Errorf("request exceeds 2 MiB")
}
var request protocol.Message
if err = json.Unmarshal(data, &request); err != nil {
return err
}
r, err := call(request)
if err != nil {
return err
}
return a.output(r)
case "run":
return a.run(ctx, pos, o, call, resolve)
}
return nil
}
func (a App) output(value any) error {
encoder := json.NewEncoder(a.Out)
encoder.SetIndent("", " ")
return encoder.Encode(value)
}
// notice writes one non-fatal line to stderr so machine-readable stdout stays
// intact. It never falls back to stdout, where it could corrupt --json output
// for an embedder that does not configure Err.
func (a App) notice(line string) {
w := a.Err
if w == nil {
w = os.Stderr
}
fmt.Fprintln(w, line)
}
// identityNote describes how this client build relates to a server response for
// human output; it is empty when both peers match.
func identityNote(response protocol.Message) string {
return buildinfo.Compare(buildinfo.Current(), protocol.MaxSupportedProtocol, response.Protocol, response.Build).Message
}
type callFunc func(protocol.Message) (protocol.Message, error)
type resolveFunc func(string) (protocol.PipelineSummary, error)
func (a App) author(ctx context.Context, command string, pos []string, o *options, call callFunc, resolve resolveFunc) error {
if len(pos) > 2 {
return fmt.Errorf("%s accepts [name] [prompt]", command)
}
if len(pos) > 0 {
if o.name != "" {
return fmt.Errorf("supply name once")
}
o.name = pos[0]
}
if len(pos) > 1 {
if o.prompt != "" {
return fmt.Errorf("supply prompt once")
}
o.prompt = pos[1]
}
var source string
var base int
if command == "edit" {
if o.name == "" {
if o.json {
return fmt.Errorf("edit --json requires a name or ID")
}
r, err := call(protocol.Message{Type: protocol.List})
if err != nil {
return err
}
p, err := tui.PickPipeline(ctx, r.Pipelines)
if err != nil {
return err
}
o.name = p.Name
}
p, err := resolve(o.name)
if err != nil {
return err
}
r, err := call(protocol.Message{Type: protocol.GetPipeline, PipelineID: p.ID, Version: o.version})
if err != nil {
return err
}
if r.Detail == nil {
return fmt.Errorf("missing pipeline detail")
}
o.name = p.Name
source = r.Detail.Source
base = r.Detail.LatestVersion
} else {
if o.name == "" {
if o.json || o.noOpen {
return fmt.Errorf("new requires a name in noninteractive mode")
}
}
if (o.name != "" && strings.TrimSpace(o.name) == "") || len(o.name) > 200 || strings.ContainsAny(o.name, "\r\n\x00") {
return fmt.Errorf("name must be 1–200 bytes without line breaks or NUL")
}
r, err := call(protocol.Message{Type: protocol.List})
if err != nil {
return err
}
for _, p := range r.Pipelines {
if p.Name == o.name {
return fmt.Errorf("pipeline already exists; use edit or choose another name")
}
}
source = pipeline.WithDefaults(pipeline.Template([]string{"worker"}, true), r.DefaultModel, r.DefaultHarness)
if o.template != "" {
r, err := call(protocol.Message{Type: protocol.ListTemplates})
if err != nil {
return err
}
found := false
for _, t := range r.Templates {
if t.Key == o.template {
source = t.Source
found = true
break
}
}
if !found {
return fmt.Errorf("template %q not found", o.template)
}
}
}
confirmation := "Create a retained draft?"
if !o.noOpen && !o.json {
confirmation = "Create a retained draft and open the configured harness?"
}
if err := a.confirmAction(confirmation, o.yes); err != nil {
return err
}
d, err := draft.Create(o.name, source, o.url, command == "new", base)
if err != nil {
return err
}
if o.json {
return a.output(d)
}
fmt.Fprintf(a.Out, "Draft: %s\nValidate: pipelines validate %q\nSubmit when ready: pipelines submit %q\n", d.Path, d.Path, d.Path)
if o.noOpen {
return nil
}
// Give the agent a directly executable command even in an uninstalled source tree.
var cmd *exec.Cmd
if o.harness == "nvim" {
cmd = exec.CommandContext(ctx, "nvim", d.Path)
} else {
executable, err := os.Executable()
if err != nil {
return err
}
cliCommand, err := harness.CLIPrefixFor(o.harness, o.url, executable)
if err != nil {
return err
}
cmd, err = author.HarnessCommand(ctx, o.harness, d, o.prompt, cliCommand)
if err != nil {
return err
}
}
cmd.Stdin = a.In
cmd.Stdout = a.Out
cmd.Stderr = a.Err
return cmd.Run()
}
func (a App) run(ctx context.Context, pos []string, o *options, call callFunc, resolve resolveFunc) error {
if len(pos) > 2 {
return fmt.Errorf("run accepts [name] [prompt]")
}
if len(pos) > 0 {
if o.name != "" {
return fmt.Errorf("supply pipeline once")
}
o.name = pos[0]
}
if len(pos) > 1 {
if o.prompt != "" {
return fmt.Errorf("supply prompt once")
}
o.prompt = pos[1]
}
if o.workspace == "" {
cwd, err := os.Getwd()
if err != nil {
return err
}
o.workspace = cwd
}
workspace, err := filepath.Abs(o.workspace)
if err != nil {
return err
}
var paths []string
for _, p := range strings.Split(o.paths, ",") {
if p = strings.TrimSpace(p); p != "" {
paths = append(paths, p)
}
}
// Pre-flight form validation of the whole-run override with the same parser
// the server uses; stage-key existence stays server-authoritative. A malformed
// value fails here, before any confirmation or run request.
if o.model != "" {
if _, err := pipeline.ParseModelOverride(o.model); err != nil {
return err
}
}
if o.yes && (o.name == "" || strings.TrimSpace(o.prompt) == "") {
return fmt.Errorf("--yes requires a pipeline and nonempty prompt")
}
if !o.json {
if o.name != "" {
p, err := resolve(o.name)
if err != nil {
return err
}
o.name = p.Name
}
if o.wait || o.key != "" || o.version > 0 {
return fmt.Errorf("--wait, --request-key and --version require --json")
}
_, err := tea.NewProgram(tui.NewRun(ctx, o.url, tui.RunOptions{Pipeline: o.name, Prompt: o.prompt, Title: o.title, Workspace: workspace, Yes: o.yes, AllowTools: o.allow, WritePaths: paths, Model: o.model, StageModels: o.stageModels}), tea.WithContext(ctx), tea.WithAltScreen()).Run()
return err
}
if o.name == "" || strings.TrimSpace(o.prompt) == "" {
return fmt.Errorf("run --json requires a pipeline and nonempty prompt")
}
p, err := resolve(o.name)
if err != nil {
return err
}
version := o.version
if version == 0 {
version = p.Version
}
confirmation := fmt.Sprintf("Run %s v%d in %s? This may edit files, execute commands and publish notifications.", p.Name, version, workspace) + o.modelSummary()
if err := a.confirmAction(confirmation, o.yes); err != nil {
return err
}
key := o.key
if key == "" {
key = fmt.Sprintf("cli-%d-%d", os.Getpid(), time.Now().UnixNano())
}
r, err := call(protocol.Message{Type: protocol.RunPipeline, PipelineID: p.ID, Version: version, RequestKey: key, Workspace: workspace, Title: o.title, Input: map[string]any{"prompt": o.prompt}, AllowTools: o.allow, WritePaths: paths, Model: o.model, StageModels: o.stageModels})
if err != nil {
return err
}
return a.finishRun(ctx, r, o, call)
}
// modelSummary describes the launch-time model overrides for the action
// confirmation, so a model mutation is visible before approval. It is empty when
// no override was supplied.
func (o *options) modelSummary() string {
if o.model == "" && len(o.stageModels) == 0 {
return ""
}
parts := []string{}
if o.model != "" {
parts = append(parts, "all stages: "+o.model)
}
keys := make([]string, 0, len(o.stageModels))
for key := range o.stageModels {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
parts = append(parts, key+": "+o.stageModels[key])
}
return " Model overrides — " + strings.Join(parts, "; ") + "."
}
func (a App) finishRun(ctx context.Context, r protocol.Message, o *options, call callFunc) error {
var err error
if o.wait {
if r.RunDetail == nil {
return fmt.Errorf("server did not return run detail")
}
// The client wait limit is separate from the per-request --timeout.
// Reaching it never cancels or replays admitted work; the run stays active.
var deadline <-chan time.Time
if o.waitTimeout > 0 {
timer := time.NewTimer(o.waitTimeout)
defer timer.Stop()
deadline = timer.C
}
for r.RunDetail.Status == "running" || r.RunDetail.Status == "queued" {
select {
case <-ctx.Done():
return ctx.Err()
case <-deadline:
return fmt.Errorf("client wait limit reached for run %d; it remains active and was not canceled; inspect it read-only with pipelines inspect %d --json, and to keep waiting rerun with --wait reusing the original --request-key instead of starting a duplicate run", r.RunDetail.ID, r.RunDetail.ID)
case <-time.After(time.Second):
}
r, err = call(protocol.Message{Type: protocol.GetRun, RunID: r.RunDetail.ID})
if err != nil {
return err
}
if r.RunDetail == nil {
return fmt.Errorf("missing run detail")
}
}
}
if err = a.output(r); err != nil {
return err
}
if o.wait && r.RunDetail.Status != "succeeded" {
return fmt.Errorf("run ended %s", r.RunDetail.Status)
}
return nil
}
// providerCheckDocker runs the provider check inside the profile's existing
// Compose service so a Docker-linked profile never falls back to a host harness.
// It streams the child's stdout/stderr and returns its exact exit code.
func (a App) providerCheckDocker(ctx context.Context, o *options, profile harness.Profile) error {
cwd, err := os.Getwd()
if err != nil {
return err
}
args := []string{
"compose", "--project-directory", profile.DockerDirectory,
"exec", "-T", "--workdir", cwd,
"pipelines", "pipelines", "provider-check",
"--harness", o.harness, "--model", o.model, "--yes", "--timeout", o.timeout.String(),
}
// Preserve the caller's output mode: a plain-text invocation must stay
// readable, while --json keeps the structured machine report.
if o.json {
args = append(args, "--json")
}
cmd := exec.CommandContext(ctx, "docker", args...)
cmd.Stdin = a.In
cmd.Stdout = a.Out
cmd.Stderr = a.Err
if err := cmd.Run(); err != nil {
var exit *exec.ExitError
if errors.As(err, &exit) {
return &ExitError{Code: exit.ExitCode()}
}
return err
}
return nil
}