0d7e81362f
Add the Run pipeline dialog with prompt, server directory and a per-run notification choice; add --notify auto/on/off to run and retry; move the live tool call onto the tool-count line and tick the reasoning duration; stop chat frames from repainting a different screen.
1613 lines
54 KiB
Go
1613 lines
54 KiB
Go
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
|
||
retryMode, retryStage, retryInputFile string
|
||
option, feedback, evidence, actor, notifyMode string
|
||
output string
|
||
conflict string
|
||
kind string
|
||
db, artifacts, olderThan string
|
||
keep int
|
||
keepSet bool
|
||
all bool
|
||
json, source, noOpen, yes, allow, createOnly, force, wait bool
|
||
version, expected, limit, retryVisit 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")
|
||
if command == "wait" {
|
||
// A wait blocks until the runs reach a terminal status, so its --timeout
|
||
// is the overall client limit (0 is the default and waits until they
|
||
// finish), not a per-request transport timeout.
|
||
f.DurationVar(&o.timeout, "timeout", 0, "Give up after this long while a run is still active (0 waits until it finishes)")
|
||
} else {
|
||
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)")
|
||
f.StringVar(&o.notifyMode, "notify", "auto", "Notifications for this run: auto (pipeline), on, or off")
|
||
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")
|
||
f.StringVar(&o.retryMode, "mode", "resume", "Retry mode: resume failed stage or restart from entry")
|
||
f.StringVar(&o.retryStage, "stage", "", "Retry this recorded stage (required when it was visited more than once)")
|
||
f.IntVar(&o.retryVisit, "visit", 0, "1-based occurrence of --stage in the recorded execution")
|
||
f.IntVar(&o.version, "version", 0, "Explicit published version of the same pipeline (default: source version)")
|
||
f.StringVar(&o.retryInputFile, "input-file", "", "JSON object merged into the selected stage input; '-' reads stdin")
|
||
f.StringVar(&o.notifyMode, "notify", "auto", "Notifications for this retry: auto, on, or off")
|
||
case "cancel", "draft-delete":
|
||
f.BoolVar(&o.yes, "yes", false, "Confirm this action without an interactive prompt")
|
||
case "retention":
|
||
f.StringVar(&o.db, "db", "", "Existing database path (default: standard data directory)")
|
||
f.StringVar(&o.artifacts, "artifacts", "", "Artifacts root (default: artifacts/ beside --db)")
|
||
f.StringVar(&o.olderThan, "older-than", "", "Select runs created before this rolling UTC duration ago (e.g. 720h, 30d, 12w)")
|
||
f.Func("keep", "Keep the newest N runs; older runs are selected (0 selects every eligible run)", func(value string) error {
|
||
n, err := strconv.Atoi(strings.TrimSpace(value))
|
||
if err != nil {
|
||
return fmt.Errorf("--keep requires an integer count")
|
||
}
|
||
o.keep, o.keepSet = n, true
|
||
return nil
|
||
})
|
||
f.BoolVar(&o.yes, "yes", false, "Approve removal without an interactive prompt (apply only)")
|
||
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.timeout == 0 && command != "wait") || 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 == "retention" {
|
||
return a.retention(ctx, o, pos)
|
||
}
|
||
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.
|
||
// `wait` uses --timeout as its overall wait limit, so its per-request transport
|
||
// timeout falls back to the usual bound.
|
||
requestTimeout := o.timeout
|
||
if requestTimeout <= 0 {
|
||
requestTimeout = 30 * time.Second
|
||
}
|
||
connectURL := o.url
|
||
dialCtx, cancel := context.WithTimeout(ctx, requestTimeout)
|
||
c, err := client.Open(dialCtx, connectURL)
|
||
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, requestTimeout)
|
||
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", u.Total, u.Succeeded, u.Failed, u.Canceled, u.Interrupted, u.Active, average)
|
||
if t := u.Usage; t != nil {
|
||
line := fmt.Sprintf("Reported model usage: %d tokens over %d stage(s)", t.TokensTotal, t.Stages)
|
||
if t.SplitKnown {
|
||
line += fmt.Sprintf(" (%d in / %d out)", t.TokensIn, t.TokensOut)
|
||
} else if t.SplitUnknownStages > 0 {
|
||
line += " (in/out split unavailable)"
|
||
}
|
||
if t.CostKnownStages > 0 {
|
||
line += fmt.Sprintf(" · $%.6f", t.CostUSD)
|
||
}
|
||
if t.CostUnknownStages > 0 {
|
||
line += fmt.Sprintf(" · cost unavailable for %d stage(s)", t.CostUnknownStages)
|
||
}
|
||
fmt.Fprintln(a.Out, line)
|
||
}
|
||
fmt.Fprint(a.Out, "\nPipeline\tRuns\tSucceeded\tFailed\tActive\n")
|
||
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 o.retryMode != "resume" && o.retryMode != "restart" {
|
||
return fmt.Errorf("--mode must be resume or restart")
|
||
}
|
||
switch strings.ToLower(strings.TrimSpace(o.notifyMode)) {
|
||
case "", "auto":
|
||
o.notifyMode = "auto"
|
||
case "on", "off":
|
||
o.notifyMode = strings.ToLower(strings.TrimSpace(o.notifyMode))
|
||
default:
|
||
return fmt.Errorf("--notify must be auto, on or off")
|
||
}
|
||
if key == "" {
|
||
key = fmt.Sprintf("retry-%d-%d", os.Getpid(), time.Now().UnixNano())
|
||
}
|
||
var retryInput map[string]any
|
||
if o.retryInputFile != "" {
|
||
var data []byte
|
||
if o.retryInputFile == "-" {
|
||
input := a.In
|
||
if input == nil {
|
||
input = os.Stdin
|
||
}
|
||
data, err = io.ReadAll(io.LimitReader(input, 64*1024+1))
|
||
} else {
|
||
var file *os.File
|
||
file, err = os.Open(o.retryInputFile)
|
||
if err == nil {
|
||
data, err = io.ReadAll(io.LimitReader(file, 64*1024+1))
|
||
_ = file.Close()
|
||
}
|
||
}
|
||
if err != nil {
|
||
return err
|
||
}
|
||
if len(data) > 64*1024 {
|
||
return fmt.Errorf("retry input exceeds 65536 bytes")
|
||
}
|
||
if err := json.Unmarshal(data, &retryInput); err != nil {
|
||
return fmt.Errorf("invalid retry input JSON: %w", err)
|
||
}
|
||
if retryInput == nil {
|
||
return fmt.Errorf("retry input must be a JSON object")
|
||
}
|
||
}
|
||
if o.retryVisit < 0 {
|
||
return fmt.Errorf("--visit must be positive")
|
||
}
|
||
r, err := call(protocol.Message{Type: typeName, RunID: id, RequestKey: key, RetryMode: o.retryMode, RetryStage: o.retryStage, RetryVisit: o.retryVisit, RetryVersion: o.version, RetryInput: retryInput, NotifyMode: o.notifyMode})
|
||
if err != nil {
|
||
return err
|
||
}
|
||
return a.finishRun(ctx, r, o, call)
|
||
}
|
||
r, err := call(protocol.Message{Type: typeName, RunID: id, RequestKey: key, RetryMode: o.retryMode})
|
||
if err != nil {
|
||
return err
|
||
}
|
||
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 "chat-adopt":
|
||
id, err := one()
|
||
if err != nil {
|
||
return err
|
||
}
|
||
r, err := call(protocol.Message{Type: protocol.ChatAdopt, ChatAdopt: &protocol.ChatAdoptRequest{SessionID: id}})
|
||
if err != nil {
|
||
return err
|
||
}
|
||
if o.json {
|
||
return a.output(r)
|
||
}
|
||
if r.ChatSession == nil {
|
||
return fmt.Errorf("server did not return the adopted session")
|
||
}
|
||
_, err = fmt.Fprintf(a.Out, "Adopted %s · %s\n", r.ChatSession.ID, r.ChatSession.Directory)
|
||
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)
|
||
case "wait":
|
||
return a.wait(ctx, pos, o, call)
|
||
}
|
||
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
|
||
}
|
||
}
|
||
switch strings.ToLower(strings.TrimSpace(o.notifyMode)) {
|
||
case "", "auto":
|
||
o.notifyMode = "auto"
|
||
case "on", "off":
|
||
o.notifyMode = strings.ToLower(strings.TrimSpace(o.notifyMode))
|
||
default:
|
||
return fmt.Errorf("--notify must be auto, on or off")
|
||
}
|
||
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, NotifyMode: o.notifyMode}), 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, NotifyMode: o.notifyMode})
|
||
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
|
||
}
|
||
final := r
|
||
err = a.awaitRuns(ctx, []protocol.Message{r}, deadline, call, runInProgress, func(terminal protocol.Message) error {
|
||
final = terminal
|
||
return nil
|
||
})
|
||
if err != nil {
|
||
var limit *waitLimitError
|
||
if errors.As(err, &limit) {
|
||
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)
|
||
}
|
||
return err
|
||
}
|
||
r = final
|
||
}
|
||
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
|
||
}
|
||
|
||
// wait polls every named run to a terminal status and reports each as it
|
||
// finishes, reusing the run --wait reattachment (GetRun) rather than a second
|
||
// mechanism. It is read-only: it resolves no workspace, never cancels, retries
|
||
// or otherwise changes a run, and a timeout is never treated as a run's
|
||
// outcome.
|
||
func (a App) wait(ctx context.Context, pos []string, o *options, call callFunc) error {
|
||
if len(pos) == 0 {
|
||
return fmt.Errorf("wait requires at least one run ID; use pipelines help wait")
|
||
}
|
||
// Resolve every id up front so an unknown run is a fast client error rather
|
||
// than something a wait would discover only after the others finish.
|
||
initial := make([]protocol.Message, 0, len(pos))
|
||
for _, value := range pos {
|
||
id, err := strconv.ParseInt(value, 10, 64)
|
||
if err != nil || id <= 0 {
|
||
return fmt.Errorf("run ID must be positive: %q", value)
|
||
}
|
||
r, err := call(protocol.Message{Type: protocol.GetRun, RunID: id})
|
||
if err != nil {
|
||
return err
|
||
}
|
||
if r.RunDetail == nil {
|
||
return fmt.Errorf("server did not return run detail for %d", id)
|
||
}
|
||
initial = append(initial, r)
|
||
}
|
||
// --timeout bounds the whole wait; 0 (the default) waits until every run
|
||
// finishes. Reaching the limit reports the still-active runs and changes
|
||
// nothing.
|
||
var deadline <-chan time.Time
|
||
if o.timeout > 0 {
|
||
timer := time.NewTimer(o.timeout)
|
||
defer timer.Stop()
|
||
deadline = timer.C
|
||
}
|
||
terminal := make([]protocol.Message, 0, len(initial))
|
||
err := a.awaitRuns(ctx, initial, deadline, call, runUnfinished, func(r protocol.Message) error {
|
||
terminal = append(terminal, r)
|
||
if o.json {
|
||
return nil
|
||
}
|
||
_, writeErr := fmt.Fprintln(a.Out, waitLine(r.RunDetail))
|
||
return writeErr
|
||
})
|
||
if err != nil {
|
||
var limit *waitLimitError
|
||
if errors.As(err, &limit) {
|
||
return fmt.Errorf("wait limit reached; %s still active and not canceled - nothing was changed; rerun pipelines wait to keep waiting", limit.Runs())
|
||
}
|
||
return err
|
||
}
|
||
if o.json {
|
||
if len(terminal) == 1 {
|
||
return a.output(terminal[0])
|
||
}
|
||
return a.output(terminal)
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// awaitRuns polls every run that active reports as unfinished until each is
|
||
// terminal, using the same GetRun reattachment the run --wait path uses, and
|
||
// calls onTerminal for each as it finishes (including runs already terminal at
|
||
// entry, in the order supplied). A deadline that passes first returns a
|
||
// *waitLimitError naming the runs still active; ctx ending first returns
|
||
// ctx.Err(). It never cancels, retries or otherwise changes a run.
|
||
func (a App) awaitRuns(ctx context.Context, runs []protocol.Message, deadline <-chan time.Time, call callFunc, active func(string) bool, onTerminal func(protocol.Message) error) error {
|
||
remaining := make([]protocol.Message, 0, len(runs))
|
||
for _, r := range runs {
|
||
if active(r.RunDetail.Status) {
|
||
remaining = append(remaining, r)
|
||
continue
|
||
}
|
||
if err := onTerminal(r); err != nil {
|
||
return err
|
||
}
|
||
}
|
||
for len(remaining) > 0 {
|
||
select {
|
||
case <-ctx.Done():
|
||
return ctx.Err()
|
||
case <-deadline:
|
||
return &waitLimitError{IDs: runIDs(remaining)}
|
||
case <-time.After(time.Second):
|
||
}
|
||
next := remaining[:0]
|
||
for _, r := range remaining {
|
||
refreshed, err := call(protocol.Message{Type: protocol.GetRun, RunID: r.RunDetail.ID})
|
||
if err != nil {
|
||
return err
|
||
}
|
||
if refreshed.RunDetail == nil {
|
||
return fmt.Errorf("server did not return run detail for %d", r.RunDetail.ID)
|
||
}
|
||
if active(refreshed.RunDetail.Status) {
|
||
next = append(next, refreshed)
|
||
continue
|
||
}
|
||
if err := onTerminal(refreshed); err != nil {
|
||
return err
|
||
}
|
||
}
|
||
remaining = next
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// runInProgress is the active set the run --wait path stops at: a run is still
|
||
// being worked on while it is queued or running.
|
||
func runInProgress(status string) bool {
|
||
return status == protocol.RunStatusQueued || status == protocol.RunStatusRunning
|
||
}
|
||
|
||
// runUnfinished is the active set `pipelines wait` blocks on: the same as
|
||
// runInProgress plus a run parked on a human decision (waiting), which has not
|
||
// finished either.
|
||
func runUnfinished(status string) bool {
|
||
return runInProgress(status) || status == protocol.RunStatusWaiting
|
||
}
|
||
|
||
// runIDs extracts the ids of the runs still active when a wait limit passed.
|
||
func runIDs(runs []protocol.Message) []int64 {
|
||
ids := make([]int64, 0, len(runs))
|
||
for _, r := range runs {
|
||
ids = append(ids, r.RunDetail.ID)
|
||
}
|
||
return ids
|
||
}
|
||
|
||
// waitLimitError reports that the client's wait limit was reached while the
|
||
// named runs were still active. The runs are untouched: a wait never cancels,
|
||
// retries or changes a run, and a timeout is never treated as its outcome.
|
||
type waitLimitError struct{ IDs []int64 }
|
||
|
||
func (e *waitLimitError) Error() string {
|
||
return "wait limit reached while run(s) " + e.Runs() + " were still active"
|
||
}
|
||
|
||
// Runs renders the still-active run ids for display.
|
||
func (e *waitLimitError) Runs() string {
|
||
parts := make([]string, 0, len(e.IDs))
|
||
for _, id := range e.IDs {
|
||
parts = append(parts, "run "+strconv.FormatInt(id, 10))
|
||
}
|
||
return strings.Join(parts, ", ")
|
||
}
|
||
|
||
// waitLine is the one-line terminal report `pipelines wait` prints: the run id,
|
||
// its status and outcome, its stage and how long it took.
|
||
func waitLine(d *protocol.RunDetail) string {
|
||
line := fmt.Sprintf("run %d · %s", d.ID, d.Status)
|
||
if outcome := strings.TrimSpace(d.Outcome); outcome != "" {
|
||
line += " (" + outcome + ")"
|
||
}
|
||
if stage := strings.TrimSpace(d.CurrentStage); stage != "" {
|
||
line += " · " + stage
|
||
}
|
||
if elapsed := runElapsed(d.CreatedAt, d.FinishedAt); elapsed != "" {
|
||
line += " · " + elapsed
|
||
}
|
||
return line
|
||
}
|
||
|
||
// runElapsed renders a run's wall-clock duration from its stored timestamps. An
|
||
// unparseable or missing start yields "" so the line omits the duration rather
|
||
// than inventing one; an empty finish uses the current time.
|
||
func runElapsed(start, end string) string {
|
||
first, err := time.Parse(time.RFC3339, start)
|
||
if err != nil {
|
||
return ""
|
||
}
|
||
last, err := time.Parse(time.RFC3339, end)
|
||
if err != nil {
|
||
if end != "" {
|
||
return ""
|
||
}
|
||
last = time.Now()
|
||
}
|
||
return max(time.Duration(0), last.Sub(first)).Round(time.Second).String()
|
||
}
|
||
|
||
// 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
|
||
}
|