Files
pipelines/internal/cli/app.go
T
alan c700b28e6a Add cross-system read-only search
One query now finds anything in the system over the wire and from the CLI.

- protocol: add Search/SearchResults message types and a SearchRequest
  (query, optional kind filter, optional limit) / SearchResponse (typed,
  ranked matches plus truncation and scan-bound counters) pair, with typed
  payloads for pipeline, version, run, step/visit, field text and artifact.
- store: add Store.Search, a read-only query over pipelines,
  pipeline_versions, pipeline_runs, run_steps (+step_control) and
  step_artifacts. Ranks exact name (3) > name substring (2) > body text (1),
  breaks ties by recency then a stable kind/target order, and reports the
  matched field. Bounds work with a 50-default/200-max result cap, a 2000-row
  per-kind scan limit and a 2000-step / 1 MiB field-text scan budget.
- terms: a bare status word or lone date expression (today, yesterday, this
  week, YYYY-MM-DD) selects runs; anything else stays free text.
- server: dispatch protocol.Search to stores[0].Search; read-only and
  unconfirmed.
- cli: add `pipelines search QUERY [--type KIND] [--limit N] [--json]`, help
  text and a BROWSE line.
- store: add OpenReadOnly so the live-database check never runs DDL.
- docs: document the grammar, kinds, ranking and bounds in docs/cli.md,
  scope the TUI omnisearch to pipelines in docs/ui-ux-review.md, and add a
  search bullet to the packaged operations reference.
- tests: protocol round trip, store/ranking/term-parsing/limit/scan-bound
  unit tests, a server end-to-end test, and an env-guarded live check.

No new dependencies; go.mod/go.sum unchanged.
2026-10-16 15:43:25 +01:00

1147 lines
37 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"
"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, template, workspace, paths, key, opencode, model 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
}
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.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.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 "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
}
// 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")
}
provider, model, ok := strings.Cut(o.model, "/")
if !ok || !stage.ValidModel(provider, model) {
return fmt.Errorf("--model requires provider/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()
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\tv%d\t%s\n", run.ID, 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)")
}
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)
}
}
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 {
fmt.Fprintf(a.Out, "%s\t%s\t%d\t%s\t%s\n", hit.Kind, hit.Target, hit.Score, hit.MatchedField, searchLabel(hit))
}
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 "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)
}
// searchLabel renders one search hit's compact human line. Each kind exposes a
// different typed payload; the target stays the navigable identity.
func searchLabel(hit protocol.SearchResult) string {
switch {
case hit.Pipeline != nil:
return fmt.Sprintf("%s · v%d · %d stages", hit.Pipeline.Name, hit.Pipeline.Version, hit.Pipeline.Stages)
case hit.Version != nil:
return fmt.Sprintf("pipeline %d · v%d · %s", hit.Version.PipelineID, hit.Version.Version, hit.Version.ContentHash)
case hit.Run != nil:
return fmt.Sprintf("run %d · %s · %s", hit.Run.ID, hit.Run.PipelineName, hit.Run.Status)
case hit.Step != nil:
return fmt.Sprintf("run %d · step %d · %s · %s", hit.Step.RunID, hit.Step.Sequence, hit.Step.Stage, hit.Step.Outcome)
case hit.Field != nil:
return fmt.Sprintf("run %d · step %d · %s: %s", hit.Field.RunID, hit.Field.Sequence, hit.Field.Field, hit.Field.Snippet)
case hit.Artifact != nil:
return fmt.Sprintf("run %d · step %d · %s · %s", hit.Artifact.RunID, hit.Artifact.Sequence, hit.Artifact.Name, hit.Artifact.ContentType)
}
return ""
}
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)
}
}
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, Workspace: workspace, Yes: o.yes, AllowTools: o.allow, WritePaths: paths}), 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
}
if err := a.confirmAction(fmt.Sprintf("Run %s v%d in %s? This may edit files, execute commands and publish notifications.", p.Name, version, workspace), 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, Input: map[string]any{"prompt": o.prompt}, AllowTools: o.allow, WritePaths: paths})
if err != nil {
return err
}
return a.finishRun(ctx, r, o, call)
}
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
}