Files
pipelines/internal/cli/app.go
T

701 lines
20 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 (
"bufio"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
tea "github.com/charmbracelet/bubbletea"
"pipelines/internal/author"
"pipelines/internal/client"
"pipelines/internal/draft"
"pipelines/internal/pipeline"
"pipelines/internal/protocol"
"pipelines/internal/tui"
)
type App struct {
Out, Err io.Writer
In io.Reader
}
type options struct {
url, name, prompt, template, workspace, paths, key, opencode string
json, source, noOpen, yes, allow, createOnly, force, wait bool
version, expected int
timeout 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 "new", "edit":
f.StringVar(&o.name, "name", "", "Pipeline name (or edit ID)")
f.StringVar(&o.prompt, "prompt", "", "Request to give OpenCode; omitted asks what to change")
f.BoolVar(&o.noOpen, "no-open", false, "Create the draft without opening OpenCode")
f.StringVar(&o.opencode, "opencode", envOr("PIPELINES_OPENCODE", "opencode"), "Host OpenCode V2 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)")
case "template":
f.BoolVar(&o.source, "source", false, "Print original Markdown instead of metadata")
case "submit":
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, "Start supplied name/prompt without interactive confirmation")
f.BoolVar(&o.allow, "allow-tools", false, "Explicitly approve declared shell/edit tools with --yes")
f.StringVar(&o.paths, "write-paths", "", "Comma-separated exact existing project-local Go files")
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")
case "runs":
f.StringVar(&o.name, "pipeline", "", "Filter by exact pipeline name or ID")
}
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 {
// 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")
}
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.version < 0 || o.expected < 0 {
return fmt.Errorf("timeout must be positive and versions nonnegative")
}
pos := f.Args()
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 {
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 "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
}
if d.Server != "" && d.Server != o.url {
return fmt.Errorf("draft belongs to server %s; select it with --url", d.Server)
}
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
}
request = protocol.Message{Type: protocol.Submit, Name: name, Source: source, CreateOnly: d.CreateOnly || o.createOnly, ExpectedVersion: expected}
}
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)
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 "show", "versions", "export":
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 == "export" {
_, err = fmt.Fprint(a.Out, r.Detail.Source)
return err
}
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":
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" {
typeName = protocol.CancelRun
}
r, err := call(protocol.Message{Type: typeName, RunID: id})
if err != nil {
return err
}
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)
}
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")
}
fmt.Fprint(a.Err, "New pipeline name: ")
name, err := bufio.NewReader(a.In).ReadString('\n')
if err != nil {
return err
}
o.name = strings.TrimSpace(name)
}
if 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.Template([]string{"worker"}, true)
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)
}
}
}
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
}
workspace, err := author.Workspace(d)
if err != nil {
return err
}
prepareCtx, cancel := context.WithTimeout(ctx, o.timeout)
session, err := author.PrepareSession(prepareCtx, o.opencode, workspace, d.Name)
cancel()
if err != nil {
return err
}
// Give the agent a directly executable command even in an uninstalled source tree.
executable, err := os.Executable()
if err != nil {
return err
}
cliCommand := shellQuote(executable) + " --url " + shellQuote(o.url)
cmd := exec.CommandContext(ctx, o.opencode, workspace, "--session", session, "--prompt", author.Prompt(d, o.prompt, cliCommand))
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.yes && len(paths) > 0 && !o.allow {
return fmt.Errorf("--write-paths with --yes requires --allow-tools")
}
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.yes {
return fmt.Errorf("noninteractive run requires --yes (tool approval remains separate)")
}
p, err := resolve(o.name)
if err != nil {
return err
}
version := o.version
if version == 0 {
version = p.Version
}
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
}
if o.wait {
if r.RunDetail == nil {
return fmt.Errorf("server did not return run detail")
}
deadline := time.NewTimer(o.timeout)
defer deadline.Stop()
for r.RunDetail.Status == "running" || r.RunDetail.Status == "queued" {
select {
case <-ctx.Done():
return ctx.Err()
case <-deadline.C:
return fmt.Errorf("timed out waiting for run %d; it remains active", 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
}
func shellQuote(value string) string { return "'" + strings.ReplaceAll(value, "'", "'\"'\"'") + "'" }