diff --git a/README.md b/README.md index 92a3ecb6..84f1aa1a 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,7 @@ Worth knowing before you script against the CLI: - **`--action '{"type":"launch"}'` is optional.** Sending a `text` action straight away works; the runtime starts the conversation itself. The launch step is shown because it makes the first turn explicit. - **A conversation with the draft runs your latest edits.** The draft runs as last compiled, so vf compiles it before `conversation run-script` and before a `send` with a `launch` action. If a later turn still ran an older build (you edited mid-conversation, or started with a `text` action), vf compiles right after it and warns, so the next turn runs the edits. `--no-compile` talks to the last build as it is; the published version is never compiled. - **Pass `--output-format json` explicitly when piping.** Inside AI coding agents (`CLAUDECODE`, `CURSOR_AGENT`, …) the default output is TOON, not JSON. -- **Capture values with `--output-format json | jq -r`** — the built-in `--jq` flag emits JSON, so strings keep their quotes. +- **Capture values with `--jq`**: `ID=$(vf project create … --jq .project.id)`. A string result prints raw, as `jq -r` prints it; anything else prints as JSON. - **`vf whoami` is offline** — it shows which credential source is configured but does not validate the token. `vf workspace list` is the real check. - **Look things up in-band**: `vf docs search "publish an environment"` and `vf docs get ` bring the documentation to the terminal — no browser, no auth. @@ -849,7 +849,7 @@ vf --output-format json | jq '.fieldName' ### jq filtering -Use `--jq` to filter or transform the response inline using a [jq](https://jqlang.org) expression. This always outputs JSON and overrides `--output-format`: +Use `--jq` to filter or transform the response inline using a [jq](https://jqlang.org) expression. A string result prints raw, as `jq -r` and `gh --jq` print it, so it can be captured as is; any other result prints as JSON (`| tojson` keeps a string quoted). `--jq` overrides `--output-format`: ```bash # Extract a single field @@ -886,21 +886,60 @@ When using `--all` (pagination) or streaming operations, output is written incre ## Error Handling -The CLI uses standard exit codes to indicate success or failure: +Each kind of failure has its own exit code, so a script can tell them apart without reading stderr: | Exit Code | Meaning | |-----------|---------| | `0` | Success | -| `1` | Error (API error, invalid input, etc.) | +| `1` | Any other failure, including API errors not listed below | +| `2` | Usage error, caught before any request: an unknown or invalid flag, a missing required flag, a bad argument | +| `3` | Authentication: not signed in, no token, HTTP 401, an expired session | +| `4` | Not found: HTTP 404 | +| `5` | Timed out: `--timeout`, or a wait's `--max-wait` ran out with runs still going | +| `6` | A test run didn't pass: `test run wait`, `test run wait-suite`, `test run create-suite --wait` | + +`vf --help` lists them too. + +In agent mode, and with `-o json` or `--jq`, an error is printed to stderr as one JSON object, with the same keys whether vf found the problem itself or the API answered with it: + +| Key | When | Meaning | +|-----|------|---------| +| `error` | always | The headline a person sees: `Couldn't get project · HTTP 404 Not Found` | +| `error_type` | always | The kind of failure: `not_found`, `missing_flag`, `validation_error`, … | +| `exit_code` | always | The code the process exits with | +| `message` | always | What went wrong, in one line: the API's own message, or the headline | +| `hints` | always | What to do next; an empty list when there is nothing to add | +| `explanation` | when vf can tell | Why it failed | +| `details` | when the API names fields, or flags are missing | The fields the request was refused for: `field`, the `flag` that sets it, `message`, `code`. A `missing_flag` error lists every missing flag here | +| `docs_url` | for most commands | The page that covers the command | +| `status_code` | when a response came back | The HTTP status | +| `body` | when a response came back | The response body as the API sent it, its own keys (such as `statusCode`) included | + +```json +{ + "error": "Couldn't get project · HTTP 404 Not Found", + "error_type": "not_found", + "exit_code": 4, + "message": "Project not found", + "explanation": "Check --project-id abc: it may be wrong, or belong to another workspace or environment.", + "hints": ["'vf project list' lists the IDs you can use"], + "docs_url": "https://www.voiceflow.com/docs/cli/commands/project", + "status_code": 404, + "body": { "statusCode": 404, "message": "Project not found" } +} +``` -On success, the response data is printed to **stdout** as JSON. On failure, error details are printed to **stderr**. +On success, the response data is printed to **stdout**. On failure, error details are printed to **stderr**. ```bash # Capture output and handle errors vf ... > output.json 2> error.log -if [ $? -ne 0 ]; then - echo "Error occurred, see error.log" -fi +case $? in + 0) ;; + 4) echo "Not found" ;; + 5) echo "Timed out; try again" ;; + *) echo "Failed, see error.log" ;; +esac ``` diff --git a/cmd/vf/main.go b/cmd/vf/main.go index af77fb02..9317349d 100644 --- a/cmd/vf/main.go +++ b/cmd/vf/main.go @@ -30,6 +30,6 @@ func main() { if msg := err.Error(); msg != "" { fmt.Fprintln(os.Stderr, msg) } - os.Exit(1) + os.Exit(cli.ExitCode(err)) // internal/cli/exitcode.go: each kind of failure has its own code } } diff --git a/internal/cli/analytics/query/daterange.go b/internal/cli/analytics/query/daterange.go new file mode 100644 index 00000000..ee9fb638 --- /dev/null +++ b/internal/cli/analytics/query/daterange.go @@ -0,0 +1,109 @@ +// This file is not generated by Speakeasy. It lets an analytics query's +// --start-date and --end-date take a day, and checks the range before it is +// sent. +// +// The API takes only a UTC time, 2026-06-01T00:00:00Z. Given a day, the +// usual way to ask for one, vf sent it as typed and printed what the API +// said: "Invalid ISO datetime", then "Invalid string: must match pattern +// /^(?:(?:\d\d[2468][048]|…/" for each date, 3 KB of regex and no format a +// person could read. A start after its end was sent too. Now a day is taken +// and sent as the time it starts, or for --end-date the time it ends, any +// other value is refused with the format, and a start after the end is +// refused before anything is sent. + +package query + +import ( + "fmt" + "strings" + "time" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/usage" +) + +// dateRanges gives each query under query that takes --start-date and +// --end-date dates that take a day, with help that says so. +func dateRanges(query *cobra.Command) { + for _, c := range query.Commands() { + start, end := c.Flags().Lookup("start-date"), c.Flags().Lookup("end-date") + if start == nil || end == nil || start.Value.Type() != "string" || end.Value.Type() != "string" { + continue + } + from := &dateValue{flag: "start-date"} + to := &dateValue{flag: "end-date", end: true} + start.Value, end.Value = from, to + ownHelp(c, "start-date", "Start of the range: a day, 2026-06-01, from 00:00 UTC, or a UTC time, 2026-06-01T09:30:00Z [required]") + ownHelp(c, "end-date", "End of the range: a day, 2026-06-30, through 23:59:59.999 UTC, or a UTC time, 2026-06-30T17:00:00Z [required]") + c.Example = strings.NewReplacer("--start-date ", "--start-date 2026-06-01", "--end-date ", "--end-date 2026-06-30").Replace(c.Example) + run := c.RunE + c.RunE = func(cmd *cobra.Command, args []string) error { + if from.given != "" && to.given != "" && from.at.After(to.at) { + return &flagutil.FlagValueError{ + Flag: "start-date", + Value: from.given, + Expected: "it is after --end-date " + to.given, + Hints: []string{"the start comes first: --start-date " + to.given + " --end-date " + from.given}, + } + } + return run(cmd, args) + } + } +} + +// ownHelp sets flag name's help on c, for --help and --usage alike. +func ownHelp(c *cobra.Command, name, help string) { + c.Flags().Lookup(name).Usage = help + _ = c.Flags().SetAnnotation(name, usage.OwnHelp, []string{"true"}) +} + +// dateValue is a range's start or end: a day, or a time. It is sent as a +// UTC time; a day as the time it starts, or, for an end, the time it ends. +type dateValue struct { + flag string + end bool + given string // as passed + at time.Time // the time it stands for + sent string // as sent +} + +func (d *dateValue) String() string { return d.sent } + +func (d *dateValue) Type() string { return "string" } + +func (d *dateValue) Set(s string) error { + s = strings.TrimSpace(s) + day, err := time.Parse(time.DateOnly, s) + switch { + case err == nil: + d.at = day + if d.end { + d.at = day.Add(24*time.Hour - time.Millisecond) + } + d.sent = d.at.Format("2006-01-02T15:04:05.000Z") + default: + at, err := parseTime(s) + if err != nil { + return fmt.Errorf("--%s takes a day (2026-06-01) or a UTC time (2026-06-01T09:30:00Z)", d.flag) + } + d.at, d.sent = at, s + if !strings.HasSuffix(s, "Z") { + // The API takes UTC only; a time with an offset is the same + // moment in UTC. + d.sent = at.UTC().Format(time.RFC3339Nano) + } + } + d.given = s + return nil +} + +// parseTime reads an ISO 8601 time with a zone, its seconds optional. +func parseTime(s string) (time.Time, error) { + at, err := time.Parse(time.RFC3339Nano, s) + if err != nil { + at, err = time.Parse("2006-01-02T15:04Z07:00", s) + } + return at, err +} diff --git a/internal/cli/analytics/query/root.go b/internal/cli/analytics/query/root.go index fa2f9823..4449b88e 100644 --- a/internal/cli/analytics/query/root.go +++ b/internal/cli/analytics/query/root.go @@ -125,6 +125,7 @@ func InitQueryRoot(parent *cobra.Command) error { return err } + dateRanges(QueryCmd) // daterange.go: dates take a day, and a range is checked parent.AddCommand(QueryCmd) return nil } diff --git a/internal/cli/bodyerror_test.go b/internal/cli/bodyerror_test.go new file mode 100644 index 00000000..568361de --- /dev/null +++ b/internal/cli/bodyerror_test.go @@ -0,0 +1,39 @@ +// This file is not generated by Speakeasy. It covers how errors.go explains +// a request body, given with --body or on stdin, that vf couldn't use. + +package cli + +import ( + "strings" + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +func TestABadBodyIsAnInvalidBodyError(t *testing.T) { + x := runWithStdin(t, "", "transcript", "search", "-p", "p1", "--body", `{"take":"ten"}`) + if x.Type != "invalid_body" || output.ExitCodeFor(x.Type, 0) != output.ExitUsage { + t.Errorf("type = %q", x.Type) + } + all := explained(x) + for _, want := range []string{ + `invalid --body: take should be a whole number, not "ten"`, + "The request wasn't sent.", + `You passed: {"take":"ten"}`, + "--body takes an object: `vf transcript search --help` shows what goes in it", + } { + if !strings.Contains(all, want) { + t.Errorf("missing %q in:\n%s", want, all) + } + } +} + +func TestABadBodyOnStdinSaysItCameOnStdin(t *testing.T) { + x := runWithStdin(t, `{"take":[1]}`+"\n", "transcript", "search", "-p", "p1") + if x.Type != "invalid_body" || x.Title != "invalid body on stdin: take should be a whole number, not a list" { + t.Errorf("got %q: %q", x.Type, x.Title) + } + if all := explained(x); !strings.Contains(all, "The body takes an object") { + t.Errorf("got:\n%s", all) + } +} diff --git a/internal/cli/confirm.go b/internal/cli/confirm.go new file mode 100644 index 00000000..59b0afe0 --- /dev/null +++ b/internal/cli/confirm.go @@ -0,0 +1,258 @@ +// This file is not generated by Speakeasy. It makes a delete ask first, at a +// terminal. +// +// `vf project delete`, `secret delete`, `environment delete` and every other +// delete sent their request at once. One Enter on the wrong picker row +// deleted an environment that was serving traffic, and nothing brings it +// back. gh, Heroku and Vercel ask first and take --yes for scripts. vf now +// does the same: +// +// Delete project "Help bot" (p1)? +// This can't be undone. +// Yes No +// +// It asks only when a person is there to answer: stdin and stderr are a +// terminal, agent mode is off, and --no-interactive isn't set. Scripts, CI, +// agents and pipes run exactly as before, and --dry-run never asks, since it +// sends nothing. The question comes after the pickers, so it can name what +// was picked, and before the request leaves (client/confirm.go). +// +// Every command named delete or delete-* asks. They are found at startup, +// so a delete the spec adds later asks too, without editing ~35 generated +// files. `environment merge` asks as well: it puts a version live on Main +// (merge.go). + +package cli + +import ( + "context" + "fmt" + "net/http" + "os" + "strings" + "sync" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + "golang.org/x/term" + + "github.com/voiceflow/cli/internal/client" + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/interactive" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/session" + "github.com/voiceflow/cli/internal/usage" +) + +// asksFirst is the annotation on a command that asks before it sends. +const asksFirst = "vf:asks-first" + +const yesHelp = "Delete without asking first. vf asks only at a terminal: scripts, CI and agents never wait for an answer." + +func init() { client.BeforeChange = confirmChange } + +// askFirst makes every delete under root, and `environment merge`, ask +// before it sends, and gives each --yes to skip the question: -y too, where +// the command doesn't already use it for something else. +func askFirst(root *cobra.Command) { + var yesFlags []yesFlag + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + help := "" + switch { + case isDelete(c): + help = yesHelp + case isMerge(c): + help = mergeYesHelp + c.Long = mergeLong // merge.go: say that it goes live at once + } + if help != "" { + if y, ok := addYes(c, help); ok { + yesFlags = append(yesFlags, y) + } + } + for _, sub := range c.Commands() { + walk(sub) + } + } + walk(root) + + // --usage lists --yes too. Its schemas are text, and rewriting them for + // ~35 commands takes about 20 ms, so it happens only when --usage asks. + pre := root.PersistentPreRunE + root.PersistentPreRunE = func(cmd *cobra.Command, args []string) error { + if usage.UsageRequested(cmd) { + yesInUsage.Do(func() { + for _, y := range yesFlags { + usage.AddFlags(y.path, y.flag) + } + }) + } + if pre == nil { + return nil + } + return pre(cmd, args) + } +} + +// yesInUsage adds --yes to the --usage schemas, once a process: they are +// package state, shared by every command tree the home prompt builds. +var yesInUsage sync.Once + +// yesFlag is a --yes for the --usage schema of the command at path. +type yesFlag struct { + path string + flag usage.UsageFlag +} + +// isDelete is whether c deletes something: it is named delete or delete-*. +func isDelete(c *cobra.Command) bool { + return c.Runnable() && (c.Name() == "delete" || strings.HasPrefix(c.Name(), "delete-")) +} + +// addYes marks c to ask first and gives it --yes, and -y when it's free. ok +// is false when c has a --yes of its own already. +func addYes(c *cobra.Command, help string) (y yesFlag, ok bool) { + if c.Annotations == nil { + c.Annotations = map[string]string{} + } + c.Annotations[asksFirst] = "true" + if c.Flags().Lookup("yes") != nil { + return yesFlag{}, false + } + short := "y" + if c.Flags().ShorthandLookup(short) != nil || c.InheritedFlags().ShorthandLookup(short) != nil { + short = "" + } + c.Flags().BoolP("yes", short, false, help) + spec := "--yes" + if short != "" { + spec = "-y --yes" + } + path := strings.TrimPrefix(c.CommandPath(), c.Root().Name()+" ") + return yesFlag{path: path, flag: usage.UsageFlag{Spec: spec, Help: help}}, true +} + +// asks is whether cmd stops to ask before it changes anything: it asks +// first, --yes and --dry-run are off, and a person is at the terminal. +func asks(cmd *cobra.Command) bool { + if cmd.Annotations[asksFirst] == "" { + return false + } + if yes, _ := flagutil.GetBoolFlag(cmd, "yes"); yes { + return false + } + if client.IsDryRun(cmd) { + return false + } + if off, _ := flagutil.GetBoolFlag(cmd, "no-interactive"); off { + return false + } + if output.IsAgentMode() { + return false + } + return atTerminal() +} + +// atTerminal is whether a person can see the question and answer it: stdin +// and stderr are a terminal. stdout may be a pipe. A var so tests can be at +// one. +var atTerminal = func() bool { + return term.IsTerminal(int(os.Stdin.Fd())) && term.IsTerminal(int(os.Stderr.Fd())) +} + +// askYesNo is a var so tests can answer it. +var askYesNo = interactive.AskYesNo + +// errNotConfirmed is the answer No. It is a cancel, so vf says "Canceled" +// and exits non-zero, as for a form closed with Ctrl-C. +var errNotConfirmed = fmt.Errorf("not confirmed: %w", context.Canceled) + +// confirmChange asks before cmd's first request that changes something, +// when cmd asks first. Anything but Yes sends nothing. +func confirmChange(cmd *cobra.Command, req *http.Request) error { + if !asks(cmd) { + return nil + } + title, note := "Delete "+deleteTarget(cmd)+"?", "This can't be undone." + if isMerge(cmd) { + title, note = mergeQuestion(cmd, req) + } + yes, err := askYesNo(req.Context(), title, note) + switch { + case err != nil: + return fmt.Errorf("%w (%v)", errNotConfirmed, err) + case !yes: + return errNotConfirmed + } + return nil +} + +// placeFlags say where a thing is, not which thing it is. They name what a +// command deletes only when it deletes the place itself: `project delete`. +var placeFlags = map[string]bool{"organization-id": true, "workspace-id": true, "project-id": true, "environment-alias": true} + +// deleteTarget names what cmd deletes: `project "Help bot" (p1)` when vf +// knows the name without asking the API, `variable v1` when it doesn't. +func deleteTarget(cmd *cobra.Command) string { + noun := deleteNoun(cmd) + if f := idFlag(cmd, noun); f != nil { + return noun + " " + named(f.Name, f.Value.String()) + } + // No flag holds its own ID (a tool message is one slot of a tool), so + // say what was given. + var given []string + cmd.LocalFlags().VisitAll(func(f *pflag.Flag) { + if f.Changed && !placeFlags[f.Name] && f.Name != "yes" && f.Name != "body" { + given = append(given, "--"+f.Name+" "+f.Value.String()) + } + }) + if len(given) == 0 { + return noun + } + return noun + " with " + strings.Join(given, " ") +} + +// deleteNoun is what cmd deletes, as its help says it ("Delete API tool"), +// or from its name. +func deleteNoun(cmd *cobra.Command) string { + if noun, ok := strings.CutPrefix(cmd.Short, "Delete "); ok && noun != "" { + return noun + } + if what, ok := strings.CutPrefix(cmd.Name(), "delete-"); ok { + return strings.ReplaceAll(what, "-", " ") + } + return strings.ReplaceAll(cmd.Parent().Name(), "-", " ") +} + +// idFlag is the flag that holds the ID of what cmd deletes, once set: +// --project-id for a project, --tool-id for an API tool, --environment-alias +// for an environment. +func idFlag(cmd *cobra.Command, noun string) *pflag.Flag { + words := strings.Fields(strings.ToLower(noun)) + if len(words) == 0 { + return nil + } + for _, base := range []string{strings.Join(words, "-"), words[len(words)-1]} { + for _, suffix := range []string{"-id", "-alias"} { + if f := cmd.Flags().Lookup(base + suffix); f != nil && f.Value.String() != "" { + return f + } + } + } + return nil +} + +// named is `"Help bot" (p1)` when vf knows what value is called: it was +// picked from a list in this run, or is current in the home prompt. +// Otherwise it is the value alone. +func named(flag, value string) string { + name := interactive.PickedName(flag, value) + if it, ok := session.Get(flag); name == "" && ok && it.Value == value && it.Name != value { + name = it.Name + } + if name == "" { + return value + } + return `"` + name + `" (` + value + `)` +} diff --git a/internal/cli/confirm_test.go b/internal/cli/confirm_test.go new file mode 100644 index 00000000..9d0ad88d --- /dev/null +++ b/internal/cli/confirm_test.go @@ -0,0 +1,302 @@ +// This file is not generated by Speakeasy. It covers confirm.go: a delete +// asks before it sends when a person is at the terminal, and only then, and +// every delete in the tree does. Requests go to a fake server. + +package cli + +import ( + "bytes" + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "regexp" + "slices" + "strings" + "sync" + "testing" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/session" +) + +// answering puts the test at a terminal (or not), answers every question +// with answer, and returns the questions asked. +func answering(t *testing.T, terminal, answer bool) *[]string { + t.Helper() + var asked []string + savedTerminal, savedAsk := atTerminal, askYesNo + atTerminal = func() bool { return terminal } + askYesNo = func(_ context.Context, title, note string) (bool, error) { + asked = append(asked, title+" "+note) + return answer, nil + } + t.Cleanup(func() { atTerminal, askYesNo = savedTerminal, savedAsk }) + return &asked +} + +// recordingAPI answers every request with {"message":"Deleted."} and +// records each as "METHOD /path". +func recordingAPI(t *testing.T) (*httptest.Server, func() []string) { + t.Helper() + var mu sync.Mutex + var got []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + mu.Lock() + got = append(got, r.Method+" "+r.URL.Path) + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"message":"Deleted."}`) + })) + t.Cleanup(srv.Close) + return srv, func() []string { + mu.Lock() + defer mu.Unlock() + return slices.Clone(got) + } +} + +// runAt runs args against srv with a dummy token, outside agent mode unless +// args turn it on, and returns what was printed and the error. +func runAt(t *testing.T, srv *httptest.Server, args ...string) (string, error) { + t.Helper() + isolate(t) + output.ResetAgentMode() + t.Cleanup(output.ResetAgentMode) + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + var buf bytes.Buffer + root.SetOut(&buf) + root.SetErr(&buf) + root.SetIn(strings.NewReader("")) + if !slices.ContainsFunc(args, func(a string) bool { return strings.HasPrefix(a, "--agent-mode") }) { + args = append(args, "--agent-mode=false") + } + root.SetArgs(append(args, "--server-url", srv.URL, "--token", "vfp_fake")) + _, err = root.ExecuteC() + return buf.String(), err +} + +func TestADeleteAsksOnlyWhenSomeoneCanAnswer(t *testing.T) { + sent := []string{"DELETE /v1/stable/project/p1"} + for _, tc := range []struct { + name string + terminal bool + args []string + asks bool + sends []string + }{ + {"at a terminal", true, nil, true, nil}, + {"--yes", true, []string{"--yes"}, false, sent}, + {"-y", true, []string{"-y"}, false, sent}, + {"--dry-run", true, []string{"--dry-run"}, false, nil}, + {"--no-interactive", true, []string{"--no-interactive"}, false, sent}, + {"agent mode", true, []string{"--agent-mode"}, false, sent}, + {"not at a terminal: a script, CI or a pipe", false, nil, false, sent}, + } { + t.Run(tc.name, func(t *testing.T) { + asked := answering(t, tc.terminal, false) + srv, requests := recordingAPI(t) + out, err := runAt(t, srv, append([]string{"project", "delete", "-p", "p1"}, tc.args...)...) + if tc.asks != (len(*asked) == 1) { + t.Errorf("asked %q, want a question: %v", *asked, tc.asks) + } + if got := requests(); !slices.Equal(got, tc.sends) { + t.Errorf("sent %q, want %q", got, tc.sends) + } + if tc.asks { + if !errors.Is(err, context.Canceled) || !strings.Contains(out, "Canceled") { + t.Errorf("No should cancel and say so: err %v, printed %q", err, out) + } + } else if err != nil { + t.Errorf("without a question, the command should run as before: %v\n%s", err, out) + } + }) + } +} + +func TestYesSendsTheDelete(t *testing.T) { + asked := answering(t, true, true) + srv, requests := recordingAPI(t) + out, err := runAt(t, srv, "secret", "delete", "-p", "p1", "-s", "s1") + if err != nil { + t.Fatalf("%v\n%s", err, out) + } + if want := []string{`Delete secret s1? This can't be undone.`}; !slices.Equal(*asked, want) { + t.Errorf("asked %q, want %q", *asked, want) + } + if got := requests(); len(got) != 1 || !strings.HasPrefix(got[0], "DELETE ") { + t.Errorf("Yes should send the delete, sent %q", got) + } +} + +// requiredArgs fills every required flag of c with a value it accepts: the +// first of its options, or a dummy ID. +func requiredArgs(c *cobra.Command) []string { + options := regexp.MustCompile(`options: ([^,)\s]+)`) + var args []string + c.LocalFlags().VisitAll(func(f *pflag.Flag) { + if len(f.Annotations["speakeasy:required"]) == 0 { + return + } + v := "x1" + if m := options.FindStringSubmatch(f.Usage); m != nil { + v = m[1] + } + args = append(args, "--"+f.Name, v) + }) + return args +} + +// deletes lists every command in the tree named delete or delete-*. +func deletes(t *testing.T) []*cobra.Command { + t.Helper() + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + var out []*cobra.Command + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + if c.Name() == "delete" || strings.HasPrefix(c.Name(), "delete-") { + out = append(out, c) + } + for _, sub := range c.Commands() { + walk(sub) + } + } + walk(root) + if len(out) < 34 { + t.Fatalf("found %d deletes; the tree had 34 when this test was written", len(out)) + } + return out +} + +// Every delete asks before it sends, not only the ones the sweep tried: No +// sends nothing, Yes sends it. +func TestEveryDeleteAsksBeforeItSends(t *testing.T) { + for _, c := range deletes(t) { + path := strings.Fields(c.CommandPath())[1:] + t.Run(strings.Join(path, " "), func(t *testing.T) { + args := append(path, requiredArgs(c)...) + for _, answer := range []bool{false, true} { + asked := answering(t, true, answer) + srv, requests := recordingAPI(t) + out, err := runAt(t, srv, args...) + if len(*asked) != 1 || !strings.HasPrefix((*asked)[0], "Delete ") { + t.Fatalf("answering %v: asked %q, want one question\n%s", answer, *asked, out) + } + changed := slices.ContainsFunc(requests(), func(r string) bool { return !strings.HasPrefix(r, "GET ") }) + if changed != answer { + t.Errorf("answering %v: sent %q\n%s", answer, requests(), out) + } + if !answer && !errors.Is(err, context.Canceled) { + t.Errorf("No should cancel, got %v", err) + } + } + }) + } +} + +func TestEveryDeleteTakesYes(t *testing.T) { + for _, c := range deletes(t) { + f := c.Flags().Lookup("yes") + if f == nil || f.Value.Type() != "bool" || f.Shorthand != "y" || c.Annotations[asksFirst] == "" { + t.Errorf("%s should ask first and take -y/--yes, has %+v", c.CommandPath(), f) + } + } +} + +func TestUsageListsYes(t *testing.T) { + srv, _ := recordingAPI(t) + out, err := runAt(t, srv, "--usage") + if err != nil { + t.Fatal(err) + } + if n := strings.Count(out, `flag "-y --yes" help="`+yesHelp+`"`); n != len(deletes(t)) { + t.Errorf("vf --usage should list -y/--yes under every delete, found %d", n) + } + if !strings.Contains(out, `flag "-y --yes" help="`+mergeYesHelp+`"`) { + t.Errorf("vf --usage should list -y/--yes under environment merge") + } +} + +// A delete the spec adds later is covered by its name alone, and -y is +// given only where the command doesn't already use it. +func TestADeleteIsFoundByItsName(t *testing.T) { + run := func(*cobra.Command, []string) error { return nil } + root := &cobra.Command{Use: "vf", RunE: run} + root.PersistentFlags().BoolP("debug", "d", false, "") + group := &cobra.Command{Use: "gadget"} + sprocket := &cobra.Command{Use: "delete-sprocket", Short: "Delete gadget sprocket", RunE: run} + gadget := &cobra.Command{Use: "delete", Short: "Delete gadget", RunE: run} + gadget.Flags().StringP("yaml-id", "y", "", "") + get := &cobra.Command{Use: "get", RunE: run} + group.AddCommand(sprocket, gadget, get) + root.AddCommand(group) + + askFirst(root) + + if f := sprocket.Flags().Lookup("yes"); f == nil || f.Shorthand != "y" || sprocket.Annotations[asksFirst] == "" { + t.Errorf("delete-sprocket should ask first and take -y/--yes: %+v", f) + } + if f := gadget.Flags().Lookup("yes"); f == nil || f.Shorthand != "" || gadget.Flags().ShorthandLookup("y").Name != "yaml-id" { + t.Errorf("where -y is taken, --yes comes without it: %+v", f) + } + if get.Flags().Lookup("yes") != nil || get.Annotations[asksFirst] != "" { + t.Errorf("a read should not ask") + } +} + +func TestTheQuestionNamesWhatItDeletes(t *testing.T) { + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + target := func(args ...string) string { + t.Helper() + c, rest, err := root.Find(args) + if err != nil { + t.Fatal(err) + } + c.Flags().VisitAll(func(f *pflag.Flag) { _ = f.Value.Set(f.DefValue); f.Changed = false }) + if err := c.ParseFlags(rest); err != nil { + t.Fatal(err) + } + return deleteTarget(c) + } + for _, tc := range []struct { + args []string + want string + }{ + {[]string{"project", "delete", "-p", "p1"}, "project p1"}, + {[]string{"environment", "delete", "-p", "p1", "-e", "staging"}, "environment staging"}, + {[]string{"api-tool", "delete", "-p", "p1", "-e", "main", "-t", "t1"}, "API tool t1"}, + {[]string{"mcp-server", "delete", "-p", "p1", "-e", "main", "-s", "s1"}, "MCP server s1"}, + {[]string{"phone-number", "delete", "-w", "w1", "-p", "n1"}, "phone number n1"}, + {[]string{"workflow", "delete-block", "-p", "p1", "--environment-alias", "main", "-w", "wf1", "-b", "b1", "--expected-steps", "s1"}, "workflow block b1"}, + {[]string{"agent", "delete-tool-message", "-p", "p1", "-e", "main", "-s", "delay", "-t", "t1"}, "agent tool message with --slot delay --tool-id t1"}, + } { + if got := target(tc.args...); got != tc.want { + t.Errorf("%s: got %q, want %q", strings.Join(tc.args[:2], " "), got, tc.want) + } + } + + // The home prompt knows what its current project is called. + session.Start() + t.Cleanup(session.Stop) + session.Set("project-id", "p1", "Help bot") + if got := target("project", "delete", "-p", "p1"); got != `project "Help bot" (p1)` { + t.Errorf("a known name should be in the question, got %q", got) + } + if got := target("project", "delete", "-p", "p2"); got != "project p2" { + t.Errorf("another project's name isn't known, got %q", got) + } +} diff --git a/internal/cli/conversation/endaction.go b/internal/cli/conversation/endaction.go new file mode 100644 index 00000000..98c621a3 --- /dev/null +++ b/internal/cli/conversation/endaction.go @@ -0,0 +1,177 @@ +// This file is not generated by Speakeasy. It makes an end action work as +// written, and cuts the API's answer to an action it can't take down to the +// form that action meant. +// +// The help's example, --action '{"type":"end"}', failed every time, with a +// 230–310-line error. Two things were wrong. The API wants a reason, +// {"type":"end","payload":{"reason":"…"}}, though its spec says the payload +// is optional. And the SDK read the bare action as a path request, so vf sent +// {"type":"end","payload":{"label":""}}. Ending a conversation matters: an +// evaluation can only run on a transcript that has ended. +// +// So an end action without a reason gets one, and goes out as an end action. +// The API takes any reason; the default says where the end came from. +// +// An action is a union of fifteen request forms, and the API's 422 lists +// every form's complaints: fifteen branches, of which only the one whose type +// matched the action says what is wrong. vf keeps that one, so the error +// reads "action.payload.reason: Invalid input for type "end": expected +// string, …" instead of "action: Invalid input" or 300 lines of JSON. An +// action whose type matches no form gets one line naming the types there are. + +package conversation + +import ( + "encoding/json" + "errors" + "fmt" + "slices" + "strings" + + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/sdk/models/operations" + "github.com/voiceflow/cli/internal/sdk/models/sdkerrors" +) + +// endReason is the reason an end action gets when it gives none. +const endReason = "Ended with vf conversation send" + +// giveEndAReason makes an end action one the API takes: it gets endReason +// when it has no reason, and is sent as an end action, without the label +// the SDK's path-request reading of it adds. Other actions are left alone. +func giveEndAReason(req *operations.StableConversationControllerSendRequest) { + action := req.Body.Action + raw, err := json.Marshal(action) + if err != nil { + return + } + var fields map[string]any + if json.Unmarshal(raw, &fields) != nil || fields["type"] != "end" { + return + } + payload, _ := fields["payload"].(map[string]any) + if payload == nil { + payload = map[string]any{} + } + if action.PathRequest != nil && payload["label"] == "" { + delete(payload, "label") + } + if payload["reason"] == nil || payload["reason"] == "" { // "": the SDK's zero value for one left out + payload["reason"] = endReason + } + fields["payload"] = payload + if raw, err = json.Marshal(fields); err != nil { + return + } + var end components.EndRequest + if json.Unmarshal(raw, &end) != nil { + return // a reason that isn't text: the API says what's wrong + } + req.Body.Action = components.CreateAnyRequestEndRequest(end) +} + +// narrowActionError cuts the API's "none of its forms" error for the action +// down to the form the action's type names. Other errors pass through. +func narrowActionError(req *operations.StableConversationControllerSendRequest, err error) error { + var apiErr *sdkerrors.SDKDefaultError + if !errors.As(err, &apiErr) || error(apiErr) != err { + return err + } + body, ok := narrowUnion([]byte(apiErr.Body), actionType(req.Body.Action)) + if !ok { + return err + } + narrowed := *apiErr + narrowed.Body = string(body) + return &narrowed +} + +// narrowUnion rewrites each invalid_union detail of an error body to the +// complaints of the branch whose type matched, the one with the fewest when +// several did, with paths from the body's root. When none matched, the type +// is wrong: one complaint lists the types there are. It reports whether it +// changed anything. +func narrowUnion(body []byte, typ string) ([]byte, bool) { + var fields map[string]any + if json.Unmarshal(body, &fields) != nil { + return nil, false + } + details, _ := fields["details"].([]any) + changed := false + var out []any + for _, d := range details { + detail, _ := d.(map[string]any) + branches, _ := detail["errors"].([]any) + if detail["code"] != "invalid_union" || len(branches) == 0 { + out = append(out, d) + continue + } + base, _ := detail["path"].([]any) + out = append(out, narrowBranches(base, branches, typ)...) + changed = true + } + if !changed { + return nil, false + } + fields["details"] = out + narrowed, err := json.Marshal(fields) + return narrowed, err == nil +} + +func narrowBranches(base []any, branches []any, typ string) []any { + var best []any + var types []string + for _, b := range branches { + issues, _ := b.([]any) + typeWrong := false + for _, i := range issues { + issue, _ := i.(map[string]any) + if path, _ := issue["path"].([]any); len(path) == 1 && path[0] == "type" { + typeWrong = true + values, _ := issue["values"].([]any) + for _, v := range values { + if s, ok := v.(string); ok && !slices.Contains(types, s) { + types = append(types, s) + } + } + } + } + if !typeWrong && (best == nil || len(issues) < len(best)) { + best = issues + } + } + if best == nil { + msg := "Invalid input: type must be one of " + strings.Join(types, ", ") + if typ != "" { + msg = fmt.Sprintf("Invalid input: type %q is none of %s", typ, strings.Join(types, ", ")) + } + return []any{map[string]any{ + "code": "invalid_value", + "message": msg, + "path": append(slices.Clip(base), "type"), + "values": types, + }} + } + out := make([]any, 0, len(best)) + for _, i := range best { + issue, _ := i.(map[string]any) + if issue == nil { + continue + } + narrowed := make(map[string]any, len(issue)) + for k, v := range issue { + narrowed[k] = v + } + path, _ := issue["path"].([]any) + narrowed["path"] = append(slices.Clip(base), path...) + if msg, _ := issue["message"].(string); msg != "" && typ != "" { + if rest, ok := strings.CutPrefix(msg, "Invalid input"); ok { + narrowed["message"] = fmt.Sprintf("Invalid input for type %q%s", typ, rest) + } else { + narrowed["message"] = fmt.Sprintf("type %q: %s", typ, msg) + } + } + out = append(out, narrowed) + } + return out +} diff --git a/internal/cli/conversation/reply.go b/internal/cli/conversation/reply.go new file mode 100644 index 00000000..8d8778cd --- /dev/null +++ b/internal/cli/conversation/reply.go @@ -0,0 +1,298 @@ +// This file is not generated by Speakeasy. It shows what the agent said, and +// shows it first, when `conversation send` prints a turn. +// +// A turn comes back as every trace the runtime made: blocks, debug messages +// carrying each tool's whole JSON schema, token accounting, and somewhere +// among them the one line the agent said. In the usability sweep one "hi" +// printed 320–580 lines with the reply two-thirds of the way down, and people +// and agents alike scrolled for it or wrote a --jq filter to dig it out. +// +// So pretty output is the turn as a chat reads: the agent's messages, its +// buttons and cards, and whether the conversation ended. TOON, agent mode's +// default, leads with the same under `agent`, as run-script's turns do. The +// other traces are counted, and --show-debug shows them. JSON, YAML, table +// and --jq still print the response as the API sent it: scripts read those. + +package conversation + +import ( + "encoding/json" + "fmt" + "io" + "sort" + "strings" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/client" + "github.com/voiceflow/cli/internal/config" + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sdk/models/operations" + "github.com/voiceflow/cli/internal/ui" +) + +const showDebugFlag = "show-debug" + +// addShowDebugFlag lets cmd show the traces a turn's reply came with. +func addShowDebugFlag(cmd *cobra.Command) { + cmd.Flags().Bool(showDebugFlag, false, "Also show the turn's other traces: blocks, debug messages, tool calls and the like. Without it, vf shows what the agent said and counts the rest. -o json always prints every trace.") +} + +// turn is what a send's answer says, read for a person or an agent. +type turn struct { + said []string // what the agent said, in order: messages, "[buttons: Yes | No]", "[card: …]" + ended bool // the conversation ended in this turn + stale bool // needsRecompile: the turn ran an older build of the draft + hidden []string // the type of each trace not in said, in order +} + +// showTurn prints a send's answer: the full response for the formats scripts +// read, and the turn as said for pretty output and TOON. +func showTurn(cmd *cobra.Command, res *operations.StableConversationControllerSendResponse) error { + format := outputFormat(cmd) + headers, _ := flagutil.GetBoolFlag(cmd, "include-headers") + if res == nil || client.IsDryRun(cmd) || headers || output.WantsRawJSON(cmd) || (format != "pretty" && format != "toon") { + return output.Result(cmd, res) + } + traces, stale, ok := readAnswer(res) + if !ok { + return output.Result(cmd, res) + } + t := readTurn(traces, stale) + debug, _ := cmd.Flags().GetBool(showDebugFlag) + if format == "toon" { + digest := t.digest() + if debug { + digest["traces"] = traces + delete(digest, "tracesHidden") + } + return output.Result(cmd, digest) + } + out, done := output.ResultWriter(cmd) + t.write(cmd, out, debug) + done() + if t.stale && skipCompile(cmd) { + // autocompile.go warns, and compiles, unless --no-compile kept the build. + warn(cmd, "This turn ran an older build of the draft: --no-compile kept it. Leave --no-compile out to run your latest edits.") + } + if debug { + fmt.Fprintln(cmd.OutOrStdout()) + return output.Result(cmd, res) + } + return nil +} + +// outputFormat is the format Result prints in, decided as it decides it: +// --output-format, then the setting, then TOON in agent mode, then pretty. +func outputFormat(cmd *cobra.Command) string { + if cmd.Flags().Changed("output-format") { + format, _ := flagutil.GetStringFlag(cmd, "output-format") + return format + } + if format := config.GetString("output-format"); format != "" { + return format + } + if output.IsAgentMode() { + return "toon" + } + return "pretty" +} + +// readAnswer is a send's answer as plain JSON values: its traces, and +// whether the turn ran a stale build. +func readAnswer(res *operations.StableConversationControllerSendResponse) (traces []map[string]any, stale bool, ok bool) { + var answer struct { + Traces []map[string]any `json:"traces"` + NeedsRecompile bool `json:"needsRecompile"` + } + if typed := res.StableConversationSendResponse; typed != nil { + raw, err := json.Marshal(typed) + if err != nil || json.Unmarshal(raw, &answer) != nil { + return nil, false, false + } + } else if !output.PeekJSON(res.HTTPMeta.Response, &answer) { + return nil, false, false + } + return answer.Traces, answer.NeedsRecompile, true +} + +// readTurn reads what the agent said from a turn's traces. A streamed +// completion's pieces join into the one message they make. +func readTurn(traces []map[string]any, stale bool) turn { + t := turn{stale: stale} + var streaming *strings.Builder + for _, trace := range traces { + kind, _ := trace["type"].(string) + payload, _ := trace["payload"].(map[string]any) + switch kind { + case "text", "speak": + if msg := text(payload, "message"); msg != "" { + t.said = append(t.said, msg) + continue + } + case "choice": + if b := buttons(payload["buttons"]); b != "" { + t.said = append(t.said, b) + continue + } + case "cardV2": + t.said = append(t.said, card("card", payload)...) + continue + case "carousel": + cards, _ := payload["cards"].([]any) + var titles []string + for _, c := range cards { + m, _ := c.(map[string]any) + titles = append(titles, text(m, "title")) + } + t.said = append(t.said, "[carousel: "+strings.Join(titles, " | ")+"]") + continue + case "visual": + if img := text(payload, "image"); img != "" { + t.said = append(t.said, "[image: "+img+"]") + continue + } + case "completion": + switch text(payload, "state") { + case "start": + streaming = &strings.Builder{} + case "content": + if streaming != nil { + streaming.WriteString(text(payload, "content")) + } + case "end": + if streaming != nil && streaming.Len() > 0 { + t.said = append(t.said, streaming.String()) + } + streaming = nil + } + continue + case "end": + t.ended = true + continue + } + t.hidden = append(t.hidden, kind) + } + return t +} + +// card is a card as said: its title and description, then its buttons. +func card(kind string, payload map[string]any) []string { + head := text(payload, "title") + if desc, _ := payload["description"].(map[string]any); text(desc, "text") != "" { + head = strings.TrimSpace(head + " · " + text(desc, "text")) + } + said := []string{"[" + kind + ": " + head + "]"} + if b := buttons(payload["buttons"]); b != "" { + said = append(said, b) + } + return said +} + +// buttons is "[buttons: Yes | No]", the form run-script's digest uses. +func buttons(v any) string { + list, _ := v.([]any) + var names []string + for _, b := range list { + m, _ := b.(map[string]any) + if name := text(m, "name"); name != "" { + names = append(names, name) + } + } + if len(names) == 0 { + return "" + } + return "[buttons: " + strings.Join(names, " | ") + "]" +} + +func text(m map[string]any, key string) string { + s, _ := m[key].(string) + return s +} + +// digest is the turn for an agent: what was said first, under `agent` as in +// run-script's turns, then the rest. TOON sorts keys, so the names keep that +// order: agent, ended, needsRecompile, tracesHidden. +func (t turn) digest() map[string]any { + said := t.said + if said == nil { + said = []string{} + } + d := map[string]any{ + "agent": said, + "ended": t.ended, + "needsRecompile": t.stale, + } + if len(t.hidden) > 0 { + d["tracesHidden"] = t.hiddenNote() + ": --show-debug shows them, and -o json prints the response as sent" + } + return d +} + +// hiddenNote counts the traces not shown, by type: "7 traces (debug ×5, block ×2)". +func (t turn) hiddenNote() string { + counts := map[string]int{} + for _, kind := range t.hidden { + counts[kind]++ + } + kinds := make([]string, 0, len(counts)) + for kind := range counts { + kinds = append(kinds, kind) + } + sort.Slice(kinds, func(i, j int) bool { + if counts[kinds[i]] != counts[kinds[j]] { + return counts[kinds[i]] > counts[kinds[j]] + } + return kinds[i] < kinds[j] + }) + parts := make([]string, len(kinds)) + for i, kind := range kinds { + parts[i] = kind + if counts[kind] > 1 { + parts[i] += fmt.Sprintf(" ×%d", counts[kind]) + } + } + noun := "traces" + if len(t.hidden) == 1 { + noun = "trace" + } + return fmt.Sprintf("%d other %s (%s)", len(t.hidden), noun, strings.Join(parts, ", ")) +} + +// write prints the turn for a person, as a chat reads: +// +// Agent On Saturdays we're open from 8 to 4. +// [buttons: Directions | Call us] +// The conversation ended. +// 7 other traces (debug ×5, block ×2) · --show-debug shows them +func (t turn) write(cmd *cobra.Command, out io.Writer, debug bool) { + u := output.UI(cmd, cmd.OutOrStdout()) + const label = "Agent " + indent := strings.Repeat(" ", len(label)) + if len(t.said) == 0 && !t.ended { + fmt.Fprintln(out, u.Muted("The agent said nothing this turn.")) + } + for i, said := range t.said { + lead := indent + if i == 0 { + lead = u.Bold(label) + } + lines := strings.Split(strings.TrimRight(said, "\n"), "\n") + for j, line := range lines { + if j > 0 { + lead = indent + } + if strings.HasPrefix(said, "[") { + line = u.Accent(line) + } + fmt.Fprintln(out, strings.TrimRight(lead+line, " ")) + } + } + if t.ended { + fmt.Fprintln(out, u.Muted("The conversation ended.")) + } + if len(t.hidden) > 0 && !debug { + fmt.Fprintln(out, u.Muted(t.hiddenNote()+" "+u.Glyph(ui.Separator)+" --show-debug shows them")) + } +} diff --git a/internal/cli/conversation/send.go b/internal/cli/conversation/send.go index 8b790442..ec45dd64 100644 --- a/internal/cli/conversation/send.go +++ b/internal/cli/conversation/send.go @@ -31,11 +31,13 @@ func initSendCmd(parent *cobra.Command) error { Use: "send", Short: "Send", Long: "Send message to a conversation.", - Example: " vf conversation send --user-id --project-id --environment-alias --action '{\"type\":\"end\"}' --version-param draft", + Example: " vf conversation send --user-id --project-id --environment-alias --action '{\"type\":\"end\"}' --version-param draft", // text.go replaces it RunE: runSendCmd, } flagutil.RegisterFlags(cmd, sendCmdMeta) addNoCompileFlag(cmd) // autocompile.go: --no-compile + addShowDebugFlag(cmd) // reply.go: --show-debug + addTextFlag(cmd) // text.go: --text, the message as typed if err := flagutil.ValidateMeta[operations.StableConversationControllerSendRequest](sendCmdMeta); err != nil { return fmt.Errorf("invalid metadata for send: %w", err) } @@ -49,15 +51,20 @@ func runSendCmd(cmd *cobra.Command, args []string) error { if usage.UsageRequested(cmd) { return usage.EmitSchema(cmd, cmd.OutOrStdout()) } - if interactive.ShouldPrompt(cmd, sendCmdMeta) { - if err := interactive.PromptAndSetFlags(cmd, sendCmdMeta); err != nil { + formMeta := withMessage(cmd, sendCmdMeta) // text.go: the form asks for the message + if interactive.ShouldPrompt(cmd, formMeta) { + if err := interactive.PromptAndSetFlags(cmd, formMeta); err != nil { return err } } + if err := textAsAction(cmd); err != nil { // text.go: --text is a text action + return err + } req, err := flagutil.BuildRequest[operations.StableConversationControllerSendRequest](cmd, sendCmdMeta, "Body", "body") if err != nil { - return err + return noMessage(cmd, err) // text.go: --text or --action } + giveEndAReason(req) // endaction.go: an end action without a reason gets one s, err := client.NewClient(cmd) if err != nil { return err @@ -82,11 +89,11 @@ func runSendCmd(cmd *cobra.Command, args []string) error { } res, err := s.Conversation.Send(cmd.Context(), *req, sdkOpts...) if err != nil { - return output.Error(cmd, err) + return output.Error(cmd, narrowActionError(req, err)) // endaction.go: only the complaints of the form the action meant } compiled := compileAfterStaleSend(cmd, s, req, res) // autocompile.go: a stale turn compiles the draft for the next - if err := output.Result(cmd, res); err != nil { + if err := showTurn(cmd, res); err != nil { // reply.go: what the agent said first; the other traces with --show-debug return err } return compiled() diff --git a/internal/cli/conversation/text.go b/internal/cli/conversation/text.go new file mode 100644 index 00000000..5dff984d --- /dev/null +++ b/internal/cli/conversation/text.go @@ -0,0 +1,108 @@ +// This file is not generated by Speakeasy. It lets `conversation send` say +// something in plain words. +// +// --action takes only JSON, in one of fifteen request shapes, and the form +// asked for the user ID and the version but never for the message, then +// failed with "needs --action". Talking to the agent is the first thing +// people do with vf, and in the usability sweep a newcomer couldn't without +// guessing {"type":"text","payload":"…"}. +// +// --text "" sends exactly that. At a terminal, when nothing says +// what to send (no --text, --action or --body), the form asks for the +// message with the other fields. --action stays for every other action: +// launch, a button's request, end. + +package conversation + +import ( + "encoding/json" + "errors" + "slices" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/interactive" + "github.com/voiceflow/cli/internal/output" +) + +const ( + textFlag = "text" + actionFlag = "action" +) + +// sendExample leads with typed words, the usual turn, then starts and ends +// a conversation. Each line runs as written; an end needs a reason (see +// endaction.go). +const sendExample = ` vf conversation send --user-id --project-id --environment-alias --version-param draft --text 'What are your hours?' + vf conversation send --user-id --project-id --environment-alias --version-param draft --action '{"type":"launch"}' + vf conversation send --user-id --project-id --environment-alias --version-param draft --action '{"type":"end","payload":{"reason":"done"}}'` + +// addTextFlag gives cmd --text, and examples that use it. +func addTextFlag(cmd *cobra.Command) { + cmd.Flags().String(textFlag, "", `The message to send, as the user would type it: vf sends {"type":"text","payload":""}. Use --action instead for any other action, such as a launch.`) + // --text gives the action as well, so an example needn't use --action + // (see examplehelp.go), and help says either will do. + flagutil.StandIn(cmd, textFlag, actionFlag) + cmd.Example = sendExample +} + +// withMessage is meta with the message as one more required field when +// nothing says what to send yet, so that at a terminal the form asks for it +// along with the rest. The field sets --text. +func withMessage(cmd *cobra.Command, meta []flagutil.FlagMeta) []flagutil.FlagMeta { + for _, name := range []string{textFlag, actionFlag, "body"} { + if flagutil.FlagChanged(cmd, name) { + return meta + } + } + return append(slices.Clip(meta), flagutil.FlagMeta{ + FlagName: textFlag, + Kind: flagutil.FlagKindString, + Required: true, + Description: "What to say to the agent, as the user would type it", + }) +} + +// textAsAction turns --text into the action it stands for, so the request, +// --dry-run included, carries it as if --action had said it. +func textAsAction(cmd *cobra.Command) error { + if !flagutil.FlagChanged(cmd, textFlag) { + return nil + } + if flagutil.FlagChanged(cmd, actionFlag) { + x := output.Explanation{ + Type: "usage_error", + Title: "--text and --action both say what to send", + Why: []string{"--text sends a text action, so it takes the place of --action."}, + Next: []string{"Keep --text to send typed words, or --action for any other action"}, + } + return output.Report(cmd, x, errors.New("--text and --action can't be combined")) + } + text, _ := cmd.Flags().GetString(textFlag) + action, err := json.Marshal(map[string]string{"type": "text", "payload": text}) + if err != nil { + return err + } + return cmd.Flags().Set(actionFlag, string(action)) +} + +// noMessage explains a send that says nothing to send, with both ways to say +// it; other errors pass through. +func noMessage(cmd *cobra.Command, err error) error { + if err == nil || err.Error() != "missing required flag: --"+actionFlag { + return err + } + x := output.Explanation{ + Type: "missing_flag", + Title: cmd.CommandPath() + " needs something to send: --text or --action", + Next: []string{ + "Say something: `" + cmd.CommandPath() + " --" + textFlag + " `", + `Or send any other action as JSON, such as a launch: --action '{"type":"launch"}'`, + }, + } + if !output.IsAgentMode() && !interactive.IsInteractive(cmd) { + x.Why = []string{"vf asks for the message only at a terminal, and this isn't one."} + } + return output.Report(cmd, x, err) +} diff --git a/internal/cli/conversation/text_test.go b/internal/cli/conversation/text_test.go new file mode 100644 index 00000000..526340bd --- /dev/null +++ b/internal/cli/conversation/text_test.go @@ -0,0 +1,48 @@ +// This file is not generated by Speakeasy. It covers text.go: at a terminal +// the form asks for the message when nothing says what to send. + +package conversation + +import ( + "testing" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/flagutil" +) + +func TestTheFormAsksForTheMessage(t *testing.T) { + cases := []struct { + args []string + asks bool + }{ + {nil, true}, + {[]string{"-u", "u1"}, true}, + {[]string{"--text", "hi"}, false}, + {[]string{"--action", `{"type":"launch"}`}, false}, + {[]string{"--body", `{"action":{"type":"launch"},"version":"draft"}`}, false}, + } + for _, c := range cases { + parent := &cobra.Command{Use: "conversation"} + if err := initSendCmd(parent); err != nil { + t.Fatal(err) + } + send := parent.Commands()[0] + if err := send.ParseFlags(c.args); err != nil { + t.Fatal(err) + } + meta := withMessage(send, sendCmdMeta) + var field *flagutil.FlagMeta + for i := range meta { + if meta[i].FlagName == textFlag { + field = &meta[i] + } + } + if asks := field != nil && field.Required; asks != c.asks { + t.Errorf("%v: the form asks for the message: %v, want %v", c.args, asks, c.asks) + } + if len(sendCmdMeta) > 0 && sendCmdMeta[len(sendCmdMeta)-1].FlagName == textFlag { + t.Fatalf("%v: withMessage changed sendCmdMeta itself", c.args) + } + } +} diff --git a/internal/cli/conversationend_test.go b/internal/cli/conversationend_test.go new file mode 100644 index 00000000..08f6aab4 --- /dev/null +++ b/internal/cli/conversationend_test.go @@ -0,0 +1,194 @@ +// This file is not generated by Speakeasy. It covers conversation/endaction.go: +// an end action works as written, and the API's error for an action it can't +// take names the form the action meant. + +package cli + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" +) + +const endedTurn = `{"needsRecompile":false,"traces":[{"type":"debug","payload":{"level":"info","message":"end of conversation triggered","context":"Action"},"time":1,"turnID":"t1"},{"type":"end","payload":{"reason":"done"},"time":2,"turnID":"t1"}]}` + +// unionError is the API's 422 for an action that is none of its forms, cut +// to five of its fifteen branches. Only the end branch's type matched. +const unionError = `{"details":[{"code":"invalid_union","errors":[ +[{"code":"invalid_value","message":"Invalid input: expected \"launch\"","path":["type"],"values":["launch"]}], +[{"code":"invalid_value","message":"Invalid input: expected \"text\"","path":["type"],"values":["text"]},{"code":"invalid_type","expected":"string","message":"Invalid input: expected string, received object","path":["payload"]}], +[{"code":"custom","message":"Invalid input","path":["type"]}], +[{"code":"invalid_type","expected":"string","message":"Invalid input: expected string, received undefined","path":["payload","reason"]}], +[{"code":"invalid_value","message":"Invalid input: expected \"dtmf\"","path":["type"],"values":["dtmf"]},{"code":"invalid_type","expected":"string","message":"Invalid input: expected string, received object","path":["payload"]}] +],"message":"Invalid input","path":["action"]}],"message":"Validation failed","statusCode":422,"statusText":"Unprocessable Entity"}` + +// endServer is the API's end rule: an end action needs payload.reason, a +// string, or the answer is unionError. It records each action it gets. +func endServer(t *testing.T) (url string, actions func() []map[string]any) { + t.Helper() + var mu sync.Mutex + var seen []map[string]any + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body struct { + Action map[string]any `json:"action"` + } + raw, _ := io.ReadAll(r.Body) + _ = json.Unmarshal(raw, &body) + mu.Lock() + seen = append(seen, body.Action) + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + payload, _ := body.Action["payload"].(map[string]any) + if _, ok := payload["reason"].(string); body.Action["type"] == "end" && !ok { + w.WriteHeader(http.StatusBadRequest) + io.WriteString(w, unionError) + return + } + io.WriteString(w, endedTurn) + })) + t.Cleanup(srv.Close) + return srv.URL, func() []map[string]any { + mu.Lock() + defer mu.Unlock() + return append([]map[string]any(nil), seen...) + } +} + +func TestSendEndsAConversationAsWritten(t *testing.T) { + cases := []struct { + name string + args []string + reason string + }{ + {"bare end", []string{"--action", `{"type":"end"}`}, "Ended with vf conversation send"}, + {"bare end in --body", []string{"--body", `{"action":{"type":"end"},"version":"published"}`}, "Ended with vf conversation send"}, + {"end with a message", []string{"--action", `{"type":"end","payload":{"message":"bye"}}`}, "Ended with vf conversation send"}, + {"end with a reason", []string{"--action", `{"type":"end","payload":{"reason":"test complete"}}`}, "test complete"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + url, actions := endServer(t) + out, errOut, err := runSend(t, url, true, c.args...) + if err != nil { + t.Fatalf("%v\n%s%s", err, out, errOut) + } + if !strings.Contains(out, "ended: true") { + t.Errorf("the conversation didn't end:\n%s", out) + } + sent := actions() + if len(sent) != 1 { + t.Fatalf("%d requests, want 1", len(sent)) + } + payload, _ := sent[0]["payload"].(map[string]any) + if sent[0]["type"] != "end" || payload["reason"] != c.reason { + t.Errorf("sent %v, want an end with reason %q", sent[0], c.reason) + } + if _, ok := payload["label"]; ok { + t.Errorf("sent a path request's label: %v", sent[0]) + } + }) + } +} + +// The help's own end example runs as written. +func TestSendHelpEndExampleRuns(t *testing.T) { + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + send, _, err := root.Find([]string{"conversation", "send"}) + if err != nil { + t.Fatal(err) + } + var example string + for _, line := range strings.Split(send.Example, "\n") { + if strings.Contains(line, `"type":"end"`) { + example = strings.TrimSpace(line) + } + } + if example == "" { + t.Fatalf("no end example in:\n%s", send.Example) + } + words := shellWords(t, strings.NewReplacer("", "x", "", "main").Replace(example)) + var action string + for i, w := range words { + if w == "--action" && i+1 < len(words) { + action = words[i+1] + } + } + url, actions := endServer(t) + out, errOut, err := runSend(t, url, true, "--action", action) + if err != nil { + t.Fatalf("%s: %v\n%s%s", example, err, out, errOut) + } + if len(actions()) != 1 || !strings.Contains(out, "ended: true") { + t.Errorf("%s didn't end the conversation:\n%s", example, out) + } +} + +// The API lists every form's complaints; vf keeps those of the form the +// action's type matched. +func TestSendActionErrorNamesTheForm(t *testing.T) { + end := []string{"--action", `{"type":"end","payload":{"reason":5}}`} + t.Run("person", func(t *testing.T) { + url, _ := endServer(t) + _, errOut, err := runSend(t, url, false, end...) + if err == nil { + t.Fatal("no error") + } + want := `action.payload.reason: Invalid input for type "end": expected string, received undefined` + if !strings.Contains(errOut, want) { + t.Errorf("the error doesn't name the form and its field, want %q:\n%s", want, errOut) + } + if strings.Contains(errOut, `expected \"launch\"`) || strings.Contains(errOut, "action: Invalid input") { + t.Errorf("the error still shows the other forms, or only the union:\n%s", errOut) + } + }) + t.Run("agent", func(t *testing.T) { + url, _ := endServer(t) + _, errOut, err := runSend(t, url, true, end...) + if err == nil { + t.Fatal("no error") + } + var e struct { + Details []struct { + Field string `json:"field"` + Message string `json:"message"` + } `json:"details"` + } + if err := json.Unmarshal([]byte(errOut), &e); err != nil { + t.Fatalf("not JSON: %v\n%s", err, errOut) + } + if len(e.Details) != 1 || e.Details[0].Field != "action.payload.reason" || !strings.Contains(e.Details[0].Message, `type "end"`) { + t.Errorf("details = %+v, want only action.payload.reason for type end", e.Details) + } + // The envelope repeats the narrowed body under "body"; it was 230-310 + // lines before narrowing. + if n := strings.Count(errOut, "\n"); n > 50 { + t.Errorf("the error is %d lines:\n%s", n, errOut) + } + }) + t.Run("a type no form has", func(t *testing.T) { + // Every branch's type is wrong: the end branch too, for a type "ned". + body := strings.Replace(unionError, `[{"code":"invalid_type","expected":"string","message":"Invalid input: expected string, received undefined","path":["payload","reason"]}]`, + `[{"code":"invalid_value","message":"Invalid input: expected \"end\"","path":["type"],"values":["end"]}]`, 1) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + io.WriteString(w, body) + })) + t.Cleanup(srv.Close) + _, errOut, err := runSend(t, srv.URL, false, "--action", `{"type":"ned","payload":{}}`) + if err == nil { + t.Fatal("no error") + } + want := `action.type: Invalid input: type "ned" is none of launch, text, end, dtmf` + if !strings.Contains(errOut, want) { + t.Errorf("want %q:\n%s", want, errOut) + } + }) +} diff --git a/internal/cli/conversationreply_test.go b/internal/cli/conversationreply_test.go new file mode 100644 index 00000000..8d69c740 --- /dev/null +++ b/internal/cli/conversationreply_test.go @@ -0,0 +1,181 @@ +// This file is not generated by Speakeasy. It covers conversation/reply.go: +// `conversation send` shows what the agent said first, and its other traces +// only on --show-debug. + +package cli + +import ( + "bytes" + "encoding/json" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +// chattyTurn is a turn as the runtime sends it: the reply sits among block +// and debug traces, one carrying a tool's whole schema. +const chattyTurn = `{"needsRecompile":false,"traces":[ +{"type":"block","payload":{"blockID":"start00000000000000000000"},"time":1,"turnID":"t1"}, +{"type":"debug","payload":{"level":"debug","message":"\"Main Agent\" starting execution","context":"Agent","metadata":{"tools":[{"name":"knowledge_base_search","schema":{"type":"object"}}]}},"time":2,"turnID":"t1"}, +{"type":"text","payload":{"message":"On Saturdays we're open 8 to 4.\nAnything else?","messageID":"m1","slate":{"id":"m1","content":[]},"ai":true},"time":3,"turnID":"t1"}, +{"type":"choice","payload":{"buttons":[{"name":"Directions"},{"name":"Call us"}]},"time":4,"turnID":"t1"}, +{"type":"cardV2","payload":{"title":"Main St store","description":{"text":"Open daily"},"buttons":[{"name":"Map"}],"imageUrl":null},"time":5,"turnID":"t1"}, +{"type":"debug","payload":{"level":"info","message":"\"Main Agent\" resources consumption","context":"Agent"},"time":6,"turnID":"t1"}, +{"type":"end","payload":{"reason":"done"},"time":7,"turnID":"t1"} +]}` + +// runSend runs `vf conversation send` against url, in agent mode or not. +func runSend(t *testing.T, url string, agent bool, args ...string) (stdout, stderr string, err error) { + t.Helper() + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("VF_SERVER_URL", url) + t.Setenv("HOME", t.TempDir()) + output.ResetAgentMode() + t.Cleanup(output.ResetAgentMode) + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + var out, errOut bytes.Buffer + root.SetOut(&out) + root.SetErr(&errOut) + root.SetIn(strings.NewReader("")) + mode := "--agent-mode=false" + if agent { + mode = "--agent-mode" + } + send := []string{"conversation", "send", "-p", "p1", "-e", "main", "-u", "u1", "-v", "published"} + root.SetArgs(append(append(send, args...), mode, "--no-interactive")) + _, err = root.ExecuteC() + return out.String(), errOut.String(), err +} + +func TestSendShowsWhatTheAgentSaidFirst(t *testing.T) { + text := []string{"-a", `{"type":"text","payload":"hours?"}`} + cases := []struct { + name string + agent bool + args []string + want []string // in this order, from the top + not []string + }{ + { + name: "pretty", + args: text, + want: []string{ + "Agent On Saturdays we're open 8 to 4.\n Anything else?\n [buttons: Directions | Call us]\n [card: Main St store · Open daily]\n [buttons: Map]\n", + "The conversation ended.", + "3 other traces (debug ×2, block) | --show-debug shows them", + }, + not: []string{"blockID", "starting execution", "needsRecompile", "knowledge_base_search"}, + }, + { + name: "TOON in agent mode", + agent: true, + args: text, + want: []string{ + `agent[4]: "On Saturdays we're open 8 to 4.\nAnything else?","[buttons: Directions | Call us]","[card: Main St store · Open daily]","[buttons: Map]"`, + "ended: true", + "needsRecompile: false", + `tracesHidden: "3 other traces (debug ×2, block): --show-debug shows them`, + }, + not: []string{"blockID", "starting execution", "traces["}, + }, + { + name: "TOON --show-debug", + agent: true, + args: append(text, "--show-debug"), + want: []string{`agent[4]: "On Saturdays`, "ended: true", "traces[7]:", "blockID: start00000000000000000000", "starting execution"}, + not: []string{"tracesHidden"}, + }, + { + name: "pretty --show-debug", + args: append(text, "--show-debug"), + want: []string{"Agent On Saturdays", "[buttons: Map]", "The conversation ended.", "traces:", "blockID:", "starting execution"}, + not: []string{"--show-debug shows them"}, + }, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + url, _ := conversationServer(t, 200, chattyTurn) + out, errOut, err := runSend(t, url, c.agent, c.args...) + if err != nil { + t.Fatalf("%v\n%s%s", err, out, errOut) + } + rest := out + for _, w := range c.want { + i := strings.Index(rest, w) + if i < 0 { + t.Fatalf("missing, or out of order: %q\n--- got:\n%s", w, out) + } + if w == c.want[0] && i != 0 { + t.Errorf("the reply isn't first:\n%s", out) + } + rest = rest[i+len(w):] + } + for _, n := range c.not { + if strings.Contains(out, n) { + t.Errorf("shows %q:\n%s", n, out) + } + } + }) + } +} + +// Scripts read the response as the API sent it: -o json, --jq and YAML keep +// every trace. +func TestSendKeepsTheWholeResponseForScripts(t *testing.T) { + text := []string{"-a", `{"type":"text","payload":"hours?"}`} + t.Run("json", func(t *testing.T) { + url, _ := conversationServer(t, 200, chattyTurn) + out, errOut, err := runSend(t, url, true, append(text, "-o", "json")...) + if err != nil { + t.Fatalf("%v\n%s", err, errOut) + } + var got, want any + if err := json.Unmarshal([]byte(out), &got); err != nil { + t.Fatalf("not JSON: %v\n%s", err, out) + } + _ = json.Unmarshal([]byte(chattyTurn), &want) + g, _ := json.Marshal(got) + w, _ := json.Marshal(want) + if string(g) != string(w) { + t.Errorf("-o json changed the response:\n got %s\nwant %s", g, w) + } + }) + t.Run("jq", func(t *testing.T) { + url, _ := conversationServer(t, 200, chattyTurn) + out, errOut, err := runSend(t, url, false, append(text, "-q", "[.traces[].type]")...) + if err != nil { + t.Fatalf("%v\n%s", err, errOut) + } + if !strings.Contains(out, `"block"`) || !strings.Contains(out, `"debug"`) { + t.Errorf("--jq didn't see every trace:\n%s", out) + } + }) + t.Run("yaml", func(t *testing.T) { + url, _ := conversationServer(t, 200, chattyTurn) + out, errOut, err := runSend(t, url, false, append(text, "-o", "yaml")...) + if err != nil { + t.Fatalf("%v\n%s", err, errOut) + } + if !strings.Contains(out, "start00000000000000000000") { + t.Errorf("-o yaml lost the block trace:\n%s", out) + } + }) +} + +// A turn that ran a stale build says so even when --no-compile keeps vf from +// compiling, since the pretty view no longer prints needsRecompile. +func TestSendSaysAStaleTurnWithNoCompile(t *testing.T) { + stale := strings.Replace(chattyTurn, `"needsRecompile":false`, `"needsRecompile":true`, 1) + url, _ := conversationServer(t, 200, stale) + out, errOut, err := runSend(t, url, false, "-a", `{"type":"text","payload":"hours?"}`, "--no-compile") + if err != nil { + t.Fatalf("%v\n%s", err, errOut) + } + if !strings.Contains(errOut, "older build of the draft") { + t.Errorf("no word of the stale build:\n%s\n%s", out, errOut) + } +} diff --git a/internal/cli/conversationtext_test.go b/internal/cli/conversationtext_test.go new file mode 100644 index 00000000..977d9ad8 --- /dev/null +++ b/internal/cli/conversationtext_test.go @@ -0,0 +1,119 @@ +// This file is not generated by Speakeasy. It covers conversation/text.go: +// `conversation send --text` says something in plain words. + +package cli + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" +) + +// sendServer answers every conversation turn with answer, and records each +// request body it gets. +func sendServer(t *testing.T, answer string) (url string, bodies func() []string) { + t.Helper() + var mu sync.Mutex + var seen []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + raw, _ := io.ReadAll(r.Body) + mu.Lock() + seen = append(seen, string(raw)) + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, answer) + })) + t.Cleanup(srv.Close) + return srv.URL, func() []string { + mu.Lock() + defer mu.Unlock() + return append([]string(nil), seen...) + } +} + +// sentAction is the action a request body carries, as JSON. +func sentAction(t *testing.T, body string) string { + t.Helper() + var b struct { + Action json.RawMessage `json:"action"` + } + if err := json.Unmarshal([]byte(body), &b); err != nil { + t.Fatalf("request body isn't JSON: %v\n%s", err, body) + } + var v any + _ = json.Unmarshal(b.Action, &v) + out, _ := json.Marshal(v) + return string(out) +} + +func TestSendTextSendsATextAction(t *testing.T) { + for _, agent := range []bool{false, true} { + url, bodies := sendServer(t, chattyTurn) + out, errOut, err := runSend(t, url, agent, "--text", `What are your "hours"?`) + if err != nil { + t.Fatalf("agent=%v: %v\n%s%s", agent, err, out, errOut) + } + sent := bodies() + if len(sent) != 1 { + t.Fatalf("agent=%v: %d requests, want 1", agent, len(sent)) + } + if got, want := sentAction(t, sent[0]), `{"payload":"What are your \"hours\"?","type":"text"}`; got != want { + t.Errorf("agent=%v: sent %s, want %s", agent, got, want) + } + } +} + +func TestSendTextAndActionAreOneOrTheOther(t *testing.T) { + for _, agent := range []bool{false, true} { + url, bodies := sendServer(t, chattyTurn) + out, errOut, err := runSend(t, url, agent, "--text", "hi", "--action", `{"type":"launch"}`) + if err == nil { + t.Fatalf("agent=%v: no error\n%s", agent, out) + } + if !strings.Contains(errOut, "--text and --action both say what to send") { + t.Errorf("agent=%v: the error doesn't name the clash:\n%s", agent, errOut) + } + if agent && !strings.Contains(errOut, `"error_type": "usage_error"`) { + t.Errorf("agent mode: not a usage error:\n%s", errOut) + } + if n := len(bodies()); n != 0 { + t.Errorf("agent=%v: %d requests sent, want none", agent, n) + } + } +} + +func TestSendWithNothingToSendNamesText(t *testing.T) { + for _, agent := range []bool{false, true} { + url, bodies := sendServer(t, chattyTurn) + _, errOut, err := runSend(t, url, agent) + if err == nil { + t.Fatalf("agent=%v: no error", agent) + } + if !strings.Contains(errOut, "needs something to send: --text or --action") || !strings.Contains(errOut, "--text ") { + t.Errorf("agent=%v: the error doesn't offer --text:\n%s", agent, errOut) + } + if n := len(bodies()); n != 0 { + t.Errorf("agent=%v: %d requests sent, want none", agent, n) + } + } +} + +// The help leads with typed words. +func TestSendHelpLeadsWithText(t *testing.T) { + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + send, _, err := root.Find([]string{"conversation", "send"}) + if err != nil { + t.Fatal(err) + } + first, _, _ := strings.Cut(strings.TrimSpace(send.Example), "\n") + if !strings.Contains(first, "--text '") || strings.Contains(first, "--action") { + t.Errorf("the first example doesn't send typed words with --text alone: %s", first) + } +} diff --git a/internal/cli/daterange_test.go b/internal/cli/daterange_test.go new file mode 100644 index 00000000..17a0248d --- /dev/null +++ b/internal/cli/daterange_test.go @@ -0,0 +1,107 @@ +// This file is not generated by Speakeasy. It covers +// analytics/query/daterange.go across every analytics query, and +// output/fieldformat.go on the API's own answer to a bad date. + +package cli + +import ( + "bytes" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +// Every analytics query takes a day for each end of its range and sends +// the time the day starts or ends; refuses a date it can't read, with the +// format; and refuses a start after its end. Only the first is sent. +func TestEveryAnalyticsQueryTakesADay(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Errorf("unexpected request %s %s", r.Method, r.URL) + })) + t.Cleanup(srv.Close) + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("VF_SERVER_URL", srv.URL) + query := find(t, testRoot(t), "analytics", "query") + checked := 0 + for _, c := range query.Commands() { + if c.Flags().Lookup("start-date") == nil || c.Flags().Lookup("end-date") == nil { + continue + } + checked++ + path := strings.Fields(strings.TrimPrefix(c.CommandPath(), "vf ")) + line, _, _ := strings.Cut(strings.TrimSpace(c.Example), "\n") + words := shellWords(t, line)[1:] + if !strings.Contains(line, "--start-date 2026-06-01") || !strings.Contains(line, "--end-date 2026-06-30") { + t.Errorf("%s: example gives no days: %s", c.CommandPath(), line) + continue + } + sent := dryRunErr(t, append(words, "--agent-mode=false")) + if !strings.Contains(sent, `"startDate": "2026-06-01T00:00:00.000Z"`) || !strings.Contains(sent, `"endDate": "2026-06-30T23:59:59.999Z"`) { + t.Errorf("%v: a day isn't sent as its start and end:\n%s", path, sent) + } + + bad := dryRunErr(t, append(words, "--agent-mode=false", "--end-date", "2026-13-45")) + if !strings.Contains(bad, "--end-date takes a day (2026-06-01) or a UTC time (2026-06-01T09:30:00Z)") || strings.Contains(bad, "Would send") { + t.Errorf("%v: a bad date:\n%s", path, bad) + } + back := dryRunErr(t, append(words, "--agent-mode=false", "--start-date", "2026-07-01")) + if !strings.Contains(back, "invalid value for --start-date: it is after --end-date 2026-06-30") || + !strings.Contains(back, "the start comes first: --start-date 2026-06-30 --end-date 2026-07-01") || strings.Contains(back, "Would send") { + t.Errorf("%v: a start after the end:\n%s", path, back) + } + } + if checked < 20 { + t.Errorf("checked only %d queries", checked) + } + + // A time, with or without its seconds or an offset, is sent in UTC. + sent := dryRunErr(t, []string{"analytics", "query", "call-count", "-p", "p1", "-i", "day", "--agent-mode=false", + "-s", "2026-06-01T09:30+02:00", "--end-date", "2026-06-01T17:00Z"}) + if !strings.Contains(sent, `"startDate": "2026-06-01T07:30:00Z"`) || !strings.Contains(sent, `"endDate": "2026-06-01T17:00Z"`) { + t.Errorf("times:\n%s", sent) + } +} + +// The API's answer to a date it can't read names the format, once a field, +// instead of giving the regex the date failed. +func TestAnAPIDateErrorNamesTheFormat(t *testing.T) { + pattern := `/^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$/` + body := `{"message":"Validation failed","details":[` + + `{"code":"invalid_format","format":"datetime","message":"Invalid ISO datetime","origin":"string","path":["endDate"],"pattern":"` + pattern + `"},` + + `{"code":"invalid_format","format":"regex","message":"Invalid string: must match pattern ` + pattern + `","origin":"string","path":["endDate"],"pattern":"` + pattern + `"}]}` + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(body)) + })) + t.Cleanup(srv.Close) + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("VF_SERVER_URL", srv.URL) + for _, agent := range []string{"--agent-mode=false", "--agent-mode=true"} { + output.ResetAgentMode() + t.Cleanup(output.ResetAgentMode) + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + var buf bytes.Buffer + root.SetOut(&buf) + root.SetErr(&buf) + root.SetArgs([]string{"analytics", "query", "call-count", "-p", "p1", "--no-interactive", agent, + "--body", `{"startDate":"2026-06-01T00:00:00Z","endDate":"yesterday","interval":"day"}`}) + _ = root.Execute() + out := buf.String() + line, want := "endDate: expected a UTC time such as 2026-06-01T09:30:00Z (--end-date)", 1 + if agent == "--agent-mode=true" { + // Once in details, and once in the API's own body, which the + // envelope keeps under body. + line, want = `"message": "expected a UTC time such as 2026-06-01T09:30:00Z"`, 2 + } + if strings.Count(out, line) != want || strings.Contains(out, "pattern") || strings.Contains(out, `\d`) { + t.Errorf("%s:\n%s", agent, out) + } + } +} diff --git a/internal/cli/docs.go b/internal/cli/docs.go index 0cd1063d..c91a38b6 100644 --- a/internal/cli/docs.go +++ b/internal/cli/docs.go @@ -170,14 +170,7 @@ func writeDocsSearchJSON(cmd *cobra.Command, results []docsSearchResult) error { if err != nil { return err } - for _, value := range filtered { - encoded, err := json.MarshalIndent(value, "", " ") - if err != nil { - return err - } - fmt.Fprintln(out, string(encoded)) - } - return nil + return output.WriteJqResults(out, filtered, false) } // docsSearchArguments builds the search tool's arguments. Besides the query, diff --git a/internal/cli/docs_test.go b/internal/cli/docs_test.go index 51d663bd..e1f6ae37 100644 --- a/internal/cli/docs_test.go +++ b/internal/cli/docs_test.go @@ -140,8 +140,8 @@ func TestDocsSearchJSONPrintsAnEmptyListForNoMatches(t *testing.T) { func TestDocsSearchJSONAppliesJq(t *testing.T) { results := []docsSearchResult{{Title: "Personal access tokens", Page: "api-reference/authentication"}} - if got := writeJSON(t, results, ".[0].page"); strings.TrimSpace(got) != `"api-reference/authentication"` { - t.Fatalf("printed %q, want only the page", got) + if got := writeJSON(t, results, ".[0].page"); got != "api-reference/authentication\n" { + t.Fatalf("printed %q, want only the page, unquoted as other commands print a string", got) } if got := writeJSON(t, results, ""); !strings.Contains(got, `"title": "Personal access tokens"`) { t.Fatalf("printed %q, want the whole list", got) diff --git a/internal/cli/errors.go b/internal/cli/errors.go index c5e19a22..0435aa6a 100644 --- a/internal/cli/errors.go +++ b/internal/cli/errors.go @@ -29,7 +29,6 @@ import ( "github.com/voiceflow/cli/internal/config" "github.com/voiceflow/cli/internal/flagutil" - "github.com/voiceflow/cli/internal/interactive" "github.com/voiceflow/cli/internal/oauth" "github.com/voiceflow/cli/internal/output" "github.com/voiceflow/cli/internal/ui" @@ -129,13 +128,16 @@ func renderError(cmd *cobra.Command, err error) error { if cmd == nil { cmd = rootCmd } + if msg := err.Error(); unknownFlagRE.MatchString(msg) || needsValueRE.MatchString(msg) || badArgumentRE.MatchString(msg) { + parseFlagsAfterError(cmd) + } if errors.Is(err, huh.ErrUserAborted) || errors.Is(err, context.Canceled) { fmt.Fprintln(cmd.ErrOrStderr(), output.UI(cmd, cmd.ErrOrStderr()).Status(ui.StatusFailed, "Canceled")) return output.AlreadyReported(err) } var fve *flagutil.FlagValueError if errors.As(err, &fve) { - if output.IsAgentMode() { + if output.WantsJSONError(cmd) { return renderFlagValueError(cmd, err) // flagerrors.go: its envelope is pinned by tests } var under []string @@ -156,6 +158,10 @@ var ( missingFlagRE = regexp.MustCompile(`^missing required flag: --(\S+)`) configFileRE = regexp.MustCompile(`^failed to (parse|read) config file (\S+): (.*)`) badTimeoutRE = regexp.MustCompile(`^invalid --timeout value "([^"]*)"`) + // The arguments a command takes, as cobra's Args validators word it. + badArgsRE = regexp.MustCompile(`^(?:accepts \d+ arg\(s\)|requires at least \d+ arg\(s\)|accepts at most \d+ arg\(s\)|accepts between \d+ and \d+ arg\(s\)|invalid argument ".*" for ")`) + // A flag's value vf couldn't use, as flagutil words it. + badInputRE = regexp.MustCompile(`^(?:failed to (?:parse|read) (?:stdin|file|--)|--\S+ got .* which isn't a JSON array|multiple union variants provided for --|expected integer enum value for --|invalid base64 for --)`) ) // explainCLIError explains an error that is not an API response. It matches @@ -165,6 +171,9 @@ func explainCLIError(cmd *cobra.Command, err error) output.Explanation { msg := err.Error() help := "`" + cmd.CommandPath() + " --help`" x := output.Explanation{Type: "usage_error", Title: firstLine(msg)} + if sx, ok := explainStrayArgs(err); ok { // strayargs.go + return sx + } if errors.Is(err, oauth.ErrSessionEnded) { x.Type = "auth_session_ended" @@ -184,6 +193,21 @@ func explainCLIError(cmd *cobra.Command, err error) output.Explanation { x.Next = []string{"Check your internet connection and run it again", "If it keeps failing, sign in again: `vf auth login`"} return x } + var body *flagutil.BodyError + if errors.As(err, &body) { + x.Type = "invalid_body" + x.Why = []string{"The request wasn't sent.", "You passed: " + body.DisplayValue()} + takes := "The body" + if !body.Stdin && body.Flag != "" { + takes = "--" + body.Flag + } + if body.Takes != "" { + x.Next = append(x.Next, takes+" takes "+body.Takes+": "+help+" shows what goes in it") + } else { + x.Next = append(x.Next, help+" shows what the body takes") + } + return x + } if errors.Is(err, flagutil.ErrStdinEmpty) { x.Type = "stdin_empty" x.Next = trimAll(strings.Split(msg, "\n")[1:]) @@ -245,8 +269,12 @@ func explainCLIError(cmd *cobra.Command, err error) output.Explanation { x.Next = []string{help + " shows what each flag takes"} return x } + var missing *flagutil.MissingFlagsError + if errors.As(err, &missing) { + return explainMissingFlags(cmd, missing.Flags) // missingflags.go + } if m := missingFlagRE.FindStringSubmatch(msg); m != nil { - return explainMissingFlag(cmd, m[1]) + return explainMissingFlags(cmd, []string{m[1]}) } if m := configFileRE.FindStringSubmatch(msg); m != nil { x.Type = "config_error" @@ -298,6 +326,12 @@ func explainCLIError(cmd *cobra.Command, err error) output.Explanation { x.Next = []string{"`vf auth signup` on its own opens the signup page", "If you already have an account and a key: `vf auth login --manual`"} case strings.HasPrefix(msg, "only https://www.voiceflow.com/docs URLs are supported"): x.Next = []string{"Search the docs instead: `vf docs search `"} + case badArgsRE.MatchString(msg): // exits 2, as a usage error: exitcode.go + x.Next = []string{help + " shows the arguments it takes"} + case badInputRE.MatchString(msg): + x.Type = "invalid_flag_value" + x.Why = []string{"The request wasn't sent."} + x.Next = []string{help + " shows what each flag takes"} default: x.Type = "error" if lines := strings.Split(strings.TrimSpace(msg), "\n"); len(lines) > 1 { @@ -307,35 +341,6 @@ func explainCLIError(cmd *cobra.Command, err error) output.Explanation { return x } -// explainMissingFlag says where the value of a missing flag comes from: for -// an ID, the list command that shows it; at a terminal, the picker. -func explainMissingFlag(cmd *cobra.Command, flag string) output.Explanation { - x := output.Explanation{ - Type: "missing_flag", - Title: cmd.CommandPath() + " needs --" + flag, - } - switch { - case output.IsAgentMode(): - x.Why = []string{"vf doesn't ask for missing values in agent mode."} - case func() bool { v, _ := flagutil.GetBoolFlag(cmd, "no-interactive"); return v }(): - x.Why = []string{"--no-interactive is set, so vf didn't ask for it."} - case !interactive.IsInteractive(cmd): - x.Why = []string{"vf asks for missing values only at a terminal, and this isn't one."} - } - if list := listCommandFor(cmd, flag); list != "" { - x.Next = append(x.Next, "`"+list+"` shows the values it takes") - } - x.Next = append(x.Next, "Pass it: `"+cmd.CommandPath()+" --"+flag+" `") - if body, ok := flagutil.StdinLeftUnread(cmd, flag); ok { - x.Why = append(x.Why, "Body flags were given, so vf didn't read stdin.") - x.Next = append([]string{"If it's in the body on stdin, add --" + body + " - to read it: the flags still win"}, x.Next...) - } - if interactive.HasPicker(flag) && !output.IsAgentMode() && !interactive.IsInteractive(cmd) { - x.Next = append(x.Next, "At a terminal, without --no-interactive, vf lets you pick it from a list") - } - return x -} - // listCommandFor is the command that lists the values an ID flag takes: // 'vf project list' for --project-id. An organization ID is on every // workspace, so 'vf workspace list' shows those. @@ -386,6 +391,27 @@ func unknownSubcommand(root *cobra.Command, args []string) (*cobra.Command, erro return cmd, fmt.Errorf("unknown command %q for %q", flags.Arg(0), cmd.CommandPath()) } +// parseFlagsAfterError reads the flags cobra didn't reach because a flag +// before them was wrong, so -o json, --jq and --agent-mode decide how that +// error is reported, as they do for any other: 'vf project get --nosuch +// -o json' is reported as JSON. Unknown flags are skipped; a flag that is +// wrong in another way stops it again. +func parseFlagsAfterError(cmd *cobra.Command) { + _, rest, err := cmd.Root().Find(commandLine()) + if err != nil { + return + } + flags := pflag.NewFlagSet(cmd.Name(), pflag.ContinueOnError) + flags.SetOutput(discard{}) + flags.ParseErrorsAllowlist.UnknownFlags = true + flags.AddFlagSet(cmd.Flags()) + flags.AddFlagSet(cmd.InheritedFlags()) + _ = flags.Parse(rest) + if f := flags.Lookup("agent-mode"); f != nil && f.Changed { + output.InitAgentMode(cmd) + } +} + // commandLine is the arguments Execute runs, which cobra reads from os.Args. func commandLine() []string { return os.Args[1:] } diff --git a/internal/cli/errors_test.go b/internal/cli/errors_test.go index 90b584be..043a6280 100644 --- a/internal/cli/errors_test.go +++ b/internal/cli/errors_test.go @@ -229,13 +229,15 @@ func TestCheckAccessFindsTheTargetAmongYourWorkspaces(t *testing.T) { // name is within two edits of any short flag name. func TestAnUnknownShortFlagSuggestsWhatItMeansElsewhere(t *testing.T) { root := testRoot(t) - update := find(t, root, "agent", "update") - if update.Flags().ShorthandLookup("p") != nil || update.Flags().Lookup("project-id") == nil { - t.Fatal("the test needs a command with --project-id and no -p") - } + // Every vf command with --project-id now takes -p (shorthands.go), so a + // command added by hand stands in for one that doesn't. + update := &cobra.Command{Use: "probe", RunE: func(*cobra.Command, []string) error { return nil }} + update.Flags().String("project-id", "", "") + update.Flags().String("name", "", "") + root.AddCommand(update) x := explainCLIError(update, errors.New("unknown shorthand flag: 'p' in -p")) if got := explained(x); !strings.Contains(got, "Did you mean `--project-id`?") || strings.Contains(got, "--jq") { - t.Errorf("-p on vf agent update:\n%s", got) + t.Errorf("-p on vf probe:\n%s", got) } if got := similarFlags(update, "pi"); len(got) != 0 { t.Errorf("--pi is near nothing, got %q", got) diff --git a/internal/cli/examplehelp.go b/internal/cli/examplehelp.go index 388b8678..a878ff36 100644 --- a/internal/cli/examplehelp.go +++ b/internal/cli/examplehelp.go @@ -91,6 +91,13 @@ func isCommandWord(word string) bool { return true } +// exampleValues replaces values the generator made up that run but +// mislead. The traffic split's '{"key":1314.98,"key1":2310.29}' named no +// environment and didn't add up to the 100 the API requires. +var exampleValues = map[string]string{ + "vf environment update-traffic-split --traffic": `'{"production":90,"staging":10}'`, +} + // quoteValues single-quotes a flag value the example spread over several // words, so the shell passes it as one: `--description provided quietly // carpool` becomes `--description 'provided quietly carpool'`. A flag left @@ -106,6 +113,13 @@ func quoteValues(c *cobra.Command, words []string) []string { if f == nil || f.Value.Type() == "bool" { continue } + if v, ok := exampleValues[c.CommandPath()+" --"+f.Name]; ok { + out = append(out, v) + if i+1 < len(words) && !strings.HasPrefix(words[i+1], "-") { + i++ + } + continue + } j := i + 1 for j < len(words) && !strings.HasPrefix(words[j], "-") { j++ @@ -122,51 +136,69 @@ func quoteValues(c *cobra.Command, words []string) []string { } // missingRequired is " --flag " for each required flag of c that -// words don't set, in the order help lists them. A union's variants are each -// marked required but are alternatives: when words set none of the union, -// only the first variant's flags are added. A union that isn't optional, like -// a body that is one as a whole, gets its first form when words set none. +// words don't set, in the order help lists them. A union that isn't +// optional, like a body that is one as a whole, is required too, but gets +// its first form when words set none. A form's own fields are required only with it +// (flagutil.RequiredWithForm), so they come with the form. func missingRequired(c *cobra.Command, words []string) []string { var add []string - variant := "" + given := flagsIn(words) c.LocalFlags().VisitAll(func(f *pflag.Flag) { - if f.Hidden || !isRequired(f) || setIn(words, f) { + if f.Hidden || !isRequired(f) || needsAForm(f) || setIn(words, f) || flagutil.StoodInFor(c, given, f.Name) { return } - if dot := strings.LastIndexByte(f.Name, '.'); dot > 0 { - if unionSetIn(words, f.Name[:strings.IndexByte(f.Name, '.')]) { - return - } - if variant == "" { - variant = f.Name[:dot] - } - if f.Name[:dot] != variant { - return - } - } add = append(add, "--"+f.Name) if f.Value.Type() != "bool" { add = append(add, placeholder(f)) } }) c.LocalFlags().VisitAll(func(f *pflag.Flag) { - form := f.Annotations[flagutil.UnionNeedsAForm] - if f.Hidden || len(form) == 0 || unionSetIn(slices.Concat(words, add), f.Name) { + if f.Hidden || !needsAForm(f) || unionSetIn(slices.Concat(words, add), f.Name) || flagutil.StoodInFor(c, given, f.Name) { return } - add = append(add, aForm(c, form[0])...) + add = append(add, aForm(c, f.Annotations[flagutil.UnionNeedsAForm][0])...) }) return add } -// aForm is the flag and value that give a union the form variant, its first: -// the variant's first field, so the example takes a plain value where it -// can, or else the variant as JSON. +// flagsIn is the names of the flags words set: --name, --name=value. +func flagsIn(words []string) []string { + var names []string + for _, w := range words { + if name, ok := strings.CutPrefix(w, "--"); ok { + name, _, _ = strings.Cut(name, "=") + names = append(names, name) + } + } + return names +} + +// needsAForm reports whether f is a union that must be given one of its +// forms. It is required, but its forms' flags give it as well as its own. +func needsAForm(f *pflag.Flag) bool { + return len(f.Annotations[flagutil.UnionNeedsAForm]) > 0 +} + +// aForm is the flags and values that give a union the form variant, its +// first: the fields the form requires, or else its first field, so the +// example takes plain values where it can, or else the form as JSON. func aForm(c *cobra.Command, variant string) []string { use := c.Flags().Lookup(variant) if use == nil { return nil } + var fields []string + c.LocalFlags().VisitAll(func(f *pflag.Flag) { + if with := f.Annotations[flagutil.RequiredWithForm]; !f.Hidden && len(with) > 0 && with[0] == variant { + fields = append(fields, "--"+f.Name) + if f.Value.Type() != "bool" { + fields = append(fields, placeholder(f)) + } + } + }) + if len(fields) > 0 { + return fields + } c.LocalFlags().VisitAll(func(f *pflag.Flag) { if use.Name == variant && !f.Hidden && strings.HasPrefix(f.Name, variant+".") && f.Value.Type() != "bool" { use = f @@ -201,8 +233,11 @@ func setIn(words []string, f *pflag.Flag) bool { } // placeholder is the value an example shows for f, in the generator's style. +// A JSON flag gets JSON it takes, written from its type: `` isn't. func placeholder(f *pflag.Flag) string { - switch { + switch json := f.Annotations[flagutil.TakesJSON]; { + case len(json) > 0 && json[0] != "": + return shellQuote(json[0]) case strings.HasPrefix(f.Usage, "Path to file"): return "" case strings.HasSuffix(f.Name, "-id"), strings.HasSuffix(f.Name, "-ids"), diff --git a/internal/cli/examplehelp_test.go b/internal/cli/examplehelp_test.go index 0bbb5c6c..1b736d10 100644 --- a/internal/cli/examplehelp_test.go +++ b/internal/cli/examplehelp_test.go @@ -92,22 +92,29 @@ func TestEveryExampleRunsAsWritten(t *testing.T) { t.Errorf("%s: example %q: %v", c.CommandPath(), line, err) continue } + if err := found.ValidateArgs(found.Flags().Args()); err != nil { // strayargs.go + t.Errorf("%s: example %q: %v", c.CommandPath(), line, err) + continue + } if i == 0 { c.LocalFlags().VisitAll(func(f *pflag.Flag) { - if !isRequired(f) || f.Hidden || f.Changed { + if !isRequired(f) || needsAForm(f) || f.Hidden || f.Changed || flagutil.StoodInFor(c, flagsIn(args), f.Name) { return } - // A union's variants are alternatives: one of them, or - // the union's JSON, is enough. - if base, _, ok := strings.Cut(f.Name, "."); ok && unionSetIn(args, base) { + t.Errorf("%s: example %q leaves out required --%s", c.CommandPath(), line, f.Name) + }) + // A form given through its flags needs each field it requires. + c.LocalFlags().VisitAll(func(f *pflag.Flag) { + with := f.Annotations[flagutil.RequiredWithForm] + if len(with) == 0 || f.Hidden || f.Changed || !formFlagsIn(args, with[0]) { return } - t.Errorf("%s: example %q leaves out required --%s", c.CommandPath(), line, f.Name) + t.Errorf("%s: example %q gives --%s.* but leaves out --%s", c.CommandPath(), line, with[0], f.Name) }) // A union that isn't optional, like a body that is one as a // whole, needs one of its forms. c.LocalFlags().VisitAll(func(f *pflag.Flag) { - if len(f.Annotations[flagutil.UnionNeedsAForm]) > 0 && !f.Hidden && !unionSetIn(args, f.Name) { + if len(f.Annotations[flagutil.UnionNeedsAForm]) > 0 && !f.Hidden && !unionSetIn(args, f.Name) && !flagutil.StoodInFor(c, flagsIn(args), f.Name) { t.Errorf("%s: example %q gives --%s none of its forms", c.CommandPath(), line, f.Name) } }) @@ -121,6 +128,17 @@ func TestEveryExampleRunsAsWritten(t *testing.T) { } } +// formFlagsIn reports whether args give the form through its field flags +// (--form.field), not as JSON. +func formFlagsIn(args []string, form string) bool { + for _, a := range args { + if strings.HasPrefix(a, "--"+form+".") { + return true + } + } + return false +} + func TestFixExample(t *testing.T) { root := &cobra.Command{Use: "vf"} function := &cobra.Command{Use: "function"} diff --git a/internal/cli/exitcode.go b/internal/cli/exitcode.go new file mode 100644 index 00000000..46fd4ec6 --- /dev/null +++ b/internal/cli/exitcode.go @@ -0,0 +1,26 @@ +// This file is not generated by Speakeasy. It is where cmd/vf/main.go gets +// the code the process exits with, and where 'vf --help' lists the codes. +// +// main.go exited 1 for every failure, so a script couldn't tell a usage +// error from a 404, a timeout or a failed test. The code an error carries is +// decided where it is reported (internal/output/exitcode.go); main only +// asks for it. + +package cli + +import ( + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/output" +) + +// ExitCode is the code vf exits with after Execute returns err. +func ExitCode(err error) int { return output.ExitCode(err) } + +// documentExitCodes ends 'vf --help' with the exit codes. Only the root +// lists them: every command shares its usage template, and the table would +// crowd the help of each one. +func documentExitCodes(root *cobra.Command) { + root.SetUsageTemplate(root.UsageTemplate() + + "{{if not .HasParent}}\nExit Codes:\n" + output.ExitCodesHelp + "\n{{end}}") +} diff --git a/internal/cli/exitcode_test.go b/internal/cli/exitcode_test.go new file mode 100644 index 00000000..b743b3ce --- /dev/null +++ b/internal/cli/exitcode_test.go @@ -0,0 +1,87 @@ +// This file is not generated by Speakeasy. It covers exitcode.go: the code vf +// exits with for each kind of failure, and 'vf --help' listing them. + +package cli + +import ( + "bytes" + "errors" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/oauth" + "github.com/voiceflow/cli/internal/output" +) + +// A mistake vf catches before sending anything exits 2; anything it can't +// place exits 1. +func TestLocalErrorsExitWithTheirKindsCode(t *testing.T) { + for _, c := range []struct { + err string + want int + }{ + {"unknown flag: --nosuch", output.ExitUsage}, + {"unknown shorthand flag: 'z' in -z", output.ExitUsage}, + {`unknown command "lsit" for "vf workspace"`, output.ExitUsage}, + {"flag needs an argument: --project-id", output.ExitUsage}, + {`invalid argument "x" for "--take" flag: strconv.ParseInt: parsing "x": invalid syntax`, output.ExitUsage}, + {"missing required flag: --project-id", output.ExitUsage}, + {"invalid value for --action: bad", output.ExitUsage}, + {`invalid --timeout value "soon": time: invalid duration "soon"`, output.ExitUsage}, + {"accepts 1 arg(s), received 0", output.ExitUsage}, + {"requires at least 1 arg(s), only received 0", output.ExitUsage}, + {"failed to parse --body as JSON: unexpected end of JSON input", output.ExitUsage}, + {"failed to read file for --file: open ./nope.txt: no such file or directory", output.ExitUsage}, + {"something odd", output.ExitFailure}, + } { + root := testRoot(t) + root.SetErr(&bytes.Buffer{}) + if got := ExitCode(renderError(root, errors.New(c.err))); got != c.want { + t.Errorf("%q exits %d, want %d", c.err, got, c.want) + } + } +} + +func TestAnEndedSessionExitsAsAuthentication(t *testing.T) { + root := testRoot(t) + root.SetErr(&bytes.Buffer{}) + if got := ExitCode(renderError(root, oauth.ErrSessionEnded)); got != output.ExitAuth { + t.Errorf("exits %d, want %d", got, output.ExitAuth) + } +} + +// What a run's outcome marked an error with survives being rendered. +func TestRenderingKeepsTheCodeAnErrorCarries(t *testing.T) { + root := testRoot(t) + root.SetErr(&bytes.Buffer{}) + err := output.WithExitCode(errors.New("1 of 2 runs did not pass"), output.ExitNotPassed) + if got := ExitCode(renderError(root, err)); got != output.ExitNotPassed { + t.Errorf("exits %d, want %d", got, output.ExitNotPassed) + } +} + +func TestRootHelpListsTheExitCodes(t *testing.T) { + root := testRoot(t) + var out bytes.Buffer + root.SetOut(&out) + root.SetArgs([]string{"--help"}) + if err := root.Execute(); err != nil { + t.Fatal(err) + } + for _, want := range []string{"Exit Codes:", " 2 Usage error", " 4 Not found: HTTP 404", " 6 A test run didn't pass"} { + if !strings.Contains(out.String(), want) { + t.Errorf("vf --help lacks %q:\n%s", want, out.String()) + } + } + + root = testRoot(t) + out.Reset() + root.SetOut(&out) + root.SetArgs([]string{"project", "get", "--help"}) + if err := root.Execute(); err != nil { + t.Fatal(err) + } + if strings.Contains(out.String(), "Exit Codes:") { + t.Errorf("only the root's help lists them:\n%s", out.String()) + } +} diff --git a/internal/cli/flagerrors.go b/internal/cli/flagerrors.go index 0fef3a2c..92cf0a76 100644 --- a/internal/cli/flagerrors.go +++ b/internal/cli/flagerrors.go @@ -6,8 +6,8 @@ // an import cycle. cli.Execute is the first point that has both the resolved // *cobra.Command and permission to import output, so the rendering happens here. // -// In agent mode this reuses output.AgentModeError, which is already the accepted -// envelope for non-API CLI errors (see configure.go and auth.go) and is already +// In agent mode, or with -o json or --jq, this reuses output.AgentModeError, the +// envelope every error has (see output/envelope.go), and is already // asserted by test/errors-teach.test.ts. Human mode keeps the plain multi-line // form, which reads better in a terminal than JSON. @@ -35,7 +35,7 @@ import ( // and can reproduce a secret that happened to be inside it. func renderFlagValueError(cmd *cobra.Command, err error) error { var fve *flagutil.FlagValueError - if !errors.As(err, &fve) || !output.IsAgentMode() { + if !errors.As(err, &fve) || !output.WantsJSONError(cmd) { return err } diff --git a/internal/cli/flaghelp_test.go b/internal/cli/flaghelp_test.go new file mode 100644 index 00000000..3e7930bb --- /dev/null +++ b/internal/cli/flaghelp_test.go @@ -0,0 +1,86 @@ +// This file is not generated by Speakeasy. It covers flagutil/description.go +// over the whole command tree: no flag's help is a placeholder, a generated +// type name or a meaningless default, and the flags every command shares say +// what they are. + +package cli + +import ( + "regexp" + "strings" + "testing" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +// generatedTypeName is a name the generator made from the spec's schema +// names: StableDocumentController_createText_overwrite_enum. +var generatedTypeName = regexp.MustCompile(`\b[A-Z][a-z0-9]+[A-Z][A-Za-z0-9]*_[A-Za-z0-9_]+\b`) + +func TestEveryFlagsHelpSaysSomething(t *testing.T) { + root := testRoot(t) + shared := map[string]string{"project-id": "project", "environment-alias": "environment", "user-id": "user"} + checked := 0 + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + for _, sub := range c.Commands() { + walk(sub) + } + c.LocalFlags().VisitAll(func(f *pflag.Flag) { + if f.Hidden { + return + } + checked++ + where := c.CommandPath() + " --" + f.Name + usage := strings.TrimSpace(strings.ReplaceAll(f.Usage, "[required]", "")) + for _, placeholder := range []string{"string value", "boolean flag", "number value", "integer value"} { + if usage == placeholder { + t.Errorf("%s: %q", where, f.Usage) + } + } + if name := generatedTypeName.FindString(f.Usage); name != "" { + t.Errorf("%s: names the type %s", where, name) + } + if f.DefValue == "null" { + t.Errorf(`%s: (default "null")`, where) + } + if subject, ok := shared[f.Name]; ok && !strings.Contains(strings.ToLower(usage), subject) { + t.Errorf("%s: %q doesn't say what it is", where, f.Usage) + } + }) + } + walk(root) + if checked < 1500 { + t.Errorf("checked only %d flags", checked) + } +} + +func TestSharedFlagsSayWhereTheValueComesFrom(t *testing.T) { + root := testRoot(t) + for _, tc := range []struct { + path []string + flag string + want string + }{ + {[]string{"agent", "update"}, "project-id", "'vf project list'"}, + {[]string{"agent", "update"}, "environment-alias", "'vf environment list'"}, + {[]string{"conversation", "send"}, "user-id", "Any string that names the conversation's user"}, + // The spec gave these the description of a neighbouring field. + {[]string{"agent", "add-tool-message"}, "project-id", "Settings → General"}, + // The spec's own description, which names the environment, stays. + {[]string{"analytics", "query", "call-count"}, "environment-alias", "to filter results by"}, + {[]string{"document", "create-text"}, "overwrite", "true or false"}, + {[]string{"evaluation", "create"}, "body-param.boolean", "The boolean form as JSON"}, + {[]string{"tool", "list"}, "playbook-id", "The playbook's ID."}, + } { + f := find(t, root, tc.path...).Flags().Lookup(tc.flag) + if f == nil || !strings.Contains(f.Usage, tc.want) { + t.Errorf("vf %s --%s: want %q in %v", strings.Join(tc.path, " "), tc.flag, tc.want, f) + } + } + // The flag still sends null when left out; help just doesn't say so. + if f := find(t, root, "environment", "publish").Flags().Lookup("description"); f == nil || f.Value.String() != "null" || f.DefValue != "" { + t.Errorf("environment publish --description: %+v", f) + } +} diff --git a/internal/cli/formhelp_test.go b/internal/cli/formhelp_test.go new file mode 100644 index 00000000..7a76ad26 --- /dev/null +++ b/internal/cli/formhelp_test.go @@ -0,0 +1,153 @@ +// This file is not generated by Speakeasy. It covers how help shows a union's +// forms over the whole command tree (flagutil/unionform.go): a form's own +// fields are required only with that form, not outright. + +package cli + +import ( + "slices" + "strings" + "testing" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/flagutil" +) + +// isFormFlag reports whether f gives one form of a union as JSON: +// --body-param.boolean, beside its --body-param.boolean.* field flags. +func isFormFlag(c *cobra.Command, f *pflag.Flag) bool { + dot := strings.LastIndexByte(f.Name, '.') + return dot > 0 && c.LocalFlags().Lookup(f.Name[:dot]) != nil && strings.Contains(f.Usage, "form as JSON") +} + +func requiredFlagNames(c *cobra.Command) []string { + var names []string + c.LocalFlags().VisitAll(func(f *pflag.Flag) { + if !f.Hidden && isRequired(f) { + names = append(names, f.Name) + } + }) + return names +} + +func TestAFormsFieldsAreRequiredOnlyWithIt(t *testing.T) { + root := testRoot(t) + marked := 0 + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + for _, sub := range c.Commands() { + walk(sub) + } + var forms []string + c.LocalFlags().VisitAll(func(f *pflag.Flag) { + if isFormFlag(c, f) { + forms = append(forms, f.Name) + } + }) + c.LocalFlags().VisitAll(func(f *pflag.Flag) { + where := c.CommandPath() + " --" + f.Name + for _, form := range forms { + if strings.HasPrefix(f.Name, form+".") && isRequired(f) { + t.Errorf("%s: a field of the %s form is listed as required outright", where, form) + } + } + with := f.Annotations[flagutil.RequiredWithForm] + if len(with) == 0 { + return + } + marked++ + if want := "[required with --" + with[0] + ".*]"; !strings.Contains(f.Usage, want) || strings.Contains(f.Usage, "[required]") { + t.Errorf("%s: help %q, want it to say %s", where, f.Usage, want) + } + }) + } + walk(root) + if marked < 50 { + t.Errorf("only %d form fields say which form requires them", marked) + } + + for path, want := range map[string][]string{ + "evaluation create": {"body-param", "project-id"}, + "test turn create": {"body-param", "environment-alias", "project-id"}, + "tool create": {"body-param", "environment-alias", "project-id"}, + } { + c, _, err := root.Find(strings.Fields(path)) + if err != nil { + t.Fatal(err) + } + if got := requiredFlagNames(c); !slices.Equal(got, want) { + t.Errorf("vf %s --help: Required Flags %v, want %v", path, got, want) + } + } + c, _, _ := root.Find([]string{"evaluation", "create"}) + if got := c.Flags().Lookup("body-param.boolean.prompt").Usage; !strings.HasSuffix(got, "[required with --body-param.boolean.*]") { + t.Errorf("evaluation create --body-param.boolean.prompt: %q", got) + } +} + +// A union that can't be left out is listed among the required flags, and its +// help says how it can be given. +func TestAUnionThatNeedsAFormIsRequired(t *testing.T) { + root := testRoot(t) + unions := 0 + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + for _, sub := range c.Commands() { + walk(sub) + } + c.LocalFlags().VisitAll(func(f *pflag.Flag) { + if f.Hidden || !needsAForm(f) { + return + } + unions++ + help := groupedFlagUsages(c.LocalFlags()) + required, _, _ := strings.Cut(help, "Optional Flags:") + if !strings.HasPrefix(help, "Required Flags:") || !strings.Contains(required, "--"+f.Name+" ") { + t.Errorf("%s --help doesn't list --%s under Required Flags", c.CommandPath(), f.Name) + } + if !strings.Contains(f.Usage, "[required") { + t.Errorf("%s --%s: help %q doesn't say it is required", c.CommandPath(), f.Name, f.Usage) + } + }) + } + walk(root) + if unions < 15 { + t.Errorf("checked only %d unions that need a form", unions) + } + + send := find(t, root, "conversation", "send") + if got := requiredFlagNames(send); !slices.Contains(got, "action") { + t.Errorf("vf conversation send --help: Required Flags %v, want --action among them", got) + } + // --text gives the action too, so help says either will do. + if got := send.Flags().Lookup("action").Usage; !strings.HasSuffix(got, " [required, or --text]") { + t.Errorf("conversation send --action: %q, want it to end \" [required, or --text]\"", got) + } + c := find(t, root, "evaluation", "create") + if got, want := c.Flags().Lookup("body-param").Usage, "[required: this, or one form's --body-param.* flags]"; !strings.HasSuffix(got, want) { + t.Errorf("evaluation create --body-param: %q, want it to end %q", got, want) + } +} + +// An example gives a form every field it requires, so it runs as written. +func TestFixExampleGivesAFormItsRequiredFields(t *testing.T) { + root := &cobra.Command{Use: "vf"} + create := &cobra.Command{Use: "create"} + root.AddCommand(create) + create.Flags().String("body-param", "", "") + for _, name := range []string{"user", "user.note", "user.text", "user.enabled", "agent", "agent.text"} { + create.Flags().String("body-param."+name, "", "") + } + _ = create.Flags().SetAnnotation("body-param", flagutil.UnionNeedsAForm, []string{"body-param.user"}) + _ = create.Flags().SetAnnotation("body-param", "speakeasy:required", []string{"true"}) + for _, name := range []string{"body-param.user.text", "body-param.user.enabled"} { + _ = create.Flags().SetAnnotation(name, flagutil.RequiredWithForm, []string{"body-param.user"}) + } + _ = create.Flags().SetAnnotation("body-param.agent.text", flagutil.RequiredWithForm, []string{"body-param.agent"}) + + if got, want := fixExample(create, " vf create"), " vf create --body-param.user.enabled --body-param.user.text "; got != want { + t.Errorf("fixExample\n got %q\nwant %q", got, want) + } +} diff --git a/internal/cli/forms_test.go b/internal/cli/forms_test.go new file mode 100644 index 00000000..21fcb040 --- /dev/null +++ b/internal/cli/forms_test.go @@ -0,0 +1,102 @@ +// This file is not generated by Speakeasy. It covers flagutil/forms.go and +// usage/ownhelp.go across every command: each union form's flag shows its +// JSON, in --help and in --usage. + +package cli + +import ( + "bytes" + "errors" + "strings" + "testing" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/usage" +) + +// Every form's flag shows the form's JSON, and no flag is left saying only +// "StableTestTurnCreateRequest_User variant as JSON". +func TestEveryFormFlagShowsItsJSON(t *testing.T) { + root := testRoot(t) + forms := 0 + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + for _, sub := range c.Commands() { + walk(sub) + } + c.LocalFlags().VisitAll(func(f *pflag.Flag) { + if strings.HasSuffix(f.Usage, "variant as JSON") { + t.Errorf("%s --%s: %s", c.CommandPath(), f.Name, f.Usage) + } + if len(f.Annotations[usage.OwnHelp]) == 0 || !strings.Contains(f.Usage, " form as JSON: ") { + return + } + forms++ + if _, shape, _ := strings.Cut(f.Usage, " form as JSON: "); !strings.HasPrefix(shape, "{") { + t.Errorf("%s --%s: %s", c.CommandPath(), f.Name, f.Usage) + } + }) + } + walk(root) + if forms < 100 { + t.Errorf("found only %d forms", forms) + } + + help := func(path ...string) string { + var buf bytes.Buffer + c := find(t, root, path...) + c.SetOut(&buf) + _ = c.Help() + return strings.Join(strings.Fields(buf.String()), " ") // the flag column's padding varies with the longest flag + } + for _, want := range []string{ + `--body-param.user string The user form as JSON: { testID: string, payload: { response: string, variableStates: string | [{ id: string, variableID: string | null, value: string | null }] } }`, + `JSON value in one of 3 forms, named by its "type": user, agent or simulation.`, + } { + if got := help("test", "turn", "create"); !strings.Contains(got, want) { + t.Errorf("test turn create --help lacks %q:\n%s", want, got) + } + } + if got := help("test", "check", "create"); !strings.Contains(got, `The response form as JSON: { turnID: string, payload: { type: "equal", value: string } | { type: "llm_eval", prompt: string } }`) { + t.Errorf("test check create --help:\n%s", got) + } +} + +// --usage gives the same JSON, for a command and for vf as a whole. +func TestUsageShowsEachFormsJSON(t *testing.T) { + want := `flag "--body-param.user " help="The user form as JSON: { testID: string, payload: { response: string, variableStates: string | [{ id: string, variableID: string | null, value: string | null }] } }"` + for _, args := range [][]string{{"test", "turn", "create", "--usage"}, {"--usage"}} { + root := testRoot(t) + var buf bytes.Buffer + root.SetOut(&buf) + root.SetArgs(args) + if err := root.Execute(); err != nil { + t.Fatal(err) + } + if !strings.Contains(buf.String(), want) || !strings.Contains(buf.String(), `flag "--body-param " help="JSON value in one of 3 forms`) { + t.Errorf("%v lacks the forms' JSON", args) + } + } +} + +// A body missing a field says what the field's form takes, rather than +// pointing at help that doesn't say. +func TestAMissingFieldGivesItsFormsJSON(t *testing.T) { + root := testRoot(t) + create := find(t, root, "test", "turn", "create") + var stderr bytes.Buffer + create.SetErr(&stderr) + cause := errors.New("error serializing request body: json: error calling MarshalJSON for type *components.StableTestTurnCreateRequest: json: error calling MarshalJSON for type *components.StableTestTurnCreateRequestUser: json: error calling MarshalJSON for type *components.StableTestTurnCreateRequestPayload1: json: error calling MarshalJSON for type *components.StableTestTurnCreateRequestVariableStates1: could not marshal union type StableTestTurnCreateRequestVariableStates1: all fields are null") + _ = output.Error(create, cause) + for _, want := range []string{ + "--body-param.user takes the user form as JSON: { testID: string, payload: { response: string, variableStates: string |", + "'vf test turn create --help' shows every form's fields", + } { + if !strings.Contains(stderr.String(), want) { + t.Errorf("missing %q in:\n%s", want, stderr.String()) + } + } +} diff --git a/internal/cli/jqfail_test.go b/internal/cli/jqfail_test.go new file mode 100644 index 00000000..b006e49c --- /dev/null +++ b/internal/cli/jqfail_test.go @@ -0,0 +1,130 @@ +// This file is not generated by Speakeasy. It covers output/jqfail.go and +// the --jq check in output/validate.go: a filter that can't run fails before +// anything is sent, and one that fails on the response says the request +// succeeded. + +package cli + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/output" +) + +const jqVariable = `{"variable":{"id":"6b0d-variable","name":"jq_probe","color":"#515A63"}}` + +var createVariable = []string{"variable", "create", "-p", "p1", "-e", "main", "--name", "jq_probe", "-c", "#515A63"} + +// agent-errors:F1: `.variable.id.foo` on a create exited 1 with a bare "jq +// error", and the variable had been created. Now the error says the request +// went through, not to run it again, and gives the new ID. +func TestAJqThatFailsAfterAWriteSaysTheWriteHappened(t *testing.T) { + stdout, stderr, err := runAgainstStdout(t, false, jqVariable, append(createVariable, "--jq", ".variable.id.foo")...) + if err == nil { + t.Fatal("the asked-for output wasn't printed, so the command should still fail") + } + if stdout != "" { + t.Errorf("stdout should hold only what --jq printed, got %q", stdout) + } + // --jq makes the error the JSON envelope, outside agent mode too. + for _, want := range []string{ + "--jq failed on the response: expected an object but got: string", + "The request itself succeeded (HTTP 201)", + "went through", + "Its id: 6b0d-variable", + "Don't run it again", + `"request_succeeded": true`, + } { + if !strings.Contains(stderr, want) { + t.Errorf("stderr lacks %q:\n%s", want, stderr) + } + } +} + +// In agent mode the envelope says so in fields, and carries the response. +func TestAJqThatFailsAfterAWriteGivesAnAgentTheResponse(t *testing.T) { + _, stderr, err := runAgainstStdout(t, true, jqVariable, append(createVariable, "--jq", ".variable.id.foo")...) + if err == nil { + t.Fatal("want an error") + } + var envelope struct { + ErrorType string `json:"error_type"` + RequestSucceeded bool `json:"request_succeeded"` + ID string `json:"id"` + Response struct { + Variable struct { + ID string `json:"id"` + } `json:"variable"` + } `json:"response"` + } + if jsonErr := json.Unmarshal([]byte(stderr), &envelope); jsonErr != nil { + t.Fatalf("stderr isn't one JSON object: %v\n%s", jsonErr, stderr) + } + if envelope.ErrorType != "jq_error" || !envelope.RequestSucceeded || envelope.ID != "6b0d-variable" || envelope.Response.Variable.ID != "6b0d-variable" { + t.Errorf("got %+v", envelope) + } +} + +// A write whose response has no ID gives the response itself. +func TestAJqThatFailsAfterAWriteWithoutAnIDShowsTheResponse(t *testing.T) { + _, stderr, err := runAgainstStdout(t, false, `{"message":"Project updated"}`, "project", "update", "-p", "p1", "--name", "x", "--jq", ".message.foo") + var envelope struct { + Response struct { + Message string `json:"message"` + } `json:"response"` + } + if err == nil || !strings.Contains(stderr, "went through") || json.Unmarshal([]byte(stderr), &envelope) != nil || envelope.Response.Message != "Project updated" { + t.Errorf("got %v:\n%s", err, stderr) + } +} + +// A read can be run again, so it says only that the filter failed. +func TestAJqThatFailsAfterAReadSaysOnlyTheFilterFailed(t *testing.T) { + _, stderr, err := runAgainstStdout(t, false, jqProject, "project", "get", "-p", "p1", "--jq", ".project.id.foo") + if err == nil || !strings.Contains(stderr, "The request itself succeeded (HTTP 200); only the filter failed.") || + strings.Contains(stderr, "run it again") || strings.Contains(stderr, `"response"`) { + t.Errorf("got %v:\n%s", err, stderr) + } +} + +// A filter that can't compile fails before the command runs at all: before +// a form, a picker's list, a draft's compile or the command's own request. +func TestAJqThatCannotRunFailsBeforeTheCommandRuns(t *testing.T) { + isolate(t) + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + ran := false + root.AddCommand(&cobra.Command{Use: "probe", RunE: func(*cobra.Command, []string) error { ran = true; return nil }}) + for _, jq := range []string{".[", ".variable | no_such_function"} { + root.SetArgs([]string{"probe", "--jq", jq, "--agent-mode=false"}) + _, err := root.ExecuteC() + if err == nil || !strings.HasPrefix(err.Error(), "invalid --jq expression") || ran { + t.Errorf("--jq %s: ran=%v, err %v", jq, ran, err) + } + } +} + +// agent-ci R4: `--jq 'error("no id")'` exited 5, gojq's code for error(), +// which vf's table calls "timed out". A failed filter exits 1, in the +// envelope as well. +func TestAJqErrorExitsOneNotTimedOut(t *testing.T) { + _, stderr, err := runAgainstStdout(t, true, jqVariable, append(createVariable, "--jq", `error("no id")`)...) + if err == nil { + t.Fatal("want an error") + } + if code := output.ExitCode(err); code != output.ExitFailure { + t.Errorf("exit code %d, want %d", code, output.ExitFailure) + } + var envelope struct { + ExitCode int `json:"exit_code"` + } + if jsonErr := json.Unmarshal([]byte(stderr), &envelope); jsonErr != nil || envelope.ExitCode != output.ExitFailure { + t.Errorf("envelope exit_code %d (%v):\n%s", envelope.ExitCode, jsonErr, stderr) + } +} diff --git a/internal/cli/jqraw_test.go b/internal/cli/jqraw_test.go new file mode 100644 index 00000000..19fd3321 --- /dev/null +++ b/internal/cli/jqraw_test.go @@ -0,0 +1,114 @@ +// This file is not generated by Speakeasy. It covers output/jqraw.go end to +// end: a --jq string prints raw, in every output format and in agent mode. + +package cli + +import ( + "bytes" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +const jqProject = `{"project":{"id":"6b0d-project","name":"Coffee","ownerID":42,"isPrivate":false,"notes":"two\nlines"}}` + +// runAgainstStdout is runAgainst with stdout and stderr apart, and agent +// mode on or off. +func runAgainstStdout(t *testing.T, agent bool, body string, args ...string) (stdout, stderr string, err error) { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.Method == http.MethodPost { + w.WriteHeader(http.StatusCreated) + } + w.Write([]byte(body)) + })) + t.Cleanup(srv.Close) + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("VF_SERVER_URL", srv.URL) + t.Setenv("HOME", t.TempDir()) + output.ResetAgentMode() + t.Cleanup(output.ResetAgentMode) + + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + var out, errOut bytes.Buffer + root.SetOut(&out) + root.SetErr(&errOut) + root.SetIn(strings.NewReader("")) + mode := "--agent-mode=false" + if agent { + mode = "--agent-mode=true" + } + root.SetArgs(append(args, mode, "--no-interactive")) + _, err = root.ExecuteC() + return out.String(), errOut.String(), err +} + +// ID=$(vf … --jq .project.id) captures the ID itself, not "the ID" in +// quotes, whatever -o says and in agent mode too. +func TestJqPrintsAStringRaw(t *testing.T) { + for _, agent := range []bool{false, true} { + for _, format := range [][]string{nil, {"-o", "json"}, {"-o", "yaml"}, {"-o", "table"}, {"-o", "toon"}} { + args := append([]string{"project", "get", "-p", "p1", "--jq", ".project.id"}, format...) + stdout, stderr, err := runAgainstStdout(t, agent, jqProject, args...) + if err != nil || stdout != "6b0d-project\n" { + t.Errorf("agent=%v %v: printed %q (stderr %q, err %v), want the bare ID", agent, format, stdout, stderr, err) + } + } + } +} + +// A string with newlines prints them, as jq -r does; several strings print +// one per line. +func TestJqPrintsEachStringOnItsOwnLine(t *testing.T) { + stdout, _, err := runAgainstStdout(t, false, jqProject, "project", "get", "-p", "p1", "--jq", ".project.notes, .project.name") + if err != nil || stdout != "two\nlines\nCoffee\n" { + t.Errorf("printed %q (err %v)", stdout, err) + } +} + +// Anything but a string is still JSON, so it can be parsed; tojson keeps a +// string quoted. +func TestJqPrintsEverythingElseAsJSON(t *testing.T) { + for jq, want := range map[string]string{ + ".project.ownerID": "42\n", + ".project.isPrivate": "false\n", + ".project.missing": "null\n", + "[.project.id]": "[\n \"6b0d-project\"\n]\n", + ".project | {id}": "{\n \"id\": \"6b0d-project\"\n}\n", + ".project.id | tojson": "\"6b0d-project\"\n", + ".project.notes | @json": "\"two\\nlines\"\n", + `.project.name | ascii_downcase`: "coffee\n", + } { + stdout, _, err := runAgainstStdout(t, false, jqProject, "project", "get", "-p", "p1", "--jq", jq, "--color", "never") + if err != nil || stdout != want { + t.Errorf("--jq %s printed %q (err %v), want %q", jq, stdout, err, want) + } + } +} + +// --jq's help says how it prints and that it overrides -o. +func TestJqHelpSaysStringsPrintRawAndItOverridesOutputFormat(t *testing.T) { + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + usage := root.PersistentFlags().Lookup("jq").Usage + for _, want := range []string{"raw", "JSON", "-o"} { + if !strings.Contains(usage, want) { + t.Errorf("--jq's help %q doesn't mention %q", usage, want) + } + } + + // --usage carries its own copy of the help, for agents. + stdout, _, err := runAgainstStdout(t, true, "{}", "--usage") + if err != nil || !strings.Contains(stdout, `flag "-q --jq " help="`+usage+`"`) { + t.Errorf("--usage doesn't give --jq's help (err %v)", err) + } +} diff --git a/internal/cli/jsonhints_test.go b/internal/cli/jsonhints_test.go new file mode 100644 index 00000000..7342066f --- /dev/null +++ b/internal/cli/jsonhints_test.go @@ -0,0 +1,135 @@ +// This file is not generated by Speakeasy. It covers flagutil/jsonexample.go +// across every JSON flag: the hints on a value the flag rejected hold, and +// help examples give JSON flags JSON. + +package cli + +import ( + "bytes" + "regexp" + "strings" + "testing" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/flagutil" +) + +// Every JSON flag that rejects a value says what it takes. The example it +// gives is one vf takes, with no key the SDK drops. Null is offered only on +// a flag that isn't required, and there it is sent as null. And a help +// example that sets a JSON flag runs. +func TestEveryJSONFlagsHintsHold(t *testing.T) { + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("VF_SERVER_URL", "http://127.0.0.1:1") + root := testRoot(t) + type jsonFlag struct { + base []string + flag *pflag.Flag + required bool + } + var flags []jsonFlag + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + for _, sub := range c.Commands() { + walk(sub) + } + line, _, _ := strings.Cut(strings.TrimSpace(c.Example), "\n") + if !strings.HasPrefix(line, "vf ") { + return + } + words := shellWords(t, line)[1:] + ownJSON := false + c.LocalFlags().VisitAll(func(f *pflag.Flag) { + if len(f.Annotations[flagutil.TakesJSON]) == 0 || f.Hidden { + return + } + // The example's own value for the flag is left out. + var base []string + for i := 0; i < len(words); i++ { + if words[i] == "--"+f.Name || (f.Shorthand != "" && words[i] == "-"+f.Shorthand) { + ownJSON = true + i++ + continue + } + base = append(base, words[i]) + } + flags = append(flags, jsonFlag{append(base, "--agent-mode=false"), f, isRequired(f)}) + }) + if ownJSON { + out := dryRunErr(t, append(words, "--agent-mode=false")) + if strings.Contains(out, "invalid value") || !strings.Contains(out, "Network call skipped") { + t.Errorf("%s: its help example fails:\n%s", c.CommandPath(), out) + } + } + } + walk(root) + if len(flags) < 100 { + t.Fatalf("found only %d JSON flags", len(flags)) + } + + exampleRE := regexp.MustCompile(`for example: --\S+ '(.+)'`) + rejected, examples := 0, 0 + for _, jf := range flags { + name := strings.Join(jf.base[:len(jf.base)-1], " ") + " --" + jf.flag.Name + out := dryRunErr(t, append(jf.base, "--"+jf.flag.Name, "[vf not json")) + if !strings.Contains(out, "invalid value for --"+jf.flag.Name) { + continue // a flag that takes plain text as well + } + rejected++ + if strings.Contains(out, `{"key":"value"}`) { + t.Errorf("%s gives a made-up example:\n%s", name, out) + } + if strings.Contains(out, "pass null") { + if jf.required { + t.Errorf("%s is required, yet offers null:\n%s", name, out) + } + sent := dryRunErr(t, append(jf.base, "--"+jf.flag.Name, "null")) + if _, body, _ := strings.Cut(sent, "Body:"); !strings.Contains(body, ": null") { + t.Errorf("%s offers null, but null isn't sent:\n%s", name, sent) + } + } + m := exampleRE.FindStringSubmatch(out) + if m == nil { + t.Logf("no example for %s:\n%s", name, out) + continue + } + examples++ + retry := dryRunErr(t, append(jf.base, "--"+jf.flag.Name, m[1])) + if strings.Contains(retry, "invalid value") || strings.Contains(retry, "weren't sent") || !strings.Contains(retry, "Network call skipped") { + t.Errorf("%s: its own example %s fails:\n%s", name, m[1], retry) + } + } + t.Logf("%d JSON flags, %d reject a value that isn't JSON, %d of those give an example", len(flags), rejected, examples) + if rejected < 100 || examples < rejected*9/10 { + t.Errorf("%d JSON flags, %d reject a value that isn't JSON, only %d of those give an example", len(flags), rejected, examples) + } +} + +// The traffic split's help example names environments, and its shares add +// up to 100, as the API requires. +func TestTrafficSplitExampleNamesEnvironments(t *testing.T) { + c := find(t, testRoot(t), "environment", "update-traffic-split") + if !strings.Contains(c.Example, `--traffic '{"production":90,"staging":10}'`) { + t.Errorf("example: %s", c.Example) + } +} + +// dryRunErr runs args as a dry run, and gives what it wrote and the error +// it ended with, as vf prints it. +func dryRunErr(t *testing.T, args []string) string { + t.Helper() + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + var buf bytes.Buffer + root.SetOut(&buf) + root.SetErr(&buf) + root.SetArgs(append(args, "--dry-run", "--no-interactive")) + if err := root.Execute(); err != nil { + buf.WriteString("\n" + err.Error()) + } + return buf.String() +} diff --git a/internal/cli/merge.go b/internal/cli/merge.go new file mode 100644 index 00000000..bc00a7dc --- /dev/null +++ b/internal/cli/merge.go @@ -0,0 +1,73 @@ +// This file is not generated by Speakeasy. It says what `vf environment +// merge` really does, and has it ask first at a terminal, as a delete does +// (confirm.go). +// +// Its help said "Merge one environment into another." To a git user, a merge +// changes a branch. This one replaces the target's live version, normally +// Main's, with the source's live version, at once and for all its traffic. +// The round-3 sweep's release manager merged Staging and found Main already +// answering with Staging's behaviour, with no question asked and nothing in +// the help to warn them. The API spec says it plainly; the help now does too. + +package cli + +import ( + "encoding/json" + "net/http" + + "github.com/spf13/cobra" +) + +const mergeLong = `Make one environment's live version live in another, normally main. + +The merge takes effect at once, with no publish step: everything the target +serves switches to the source's live version. That is what the source last +published, not its draft, so publish the source first. Anything published to +the target since the source was cloned from it is replaced. The target's +previous version stays in its version history. + +At a terminal, vf asks before it merges; --yes skips the question. +--remove-source-environment also deletes the source after the merge.` + +const mergeYesHelp = "Merge without asking first. vf asks only at a terminal: scripts, CI and agents never wait for an answer." + +// isMerge is whether c is `vf environment merge`. +func isMerge(c *cobra.Command) bool { + return c.Name() == "merge" && c.HasParent() && c.Parent().Name() == "environment" +} + +// mergeQuestion says what goes live where: "Merge staging into main?". +// The aliases come from the request itself, so --body counts too. +func mergeQuestion(cmd *cobra.Command, req *http.Request) (title, note string) { + var body struct { + Source string `json:"sourceEnvironmentAlias"` + Target string `json:"targetEnvironmentAlias"` + Remove bool `json:"removeSourceEnvironment"` + } + if req.GetBody != nil { + if r, err := req.GetBody(); err == nil { + _ = json.NewDecoder(r).Decode(&body) + _ = r.Close() + } + } + if body.Source == "" { + body.Source = flagValue(cmd, "source-environment-alias") + } + if body.Target == "" { + body.Target = flagValue(cmd, "target-environment-alias") + } + title = "Merge " + body.Source + " into " + body.Target + "?" + note = body.Source + "'s live version goes live on " + body.Target + " now, for all of " + + body.Target + "'s traffic. Its draft isn't included." + if body.Remove { + note += " Then " + body.Source + " is deleted." + } + return title, note +} + +func flagValue(cmd *cobra.Command, name string) string { + if f := cmd.Flags().Lookup(name); f != nil { + return f.Value.String() + } + return "" +} diff --git a/internal/cli/merge_test.go b/internal/cli/merge_test.go new file mode 100644 index 00000000..9ea03b69 --- /dev/null +++ b/internal/cli/merge_test.go @@ -0,0 +1,91 @@ +// This file is not generated by Speakeasy. It covers merge.go: `vf +// environment merge` says in its help that it goes live at once, and asks +// first at a terminal, naming the source and the target. + +package cli + +import ( + "context" + "errors" + "slices" + "strings" + "testing" +) + +func TestMergeHelpSaysItGoesLive(t *testing.T) { + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + merge, _, err := root.Find([]string{"environment", "merge"}) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{"live version live in another, normally main", "takes effect at once", "not its draft, so publish the source first", "--yes"} { + if !strings.Contains(merge.Long, want) { + t.Errorf("merge help should say %q:\n%s", want, merge.Long) + } + } + if first, _, _ := strings.Cut(merge.Long, "\n"); len(first) > 80 { + t.Errorf("the form's header shows the first line alone, so it should be a short sentence: %q", first) + } + if f := merge.Flags().Lookup("yes"); f == nil || f.Shorthand != "y" || !strings.HasPrefix(f.Usage, "Merge without asking") { + t.Errorf("merge should take -y/--yes: %+v", f) + } +} + +func TestMergeAsksOnlyWhenSomeoneCanAnswer(t *testing.T) { + args := []string{"environment", "merge", "-p", "p1", "-s", "staging", "-t", "main"} + sent := []string{"PUT /v1/stable/environment/merge"} + for _, tc := range []struct { + name string + terminal bool + args []string + asks bool + sends []string + }{ + {"at a terminal", true, nil, true, nil}, + {"--yes", true, []string{"--yes"}, false, sent}, + {"--dry-run", true, []string{"--dry-run"}, false, nil}, + {"agent mode", true, []string{"--agent-mode"}, false, sent}, + {"not at a terminal", false, nil, false, sent}, + } { + t.Run(tc.name, func(t *testing.T) { + asked := answering(t, tc.terminal, false) + srv, requests := recordingAPI(t) + out, err := runAt(t, srv, append(slices.Clone(args), tc.args...)...) + if tc.asks { + want := []string{"Merge staging into main? staging's live version goes live on main now, for all of main's traffic. Its draft isn't included."} + if !slices.Equal(*asked, want) { + t.Errorf("asked %q, want %q", *asked, want) + } + if !errors.Is(err, context.Canceled) { + t.Errorf("No should cancel, got %v\n%s", err, out) + } + } else if len(*asked) != 0 || err != nil { + t.Errorf("should run without asking: asked %q, err %v\n%s", *asked, err, out) + } + if got := requests(); !slices.Equal(got, tc.sends) { + t.Errorf("sent %q, want %q", got, tc.sends) + } + }) + } +} + +// The question reads what is about to be sent, so a body given whole names +// the same environments, and says when the source goes too. +func TestTheMergeQuestionReadsTheRequest(t *testing.T) { + asked := answering(t, true, true) + srv, requests := recordingAPI(t) + body := `{"sourceEnvironmentAlias":"dev","targetEnvironmentAlias":"main","removeSourceEnvironment":true}` + out, err := runAt(t, srv, "environment", "merge", "-p", "p1", "--body", body) + if err != nil { + t.Fatalf("%v\n%s", err, out) + } + if len(*asked) != 1 || !strings.HasPrefix((*asked)[0], "Merge dev into main? ") || !strings.HasSuffix((*asked)[0], "Then dev is deleted.") { + t.Errorf("asked %q", *asked) + } + if got := requests(); len(got) != 1 { + t.Errorf("Yes should send the merge, sent %q", got) + } +} diff --git a/internal/cli/missingflags.go b/internal/cli/missingflags.go new file mode 100644 index 00000000..8661fd70 --- /dev/null +++ b/internal/cli/missingflags.go @@ -0,0 +1,164 @@ +// This file is not generated by Speakeasy. It explains a command run without +// some of its required flags: all of them in one error, where their values +// come from, and the command line that gives them. +// +// vf named one missing flag per run, so a command missing three took three +// runs to learn of them, and the fix it showed dropped the flags already +// given: `vf conversation send -u x` said "Pass it: `vf conversation send +// --project-id `", without -u, and named --environment-alias only +// on the next run. + +package cli + +import ( + "regexp" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/interactive" + "github.com/voiceflow/cli/internal/output" +) + +// explainMissingFlags says which required flags cmd was run without, for an +// ID where its values are listed, at a terminal that a picker offers them, +// and the whole command line with them added. +func explainMissingFlags(cmd *cobra.Command, flags []string) output.Explanation { + names := make([]string, len(flags)) + for i, f := range flags { + names[i] = "--" + f + if stand := flagutil.StandInFor(cmd, f); stand != "" { + names[i] = "--" + stand + " (or --" + f + ")" // standin.go: `send --text` gives the action + } + } + x := output.Explanation{ + Type: "missing_flag", + Title: cmd.CommandPath() + " needs " + andList(names), + } + switch { + case output.IsAgentMode(): + x.Why = []string{"vf doesn't ask for missing values in agent mode."} + case func() bool { v, _ := flagutil.GetBoolFlag(cmd, "no-interactive"); return v }(): + x.Why = []string{"--no-interactive is set, so vf didn't ask for " + map[bool]string{true: "them", false: "it"}[len(flags) > 1] + "."} + case !interactive.IsInteractive(cmd): + x.Why = []string{"vf asks for missing values only at a terminal, and this isn't one."} + } + + var pickers []string + for i, f := range flags { + if list := listCommandFor(cmd, f); list != "" { + takes := "it takes" + if len(flags) > 1 { + takes = names[i] + " takes" + } + x.Next = append(x.Next, "`"+list+"` shows the values "+takes) + } + if interactive.HasPicker(f) { + pickers = append(pickers, names[i]) + } + } + pass := "Pass it: `" + if len(flags) > 1 { + pass = "Pass them: `" + } + x.Next = append(x.Next, pass+commandLineWith(cmd, flags)+"`") + + for _, f := range flags { + if body, ok := flagutil.StdinLeftUnread(cmd, f); ok { + it := "it's" + if len(flags) > 1 { + it = "they're" + } + x.Why = append(x.Why, "Body flags were given, so vf didn't read stdin.") + x.Next = append([]string{"If " + it + " in the body on stdin, add --" + body + " - to read it: the flags still win"}, x.Next...) + break + } + } + if len(pickers) > 0 && !output.IsAgentMode() && !interactive.IsInteractive(cmd) { + what := "it" + if len(flags) > 1 { + what = andList(pickers) + } + x.Next = append(x.Next, "At a terminal, without --no-interactive, vf lets you pick "+what+" from a list") + } + + // A program reading the JSON gets the flags as a list, too. + if output.WantsJSONError(cmd) { + for _, f := range flags { + msg := "required" + if stand := flagutil.StandInFor(cmd, f); stand != "" { + msg = "required, or --" + stand + } + x.Details = append(x.Details, output.FieldError{Flag: "--" + f, Message: msg}) + } + } + return x +} + +// commandLineWith is the command line that runs cmd with the flags it was +// given and the missing ones added, each as : vf conversation send +// --user-id x --project-id . Global flags are left out. +func commandLineWith(cmd *cobra.Command, missing []string) string { + words := []string{cmd.CommandPath()} + cmd.LocalFlags().VisitAll(func(f *pflag.Flag) { + if f.Changed { + words = append(words, givenFlag(f)...) + } + }) + for _, name := range missing { + if stand := flagutil.StandInFor(cmd, name); stand != "" { + name = stand // the simpler way to give it + } + words = append(words, "--"+name, "") + } + return strings.Join(words, " ") +} + +// givenFlag is f as it would be written again on a command line. A secret +// is not repeated. +func givenFlag(f *pflag.Flag) []string { + name := "--" + f.Name + if f.Value.Type() == "bool" { + if f.Value.String() == "true" { + return []string{name} + } + return []string{name + "=false"} + } + if interactive.IsSecretFlag(f.Name, f.Usage) { + return []string{name, ""} + } + values := []string{f.Value.String()} + if s, ok := f.Value.(pflag.SliceValue); ok { + values = s.GetSlice() + } + var words []string + for _, v := range values { + words = append(words, name, shellWord(v)) + } + return words +} + +var plainWord = regexp.MustCompile(`^[A-Za-z0-9_./:@%+=,-]+$`) + +// shellWord is v as one word for a shell: as it is when it can be, in double +// quotes otherwise. A long or multi-line value, a prompt or a body, would +// bury the line, so it is . +func shellWord(v string) string { + switch { + case len(v) > 60 || strings.ContainsAny(v, "\n`"): + return "" + case plainWord.MatchString(v): + return v + } + return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`, `$`, `\$`).Replace(v) + `"` +} + +// andList is "--a", "--a and --b", or "--a, --b and --c". +func andList(items []string) string { + if len(items) < 2 { + return strings.Join(items, "") + } + return strings.Join(items[:len(items)-1], ", ") + " and " + items[len(items)-1] +} diff --git a/internal/cli/missingflags_test.go b/internal/cli/missingflags_test.go new file mode 100644 index 00000000..c5630a73 --- /dev/null +++ b/internal/cli/missingflags_test.go @@ -0,0 +1,107 @@ +// This file is not generated by Speakeasy. It covers missingflags.go: a +// command run without several required flags names them all in one error, +// with one command line that gives them. + +package cli + +import ( + "strings" + "testing" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/output" +) + +// `vf variable create -p p1 -n "two words"` is missing two flags, and one run +// names both, and the command line keeps the flags already given. +func TestEveryMissingFlagIsNamedInOneRun(t *testing.T) { + x := runWithStdin(t, "", "variable", "create", "-p", "p1", "-n", "two words") + if x.Type != "missing_flag" { + t.Fatalf("type = %q:\n%s", x.Type, explained(x)) + } + all := explained(x) + for _, want := range []string{ + "vf variable create needs --environment-alias and --color-param", + "--no-interactive is set, so vf didn't ask for them.", + "`vf environment list` shows the values --environment-alias takes", + "Pass them: `vf variable create --name \"two words\" --project-id p1 --environment-alias --color-param `", + } { + if !strings.Contains(all, want) { + t.Errorf("missing %q in:\n%s", want, all) + } + } + if n := strings.Count(all, "Pass "); n != 1 { + t.Errorf("want one command line, got %d:\n%s", n, all) + } +} + +// In JSON the missing flags are a list, too. +func TestMissingFlagsAreDetailsInJSON(t *testing.T) { + root := testRoot(t) + t.Setenv("FORCE_AGENT_MODE", "1") + output.InitAgentMode(root) + create := find(t, root, "variable", "create") + x := explainMissingFlags(create, []string{"environment-alias", "color-param"}) + var flags []string + for _, d := range x.Details { + flags = append(flags, d.Flag) + } + if strings.Join(flags, " ") != "--environment-alias --color-param" { + t.Errorf("details = %+v", x.Details) + } +} + +// The command line repeats what was given so it can be run again, but no +// secret, and no value long enough to bury it. +func TestTheCommandLineRepeatsWhatWasGiven(t *testing.T) { + cmd := &cobra.Command{Use: "send"} + cmd.Flags().String("user-id", "", "") + cmd.Flags().String("api-key", "", "") + cmd.Flags().String("prompt", "", "") + cmd.Flags().String("note", "", "") + cmd.Flags().StringSlice("tag", nil, "") + cmd.Flags().Bool("force", false, "") + cmd.Flags().Bool("wait", true, "") + if err := cmd.ParseFlags([]string{ + "--user-id", "u-1", "--api-key", "sk_live_x", "--prompt", strings.Repeat("long ", 30), + "--note", `say "$HOME"`, "--tag", "a", "--tag", "b", "--force", "--wait=false", + }); err != nil { + t.Fatal(err) + } + got := commandLineWith(cmd, []string{"action"}) + want := `send --api-key --force --note "say \"\$HOME\"" --prompt --tag a --tag b --user-id u-1 --wait=false --action ` + if got != want { + t.Errorf("got %s\nwant %s", got, want) + } + if strings.Contains(got, "sk_live") { + t.Error("a secret was repeated") + } +} + +func TestAndList(t *testing.T) { + for want, items := range map[string][]string{ + "--a": {"--a"}, + "--a and --b": {"--a", "--b"}, + "--a, --b and --c": {"--a", "--b", "--c"}, + } { + if got := andList(items); got != want { + t.Errorf("andList(%v) = %q", items, got) + } + } +} + +// `conversation send` without an action names --text first, the plain way to +// give one, and its command line uses it. +func TestAMissingActionNamesText(t *testing.T) { + x := runWithStdin(t, "", "conversation", "send", "-p", "p1", "-e", "main", "-v", "draft") + all := explained(x) + for _, want := range []string{ + "vf conversation send needs --user-id and --text (or --action)", + "--user-id --text `", + } { + if !strings.Contains(all, want) { + t.Errorf("missing %q in:\n%s", want, all) + } + } +} diff --git a/internal/cli/namehelp.go b/internal/cli/namehelp.go new file mode 100644 index 00000000..6414be3e --- /dev/null +++ b/internal/cli/namehelp.go @@ -0,0 +1,46 @@ +// This file is not generated by Speakeasy. It has help name vf's commands and +// flags where the spec's descriptions name MCP tools and API fields. +// +// The descriptions are written for the MCP server and the API too, so +// `event create --workflow-id` said "as a workflow ID from +// voiceflow_workflow.list", `test run wait --run-ids` "the IDs create_run or +// create_many_runs returned", and `secret set-value -e` "Requires +// 'versionVariant'". Help now says 'vf workflow list', 'vf test run create' +// and --version-variant (flagutil/apinames.go, which also rewrites the +// server's messages). Done once at startup, over the whole tree, it covers the +// next description the spec adds. + +package cli + +import ( + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/usage" +) + +// nameVFCommandsInHelp rewrites the MCP tool and API field names in the help +// of every command under root as vf commands and flags. +func nameVFCommandsInHelp(root *cobra.Command) { + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + if c != root { + c.Short = flagutil.VFNamesInHelp(c, "", c.Short) + c.Long = flagutil.VFNamesInHelp(c, "", c.Long) + c.LocalFlags().VisitAll(func(f *pflag.Flag) { + // A union's help from its types (flagutil/forms.go) names + // JSON keys and the values a form is named by, as typed: + // "kind": goToBlock is not --action.go-to-block. + if len(f.Annotations[usage.OwnHelp]) > 0 { + return + } + f.Usage = flagutil.VFNamesInHelp(c, f.Name, f.Usage) + }) + } + for _, sub := range c.Commands() { + walk(sub) + } + } + walk(root) +} diff --git a/internal/cli/namehelp_test.go b/internal/cli/namehelp_test.go new file mode 100644 index 00000000..0a5210d3 --- /dev/null +++ b/internal/cli/namehelp_test.go @@ -0,0 +1,87 @@ +// This file is not generated by Speakeasy. It covers namehelp.go: no help +// names an MCP tool, or quotes an API field where the command has a flag. + +package cli + +import ( + "regexp" + "strings" + "testing" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +var ( + mcpToolName = regexp.MustCompile(`\bvoiceflow_[a-z_]+(?:\.[a-z_]+)?`) + quotedField = regexp.MustCompile("['`]([a-z][a-z0-9]*(?:[A-Z][A-Za-z0-9]*)+)['`]") + camelToKebab = strings.NewReplacer("IDs", "-ids", "ID", "-id", "URL", "-url") +) + +func TestHelpNamesVFCommandsAndFlags(t *testing.T) { + root := testRoot(t) + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + for _, sub := range c.Commands() { + walk(sub) + } + check := func(where, text string) { + if name := mcpToolName.FindString(text); name != "" { + t.Errorf("%s names the MCP tool %s", where, name) + } + for _, m := range quotedField.FindAllStringSubmatch(text, -1) { + name := strings.ToLower(regexp.MustCompile(`([a-z0-9])([A-Z])`).ReplaceAllString(camelToKebab.Replace(m[1]), "$1-$2")) + c.LocalFlags().VisitAll(func(f *pflag.Flag) { + if f.Name == name { + t.Errorf("%s says %s for --%s", where, m[0], f.Name) + } + }) + } + } + check(c.CommandPath(), c.Long) + c.LocalFlags().VisitAll(func(f *pflag.Flag) { check(c.CommandPath()+" --"+f.Name, f.Usage) }) + } + walk(root) + + for _, tc := range []struct { + path []string + flag, want string + }{ + {[]string{"test", "run", "wait"}, "run-ids", "the IDs 'vf test run create'"}, + {[]string{"event", "create"}, "workflow-id", "a workflow ID from 'vf workflow list'"}, + {[]string{"secret", "set-value"}, "environment-alias", "Requires --version-variant"}, + {[]string{"agent", "add-tool-message"}, "tool-id", "Exactly one of --tool-id and --native-tool"}, + {[]string{"workflow", "add-branch"}, "body-param.buttons.to", "in 'vf workflow add-blocks', a block key"}, + } { + f := find(t, root, tc.path...).Flags().Lookup(tc.flag) + if f == nil || !strings.Contains(f.Usage, tc.want) { + t.Errorf("vf %s --%s: want %q in %v", strings.Join(tc.path, " "), tc.flag, tc.want, f) + } + } +} + +// round-4 fix-verifier F2: the rename turned the kinds a form is named by, +// goToBlock and callForward, into flag names, so the value to type in the +// JSON was nowhere in help. A union's help from its types is left alone. +func TestAFormsKindIsNotRenamed(t *testing.T) { + root := testRoot(t) + for _, tc := range []struct { + path []string + flag string + kinds []string + }{ + {[]string{"workflow", "replace-action"}, "action", []string{"goToBlock", "callForward"}}, + {[]string{"workflow", "insert-step"}, "step", []string{"callForward"}}, + } { + c := find(t, root, tc.path...) + help := c.Flags().Lookup(tc.flag).Usage + for _, kind := range tc.kinds { + if !strings.Contains(help, kind) { + t.Errorf("%s --%s doesn't name the kind %s: %s", c.CommandPath(), tc.flag, kind, help) + } + } + if strings.Contains(help, "--"+tc.flag+".call-forward or") || strings.Contains(help, "or --"+tc.flag+".call-forward") || strings.Contains(help, "--"+tc.flag+".go-to-block, ") { + t.Errorf("%s --%s names a flag where a kind belongs: %s", c.CommandPath(), tc.flag, help) + } + } +} diff --git a/internal/cli/root.go b/internal/cli/root.go index 788bc291..8fd201c5 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -71,7 +71,7 @@ func NewRootCommand() (*cobra.Command, error) { return err } output.InitAgentMode(cmd) - return nil + return output.ValidateJq(cmd) // output/validate.go: a filter that can't run fails before anything is asked or sent }, } if err := agent.InitAgentRoot(rootCmd); err != nil { @@ -183,7 +183,7 @@ func NewRootCommand() (*cobra.Command, error) { rootCmd.PersistentFlags().String("color", "auto", "Control colored output: auto (color when output is a TTY), always, or never. Respects NO_COLOR and FORCE_COLOR env vars.") // jq filtering flag - rootCmd.PersistentFlags().StringP("jq", "q", "", "Filter and transform output using a jq expression (e.g., '.name', '.items[] | .id')") + rootCmd.PersistentFlags().StringP("jq", "q", "", output.JqUsage) // output/jqraw.go: says strings print raw and -o is ignored // Global server URL flag rootCmd.PersistentFlags().String("server-url", "", "Override the default server URL") @@ -241,7 +241,12 @@ func NewRootCommand() (*cobra.Command, error) { describeBodyFlags(rootCmd) // bodyhelp.go: --body says how stdin is read fixExamples(rootCmd) // examplehelp.go: every example runs as written + rejectStrayArgs(rootCmd) // strayargs.go: a command that takes no arguments says so + askFirst(rootCmd) // confirm.go: deletes and merges ask before they send, at a terminal + + nameVFCommandsInHelp(rootCmd) // namehelp.go: vf's commands and flags, not MCP tools and API fields rootCmd.SetUsageTemplate(groupedUsageTemplate()) + documentExitCodes(rootCmd) // exitcode.go: 'vf --help' lists the exit codes return rootCmd, nil } diff --git a/internal/cli/shorthands_test.go b/internal/cli/shorthands_test.go new file mode 100644 index 00000000..9a465211 --- /dev/null +++ b/internal/cli/shorthands_test.go @@ -0,0 +1,64 @@ +// This file is not generated by Speakeasy. It covers flagutil/shorthands.go +// over the whole command tree: -p and -e mean one thing on every command. + +package cli + +import ( + "testing" + + "github.com/spf13/cobra" +) + +// `vf agent update -p $P -e main` failed with "unknown flag", while `vf agent +// get -p $P -e main` worked: 47 commands lacked -p and 36 lacked -e. +func TestEveryProjectAndEnvironmentFlagHasItsShorthand(t *testing.T) { + root := testRoot(t) + checked := 0 + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + for _, sub := range c.Commands() { + walk(sub) + } + for name, letter := range map[string]string{"project-id": "p", "environment-alias": "e"} { + f := c.LocalFlags().Lookup(name) + if f == nil { + continue + } + checked++ + if got := c.Flags().ShorthandLookup(letter); got != f { + held := "nothing" + if got != nil { + // Another flag of the command has the letter: decide which + // keeps it, and say so in shorthands.go. + held = "--" + got.Name + } + t.Errorf("%s: -%s is %s, not --%s", c.CommandPath(), letter, held, name) + } + } + } + walk(root) + if checked < 400 { + t.Errorf("checked only %d flags", checked) + } +} + +// A command without --project-id or --environment-alias keeps the letters it +// had: changing them would break the scripts that use them. +func TestShorthandsElsewhereKeepTheirMeaning(t *testing.T) { + root := testRoot(t) + for _, tc := range []struct { + path []string + letter, flag string + }{ + {[]string{"evaluation", "run"}, "e", "evaluation-id"}, + {[]string{"analytics", "query", "workspace-token-usage"}, "e", "end-date"}, + {[]string{"analytics", "query", "workspace-token-usage"}, "p", "project-ids"}, + {[]string{"phone-number", "get"}, "p", "phone-number-id"}, + {[]string{"document", "preview-sitemap"}, "e", "exclude"}, + } { + c := find(t, root, tc.path...) + if f := c.Flags().ShorthandLookup(tc.letter); f == nil || f.Name != tc.flag { + t.Errorf("%s -%s: got %v, want --%s", c.CommandPath(), tc.letter, f, tc.flag) + } + } +} diff --git a/internal/cli/strayargs.go b/internal/cli/strayargs.go new file mode 100644 index 00000000..5e20172b --- /dev/null +++ b/internal/cli/strayargs.go @@ -0,0 +1,142 @@ +// This file is not generated by Speakeasy. It makes a command that takes no +// arguments say so when it is given some. +// +// A generated command reads every value from a flag, and cobra hands it any +// other word as an argument, which it ignored. So `vf conversation send … "hello"` +// sent no text and failed on a missing --action, `vf variable list -p X -e main +// extra-arg` and `vf version extra` ran as if the word weren't there, and +// `--name my agent` saved "my". The word was usually a value meant for a flag, +// and nothing said it had been dropped. +// +// rejectStrayArgs gives every such command a validator, once, at startup, +// and replaces cobra.NoArgs, whose error reads as if the word were a +// subcommand. A command that takes arguments of its own (`vf docs search +// `) says so with Args and is left alone, as is a group, whose stray +// words are unknownSubcommand's (errors.go), and the root, whose words are +// the home prompt's. + +package cli + +import ( + "errors" + "fmt" + "reflect" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/output" +) + +// strayArgsError reports the arguments a command that takes none was given. +type strayArgsError struct { + path string + args []string + flags bool // the command has flags of its own + text bool // it has --text, so the words were likely a message + id string // the one required ID flag not given, which a lone word likely meant +} + +func (e *strayArgsError) Error() string { + msg := e.path + " takes no arguments (got " + quoteArgs(e.args) + ")" + if e.flags { + msg += "; pass values with flags" + } + return msg +} + +// rejectStrayArgs gives every command under root that takes no arguments a +// validator that rejects them. +func rejectStrayArgs(root *cobra.Command) { + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + for _, sub := range c.Commands() { + walk(sub) + } + if c != root && !c.HasSubCommands() && (c.Args == nil || isNoArgs(c.Args)) { + c.Args = noArgs + } + } + walk(root) +} + +// isNoArgs reports whether args is cobra.NoArgs, whose error, `unknown +// command "hello" for "vf unlink"`, reads as if the word were a subcommand. +func isNoArgs(args cobra.PositionalArgs) bool { + return reflect.ValueOf(args).Pointer() == reflect.ValueOf(cobra.NoArgs).Pointer() +} + +// noArgs fails when args holds anything. +func noArgs(cmd *cobra.Command, args []string) error { + if len(args) == 0 { + return nil + } + // cobra checks arguments before PersistentPreRunE, the first place that + // applies --agent-mode, and the flags are parsed by now. + output.InitAgentMode(cmd) + return &strayArgsError{path: cmd.CommandPath(), args: args, flags: hasOwnFlags(cmd), text: cmd.Flags().Lookup("text") != nil, id: missingIDFlag(cmd)} +} + +// missingIDFlag is cmd's one required ID flag that wasn't given, such as +// `transcript get`'s --transcript-id, or "" when there isn't exactly one. +// The project and workspace are left out: a link or the home prompt fills +// them in after this check. +func missingIDFlag(cmd *cobra.Command) string { + var ids []string + cmd.LocalFlags().VisitAll(func(f *pflag.Flag) { + switch { + case f.Changed, !strings.HasSuffix(f.Name, "-id"), len(f.Annotations["speakeasy:required"]) == 0: + case f.Name == "project-id", f.Name == "workspace-id", f.Name == "organization-id": + default: + ids = append(ids, f.Name) + } + }) + if len(ids) != 1 { + return "" + } + return ids[0] +} + +// explainStrayArgs explains a strayArgsError. Nothing was run. +func explainStrayArgs(err error) (output.Explanation, bool) { + var e *strayArgsError + if !errors.As(err, &e) { + return output.Explanation{}, false + } + x := output.Explanation{Type: "usage_error", Title: e.Error(), Why: []string{"Nothing was run."}} + if e.text { + // `conversation send … hello there` is a message: say how to send it. + x.Next = append(x.Next, "To send it as a message: `--text "+shellQuote(strings.Join(e.args, " "))+"`") + } + if e.id != "" && len(e.args) == 1 && !e.text { + // `transcript get 6b0d…` meant the ID. + x.Next = append(x.Next, "To give it as the ID: `"+e.path+" --"+e.id+" "+shellWord(e.args[0])+"`") + } + if e.flags { + x.Next = append(x.Next, "`"+e.path+" --help` lists its flags") + if len(e.args) > 1 { + // Several words were likely one value that needed quotes. + x.Next = append(x.Next, "A value with spaces needs quotes: `--name \"two words\"`") + } + } + return x, true +} + +// hasOwnFlags reports whether cmd has flags of its own to show in help. +func hasOwnFlags(cmd *cobra.Command) bool { + own := false + cmd.LocalNonPersistentFlags().VisitAll(func(f *pflag.Flag) { + own = own || (!f.Hidden && f.Name != "help") + }) + return own +} + +// quoteArgs lists args quoted: "hello", "there". +func quoteArgs(args []string) string { + quoted := make([]string, len(args)) + for i, a := range args { + quoted[i] = fmt.Sprintf("%q", a) + } + return strings.Join(quoted, ", ") +} diff --git a/internal/cli/strayargs_test.go b/internal/cli/strayargs_test.go new file mode 100644 index 00000000..cd053583 --- /dev/null +++ b/internal/cli/strayargs_test.go @@ -0,0 +1,135 @@ +// This file is not generated by Speakeasy. It covers strayargs.go across +// every command. + +package cli + +import ( + "bytes" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/output" +) + +// ownArgs are the commands that declare their arguments themselves. +var ownArgs = map[string]bool{ + "vf docs search": true, // + "vf docs get": true, // +} + +// Every command that takes no arguments rejects a stray word, rather than +// running as if it weren't there. +func TestEveryCommandRejectsStrayArguments(t *testing.T) { + root := testRoot(t) + checked, own := 0, 0 + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + for _, sub := range c.Commands() { + walk(sub) + } + if c == root || c.HasSubCommands() || !c.Runnable() { + return + } + if ownArgs[c.CommandPath()] { + own++ + return + } + err := c.ValidateArgs([]string{"hello"}) + if err == nil { + t.Errorf("%s accepted a stray argument", c.CommandPath()) + } else if !strings.HasPrefix(err.Error(), c.CommandPath()+` takes no arguments (got "hello")`) { + t.Errorf("%s: %v", c.CommandPath(), err) + } + if err := c.ValidateArgs(nil); err != nil { + t.Errorf("%s with no arguments: %v", c.CommandPath(), err) + } + checked++ + } + walk(root) + if checked < 250 || own != len(ownArgs) { + t.Errorf("checked %d commands, and %d of %d that declare their own arguments", checked, own, len(ownArgs)) + } +} + +// `vf conversation send … "hello"` used to drop the word and fail on a +// missing --action; now it names the word, sends nothing, and is a usage +// error in both modes. +func TestAStrayArgumentIsNamedAndNothingIsSent(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Errorf("unexpected request %s %s", r.Method, r.URL) + })) + t.Cleanup(srv.Close) + t.Setenv("VF_TOKEN", "vfp_fake") + for _, agent := range []string{"--agent-mode=false", "--agent-mode=true"} { + output.ResetAgentMode() + t.Cleanup(output.ResetAgentMode) + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + var buf bytes.Buffer + root.SetOut(&buf) + root.SetErr(&buf) + root.SetArgs([]string{"conversation", "send", "-p", "p1", "-u", "u1", "-e", "main", "-v", "draft", + "--action", `{"type":"launch"}`, "hello", "there", "--server-url", srv.URL, "--no-interactive", agent}) + cmd, err := root.ExecuteC() + var stray *strayArgsError + if !errors.As(err, &stray) { + t.Fatalf("%s: want a stray-argument error, got %v\n%s", agent, err, buf.String()) + } + x := explainCLIError(cmd, err) + want := `vf conversation send takes no arguments (got "hello", "there"); pass values with flags` + if x.Type != "usage_error" || x.Title != want || !strings.Contains(explained(x), "`vf conversation send --help` lists its flags") || + !strings.Contains(explained(x), "To send it as a message: `--text 'hello there'`") { + t.Errorf("%s: got %+v", agent, x) + } + if got := output.IsAgentMode(); got != (agent == "--agent-mode=true") { + t.Errorf("%s: agent mode is %v", agent, got) + } + } +} + +// A command with no flags of its own doesn't point at flags. +func TestAStrayArgumentToACommandWithoutFlags(t *testing.T) { + root := testRoot(t) + version := find(t, root, "version") + err := version.ValidateArgs([]string{"extra"}) + x, ok := explainStrayArgs(err) + if !ok || x.Title != `vf version takes no arguments (got "extra")` || len(x.Next) != 0 { + t.Errorf("got %+v", x) + } +} + +// A command that says cobra.NoArgs gets the same error, not cobra's +// `unknown command "hello"`. +func TestCobraNoArgsGetsTheSameError(t *testing.T) { + root := &cobra.Command{Use: "vf"} + unlink := &cobra.Command{Use: "unlink", Args: cobra.NoArgs, RunE: func(*cobra.Command, []string) error { return nil }} + root.AddCommand(unlink) + rejectStrayArgs(root) + err := unlink.ValidateArgs([]string{"hello"}) + if err == nil || err.Error() != `vf unlink takes no arguments (got "hello")` { + t.Errorf("got %v", err) + } +} + +// round-4 human-poweruser: `transcript get ` got a hint about quoting +// spaces. A lone word on a command with one required ID flag not given is +// offered as that ID. +func TestALoneStrayWordIsOfferedAsTheID(t *testing.T) { + root := testRoot(t) + get := find(t, root, "transcript", "get") + if err := get.ParseFlags([]string{"-p", "p1"}); err != nil { + t.Fatal(err) + } + x, ok := explainStrayArgs(get.ValidateArgs([]string{"6b0dabc"})) + all := explained(x) + if !ok || !strings.Contains(all, "To give it as the ID: `vf transcript get --transcript-id 6b0dabc`") || strings.Contains(all, "needs quotes") { + t.Errorf("got:\n%s", all) + } +} diff --git a/internal/cli/tableview_test.go b/internal/cli/tableview_test.go index fd6650e0..2bcae3d5 100644 --- a/internal/cli/tableview_test.go +++ b/internal/cli/tableview_test.go @@ -20,3 +20,90 @@ func TestOutputTableShowsWhatAResponseWraps(t *testing.T) { t.Errorf("transcript search -o table dropped the transcripts: %v\n%s", err, out) } } + +// tableLines runs args with -o table and returns the lines it printed, each +// with its runs of spaces closed up to one. +func tableLines(t *testing.T, body string, args ...string) []string { + t.Helper() + out, err := runAgainst(t, body, append(args, "-o", "table")...) + if err != nil { + t.Fatalf("%s: %v\n%s", strings.Join(args, " "), err, out) + } + if strings.Contains(out, "UNKNOWNRAW") { + t.Errorf("%s printed the Go union's fields:\n%s", strings.Join(args, " "), out) + } + lines := strings.Split(strings.TrimRight(out, "\n"), "\n") + for i, line := range lines { + lines[i] = strings.Join(strings.Fields(line), " ") + } + return lines +} + +func wantLines(t *testing.T, got []string, want ...string) { + t.Helper() + for _, w := range want { + found := false + for _, line := range got { + if line == w { + found = true + } + } + if !found { + t.Errorf("no line %q in:\n%s", w, strings.Join(got, "\n")) + } + } +} + +// agent-builder:F6: a tool list's rows are a union, and printed as +// `UNKNOWNRAW TYPE` with no ID. +func TestOutputTableShowsAUnionListAsTheKindsItHolds(t *testing.T) { + lines := tableLines(t, `{"tools":[ + {"id":"6b0d-tool1","type":"function","functionID":"fn1","description":"Looks up the weather","asyncExecution":false,"createdAt":"2026-11-30T17:24:13Z","updatedAt":"2026-11-30T17:24:13Z","messages":null,"toolSound":null,"captureInputVariables":{},"inputVariables":{},"captureResponse":{}}, + {"id":"6b0d-tool2","type":"workflow","workflowID":"wf1","description":"Legacy","requiredVariables":[],"createdAt":"2026-11-30T17:24:13Z","updatedAt":"2026-11-30T17:24:13Z"}]}`, + "tool", "list", "--project-id", "p1", "-e", "main") + wantLines(t, lines, + "ID TYPE CREATED AT UPDATED AT DESCRIPTION FUNCTION ID ASYNC EXECUTION WORKFLOW ID", + "6b0d-tool1 function 2026-11-30T17:24:13Z 2026-11-30T17:24:13Z Looks up the weather fn1 false", + "6b0d-tool2 workflow 2026-11-30T17:24:13Z 2026-11-30T17:24:13Z Legacy wf1") +} + +// human-newcomer:F9: `document list` showed only ID and FOLDERID. A +// document's name and type are under "data", its status under "status". +func TestOutputTableShowsADocumentsNameTypeAndStatus(t *testing.T) { + lines := tableLines(t, `{"documents":[ + {"id":"6b0d-doc1","data":{"type":"text","name":"faq.txt","canEdit":true},"status":{"type":"SUCCESS"},"folderID":null}, + {"id":"6b0d-doc2","data":{"type":"url","name":"https://example.com/hours","url":"https://example.com/hours"},"status":{"type":"ERROR","data":{"message":"HTTP 429"}},"folderID":"f1"}]}`, + "document", "list", "-p", "p1", "-e", "main") + wantLines(t, lines, + "ID NAME TYPE STATUS FOLDER ID", + "6b0d-doc1 faq.txt text SUCCESS", + "6b0d-doc2 https://example.com/hours url ERROR f1") +} + +// human-newcomer:F2: a conversation's traces printed as `UNKNOWNRAW TYPE` +// and hid the reply. +func TestOutputTableShowsWhatAConversationSaid(t *testing.T) { + lines := tableLines(t, `{"traces":[ + {"type":"block","payload":{"blockID":"start"},"time":1796059460997}, + {"type":"text","payload":{"message":"We open at 8.","slate":{"id":"s","content":[]},"messageID":"m1"},"time":1796059460999}, + {"type":"end","time":1796059461000}],"needsRecompile":false}`, + "conversation", "send", "-p", "p1", "-e", "main", "-u", "u1", "-v", "draft", "--no-compile", "--action", `{"type":"launch"}`) + wantLines(t, lines, + "TYPE MESSAGE TIME", + "text We open at 8. 1796059460999", + "NEEDS RECOMPILE false") +} + +// fix-verifier:N5: a test run's logs printed as `UNKNOWNRAW TYPE`, then +// the run. +func TestOutputTableShowsATestRunsLogs(t *testing.T) { + lines := tableLines(t, `{"run":{"id":"R1","testID":"T1","status":"passed","failReason":null,"totalChecks":1,"passedChecks":1,"totalCredits":0.5,"createdAt":"2026-11-30T17:24:13Z", + "logs":[{"id":"l1","type":"action","payload":{"type":"launch"},"createdAt":"2026-11-30T17:24:14Z","seq":1}, + {"id":"l2","type":"trace","payload":{"type":"text","payload":{"message":"Hi"}},"createdAt":"2026-11-30T17:24:15Z","seq":2}]}}`, + "test", "run", "get", "-p", "p1", "-e", "main", "--run-id", "R1") + wantLines(t, lines, + "ID TYPE PAYLOAD TYPE CREATED AT SEQ", + "l1 action launch 2026-11-30T17:24:14Z 1", + "l2 trace text 2026-11-30T17:24:15Z 2", + "STATUS passed") +} diff --git a/internal/cli/test/run/createsuite_wait.go b/internal/cli/test/run/createsuite_wait.go index e7106664..3f561672 100644 --- a/internal/cli/test/run/createsuite_wait.go +++ b/internal/cli/test/run/createsuite_wait.go @@ -31,7 +31,6 @@ import ( "strings" "time" - "github.com/itchyny/gojq" "github.com/spf13/cobra" "github.com/spf13/pflag" "github.com/voiceflow/cli/internal/client" @@ -90,8 +89,8 @@ func addCreateSuiteWait(cmd *cobra.Command) { With --wait, the command waits until every run has finished, then prints the suite's results: counts, and the runs that did not pass with their failed checks. -It exits 0 only when every run passed. It exits 1 when a run failed or was -canceled, or when --max-wait (30 minutes by default) ran out first.` +It exits 0 only when every run passed. It exits 6 when a run failed or was +canceled, and 5 when --max-wait (30 minutes by default) ran out first.` cmd.Example += ` vf test run create-suite --project-id --environment-alias --all --wait vf test run create-suite --project-id --environment-alias --test-ids , --wait @@ -125,26 +124,15 @@ canceled, or when --max-wait (30 minutes by default) ran out first.` if err != nil { return err } + // A failure to start the suite, such as a missing flag or a bad + // --body, is explained by cli.Execute like any command's, in agent + // mode as the JSON envelope, with the exit code its kind has. Every + // failure after the suite has started is reported here. if client.IsDryRun(cmd) { - return inAgentEnvelope(cmd, runCreateSuite(cmd, args)) + return runCreateSuite(cmd, args) } - return inAgentEnvelope(cmd, runCreateSuiteAndWait(cmd, opts)) - } -} - -// inAgentEnvelope makes sure that in agent mode an error from --wait reaches -// stderr as the structured envelope, after the JSON progress events, and never -// as prose. Errors already printed (by output.Error or output.AgentModeError) -// have an empty message, the same thing main.go checks before printing, and -// flag-value errors are rendered by cli.Execute, so both are left alone. Every -// failure after the suite has started is reported explicitly, so what reaches -// this is a failure to start it. -func inAgentEnvelope(cmd *cobra.Command, err error) error { - var flagErr *flagutil.FlagValueError - if err == nil || err.Error() == "" || errors.As(err, &flagErr) || !output.IsAgentMode() { - return err + return runCreateSuiteAndWait(cmd, opts) } - return output.AgentModeError(cmd, "test_suite_start_failed", err.Error(), nil) } // splitSuiteIDFlags splits each value of --test-ids and --folder-ids on commas. @@ -209,11 +197,7 @@ func suiteWaitOptionsFrom(cmd *cobra.Command) (suiteWaitOptions, error) { // cannot run would otherwise fail after the whole wait. Compiling catches // unknown functions as well as syntax errors. if expression, _ := flagutil.GetStringFlag(cmd, "jq"); expression != "" { - query, err := gojq.Parse(expression) - if err == nil { - _, err = gojq.Compile(query) - } - if err != nil { + if err := output.CompileJq(expression); err != nil { return suiteWaitOptions{}, suiteError(cmd, "invalid_flag_value", fmt.Sprintf("invalid --jq expression %q: %v", expression, err), []string{"Fix the expression, or drop --jq; nothing was started"}) } @@ -534,7 +518,7 @@ func suiteWaitFailed(cmd *cobra.Command, target suiteTarget, err error) error { func suiteAPIFailed(cmd *cobra.Command, target suiteTarget, err error) error { resume := "The suite keeps running; once that is fixed, keep waiting with: " + target.resume() stderr := cmd.ErrOrStderr() - if !output.IsAgentMode() { + if !output.WantsJSONError(cmd) { reported := output.Error(cmd, err) if reported.Error() == "" { fmt.Fprintln(stderr, resume) @@ -555,22 +539,24 @@ func suiteAPIFailed(cmd *cobra.Command, target suiteTarget, err error) error { hints, _ := fields["hints"].([]any) fields["hints"] = append(hints, resume) fields["bulkID"] = target.bulkID - data, _ := json.MarshalIndent(fields, "", " ") + data := output.MarshalEnvelope(fields) fmt.Fprintln(stderr, string(data)) return reported } // suiteError reports a failure of --wait or of a suite. In agent mode that is // the structured envelope every other failure uses; otherwise a message and -// hints on stderr. +// hints on stderr. Either way the process exits with errorType's code: 6 for +// runs that didn't pass, 5 for runs still going, 2 for a bad flag. func suiteError(cmd *cobra.Command, errorType, message string, hints []string) error { if output.IsAgentMode() { return output.AgentModeError(cmd, errorType, message, hints) } + code := output.ExitCodeFor(errorType, 0) if len(hints) == 0 { - return errors.New(message) + return output.WithExitCode(errors.New(message), code) } - return errors.New(message + "\n " + strings.Join(hints, "\n ")) + return output.WithExitCode(errors.New(message+"\n "+strings.Join(hints, "\n ")), code) } func sleepContext(ctx context.Context, duration time.Duration) error { diff --git a/internal/cli/test/run/wait_exit.go b/internal/cli/test/run/wait_exit.go index 8539a9c7..33e37192 100644 --- a/internal/cli/test/run/wait_exit.go +++ b/internal/cli/test/run/wait_exit.go @@ -6,9 +6,9 @@ // runs and then waited for them went green on failing tests. Now the three // agree: once the result is printed, a run that failed or was canceled, a run // still going when the wait stopped, or a run ID that wasn't found makes the -// command exit 1, and the error says which. -o json and --jq skip decoding -// the response, so the verdict reads the raw body and puts it back to be -// printed as before. +// command exit non-zero (6, 5 and 4: internal/output/exitcode.go), and the +// error says which. -o json and --jq skip decoding the response, so the +// verdict reads the raw body and puts it back to be printed as before. package run diff --git a/internal/cli/unknownkeys_test.go b/internal/cli/unknownkeys_test.go new file mode 100644 index 00000000..83cc0d75 --- /dev/null +++ b/internal/cli/unknownkeys_test.go @@ -0,0 +1,88 @@ +// This file is not generated by Speakeasy. It covers flagutil/unknownkeys.go +// across every command that takes a body. + +package cli + +import ( + "strings" + "testing" + + "github.com/spf13/cobra" +) + +// Every --body, and stdin, names a key its request has no field for, rather +// than dropping it without a word. A body that is a union as a whole needs +// one of its forms first, so it gets the form its help example gives. +func TestEveryBodyNamesAKeyItDropped(t *testing.T) { + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("VF_SERVER_URL", "http://127.0.0.1:1") + root := testRoot(t) + var paths [][]string + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + for _, sub := range c.Commands() { + walk(sub) + } + if c.LocalFlags().Lookup("body") != nil && c.LocalFlags().Lookup("body-param") == nil { + paths = append(paths, strings.Fields(strings.TrimPrefix(c.CommandPath(), "vf "))) + } + } + walk(root) + if len(paths) < 100 { + t.Fatalf("found only %d commands with a body", len(paths)) + } + for _, path := range paths { + out, err := dryRun(append(path, "--body", `{"vfNoSuchKey":1}`, "--agent-mode=false")) + if err != nil { + t.Fatalf("%v: %v", path, err) + } + if !strings.Contains(out, "has keys vf "+strings.Join(path, " ")+" doesn't take, so they weren't sent: vfNoSuchKey") { + t.Errorf("vf %s --body didn't name the key it dropped:\n%s", strings.Join(path, " "), out) + } + } + + // Stdin, and a body that is the whole request. + phone := `{"name":"n","workspaceID":"w1","provider":"vonage","value":"v","vonageAPIKey":"k","vonageAPISecret":"s","vonageSignatureSecret":"x","vfNoSuchKey":1}` + for _, c := range []struct { + path []string + body string + }{ + {[]string{"variable", "create", "-p", "p1", "-e", "main"}, `{"vfNoSuchKey":1}`}, + {[]string{"project", "create"}, `{"vfNoSuchKey":1}`}, + {[]string{"phone-number", "create"}, phone}, + } { + path := c.path + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + var buf strings.Builder + root.SetOut(&buf) + root.SetErr(&buf) + root.SetIn(strings.NewReader(c.body)) + root.SetArgs(append(path, "--dry-run", "--no-interactive", "--agent-mode=false")) + _ = root.Execute() + if !strings.Contains(buf.String(), "stdin has keys vf "+path[0]+" create doesn't take, so they weren't sent: vfNoSuchKey") { + t.Errorf("%v on stdin:\n%s", path, buf.String()) + } + } + + // A whole-body union, given its form. + out, _ := dryRun([]string{"test", "turn", "create", "-p", "p1", "-e", "main", "--agent-mode=false", + "--body", `{"type":"user","testID":"t1","payload":{"text":"hi","response":"","variableStates":[]}}`}) + if !strings.Contains(out, "sent: payload.text\n payload takes: response, variableStates") { + t.Errorf("test turn create:\n%s", out) + } + // A variant's JSON flag. + out, _ = dryRun([]string{"tool", "create", "-p", "p1", "-e", "main", "--agent-mode=false", + "--body-param.function", `{"functionID":"f1","target":{"type":"agent"}}`}) + if !strings.Contains(out, "--body-param.function has keys vf tool create doesn't take, so they weren't sent: target.type") { + t.Errorf("tool create:\n%s", out) + } + // A JSON flag. + out, _ = dryRun([]string{"conversation", "send", "-p", "p1", "-u", "u1", "-e", "main", "-v", "draft", "--no-compile", "--agent-mode=false", + "--action", `{"type":"launch"}`, "--config-param", `{"excludeTypes":[],"vfNoSuchKey":1}`}) + if !strings.Contains(out, "--config-param has keys vf conversation send doesn't take, so they weren't sent: vfNoSuchKey") { + t.Errorf("conversation send:\n%s", out) + } +} diff --git a/internal/cli/waitexit_test.go b/internal/cli/waitexit_test.go index a3a24129..cab55981 100644 --- a/internal/cli/waitexit_test.go +++ b/internal/cli/waitexit_test.go @@ -81,6 +81,9 @@ func TestTestRunWaitExitsNonZeroUnlessEveryRunPassed(t *testing.T) { if err == nil || !strings.Contains(err.Error(), "1 of 2 runs did not pass") { t.Errorf("a run failed, but got error %v; output:\n%s", err, out) } + if code := ExitCode(err); code != output.ExitNotPassed { + t.Errorf("a run failed, so it exits %d, but got %d", output.ExitNotPassed, code) + } if !strings.Contains(out, "failed") { t.Errorf("the result wasn't printed before the error:\n%s", out) } @@ -89,6 +92,9 @@ func TestTestRunWaitExitsNonZeroUnlessEveryRunPassed(t *testing.T) { if err == nil || !strings.Contains(err.Error(), "still going") { t.Errorf("a run was still going, but got error %v; output:\n%s", err, out) } + if code := ExitCode(err); code != output.ExitTimeout { + t.Errorf("a run was still going, so it exits %d, but got %d", output.ExitTimeout, code) + } }) } } @@ -99,6 +105,9 @@ func TestTestRunWaitSaysWhichRunsWerentFound(t *testing.T) { if err == nil || !strings.Contains(err.Error(), "weren't found: nope") { t.Errorf("got %v", err) } + if code := ExitCode(err); code != output.ExitNotFound { + t.Errorf("exits %d, want %d", code, output.ExitNotFound) + } } func TestTestRunWaitSuiteExitsNonZeroWhenARunFailed(t *testing.T) { @@ -115,8 +124,8 @@ func TestTestRunWaitSuiteExitsNonZeroWhenARunFailed(t *testing.T) { if out, err := runAgainst(t, suite(2, 0), append(args, format...)...); err != nil { t.Errorf("%v: all passed, but got error %v; output:\n%s", format, err, out) } - if out, err := runAgainst(t, suite(1, 1), append(args, format...)...); err == nil { - t.Errorf("%v: a run failed, but it exited 0; output:\n%s", format, out) + if out, err := runAgainst(t, suite(1, 1), append(args, format...)...); ExitCode(err) != output.ExitNotPassed { + t.Errorf("%v: a run failed, but it exits %d, not %d; output:\n%s", format, ExitCode(err), output.ExitNotPassed, out) } } } diff --git a/internal/client/client.go b/internal/client/client.go index 04407feb..ead725a0 100644 --- a/internal/client/client.go +++ b/internal/client/client.go @@ -56,6 +56,7 @@ func NewClient(cmd *cobra.Command) (*sdk.VoiceflowSDK, error) { httpClient = WrapClientForTimeout(httpClient, timeout) // timeout.go: --timeout covers reading the response too httpClient = WrapClientForSpinner(cmd, httpClient) // spinner.go: ✻ while a request is in flight httpClient = WrapClientForDiagnostics(cmd, httpClient) + httpClient = WrapClientForConfirm(cmd, httpClient) // confirm.go: a delete asks before it sends, at a terminal sdkOpts = append(sdkOpts, sdk.WithClient(httpClient)) return sdk.New(sdkOpts...), nil } diff --git a/internal/client/confirm.go b/internal/client/confirm.go new file mode 100644 index 00000000..f23fc6a3 --- /dev/null +++ b/internal/client/confirm.go @@ -0,0 +1,57 @@ +// This file is not generated by Speakeasy. It gives a command one moment to +// ask before it changes anything: after the form and the pickers have filled +// its flags, and before its request leaves. internal/cli/confirm.go decides +// which commands ask, and what. +// +// A generated command sends its request at the end of its RunE, right after +// the form asks for any missing ID, so no cobra hook runs at the right time: +// PersistentPreRunE is too early to name what a picker hasn't picked yet. +// The request itself is the one point every command passes through. + +package client + +import ( + "net/http" + + "github.com/spf13/cobra" +) + +// BeforeChange, when set, runs before a command's first request that is not +// a read. An error stops that request: nothing is sent, and the command gets +// the error back. +var BeforeChange func(cmd *cobra.Command, req *http.Request) error + +// WrapClientForConfirm runs BeforeChange before the first request that +// changes something. Reads go straight through: a picker's list comes before +// the question it feeds. A dry run sends nothing, so it never asks. +func WrapClientForConfirm(cmd *cobra.Command, inner HTTPClient) HTTPClient { + if BeforeChange == nil || IsDryRun(cmd) { + return inner + } + return &confirmClient{cmd: cmd, inner: inner} +} + +type confirmClient struct { + cmd *cobra.Command + inner HTTPClient + asked bool +} + +func (c *confirmClient) Do(req *http.Request) (*http.Response, error) { + if !c.asked && changes(req.Method) { + c.asked = true + if err := BeforeChange(c.cmd, req); err != nil { + return nil, err + } + } + return c.inner.Do(req) +} + +// changes is whether a request with method can change something. +func changes(method string) bool { + switch method { + case http.MethodGet, http.MethodHead, http.MethodOptions: + return false + } + return true +} diff --git a/internal/client/confirm_test.go b/internal/client/confirm_test.go new file mode 100644 index 00000000..0ed4df62 --- /dev/null +++ b/internal/client/confirm_test.go @@ -0,0 +1,88 @@ +// This file is not generated by Speakeasy. It covers confirm.go: the hook +// runs once, before the first request that changes something, and an error +// from it sends nothing. + +package client + +import ( + "errors" + "net/http" + "testing" + + "github.com/spf13/cobra" +) + +type recordingClient struct{ sent []string } + +func (c *recordingClient) Do(req *http.Request) (*http.Response, error) { + c.sent = append(c.sent, req.Method) + return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}, nil +} + +func withBeforeChange(t *testing.T, hook func(*cobra.Command, *http.Request) error) { + t.Helper() + saved := BeforeChange + BeforeChange = hook + t.Cleanup(func() { BeforeChange = saved }) +} + +func send(t *testing.T, c HTTPClient, method string) error { + t.Helper() + req, err := http.NewRequest(method, "http://vf.invalid/x", nil) + if err != nil { + t.Fatal(err) + } + _, err = c.Do(req) + return err +} + +func TestBeforeChangeRunsOnceBeforeTheFirstChange(t *testing.T) { + cmd := &cobra.Command{Use: "delete"} + cmd.Flags().Bool("dry-run", false, "") + var hooked []string + withBeforeChange(t, func(_ *cobra.Command, req *http.Request) error { + hooked = append(hooked, req.Method) + return nil + }) + inner := &recordingClient{} + c := WrapClientForConfirm(cmd, inner) + for _, m := range []string{http.MethodGet, http.MethodDelete, http.MethodPut} { + if err := send(t, c, m); err != nil { + t.Fatal(err) + } + } + if len(hooked) != 1 || hooked[0] != http.MethodDelete { + t.Errorf("the hook should run once, before the first change (the GET is a picker's list): %q", hooked) + } + if len(inner.sent) != 3 { + t.Errorf("every request should be sent after a yes: %q", inner.sent) + } +} + +func TestAnErrorFromBeforeChangeSendsNothing(t *testing.T) { + cmd := &cobra.Command{Use: "delete"} + cmd.Flags().Bool("dry-run", false, "") + no := errors.New("no") + withBeforeChange(t, func(*cobra.Command, *http.Request) error { return no }) + inner := &recordingClient{} + if err := send(t, WrapClientForConfirm(cmd, inner), http.MethodDelete); !errors.Is(err, no) { + t.Errorf("the hook's error should come back, got %v", err) + } + if len(inner.sent) != 0 { + t.Errorf("nothing should be sent after a no: %q", inner.sent) + } +} + +func TestADryRunNeverAsks(t *testing.T) { + cmd := &cobra.Command{Use: "delete"} + cmd.Flags().Bool("dry-run", false, "") + _ = cmd.Flags().Set("dry-run", "true") + withBeforeChange(t, func(*cobra.Command, *http.Request) error { + t.Error("a dry run sends nothing, so it should not ask") + return nil + }) + inner := &recordingClient{} + if c := WrapClientForConfirm(cmd, inner); c != HTTPClient(inner) { + t.Errorf("a dry run should not be wrapped") + } +} diff --git a/internal/flagutil/apinames.go b/internal/flagutil/apinames.go new file mode 100644 index 00000000..bdeb6aa2 --- /dev/null +++ b/internal/flagutil/apinames.go @@ -0,0 +1,300 @@ +// This file is not generated by Speakeasy. It puts vf's own names where text +// from the API names an MCP tool or an API field. +// +// The spec's descriptions and the server's messages are written for the MCP +// server and the HTTP API as much as for vf. So vf's help and errors said +// "Copy a workflow ID from voiceflow_workflow.list", "the IDs create_run or +// create_many_runs returned", "Pass the run IDs vf_test_create_run … +// returned", "Requires 'versionVariant'" and "oldString was not found": names +// no vf command or flag has, which an agent may then try to call. 8755ede +// rewrote one form in server messages, a sibling command's name +// (search_instructions); this rewrites them all, in messages and in help: +// +// - an MCP tool, voiceflow_workflow.list or vf_test_create_run, becomes the +// vf command with the same words: `vf workflow list`, `vf test run create`; +// - an operation, create_run or add_blocks, the command with those words in +// the command's own group: `vf test run create`, `vf workflow add-blocks`; +// - an API field, environmentAlias or oldString, the command's flag for it: +// --environment-alias, --old-string. A field the command has no flag for +// stays, as does one in a JSON shape ("{ testID: string }") or a list of +// options, where it is a key or a value rather than a flag. +// +// A name with no such command or flag is left as it is. + +package flagutil + +import ( + "regexp" + "slices" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +// VFNamesInMessage rewrites the MCP tool and API field names in a server +// message as cmd's vf commands, in backticks, and flags. +func VFNamesInMessage(cmd *cobra.Command, message string) string { + return vfNames(cmd, message, "`", "") +} + +// VFNamesInHelp rewrites them in the help of cmd, or of its flag flag, with +// commands in single quotes: pflag would read backticks as a placeholder. +func VFNamesInHelp(cmd *cobra.Command, flag, text string) string { + return vfNames(cmd, text, "'", flag) +} + +var ( + // mcpTool is an MCP tool and, after a dot, its operation: + // voiceflow_workflow.list, vf_test_create_run. + mcpTool = regexp.MustCompile("[`']?\\b(?:voiceflow|vf)_[a-z]+(?:_[a-z]+)*(?:\\.[a-z]+(?:_[a-z]+)*)?\\b[`']?") + // operation is an MCP operation: search_instructions, create_many_runs. + operation = regexp.MustCompile("[`']?\\b[a-z]+(?:_[a-z]+)+\\b[`']?") + // apiField is a camelCase field name: environmentAlias, toolID, versionIDs. + apiField = regexp.MustCompile("[`']?\\b[a-z][a-z0-9]*(?:[A-Z][A-Za-z0-9]*)+\\b[`']?") +) + +func vfNames(cmd *cobra.Command, text, quote, flag string) string { + if cmd == nil || cmd.Root() == cmd || !strings.ContainsAny(text, "_ABCDEFGHIJKLMNOPQRSTUVWXYZ") { + return text + } + named := func(c *cobra.Command) string { return quote + c.CommandPath() + quote } + text = renameEach(mcpTool, text, func(name string, _, _ int) (string, bool) { + name = strings.TrimPrefix(strings.TrimPrefix(name, "voiceflow_"), "vf_") + if c := commandNamed(cmd.Root(), nameWords(name)); c != nil { + return named(c), true + } + return "", false + }) + text = renameEach(operation, text, func(name string, _, _ int) (string, bool) { + if c := operationOf(cmd, nameWords(name)); c != nil { + return named(c), true + } + return "", false + }) + literal := literalSpans(text) + return renameEach(apiField, text, func(field string, start, end int) (string, bool) { + before, after := strings.TrimRight(text[:start], "`'"), strings.TrimLeft(text[end:], "`'") + switch { + case inSpans(literal, start), + strings.HasPrefix(after, ":"), strings.HasPrefix(after, "="), // a key: { testID: … }, ?environmentAlias=main + strings.HasSuffix(before, "."), len(after) > 1 && after[0] == '.' && isLetter(after[1]), // a path: action.payload + strings.HasSuffix(before, "?"), strings.HasSuffix(before, "&"), strings.HasSuffix(before, "/"): + return "", false + } + if f := flagFor(cmd, kebab(field), flag); f != nil { + return "--" + f.Name, true + } + return "", false + }) +} + +// renameEach replaces each name re matches in text that rename gives a new +// name, start and end being where the name is. A name quoted on both sides +// loses its quotes: the new name brings its own, or needs none. +func renameEach(re *regexp.Regexp, text string, rename func(name string, start, end int) (string, bool)) string { + var b strings.Builder + last := 0 + for _, loc := range re.FindAllStringIndex(text, -1) { + m := text[loc[0]:loc[1]] + name := strings.TrimLeft(m, "`'") + start := loc[0] + len(m) - len(name) + name = strings.TrimRight(name, "`'") + end := start + len(name) + to, ok := rename(name, start, end) + if !ok { + continue + } + if start > loc[0] && end < loc[1] { + start, end = loc[0], loc[1] // 'environmentAlias' → --environment-alias + } + b.WriteString(text[last:start]) + b.WriteString(to) + last = end + } + b.WriteString(text[last:]) + return b.String() +} + +// nameWords are the words of a command or MCP name, each without a plural +// s, sorted: create_many_runs and "run create-many" are both create many run. +func nameWords(name string) []string { + words := strings.FieldsFunc(name, func(r rune) bool { return r == '_' || r == '-' || r == ' ' || r == '.' }) + for i, w := range words { + if len(w) > 3 { + words[i] = strings.TrimSuffix(w, "s") + } + } + slices.Sort(words) + return words +} + +// commandNamed is the command under root whose path has the words of an MCP +// tool name, its group's words first (vf_now names no group, so nothing). +// When no command has exactly those words, one with a word more will do if +// it is the only one: wait_suite is `vf test run wait-suite`. +func commandNamed(root *cobra.Command, words []string) *cobra.Command { + var exact, near []*cobra.Command + var walk func(c *cobra.Command, group []string) + walk = func(c *cobra.Command, group []string) { + for _, sub := range c.Commands() { + if sub.Hidden || !sub.IsAvailableCommand() { + continue + } + g := group + if g == nil { + g = nameWords(sub.Name()) + } + walk(sub, g) + path := nameWords(strings.TrimPrefix(sub.CommandPath(), root.Name()+" ")) + if !containsAll(words, g) { + continue + } + switch { + case slices.Equal(path, words): + exact = append(exact, sub) + case len(path) == len(words)+1 && containsAll(path, words): + near = append(near, sub) + } + } + } + walk(root, nil) + if len(exact) == 1 { + return exact[0] + } + if len(exact) == 0 && len(near) == 1 { + return near[0] + } + return nil +} + +// operationOf is the command in cmd's group whose words, below the group, +// are words: create_run in `vf test` is `vf test run create`. +func operationOf(cmd *cobra.Command, words []string) *cobra.Command { + group := cmd + for group.HasParent() && group.Parent().HasParent() { + group = group.Parent() + } + var found []*cobra.Command + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + for _, sub := range c.Commands() { + if sub.Hidden || !sub.IsAvailableCommand() { + continue + } + if slices.Equal(nameWords(strings.TrimPrefix(sub.CommandPath(), group.CommandPath()+" ")), words) { + found = append(found, sub) + } + walk(sub) + } + } + walk(group) + if len(found) == 1 { + return found[0] + } + return nil +} + +// flagFor is cmd's flag for the field named kebab: --environment-alias for +// environmentAlias, or a form's --body-param.agent.test-id for testID. Of +// several forms' flags, the one in the same form as the flag near is taken. +func flagFor(cmd *cobra.Command, kebab, near string) *pflag.Flag { + var found []*pflag.Flag + cmd.Flags().VisitAll(func(f *pflag.Flag) { + if !f.Hidden && (f.Name == kebab || strings.HasSuffix(f.Name, "."+kebab)) { + found = append(found, f) + } + }) + if len(found) > 1 { + form := near[:max(strings.LastIndexByte(near, '.'), 0)] + found = slices.DeleteFunc(found, func(f *pflag.Flag) bool { + return form == "" || !strings.HasPrefix(f.Name, form+".") + }) + } + if len(found) == 1 { + return found[0] + } + return nil +} + +// kebab is a camelCase field name as a flag name: toolID is tool-id, +// versionIDs version-ids, sitemapURL sitemap-url. +func kebab(field string) string { + field = strings.NewReplacer("IDs", "Ids", "URLs", "Urls").Replace(field) + var b strings.Builder + for i, r := range field { + upper := r >= 'A' && r <= 'Z' + if upper && i > 0 { + prev := field[i-1] + nextLower := i+1 < len(field) && field[i+1] >= 'a' && field[i+1] <= 'z' + if prev < 'A' || prev > 'Z' || nextLower { + b.WriteByte('-') + } + } + b.WriteRune(r) + } + return strings.ToLower(b.String()) +} + +// literalSpans are the parts of text where a camelCase word is a JSON key or +// an option's value, not a field to set: "{ type: string, testID: string }" +// and "options: endTool, cardTool". +func literalSpans(text string) [][2]int { + var spans [][2]int + depth, open := 0, 0 + for i, r := range text { + switch r { + case '{': + if depth == 0 { + open = i + } + depth++ + case '}': + if depth > 0 { + if depth--; depth == 0 { + spans = append(spans, [2]int{open, i}) + } + } + } + } + if depth > 0 { + spans = append(spans, [2]int{open, len(text)}) + } + for from := 0; ; { + i := strings.Index(text[from:], "options: ") + if i < 0 { + break + } + start := from + i + end := strings.IndexByte(text[start:], ')') + if end < 0 { + end = len(text) - start + } + spans = append(spans, [2]int{start, start + end}) + from = start + end + } + return spans +} + +func inSpans(spans [][2]int, i int) bool { + for _, s := range spans { + if i >= s[0] && i <= s[1] { + return true + } + } + return false +} + +func containsAll(have, want []string) bool { + rest := slices.Clone(have) + for _, w := range want { + i := slices.Index(rest, w) + if i < 0 { + return false + } + rest = slices.Delete(rest, i, i+1) + } + return true +} + +func isLetter(b byte) bool { return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') } diff --git a/internal/flagutil/apinames_test.go b/internal/flagutil/apinames_test.go new file mode 100644 index 00000000..3254c4b0 --- /dev/null +++ b/internal/flagutil/apinames_test.go @@ -0,0 +1,93 @@ +// This file is not generated by Speakeasy. It covers apinames.go. + +package flagutil + +import ( + "testing" + + "github.com/spf13/cobra" +) + +// namesTree is a small vf: test run create/wait/wait-suite, workflow list +// and add-blocks, agent patch-instructions/search-instructions. +func namesTree() map[string]*cobra.Command { + root := &cobra.Command{Use: "vf"} + cmds := map[string]*cobra.Command{} + add := func(parent *cobra.Command, path string, names ...string) { + for _, n := range names { + c := &cobra.Command{Use: n, RunE: func(*cobra.Command, []string) error { return nil }} + parent.AddCommand(c) + cmds[path+n] = c + } + } + add(root, "", "test", "workflow", "agent") + add(cmds["test"], "test ", "run") + add(cmds["test run"], "test run ", "create", "wait", "wait-suite", "create-suite") + add(cmds["workflow"], "workflow ", "list", "add-blocks", "link") + add(cmds["agent"], "agent ", "patch-instructions", "search-instructions", "get") + cmds["agent patch-instructions"].Flags().String("old-string", "", "") + cmds["agent patch-instructions"].Flags().String("environment-alias", "", "") + secret := cmds["agent get"] + secret.Flags().String("version-variant", "", "") + secret.Flags().String("environment-alias", "", "") + secret.Flags().String("body-param.number.maximum-value", "", "") + secret.Flags().String("body-param.number.maximum-prompt", "", "") + secret.Flags().String("body-param.string.maximum-value", "", "") + return cmds +} + +func TestVFNamesInMessage(t *testing.T) { + cmds := namesTree() + cases := []struct{ cmd, in, want string }{ + // 8755ede's case: a sibling command. + {"agent patch-instructions", "Use search_instructions to find it.", "Use `vf agent search-instructions` to find it."}, + // MCP tools, in either naming. + {"test run wait", "Pass the run IDs vf_test_create_run returned.", "Pass the run IDs `vf test run create` returned."}, + {"agent patch-instructions", "Copy a workflow ID from voiceflow_workflow.list.", "Copy a workflow ID from `vf workflow list`."}, + {"test run wait", "Then voiceflow_test.wait_suite.", "Then `vf test run wait-suite`."}, + // An operation of the command's group, below it. + {"test run wait", "the IDs create_run returned", "the IDs `vf test run create` returned"}, + // An API field the command has a flag for. + {"agent patch-instructions", "oldString was not found in the current text.", "--old-string was not found in the current text."}, + {"agent patch-instructions", "Without `environmentAlias` it writes main.", "Without --environment-alias it writes main."}, + // Names with no command or flag stay. + {"test run wait", "vf_user_timezone, create_many_runs and testID stay.", "vf_user_timezone, create_many_runs and testID stay."}, + // A key in JSON, a query string or a path is not a flag. + {"agent patch-instructions", "Expected { oldString: string }", "Expected { oldString: string }"}, + {"agent patch-instructions", "GET /x?environmentAlias=main", "GET /x?environmentAlias=main"}, + {"agent patch-instructions", "body.oldString is required", "body.oldString is required"}, + } + for _, tc := range cases { + if got := VFNamesInMessage(cmds[tc.cmd], tc.in); got != tc.want { + t.Errorf("%s: %q\n got %q\nwant %q", tc.cmd, tc.in, got, tc.want) + } + } +} + +func TestVFNamesInHelp(t *testing.T) { + cmds := namesTree() + get := cmds["agent get"] + cases := []struct{ flag, in, want string }{ + // Commands in help are single-quoted: pflag reads backticks. + {"", "as read with voiceflow_agent.get.", "as read with 'vf agent get'."}, + {"version-variant", "Required with 'environmentAlias'.", "Required with --environment-alias."}, + // Of two forms' flags, the one in the flag's own form. + {"body-param.number.maximum-prompt", "What warrants the 'maximumValue' score.", "What warrants the --body-param.number.maximum-value score."}, + {"", "What warrants the 'maximumValue' score.", "What warrants the 'maximumValue' score."}, + // Option values are values, not flags. + {"", "The variant (options: versionVariant, other)", "The variant (options: versionVariant, other)"}, + } + for _, tc := range cases { + if got := VFNamesInHelp(get, tc.flag, tc.in); got != tc.want { + t.Errorf("--%s: %q\n got %q\nwant %q", tc.flag, tc.in, got, tc.want) + } + } +} + +func TestKebab(t *testing.T) { + for in, want := range map[string]string{"toolID": "tool-id", "versionIDs": "version-ids", "sitemapURL": "sitemap-url", "llmGeneratedQ": "llm-generated-q", "oldString": "old-string"} { + if got := kebab(in); got != want { + t.Errorf("kebab(%s) = %s, want %s", in, got, want) + } + } +} diff --git a/internal/flagutil/description.go b/internal/flagutil/description.go index 730d8760..8381ee21 100644 --- a/internal/flagutil/description.go +++ b/internal/flagutil/description.go @@ -22,10 +22,32 @@ // descriptions across eight generated files — would be twelve standing merge // conflicts that silently stop covering a thirteenth flag the day the spec adds // one. +// +// It also gives a flag words where the spec gave it none. The generator fills +// the gap with the flag's type, which help already shows, or with a generated +// type name: +// +// -p, --project-id string [required] +// --timezone string string value +// --overwrite string JSON value (one of: boolean | StableDocumentController_createText_overwrite_enum) +// --body-param.boolean string StableEvaluationCreateRequest_Boolean variant as JSON +// --description string An optional description … (default "null") +// +// describeFlag gives the flags every command shares (--project-id, +// --environment-alias, --user-id) a real description, an ID flag "The +// workflow's ID", and a few common names their meaning; drops a placeholder +// that only repeats the type; lists a boolean-or-enum union's values; and +// names a union's forms by what the user types. hideNullDefault drops +// `(default "null")`: leaving the flag out sends null, which it does anyway. package flagutil -import "strings" +import ( + "regexp" + "strings" + + "github.com/spf13/cobra" +) // flagDescription prepares an OpenAPI description for use as a pflag usage // string, neutralizing backticks so they cannot be read as a value placeholder. @@ -35,3 +57,124 @@ func flagDescription(description string) string { } return strings.ReplaceAll(description, "`", "'") } + +// sharedFlags are the flags most commands take, described the same way on +// every one. A spec description that names the subject (an analytics +// filter's "The ID or alias of the environment to filter results by") is +// kept; a missing one, or one the spec copied from a neighbouring field +// ("Addresses one message on one tool" on --project-id), is replaced. +var sharedFlags = map[string]struct{ subject, text string }{ + "project-id": {"project", "The project's ID: in Creator, under the agent's Settings → General, or from 'vf project list'."}, + "environment-alias": {"environment", "The environment's alias, such as main or dev; 'vf environment list' lists them."}, + "user-id": {"user", "Any string that names the conversation's user. Use the same one to continue the conversation."}, +} + +// commonFlags describe a name that means one thing wherever the spec left it +// undescribed. +var commonFlags = map[string]string{ + "timezone": "A time zone name, such as America/New_York.", + "cursor": "The cursor the previous page returned, to get the next one.", + "global": "The agent's own, not a playbook's.", +} + +// placeholders are what the generator writes for an undescribed field: its +// type, which help shows already. +var placeholders = map[string]bool{"string value": true, "number value": true, "integer value": true, "boolean flag": true} + +// describeFlag is m with a description that says what the flag is: see the +// top of this file. +func describeFlag(m FlagMeta) FlagMeta { + m.Description = describe(m.FlagName, m.Kind, m.Description) + if m.Union != nil { + u := *m.Union // the generated metadata is shared; leave it as it is + u.TypeDescription = unionValues(u.TypeDescription) + u.Variants = append([]UnionVariantMeta(nil), u.Variants...) + for i, v := range u.Variants { + if generated, ok := strings.CutSuffix(v.Description, " variant as JSON"); ok && !strings.Contains(generated, " ") { + u.Variants[i].Description = formAsJSON(m.FlagName, v) + } + } + m.Union = &u + } + return m +} + +// DescribeFlag is m as help describes it, for the other places that show a +// flag's description, such as a form's field. +func DescribeFlag(m FlagMeta) FlagMeta { return describeFlag(m) } + +// describe is the description of the flag name: the spec's own when it says +// something, a better one when it doesn't. Its "(options: …)" and +// "[required]" stay. +func describe(name string, kind FlagKind, description string) string { + text, required := strings.CutSuffix(strings.TrimSpace(description), "[required]") + text = strings.TrimSpace(text) + options := "" + if strings.HasPrefix(text, "options: ") { + text, options = "", text + } else if i := strings.LastIndex(text, " (options: "); i >= 0 && strings.HasSuffix(text, ")") { + text, options = text[:i], strings.TrimSuffix(text[i+2:], ")") + } + + base := name[strings.LastIndexByte(name, '.')+1:] // a form's field: body-param.agent.test-id + shared, isShared := sharedFlags[base] + switch { + case isShared && !strings.Contains(strings.ToLower(text), shared.subject): + text = shared.text + case text != "" && !placeholders[text]: + // the spec's own words + case commonFlags[base] != "": + text = commonFlags[base] + case kind == FlagKindBool && strings.HasPrefix(base, "include-"): + text = "Include the " + strings.ReplaceAll(strings.TrimPrefix(base, "include-"), "-", " ") + " in the response." + case strings.HasSuffix(base, "-id"): + text = "The " + strings.ReplaceAll(strings.TrimSuffix(base, "-id"), "-", " ") + "'s ID." + default: + text = "" // help shows the type already + } + + out := text + switch { + case options != "" && out != "": + out += " (" + options + ")" + case options != "": + out = options + } + if required { + out = strings.TrimSpace(out + " [required]") + } + return out +} + +// booleanOrEnum is a union of a boolean and its string form, which the +// generator writes with the enum's type name: +// "JSON value (one of: boolean | StableDocumentController_createText_overwrite_enum)". +var booleanOrEnum = regexp.MustCompile(`^JSON value \(one of: boolean \| [A-Z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)+_enum\)$`) + +// unionValues lists the values of a union that is a boolean or its string +// form in place of the enum's type name. Every such enum's values are "true" +// and "false"; TestBooleanEnumsAreTrueAndFalse checks the next one too. +func unionValues(typeDescription string) string { + if booleanOrEnum.MatchString(typeDescription) { + return "true or false" + } + return typeDescription +} + +// formAsJSON describes the flag that takes a union's form v whole, as JSON, +// by the name the user types for it rather than its generated type name. +func formAsJSON(union string, v UnionVariantMeta) string { + form := strings.TrimPrefix(v.FlagName, union+".") + if v.CanExpand && len(v.Fields) > 0 { + return "The " + form + " form as JSON, instead of its --" + v.FlagName + ".* flags." + } + return "The " + form + " form as JSON." +} + +// hideNullDefault keeps help from showing (default "null") on a flag that +// sends null when it is left out, which is what leaving it out means anyway. +func hideNullDefault(cmd *cobra.Command, m FlagMeta) { + if f := cmd.Flags().Lookup(m.FlagName); f != nil && f.DefValue == "null" { + f.DefValue = "" + } +} diff --git a/internal/flagutil/description_test.go b/internal/flagutil/description_test.go new file mode 100644 index 00000000..c7e73cde --- /dev/null +++ b/internal/flagutil/description_test.go @@ -0,0 +1,78 @@ +// This file is not generated by Speakeasy. It covers description.go. + +package flagutil + +import ( + "os" + "path/filepath" + "regexp" + "strings" + "testing" +) + +func TestDescribe(t *testing.T) { + cases := []struct { + name string + kind FlagKind + in string + want string + }{ + {"project-id", FlagKindString, "[required]", "The project's ID: in Creator, under the agent's Settings → General, or from 'vf project list'. [required]"}, + {"project-id", FlagKindString, "The ID of the project the number should reach. [required]", "The ID of the project the number should reach. [required]"}, + {"environment-alias", FlagKindString, "Addresses one message on one tool. [required]", "The environment's alias, such as main or dev; 'vf environment list' lists them. [required]"}, + {"timezone", FlagKindString, "string value", "A time zone name, such as America/New_York."}, + {"include-prompt", FlagKindBool, "boolean flag", "Include the prompt in the response."}, + {"body-param.agent.test-id", FlagKindString, "[required]", "The test's ID. [required]"}, + {"interval", FlagKindEnum, "options: hour, day [required]", "options: hour, day [required]"}, + {"slot", FlagKindEnum, "Says what. (options: a, b) [required]", "Says what. (options: a, b) [required]"}, + {"name", FlagKindString, "string value", ""}, + {"filter-conversation", FlagKindBool, "boolean flag", ""}, + {"name", FlagKindString, "[required]", "[required]"}, + } + for _, tc := range cases { + if got := describe(tc.name, tc.kind, tc.in); got != tc.want { + t.Errorf("describe(%s, %q)\n got %q\nwant %q", tc.name, tc.in, got, tc.want) + } + } +} + +// unionValues reads "boolean | X_enum" as "true or false" without seeing the +// enum. That holds while every such enum's values are "true" and "false": +// this test reads each one the generated commands use and checks. +func TestBooleanEnumsAreTrueAndFalse(t *testing.T) { + enumName := regexp.MustCompile(`one of: boolean \| ([A-Za-z0-9_]+_enum)\)`) + var names []string + _ = filepath.WalkDir(filepath.Join("..", "cli"), func(path string, d os.DirEntry, err error) error { + if err != nil || d.IsDir() || !strings.HasSuffix(path, ".go") { + return err + } + src, _ := os.ReadFile(path) + for _, m := range enumName.FindAllStringSubmatch(string(src), -1) { + names = append(names, m[1]) + } + return nil + }) + if len(names) < 30 { + t.Fatalf("found only %d boolean-or-enum unions", len(names)) + } + models, _ := filepath.Glob(filepath.Join("..", "sdk", "models", "*", "*.go")) + var sdk strings.Builder + for _, path := range models { + src, _ := os.ReadFile(path) + sdk.Write(src) + } + for _, name := range names { + goName := "" + for _, part := range strings.Split(name, "_") { + goName += strings.ToUpper(part[:1]) + part[1:] + } + values := regexp.MustCompile(`(?m)^\s+`+goName+`\w* +`+goName+` = "([^"]*)"`).FindAllStringSubmatch(sdk.String(), -1) + var got []string + for _, v := range values { + got = append(got, v[1]) + } + if strings.Join(got, ",") != "true,false" { + t.Errorf("%s (%s) has the values %q: help would say only \"true or false\"", name, goName, got) + } + } +} diff --git a/internal/flagutil/forms.go b/internal/flagutil/forms.go new file mode 100644 index 00000000..b8bfa465 --- /dev/null +++ b/internal/flagutil/forms.go @@ -0,0 +1,131 @@ +// This file is not generated by Speakeasy. It writes each union form's JSON +// into the help of the flag that takes it (shape.go). +// +// A form's flag said only "StableTestTurnCreateRequest_User variant as +// JSON", and the union's own flag gave every form as `payload: object`. Now +// `--body-param.user` says `The user form as JSON: { testID: string, +// payload: { response: string, variableStates: string | [{ … }] } }`, in +// --help and --usage alike. +// +// The flags are registered before anything names the request type, and +// only ValidateMeta, called right after with the same metadata, knows it. So +// RegisterFlags remembers the command its metadata went to, and +// ValidateMeta describes that command's flags. + +package flagutil + +import ( + "fmt" + "reflect" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/usage" +) + +// registered is the command each metadata slice was registered on, by its +// first entry, until ValidateMeta describes it. +var registered = map[*FlagMeta]*cobra.Command{} + +// rememberCommand notes that meta's flags were registered on cmd. +func rememberCommand(cmd *cobra.Command, meta []FlagMeta) { + if len(meta) > 0 { + registered[&meta[0]] = cmd + } +} + +// describeForms gives the flags of each discriminated union in meta the +// JSON they take. t is the request type meta describes. +func describeForms(t reflect.Type, meta []FlagMeta) { + if len(meta) == 0 { + return + } + cmd := registered[&meta[0]] + delete(registered, &meta[0]) + if cmd == nil { + return + } + markJSONFlags(cmd, t, meta) // jsonexample.go + for _, m := range meta { + if m.Kind != FlagKindUnion || m.Union == nil || !m.Union.Discriminated || len(m.Union.Variants) == 0 { + continue + } + ut, ok := fieldTypeAt(t, m.FieldPath) + if !ok { + continue + } + ut = unionValueType(shapeType(ut)) + key := "" + var names []string + for _, v := range m.Union.Variants { + field, ok := ut.FieldByName(v.FieldName) + if !ok { + continue + } + if d, ok := shapeType(field.Type).FieldByName(m.Union.DiscriminatorKey); ok { + key = jsonName(d) + } + names = append(names, v.DiscriminatorValue) + setOwnHelp(cmd, v.FlagName, "The "+v.DiscriminatorValue+" form as JSON: "+typeShape(field.Type, key)) + } + if key == "" || len(names) == 0 { + continue + } + setOwnHelp(cmd, m.FlagName, fmt.Sprintf("JSON value in one of %d forms, named by its %q: %s. --%s.
takes a form's JSON without %q, and its help shows the form's fields", + len(names), key, orList(names), m.FlagName, key)) + } +} + +// setOwnHelp sets flag name's help, and marks it for --usage to show. +func setOwnHelp(cmd *cobra.Command, name, help string) { + f := cmd.Flags().Lookup(name) + if f == nil { + return + } + f.Usage = keepRequired(f.Usage, help) + _ = cmd.Flags().SetAnnotation(name, usage.OwnHelp, []string{"true"}) +} + +// FormHelp is the help of the flag that takes the form of a union named +// form, such as --body-param.user for "user", and that flag's name. +func FormHelp(cmd *cobra.Command, form string) (flag, help string, ok bool) { + cmd.LocalFlags().VisitAll(func(f *pflag.Flag) { + if !ok && strings.HasSuffix(f.Name, "."+form) && len(f.Annotations[usage.OwnHelp]) > 0 { + flag, help, ok = f.Name, f.Usage, true + } + }) + return flag, help, ok +} + +// helpListsFields says what cmd's help shows of its body: the JSON its +// flags take, when it has flags that show theirs. +func helpListsFields(cmd *cobra.Command) string { + shows := false + cmd.LocalFlags().VisitAll(func(f *pflag.Flag) { + shows = shows || len(f.Annotations[usage.OwnHelp]) > 0 + }) + if shows { + return "`" + cmd.CommandPath() + " --help` shows the JSON its flags take" + } + return "`" + cmd.CommandPath() + " --help` lists the flags that set the body" +} + +// orList joins names as "a, b or c". +func orList(names []string) string { + if len(names) < 2 { + return strings.Join(names, "") + } + return strings.Join(names[:len(names)-1], ", ") + " or " + names[len(names)-1] +} + +// keepRequired carries over the "[required…]" that old ends with, which +// unionform.go and standin.go write before the forms' JSON is known, so a +// required union still says it is. +func keepRequired(old, help string) string { + if i := strings.LastIndex(old, " [required"); i >= 0 && strings.HasSuffix(old, "]") { + return help + old[i:] + } + return help +} diff --git a/internal/flagutil/inputerror.go b/internal/flagutil/inputerror.go new file mode 100644 index 00000000..a55c4c44 --- /dev/null +++ b/internal/flagutil/inputerror.go @@ -0,0 +1,441 @@ +// This file is not generated by Speakeasy. It says what is wrong with JSON a +// flag or stdin was given, in words for the person who wrote it. +// +// The decoder's own words reached the reader: Go and SDK type names, and the +// SDK's label for every failure, "error unmarshalling json response body", +// though no request had been sent and the JSON was the user's: +// +// failed to parse --body as JSON: json: cannot unmarshal array into Go value of type components.StableProjectUpdateRequest +// failed to parse --body as JSON: json: cannot unmarshal string into Go value of type int64 +// invalid value for --action: error unmarshalling json response body: unexpected end of JSON input +// invalid value for --action: error unmarshalling json response body: could not unmarshal `{…}` into any supported union types for AnyRequest +// +// None of them said which field was wrong, or what the flag takes. Now the +// error names the flag, says where the JSON breaks off or which field has the +// wrong kind of value ("take should be a whole number, not "ten""), and says +// what the flag takes. + +package flagutil + +import ( + "encoding/json" + "errors" + "fmt" + "reflect" + "regexp" + "sort" + "strconv" + "strings" + "time" +) + +// BodyError is a request body, given with a flag or on stdin, that vf +// couldn't use. internal/cli explains it as an invalid_body error. +type BodyError struct { + Flag string // the whole-body flag, without dashes: "body" + Stdin bool // the body came on stdin, not with the flag + Value string // what was given + Problem string // what's wrong: `take should be a whole number, not "ten"` + Takes string // what a body is: "an object"; "" when vf can't say + Cause error +} + +func (e *BodyError) Error() string { return "invalid " + e.Source() + ": " + e.Problem } + +func (e *BodyError) Unwrap() error { return e.Cause } + +// Source is where the body came from: "--body", or "body on stdin". +func (e *BodyError) Source() string { + if e.Stdin { + return "body on stdin" + } + return "--" + e.Flag +} + +// DisplayValue is the body shortened for an error, as FlagValueError's is. +func (e *BodyError) DisplayValue() string { return truncateForError(e.Value) } + +// bodyError is the error for a body, meant for a value of type target, that +// didn't decode. +func bodyError(flag string, stdin bool, value string, target reflect.Type, cause error) error { + return &BodyError{ + Flag: flag, Stdin: stdin, Value: strings.TrimSpace(value), Cause: cause, + Problem: jsonProblem(cause, target, value), + Takes: kindWords(jsonKind(target), target), + } +} + +// unionError is the error for a union flag's JSON that is none of its forms. +// takes is what the flag takes, from unionTakes or variantTakes; target is +// the type of the one form a variant's flag takes, or nil. +func unionError(flag, takes, value string, target reflect.Type, cause error) error { + problem := jsonProblem(cause, target, value) + if problem == noFormProblem { + problem = "it isn't any of the forms --" + flag + " takes" + } + var hints []string + if takes != "" { + hints = append(hints, "--"+flag+" takes "+takes) + } + return &FlagValueError{Flag: flag, Value: value, Expected: problem, Hints: hints, Cause: cause} +} + +const noFormProblem = "it isn't any of the forms this flag takes" + +var ( + goTypeRE = regexp.MustCompile(`cannot unmarshal (\w+)(?: "?[^"]*"?)? into Go (?:struct field (\S+) of type|value of type) (\S+)`) + sdkNameRE = regexp.MustCompile(`\b[A-Z]\w*_\w+\b`) + goTypeNameRE = regexp.MustCompile(`(?:Go (?:struct field \S+ of )?(?:value of )?type|union types for) \S+`) +) + +// jsonProblem is what's wrong with input, JSON meant for a value of type +// target (nil when that isn't known), in plain words. +func jsonProblem(cause error, target reflect.Type, input string) string { + var syntax *json.SyntaxError + if errors.As(cause, &syntax) { + return syntaxProblem(syntax.Error(), syntax.Offset) + } + if target != nil { + if problem, ok := firstMismatch(target, input); ok { + return problem + } + } + var mismatch *json.UnmarshalTypeError + if errors.As(cause, &mismatch) { + return kindProblem(mismatch.Field, kindWords(jsonKind(mismatch.Type), mismatch.Type), mismatch.Value) + } + + msg := cause.Error() + for _, prefix := range []string{"error unmarshalling json response body: ", "error unmarshaling json response body: ", "json: "} { + msg = strings.TrimPrefix(msg, prefix) + } + switch m := goTypeRE.FindStringSubmatch(msg); { + case m != nil: + field := m[2] + if i := strings.IndexByte(field, '.'); i >= 0 { + field = field[i+1:] // "Request.take": the Go type, then the field's path + } + return kindProblem(field, goTypeWords(m[3]), m[1]) + case msg == "unexpected end of JSON input": + return syntaxProblem(msg, 0) + case strings.Contains(msg, "into any supported union types"): + return noFormProblem + case strings.HasPrefix(msg, "missing required fields: "): + return "it needs " + strings.TrimPrefix(msg, "missing required fields: ") + } + return goTypeNameRE.ReplaceAllString(msg, "the type it takes") +} + +// syntaxProblem says where JSON stops being JSON. +func syntaxProblem(msg string, offset int64) string { + if msg == "unexpected end of JSON input" { + return `the JSON ends too soon: a closing }, ] or " is missing` + } + if offset <= 1 { + return "it isn't JSON" + } + what := msg + for _, c := range []struct{ decoder, plain string }{ + {"looking for beginning of object key string", "a key must be in double quotes"}, + {"after object key:value pair", "a comma or } is missing"}, + {"after object key", "a key must be followed by a colon"}, + {"after array element", "a comma or ] is missing"}, + {"looking for beginning of value", "a value is missing, or isn't JSON (text goes in double quotes)"}, + {"in string literal", "text has a character that must be escaped"}, + {"after top-level value", "there is more after the JSON value"}, + } { + if strings.Contains(msg, c.decoder) { + what = c.plain + break + } + } + return fmt.Sprintf("it isn't valid JSON at character %d: %s", offset, what) +} + +// kindProblem is "take should be a whole number, not "ten"". +func kindProblem(field, want, got string) string { + subject := "it" + switch { + case strings.HasPrefix(field, "["): + subject = "item " + field // "item [0]" of a list + case field != "": + subject = field + } + if want == "" { + return subject + " can't be " + valueWords(got) + } + return subject + " should be " + want + ", not " + valueWords(got) +} + +// valueWords is a JSON value, or the decoder's name for its kind: "string", +// "number 1.5", "array". +func valueWords(v string) string { + kind, literal, _ := strings.Cut(v, " ") + switch kind { + case "string": + if literal != "" && len(literal) <= 40 { + return strconv.Quote(literal) + } + return "text" + case "number": + if literal != "" { + return literal + } + return "a number" + case "bool": + if literal != "" { + return literal + } + return "true or false" + case "array": + return "a list" + case "object": + return "an object" + } + return v +} + +// jsonKind is the kind of JSON value t is decoded from: "object", "array", +// "string", "number" or "bool", or "" when vf can't say, as for a union. +func jsonKind(t reflect.Type) string { + for t != nil && t.Kind() == reflect.Ptr { + t = t.Elem() + } + if t == nil { + return "" + } + if u := unionValueType(t); u != t { // OptionalNullable[T] + return jsonKind(u) + } + if t == reflect.TypeOf(time.Time{}) { + return "string" + } + switch t.Kind() { + case reflect.String: + return "string" + case reflect.Bool: + return "bool" + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, + reflect.Float32, reflect.Float64: + return "number" + case reflect.Slice, reflect.Array: + if t.Elem().Kind() == reflect.Uint8 { + return "" + } + return "array" + case reflect.Map: + if t.Key().Kind() == reflect.Bool { // OptionalNullable of a non-struct + return jsonKind(t.Elem()) + } + return "object" + case reflect.Struct: + tagged := false + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if f.Tag.Get("union") != "" { + return "" // a union: one of several kinds + } + if name, _, _ := strings.Cut(f.Tag.Get("json"), ","); name != "" && name != "-" { + tagged = true + } + } + if tagged { + return "object" + } + } + return "" +} + +// kindWords says what a value of kind is, for the reader: "a whole number". +func kindWords(kind string, t reflect.Type) string { + switch kind { + case "object": + return "an object" + case "array": + return "a list" + case "string": + for t != nil && t.Kind() == reflect.Ptr { + t = t.Elem() + } + if t == reflect.TypeOf(time.Time{}) { + return `a date and time, such as "2024-01-15T10:30:00Z"` + } + return "text" + case "bool": + return "true or false" + case "number": + for t != nil && (t.Kind() == reflect.Ptr || (t.Kind() == reflect.Map && t.Key().Kind() == reflect.Bool)) { + t = t.Elem() + } + if t != nil && t.Kind() != reflect.Float32 && t.Kind() != reflect.Float64 { + return "a whole number" + } + return "a number" + } + return "" +} + +// goTypeWords is kindWords for a Go type known only by its name, as an +// error message gives it: "int64", "[]string", "components.Request". +func goTypeWords(name string) string { + name = strings.TrimLeft(name, "*") + switch { + case strings.HasPrefix(name, "[]"): + return "a list" + case strings.HasPrefix(name, "map["), strings.Contains(name, "."): + return "an object" + case name == "string": + return "text" + case name == "bool": + return "true or false" + case strings.HasPrefix(name, "float"): + return "a number" + case strings.HasPrefix(name, "int"), strings.HasPrefix(name, "uint"): + return "a whole number" + } + return "" +} + +// firstMismatch finds the first value in input whose kind isn't the kind +// its place in target takes, and says so: "take should be a whole number, +// not "ten"". The SDK decodes a body field by field, so the decoder's own +// error doesn't say which field it was on. +func firstMismatch(target reflect.Type, input string) (string, bool) { + dec := json.NewDecoder(strings.NewReader(input)) + dec.UseNumber() + var v interface{} + if dec.Decode(&v) != nil { + return "", false + } + return mismatchIn(target, v, "") +} + +func mismatchIn(t reflect.Type, v interface{}, path string) (string, bool) { + want := jsonKind(t) + if want == "" || v == nil { + return "", false + } + got, literal := kindOfValue(v) + if got != want { + return kindProblem(path, kindWords(want, t), strings.TrimSpace(got+" "+literal)), true + } + for t.Kind() == reflect.Ptr { + t = t.Elem() + } + if u := unionValueType(t); u != t { + t = u + } else if t.Kind() == reflect.Map && t.Key().Kind() == reflect.Bool { + t = t.Elem() + for t.Kind() == reflect.Ptr { + t = t.Elem() + } + } + switch val := v.(type) { + case []interface{}: + for i, item := range val { + if p, ok := mismatchIn(t.Elem(), item, fmt.Sprintf("%s[%d]", path, i)); ok { + return p, true + } + } + case map[string]interface{}: + keys := make([]string, 0, len(val)) + for k := range val { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + var ft reflect.Type + if t.Kind() == reflect.Map { + ft = t.Elem() + } else if f, ok := jsonField(t, k); ok { + ft = f.Type + } + if ft == nil { + continue + } + if p, ok := mismatchIn(ft, val[k], strings.TrimPrefix(path+"."+k, ".")); ok { + return p, true + } + } + } + return "", false +} + +// jsonField is t's field that the JSON key name decodes into. A field the SDK +// reads from a string, such as a big number, is left out. +func jsonField(t reflect.Type, name string) (reflect.StructField, bool) { + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if tag, _, _ := strings.Cut(f.Tag.Get("json"), ","); tag != name { + continue + } + for _, key := range []string{"bigint", "decimal", "integer", "number"} { + if f.Tag.Get(key) != "" { + return f, false + } + } + return f, true + } + return reflect.StructField{}, false +} + +// kindOfValue is the JSON kind of a decoded value, and the value itself for +// a string, number or bool. +func kindOfValue(v interface{}) (kind, literal string) { + switch val := v.(type) { + case map[string]interface{}: + return "object", "" + case []interface{}: + return "array", "" + case string: + return "string", val + case json.Number: + return "number", val.String() + case bool: + return "bool", strconv.FormatBool(val) + } + return "", "" +} + +// unionTakes is what a union flag takes, from its description of its forms: +// "JSON value (one of: string | number)" is "JSON, one of: string | number". +func unionTakes(desc string) string { + if f := plainForms(desc); f != "" { + return "JSON, one of: " + f + } + return "" +} + +// variantTakes is what the flag for one variant of a union takes: the form +// its union's description gives for it, "JSON: { type: string, payload: +// object }". +func variantTakes(desc, variant string) string { + forms := plainForms(desc) + start := strings.Index(forms, variant+": {") + if start < 0 || (start > 0 && !strings.HasSuffix(forms[:start], ", ")) { + return "" + } + form := forms[start+len(variant)+2:] + depth := 0 + for i, r := range form { + switch r { + case '{': + depth++ + case '}': + if depth--; depth == 0 { + return "JSON: " + form[:i+1] + } + } + } + return "" +} + +// plainForms is a union flag's description of its forms without the SDK's +// names: "JSON value (one of: string | number)" is "string | number". +func plainForms(desc string) string { + d := strings.TrimSpace(strings.TrimPrefix(desc, "JSON value")) + d = strings.TrimSuffix(strings.TrimPrefix(d, "("), ")") + d = strings.TrimPrefix(strings.TrimPrefix(d, "one of: "), "variants: ") + return sdkNameRE.ReplaceAllString(d, "string") +} diff --git a/internal/flagutil/inputerror_test.go b/internal/flagutil/inputerror_test.go new file mode 100644 index 00000000..ba4b26ae --- /dev/null +++ b/internal/flagutil/inputerror_test.go @@ -0,0 +1,154 @@ +// This file is not generated by Speakeasy. It covers inputerror.go: JSON a +// flag or stdin was given that vf couldn't use is explained in plain words, +// with no Go or SDK type names and no "response body". + +package flagutil + +import ( + "errors" + "reflect" + "strings" + "testing" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/sdk/models/operations" + "github.com/voiceflow/cli/internal/sdk/sdkinternal/utils" +) + +// internals are the words the decoder used that mean nothing to the person +// who wrote the JSON. +var internals = []string{"Go value", "Go struct", "response body", "union types", "components.", "jsontext", "int64", "unmarshal"} + +func plain(t *testing.T, msg string) { + t.Helper() + for _, word := range internals { + if strings.Contains(msg, word) { + t.Errorf("%q says %q", msg, word) + } + } +} + +// buildSearch runs BuildRequest for `vf transcript search` with --body. +func buildSearch(t *testing.T, body string) error { + t.Helper() + cmd := &cobra.Command{Use: "search"} + cmd.Flags().String("project-id", "", "") + cmd.Flags().String("body", "", "") + if err := cmd.ParseFlags([]string{"--project-id", "p", "--body", body}); err != nil { + t.Fatal(err) + } + meta := []FlagMeta{{FlagName: "project-id", FieldPath: "ProjectID", Kind: FlagKindString, Required: true}} + _, err := BuildRequest[operations.StableTranscriptControllerSearchV2Request](cmd, meta, "Body", "body") + return err +} + +// A --body that is the wrong kind of value, or not JSON, names the flag and +// says what's wrong where. +func TestABadBodySaysWhatsWrongInPlainWords(t *testing.T) { + for body, want := range map[string]string{ + `{"take":"ten"}`: `invalid --body: take should be a whole number, not "ten"`, + `[1,2]`: `invalid --body: it should be an object, not a list`, + `{bad`: `invalid --body: it isn't valid JSON at character 2: a key must be in double quotes`, + `{"take":1`: `invalid --body: the JSON ends too soon: a closing }, ] or " is missing`, + `{"take":1} extra`: `invalid --body: it isn't valid JSON at character 12: there is more after the JSON value`, + } { + err := buildSearch(t, body) + var bodyErr *BodyError + if !errors.As(err, &bodyErr) { + t.Errorf("%s: got %v, want a BodyError", body, err) + continue + } + if err.Error() != want { + t.Errorf("%s:\n got %s\nwant %s", body, err, want) + } + if bodyErr.Takes != "an object" { + t.Errorf("%s: takes %q, want an object", body, bodyErr.Takes) + } + plain(t, err.Error()) + } +} + +// A union flag says what's wrong and the forms it takes, and a variant's +// flag the one form it takes. +func TestAUnionFlagSaysWhatItTakes(t *testing.T) { + decode := func(value string) error { + var v components.AnyRequest + return utils.UnmarshalJsonFromString(value, &v, "") + } + forms := "JSON value (one of: { type: string, payload: string } | { type: string, payload: object })" + for value, want := range map[string]string{ + `What are your hours`: "invalid value for --action: it isn't JSON", + `{"type":"text","payload":"hi"`: `invalid value for --action: the JSON ends too soon: a closing }, ] or " is missing`, + `{"type":"bogus_type","payload":"x"}`: "invalid value for --action: it isn't any of the forms --action takes", + } { + err := unionError("action", unionTakes(forms), value, nil, decode(value)) + var fve *FlagValueError + if !errors.As(err, &fve) || !strings.HasPrefix(err.Error(), want+"\n") { + t.Errorf("%s:\n got %v\nwant %s", value, err, want) + continue + } + if len(fve.Hints) != 1 || fve.Hints[0] != "--action takes JSON, one of: { type: string, payload: string } | { type: string, payload: object }" { + t.Errorf("hints = %q", fve.Hints) + } + plain(t, err.Error()) + } + + variants := "JSON value (variants: user: { type: string, testID: string, payload: object }, agent: { type: string, payload: object })" + if got := variantTakes(variants, "agent"); got != "JSON: { type: string, payload: object }" { + t.Errorf("variantTakes = %q", got) + } + if got := variantTakes(variants, "user"); got != "JSON: { type: string, testID: string, payload: object }" { + t.Errorf("variantTakes = %q", got) + } + if got := plainForms("JSON value (one of: boolean | StableDocumentController_createText_overwrite_enum)"); got != "boolean | string" { + t.Errorf("an SDK name is left in %q", got) + } +} + +// The decoder's words, where vf has only its message, are put plainly too. +func TestTheDecodersWordsArePutPlainly(t *testing.T) { + for msg, want := range map[string]string{ + "error unmarshalling json response body: cannot unmarshal string into Go value of type map[string]jsontext.Value": "it should be an object, not text", + "json: cannot unmarshal object into Go value of type []jsontext.Value": "it should be a list, not an object", + "json: cannot unmarshal string into Go struct field Request.take of type int64": "take should be a whole number, not text", + "error unmarshalling json response body: missing required fields: type, payload": "it needs type, payload", + } { + if got := jsonProblem(errors.New(msg), nil, ""); got != want { + t.Errorf("%s:\n got %s\nwant %s", msg, got, want) + } + } +} + +// The walk finds a nested field, an item in a list, and leaves alone a field +// the SDK reads from a string, and a union, which takes more than one kind. +func TestTheMismatchIsFoundWhereItIs(t *testing.T) { + type item struct { + Name string `json:"name"` + } + type body struct { + Items []item `json:"items"` + Big *int64 `bigint:"string" json:"big"` + Any components.AnyRequest `json:"any"` + On *bool `json:"on,omitempty"` + } + target := reflect.TypeOf(body{}) + for input, want := range map[string]string{ + `{"items":[{"name":"a"},{"name":7}]}`: "items[1].name should be text, not 7", + `{"on":"yes"}`: `on should be true or false, not "yes"`, + `{"items":{}}`: "items should be a list, not an object", + } { + if got, ok := firstMismatch(target, input); !ok || got != want { + t.Errorf("%s: got %q, want %q", input, got, want) + } + } + for _, input := range []string{`{"big":"12345678901234567890"}`, `{"any":"text"}`, `{"on":null}`, `{"other":1}`} { + if got, ok := firstMismatch(target, input); ok { + t.Errorf("%s: nothing is wrong, got %q", input, got) + } + } + if got, _ := firstMismatch(reflect.TypeOf([]item{}), `["abc"]`); got != `item [0] should be an object, not "abc"` { + t.Errorf("a top-level list's item: got %q", got) + } +} diff --git a/internal/flagutil/jsonerror.go b/internal/flagutil/jsonerror.go index 9e077e69..5f6f461f 100644 --- a/internal/flagutil/jsonerror.go +++ b/internal/flagutil/jsonerror.go @@ -19,7 +19,6 @@ import ( "encoding/json" "fmt" "reflect" - "strings" ) // notJSONError explains why a structured JSON flag rejected its value. @@ -45,71 +44,29 @@ func jsonValueError(t reflect.Type, val string, m FlagMeta, cause error) error { hints = append(hints, "the value is not valid JSON") } - if example := jsonShapeExample(t); example != "" { - hints = append(hints, fmt.Sprintf("expected shape: --%s '%s'", m.FlagName, example)) + // The keys and an example come from the field's own type (jsonexample.go). + if shape := jsonShape(t); shape != "" { + hints = append(hints, "--"+m.FlagName+" takes "+shape) } - if detail := unmarshalDetail(cause); detail != "" { - hints = append(hints, detail) + if example := jsonExample(t, m.Annotations); example != "" { + hints = append(hints, fmt.Sprintf("for example: --%s '%s'", m.FlagName, example)) } - hints = append(hints, "pass null to clear the field: --"+m.FlagName+" null") - - return &FlagValueError{Flag: m.FlagName, Value: val, Expected: expected, Hints: hints, Cause: cause} -} - -// jsonShapeExample returns a value of the right shape for t, or "" when the -// shape cannot be stated confidently. -// -// The example must be something the CLI would actually accept. The first -// version of this hint hardcoded an object for every destination, so on the -// array-valued flags it told the caller to pass a value the same binary -// rejects — and a caller following the instruction exactly got back the -// identical error, with nothing new to try. A wrong example is worse than no -// example, so an unrecognized shape returns "" and the hint is omitted. -func jsonShapeExample(t reflect.Type) string { - for t.Kind() == reflect.Ptr { - t = t.Elem() + if detail := unmarshalDetail(cause, t, val); detail != "" { + hints = append(hints, detail) } - // OptionalNullable[T] == map[bool]*T — unwrap to the value it carries. - if t.Kind() == reflect.Map && t.Key().Kind() == reflect.Bool && t.Elem().Kind() == reflect.Ptr { - t = t.Elem().Elem() - for t.Kind() == reflect.Ptr { - t = t.Elem() - } + if !m.Required && sendsNull(t, m.Annotations) { + hints = append(hints, "pass null to clear the field: --"+m.FlagName+" null") } - switch t.Kind() { - case reflect.Slice, reflect.Array: - return `[{"key":"value"}]` - case reflect.Map, reflect.Struct: - return `{"key":"value"}` - case reflect.String: - // A nullable string is JSON-typed so that null can be expressed at all, - // which is why prose has to arrive JSON-quoted. Nothing said so before; - // the error named the first character of the sentence and stopped. - return `"your text here"` - default: - return "" - } + return &FlagValueError{Flag: m.FlagName, Value: val, Expected: expected, Hints: hints, Cause: cause} } -// unmarshalDetail surfaces what the JSON decoder objected to, minus a prefix -// that is wrong in this context. -// -// The SDK's unmarshaler labels every failure "error unmarshalling json response -// body", but a flag value is a request the CLI has not sent yet — there is no -// response. Left intact it sends the reader looking for a server problem that -// does not exist. The remainder is worth keeping: it names the Go type that was -// expected, which is the only place that information appears at all. -func unmarshalDetail(cause error) string { +// unmarshalDetail says what the JSON decoder objected to, in plain words +// (inputerror.go): "it should be an object, not a list", where the decoder +// said "cannot unmarshal array into Go value of type map[string]jsontext.Value". +func unmarshalDetail(cause error, t reflect.Type, val string) string { if cause == nil { return "" } - detail := cause.Error() - for _, prefix := range []string{"error unmarshalling json response body: ", "json: "} { - detail = strings.TrimPrefix(detail, prefix) - } - if detail == "" { - return "" - } - return "decoder reported: " + detail + return jsonProblem(cause, t, val) } diff --git a/internal/flagutil/jsonexample.go b/internal/flagutil/jsonexample.go new file mode 100644 index 00000000..86872891 --- /dev/null +++ b/internal/flagutil/jsonexample.go @@ -0,0 +1,185 @@ +// This file is not generated by Speakeasy. It writes the hints on a value a +// JSON flag rejected from the type the flag takes (shape.go). +// +// The hint was one of three fixed strings, picked by the kind of value: +// '[{"key":"value"}]' for every list and '{"key":"value"}' for every object. +// --playbooks takes [{ playbookID: string, … }], so following the hint sent +// a playbook with no ID and a key the SDK drops. --traffic takes numbers, so +// following it failed again. And every flag ended "pass null to clear the +// field", --traffic too, which is required, and --playbooks, which null +// leaves out rather than clears. Now the hints give the keys the flag takes +// and an example written from them, which the decoder is shown to take +// before it is offered. Null is offered only where it is sent as null. + +package flagutil + +import ( + "math/big" + "reflect" + "slices" + "strconv" + "strings" + "time" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/sdk/sdkinternal/utils" + "github.com/voiceflow/cli/internal/sdk/types" +) + +// TakesJSON marks a flag whose value is decoded as JSON into a field. It +// holds the flag's example, or "" when it has none, for a help example +// that would otherwise give the flag ``, which it rejects. +const TakesJSON = "vf:takes-json" + +// markJSONFlags marks each JSON flag in meta, registered on cmd for request +// type t, with its example. +func markJSONFlags(cmd *cobra.Command, t reflect.Type, meta []FlagMeta) { + for _, m := range meta { + if m.Kind != FlagKindJSON || cmd.Flags().Lookup(m.FlagName) == nil { + continue + } + example := "" + if ft, ok := fieldTypeAt(t, m.FieldPath); ok { + example = jsonExample(ft, m.Annotations) + } + _ = cmd.Flags().SetAnnotation(m.FlagName, TakesJSON, []string{example}) + } +} + +// jsonShape is what a JSON flag of type t takes, as `[{ playbookID: string, +// … }]`, or "" when t is no object or list. +func jsonShape(t reflect.Type) string { + shape := typeShape(t, "") + if !strings.HasPrefix(shape, "{") && !strings.HasPrefix(shape, "[") { + return "" + } + return shape +} + +// jsonExample is a value of type t, as JSON, that a flag with annotations +// decodes: every key that is required, with a placeholder, or else the +// first key whose value is a placeholder. A placeholder, unlike false or 0, +// is no setting the API would quietly apply. It is "" when no such value can +// be written, as for an enum whose values Go can't list. +func jsonExample(t reflect.Type, annotations string) string { + example, ok := exampleOf(t, "", t, nil) + if !ok || strings.Contains(example, "'") || !decodesAs(t, example, annotations) { + return "" + } + return example +} + +// exampleOf writes a value of t. name is the key it is under, for a +// string's placeholder, and owner the type that holds it, for an enum's +// value. +func exampleOf(t reflect.Type, name string, owner reflect.Type, seen []reflect.Type) (string, bool) { + t = shapeType(t) + if literal := enumLiteral(t, owner); literal != "" { + return literal, true + } + switch t.Kind() { + case reflect.Struct: + switch t { + case reflect.TypeOf(big.Int{}): + return "0", true + case reflect.TypeOf(time.Time{}): + return `"2026-01-01T00:00:00Z"`, true + case reflect.TypeOf(types.Date{}): + return `"2026-01-01"`, true + } + if slices.Contains(seen, t) { + return "", false + } + seen = append(seen, t) + if isUnion(t) { + for _, f := range unionMembers(t) { + if v, ok := exampleOf(f.Type, name, t, seen); ok { + return v, true + } + } + return "", false + } + return objectExample(t, seen) + case reflect.Map: + v, ok := exampleOf(t.Elem(), "value", owner, seen) + return `{"":` + v + `}`, ok + case reflect.Slice, reflect.Array: + if t.Elem().Kind() == reflect.Uint8 { + return `""`, true + } + v, ok := exampleOf(t.Elem(), name, owner, seen) + return "[" + v + "]", ok + case reflect.String: + if t.PkgPath() != "" && implementsUnmarshaler(t) { + return "", false // an enum whose values Go can't list + } + if name == "" { + name = "value" + } + return strconv.Quote("<" + name + ">"), true + case reflect.Bool: + return "false", true + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, + reflect.Float32, reflect.Float64: + return "0", true + case reflect.Interface: + return `""`, true + } + return "", false +} + +// objectExample writes struct t with its required keys, or, when none is +// required, its first key that holds a placeholder. +func objectExample(t reflect.Type, seen []reflect.Type) (string, bool) { + var keys []string + optional := "" + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + name := jsonName(f) + if !f.IsExported() || name == "-" || f.Tag.Get("additionalProperties") == "true" { + continue + } + v, ok := exampleOf(f.Type, name, t, seen) + if optionalField(f) { + if ok && optional == "" && strings.Contains(v, `"<`) { + optional = strconv.Quote(name) + ":" + v + } + continue + } + if !ok { + return "", false + } + keys = append(keys, strconv.Quote(name)+":"+v) + } + if len(keys) == 0 && optional != "" { + keys = append(keys, optional) + } + return "{" + strings.Join(keys, ",") + "}", true +} + +// decodesAs reports whether a flag of type t with annotations takes val, as +// buildJSONField decodes it. +func decodesAs(t reflect.Type, val, annotations string) bool { + if t.Kind() == reflect.Ptr { + holder := reflect.New(t) + holder.Elem().Set(reflect.New(t.Elem())) + return utils.UnmarshalJsonFromString(val, holder.Interface(), annotations) == nil + } + return utils.UnmarshalJsonFromString(val, reflect.New(t).Interface(), annotations) == nil +} + +// sendsNull reports whether null, passed to a flag of type t, is sent as +// null and so clears the field: an OptionalNullable is, and so is a pointer +// or interface the SDK writes even when empty. On any other flag null +// leaves the field out, which changes nothing. +func sendsNull(t reflect.Type, annotations string) bool { + switch { + case t.Kind() == reflect.Map && t.Key().Kind() == reflect.Bool && t.Elem().Kind() == reflect.Ptr: + return true + case t.Kind() == reflect.Ptr || t.Kind() == reflect.Interface: + return !strings.Contains(reflect.StructTag(annotations).Get("json"), ",omit") + } + return false +} diff --git a/internal/flagutil/jsonexample_test.go b/internal/flagutil/jsonexample_test.go new file mode 100644 index 00000000..fc85f2d0 --- /dev/null +++ b/internal/flagutil/jsonexample_test.go @@ -0,0 +1,65 @@ +// This file is not generated by Speakeasy. It covers jsonexample.go against +// the SDK's own request types. + +package flagutil + +import ( + "errors" + "reflect" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/sdk/optionalnullable" +) + +// hintsFor is the hints a JSON flag of type T gives on a value it rejected. +func hintsFor[T any](m FlagMeta) string { + err := jsonValueError(reflect.TypeOf((*T)(nil)).Elem(), "[vf", m, errors.New("bad")) + return strings.Join(err.(*FlagValueError).Hints, "\n") +} + +func TestJSONHintsComeFromTheFieldsType(t *testing.T) { + for _, c := range []struct { + name string + hints string + want, not []string + }{{ + name: "--playbooks, a list null leaves out", + hints: hintsFor[[]components.StableAgentUpdateRequestV2Playbook](FlagMeta{FlagName: "playbooks", Annotations: `json:"playbooks,omitempty"`}), + want: []string{ + "--playbooks takes [{ condition?: ", + "description: string | null, requiredVariables?: [", + `for example: --playbooks '[{"description":"","playbookID":""}]'`, + }, + not: []string{`"key"`, "null to clear"}, + }, { + name: "--traffic, a required map of numbers", + hints: hintsFor[map[string]float64](FlagMeta{FlagName: "traffic", Required: true, Annotations: `json:"traffic"`}), + want: []string{"--traffic takes { : number }", `for example: --traffic '{"":0}'`}, + not: []string{`"value"`, "null"}, + }, { + name: "--llm, an object with nothing required", + hints: hintsFor[*components.StableAgentUpdateRequestV2Llm](FlagMeta{FlagName: "llm", Optional: true, Annotations: `json:"llm,omitempty"`}), + want: []string{"--llm takes { priorityProcessing?: boolean, defaults?: { model?: string", `for example: --llm '{"defaults":{"model":""}}'`}, + not: []string{"null to clear"}, + }, { + name: "--condition, which null clears", + hints: hintsFor[optionalnullable.OptionalNullable[components.StableAgentWorkflowAddRequestCondition]](FlagMeta{FlagName: "condition", Optional: true, Annotations: `json:"condition,omitempty"`}), + // Its type takes only "value-variable", which Go can't list: the + // keys, and no example that would fail. + want: []string{"--condition takes { type: string, matchAll: boolean, assertions: [", "pass null to clear the field: --condition null"}, + not: []string{"for example"}, + }} { + for _, w := range c.want { + if !strings.Contains(c.hints, w) { + t.Errorf("%s: no %q in\n%s", c.name, w, c.hints) + } + } + for _, n := range c.not { + if strings.Contains(c.hints, n) { + t.Errorf("%s: %q in\n%s", c.name, n, c.hints) + } + } + } +} diff --git a/internal/flagutil/metadata.go b/internal/flagutil/metadata.go index 4d55dea2..608a4602 100644 --- a/internal/flagutil/metadata.go +++ b/internal/flagutil/metadata.go @@ -104,8 +104,11 @@ type FlagMeta struct { // Flags that already exist as inherited persistent flags (e.g., global security // credentials) are skipped to prevent local flags from shadowing them. func RegisterFlags(cmd *cobra.Command, meta []FlagMeta) { + rememberCommand(cmd, meta) // forms.go: ValidateMeta describes the forms' flags; before the shorthands, which may copy meta + meta = withConventionalShorthands(cmd, meta) // shorthands.go: -p and -e mean one thing everywhere for _, m := range meta { m.Description = flagDescription(m.Description) // see description.go + m = describeFlag(m) // description.go: words where the spec gave a type or none m.Description = describeList(m) // listflags.go: how to pass several values // Skip if a flag with this name already exists — either inherited from // a parent command (persistent globals/security) or already registered @@ -119,6 +122,7 @@ func RegisterFlags(cmd *cobra.Command, meta []FlagMeta) { if m.Union != nil { registerUnionFlags(cmd, m) markUnionNeedsAForm(cmd, m) // unionform.go: help examples give it a form + markFormFields(cmd, m) // unionform.go: a form's fields are required only with it } case FlagKindFile, FlagKindFileArray, FlagKindBytes: registerStringFlag(cmd, m) @@ -149,6 +153,7 @@ func RegisterFlags(cmd *cobra.Command, meta []FlagMeta) { cmd.Flags().StringArray(m.FlagName, nil, m.Description) } } + hideNullDefault(cmd, m) // description.go: (default "null") says nothing if m.Required { if f := cmd.Flags().Lookup(m.FlagName); f != nil { @@ -176,6 +181,7 @@ func registerStringFlag(cmd *cobra.Command, m FlagMeta) { func ValidateMeta[T any](meta []FlagMeta) error { var zero T v := reflect.ValueOf(&zero).Elem() + describeForms(v.Type(), meta) // forms.go: each union form's flag shows its JSON for _, m := range meta { if m.Kind == FlagKindUnion { // Validate that the union FieldPath resolves; variant fields are validated at build time @@ -240,14 +246,15 @@ func BuildRequest[T any](cmd *cobra.Command, meta []FlagMeta, bodyFieldPath stri return nil, fmt.Errorf("failed to resolve body field %q: %w", bodyFieldPath, err) } if err := unmarshalIntoField(bodyField, []byte(bodyJSON)); err != nil { - return nil, fmt.Errorf("failed to parse --%s as JSON: %w", bodyFlagName, err) + return nil, bodyError(bodyFlagName, false, bodyJSON, bodyField.Type(), err) // inputerror.go: says what's wrong in plain words } } else { if err := json.Unmarshal([]byte(bodyJSON), &req); err != nil { - return nil, fmt.Errorf("failed to parse --%s as JSON: %w", bodyFlagName, err) + return nil, bodyError(bodyFlagName, false, bodyJSON, v.Type(), err) // inputerror.go } v = reflect.ValueOf(&req).Elem() // refresh after unmarshal } + warnUnknownKeys(cmd, "--"+bodyFlagName, []byte(bodyJSON), bodyValue(v, bodyFieldPath)) // unknownkeys.go: say which keys the SDK dropped bodyPrePopulated = true } } @@ -271,14 +278,15 @@ func BuildRequest[T any](cmd *cobra.Command, meta []FlagMeta, bodyFieldPath stri return nil, fmt.Errorf("failed to resolve body field %q: %w", bodyFieldPath, err) } if err := unmarshalIntoField(bodyField, stdinData); err != nil { - return nil, fmt.Errorf("failed to parse stdin as JSON: %w", err) + return nil, bodyError(bodyFlagName, true, string(stdinData), bodyField.Type(), err) // inputerror.go } } else { if err := json.Unmarshal(stdinData, &req); err != nil { - return nil, fmt.Errorf("failed to parse stdin as JSON: %w", err) + return nil, bodyError(bodyFlagName, true, string(stdinData), v.Type(), err) // inputerror.go } v = reflect.ValueOf(&req).Elem() // refresh after unmarshal } + warnUnknownKeys(cmd, "stdin", stdinData, bodyValue(v, bodyFieldPath)) // unknownkeys.go: say which keys the SDK dropped bodyPrePopulated = true } } @@ -316,6 +324,7 @@ func BuildRequest[T any](cmd *cobra.Command, meta []FlagMeta, bodyFieldPath stri } // Priority 3: individual flags — only Changed() flags modify the struct + var missing missingFlags // missing.go: every missing required flag in one error for _, m := range meta { var err error if m.Kind == FlagKindUnion { @@ -325,10 +334,13 @@ func BuildRequest[T any](cmd *cobra.Command, meta []FlagMeta, bodyFieldPath stri } else { err = buildFieldOnValue(cmd, v, m) } - if err != nil { + if err = missing.collect(err); err != nil { // missing.go return nil, err } } + if err := missing.err(); err != nil { // missing.go + return nil, err + } return &req, nil } @@ -369,8 +381,9 @@ func BuildRequestBody[T any](cmd *cobra.Command, flagName string, annotations st return &req, nil } if err := utils.UnmarshalJsonFromString(requestData, &req, annotations); err != nil { - return nil, fmt.Errorf("invalid %s: %w", flagName, err) + return nil, bodyError(flagName, !FlagChanged(cmd, flagName), requestData, reflect.TypeOf(&req).Elem(), err) // inputerror.go } + warnUnknownKeys(cmd, bodySource(cmd, flagName), []byte(requestData), reflect.ValueOf(&req).Elem()) // unknownkeys.go: say which keys the SDK dropped return &req, nil } @@ -866,6 +879,7 @@ func buildJSONField(cmd *cobra.Command, v reflect.Value, m FlagMeta) error { } field.Set(target.Elem()) } + warnUnknownKeys(cmd, "--"+m.FlagName, []byte(val), field) // unknownkeys.go: say which keys the SDK dropped return nil } @@ -1183,9 +1197,10 @@ func buildUnionField(cmd *cobra.Command, root reflect.Value, m FlagMeta) error { jsonStr, _ := GetStringFlag(cmd, m.FlagName) target := reflect.New(unionType) if err := utils.UnmarshalJsonFromString(jsonStr, target.Interface(), ""); err != nil { - return fmt.Errorf("invalid value for --%s: %w", m.FlagName, err) + return unionError(m.FlagName, unionTakes(u.TypeDescription), jsonStr, nil, err) // inputerror.go: says what's wrong, and the forms it takes } setUnionFieldValue(unionField, target, isPtr) + warnUnknownKeys(cmd, "--"+m.FlagName, []byte(jsonStr), target) // unknownkeys.go: say which keys the SDK dropped return nil } @@ -1209,9 +1224,10 @@ func buildUnionField(cmd *cobra.Command, root reflect.Value, m FlagMeta) error { jsonStr, _ := GetStringFlag(cmd, v.FlagName) variantPtr := reflect.New(variantType) if err := utils.UnmarshalJsonFromString(jsonStr, variantPtr.Interface(), ""); err != nil { - return fmt.Errorf("invalid value for --%s: %w", v.FlagName, err) + return unionError(v.FlagName, variantTakes(u.TypeDescription, v.DiscriminatorValue), jsonStr, variantType, err) // inputerror.go } injectDiscriminator(variantPtr.Elem(), u.DiscriminatorKey, v.DiscriminatorValue) + warnUnknownKeys(cmd, "--"+v.FlagName, []byte(jsonStr), variantPtr) // unknownkeys.go: say which keys the SDK dropped unionVal := assembleUnionValue(unionType, v.FieldName, variantPtr) setUnionFieldValue(unionField, unionVal, isPtr) return nil diff --git a/internal/flagutil/missing.go b/internal/flagutil/missing.go new file mode 100644 index 00000000..e7e7a8d5 --- /dev/null +++ b/internal/flagutil/missing.go @@ -0,0 +1,55 @@ +// This file is not generated by Speakeasy. It reports every required flag a +// command was run without in one error. +// +// BuildRequest returned the first missing flag it came to, so a command +// missing three took three runs to learn of them: `vf conversation send -u x` +// said it needed --project-id, then, with that, --environment-alias, then +// --action. BuildRequest now goes through every flag before it fails, and +// names them all. + +package flagutil + +import ( + "regexp" + "strings" +) + +// MissingFlagsError is the required flags a command was run without, in the +// order the command defines them. internal/cli explains it. +type MissingFlagsError struct { + Flags []string // names, without dashes +} + +func (e *MissingFlagsError) Error() string { + if len(e.Flags) == 1 { + return "missing required flag: --" + e.Flags[0] + } + return "missing required flags: --" + strings.Join(e.Flags, ", --") +} + +// missingFlagRE is how the builders say a required flag is missing. +var missingFlagRE = regexp.MustCompile(`^missing required flag: --(\S+)$`) + +// missingFlags gathers the missing required flags BuildRequest finds. +type missingFlags struct{ flags []string } + +// collect keeps err if it says a required flag is missing, so the next flag +// is checked too, and returns any other error. +func (c *missingFlags) collect(err error) error { + if err == nil { + return nil + } + if m := missingFlagRE.FindStringSubmatch(err.Error()); m != nil { + c.flags = append(c.flags, m[1]) + return nil + } + return err +} + +// err is every missing flag as one error, or nil when none is missing. +func (c *missingFlags) err() error { + if len(c.flags) == 0 { + return nil + } + return &MissingFlagsError{Flags: c.flags} +} diff --git a/internal/flagutil/missing_test.go b/internal/flagutil/missing_test.go new file mode 100644 index 00000000..9bbe2a9c --- /dev/null +++ b/internal/flagutil/missing_test.go @@ -0,0 +1,76 @@ +// This file is not generated by Speakeasy. It covers missing.go: BuildRequest +// names every missing required flag in one error. + +package flagutil + +import ( + "errors" + "reflect" + "testing" + + "github.com/spf13/cobra" +) + +type missingTestRequest struct { + ProjectID string + EnvironmentAlias string + Limit int64 + Config *struct { + On bool `json:"on"` + } + UserID string +} + +var missingTestMeta = []FlagMeta{ + {FlagName: "project-id", FieldPath: "ProjectID", Kind: FlagKindString, Required: true}, + {FlagName: "environment-alias", FieldPath: "EnvironmentAlias", Kind: FlagKindString, Required: true}, + {FlagName: "limit", FieldPath: "Limit", Kind: FlagKindInt64, Required: true}, + {FlagName: "config", FieldPath: "Config", Kind: FlagKindJSON, Optional: true}, + {FlagName: "user-id", FieldPath: "UserID", Kind: FlagKindString, Required: true}, +} + +func buildMissing(t *testing.T, args ...string) error { + t.Helper() + cmd := &cobra.Command{Use: "send"} + RegisterFlags(cmd, missingTestMeta) + if err := cmd.ParseFlags(args); err != nil { + t.Fatal(err) + } + _, err := BuildRequest[missingTestRequest](cmd, missingTestMeta, "", "") + return err +} + +// One run names every missing flag, in the order the command defines them. +func TestEveryMissingRequiredFlagIsNamedAtOnce(t *testing.T) { + err := buildMissing(t, "--environment-alias", "main") + var missing *MissingFlagsError + if !errors.As(err, &missing) { + t.Fatalf("got %v, want a MissingFlagsError", err) + } + if want := []string{"project-id", "limit", "user-id"}; !reflect.DeepEqual(missing.Flags, want) { + t.Errorf("flags = %v, want %v", missing.Flags, want) + } + if got, want := err.Error(), "missing required flags: --project-id, --limit, --user-id"; got != want { + t.Errorf("Error() = %q, want %q", got, want) + } +} + +// One missing flag reads as it always has. +func TestOneMissingFlagReadsAsBefore(t *testing.T) { + err := buildMissing(t, "--project-id", "p", "--environment-alias", "main", "--limit", "5") + if err == nil || err.Error() != "missing required flag: --user-id" { + t.Errorf("got %v", err) + } + if err := buildMissing(t, "--project-id", "p", "--environment-alias", "main", "--limit", "5", "--user-id", "u"); err != nil { + t.Errorf("nothing is missing, got %v", err) + } +} + +// A value vf can't use is its own error, not a missing flag. +func TestABadValueIsNotAMissingFlag(t *testing.T) { + err := buildMissing(t, "--config", "{not json") + var missing *MissingFlagsError + if err == nil || errors.As(err, &missing) { + t.Errorf("got %v, want the bad --config", err) + } +} diff --git a/internal/flagutil/shape.go b/internal/flagutil/shape.go new file mode 100644 index 00000000..3663f414 --- /dev/null +++ b/internal/flagutil/shape.go @@ -0,0 +1,239 @@ +// This file is not generated by Speakeasy. It writes out the JSON a Go +// request type takes: its keys, and what each holds. +// +// The generated help names a union's forms but not what goes in them: `vf +// test turn create` showed `payload: object` for every turn, and each form's +// own flag said only "StableTestTurnCreateRequest_User variant as JSON". +// Building a test from help alone was impossible; the testers who managed it +// read the docs' curl examples or the SDK's source. And the hint on a body +// vf couldn't build, "`vf test turn create --help` lists the body's fields", +// pointed at that same help. The SDK's types know every key, so the help is +// written from them. + +package flagutil + +import ( + "encoding/json" + "math/big" + "reflect" + "strconv" + "strings" + "time" + "unicode" + + "github.com/voiceflow/cli/internal/sdk/types" +) + +// maxShape is the longest a shape is let run before its biggest nested +// objects are shortened to {…}. +const maxShape = 400 + +// typeShape writes the JSON t takes, as `{ testID: string, payload: { +// response: string } }`. A key that may be left out is marked `?`. omit is +// a key to leave out, such as a form's "type", which its flag sets. When +// the whole is longer than maxShape, the biggest object nested in it is +// written {…}, then the next, until it fits; small ones, like a tool's +// `target: { global?: boolean, playbookID?: string }`, stay whole. +func typeShape(t reflect.Type, omit string) string { + w := shapeWriter{collapsed: map[reflect.Type]bool{}} + for { + w.sizes = map[reflect.Type]int{} + shape := w.write(t, omit, true, nil) + if len(shape) <= maxShape { + return shape + } + var biggest reflect.Type + for typ, n := range w.sizes { + if biggest == nil || n > w.sizes[biggest] || (n == w.sizes[biggest] && typ.String() < biggest.String()) { + biggest = typ + } + } + if biggest == nil { + return shape + } + w.collapsed[biggest] = true + } +} + +// shapeWriter writes shapes, with the object types it was told to shorten +// written {…}, and notes how long each nested object type ran. +type shapeWriter struct { + collapsed map[reflect.Type]bool + sizes map[reflect.Type]int +} + +// write writes t's shape. root is the outermost object, never shortened. +// seen holds the types being written, so a type that holds itself ends. +func (w *shapeWriter) write(t reflect.Type, omit string, root bool, seen []reflect.Type) string { + t = shapeType(t) + switch t.Kind() { + case reflect.Struct: + switch { + case t == reflect.TypeOf(big.Int{}): + return "number" + case t == reflect.TypeOf(time.Time{}), t == reflect.TypeOf(types.Date{}): + return "string" + } + for _, s := range seen { + if s == t { + return "{…}" + } + } + if w.collapsed[t] && !root { + return "{…}" + } + seen = append(seen, t) + var shape string + if isUnion(t) { + var forms []string + for _, f := range unionMembers(t) { + forms = append(forms, w.write(f.Type, "", root, seen)) + } + shape = strings.Join(forms, " | ") + } else { + shape = w.writeObject(t, omit, seen) + } + if !root && shape != "{}" { + w.sizes[t] = max(w.sizes[t], len(shape)) + } + return shape + case reflect.Map: + return "{ : " + w.write(t.Elem(), "", false, seen) + " }" + case reflect.Slice, reflect.Array: + if t.Elem().Kind() == reflect.Uint8 { + return "string" + } + return "[" + w.write(t.Elem(), "", false, seen) + "]" + case reflect.String: + return "string" + case reflect.Bool: + return "boolean" + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, + reflect.Float32, reflect.Float64: + return "number" + } + return "any" +} + +// writeObject writes struct t's keys. +func (w *shapeWriter) writeObject(t reflect.Type, omit string, seen []reflect.Type) string { + var keys []string + open := false + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if f.Tag.Get("additionalProperties") == "true" { + open = true + continue + } + name := jsonName(f) + if !f.IsExported() || name == "-" || name == omit { + continue + } + value := enumLiteral(shapeType(f.Type), t) + if value == "" { + value = w.write(f.Type, "", false, seen) + } + if optionalField(f) { + name += "?" + } else if f.Type.Kind() == reflect.Ptr { + value += " | null" + } + keys = append(keys, name+": "+value) + } + if open { + keys = append(keys, "…") + } + if len(keys) == 0 { + return "{}" + } + return "{ " + strings.Join(keys, ", ") + " }" +} + +var enumLiterals = map[reflect.Type]string{} + +// enumLiteral is `"user"` when t is an enum that takes only that value, as +// a form's "type" does, and "" otherwise. Go can't list an enum's values, +// so the words t's name and its owner's end with are tried: the user +// form's StableTestTurnCreateRequestTypeUser takes "user", and +// SimulationTurnTestJudgeLLMEval's type takes "llm_eval". A guess counts +// only when the SDK's own decoder takes it and refuses anything else. +func enumLiteral(t, owner reflect.Type) string { + if t.Kind() != reflect.String || t.Name() == "" || t.PkgPath() == "" || !implementsUnmarshaler(t) { + return "" + } + if literal, ok := enumLiterals[t]; ok { + return literal + } + takes := func(s string) bool { + data, _ := json.Marshal(s) + return json.Unmarshal(data, reflect.New(t).Interface()) == nil + } + found := map[string]bool{} + if !takes("\x00vf") { + for _, name := range []string{t.Name(), owner.Name()} { + words := camelWords(name) + if n := len(words); n > 0 && words[n-1] == "Type" { + words = words[:n-1] + } + for k := 1; k <= 3 && k <= len(words); k++ { + tail := words[len(words)-k:] + for _, sep := range []string{"_", "", "-"} { + for _, s := range []string{strings.ToLower(strings.Join(tail, sep)), strings.Join(tail, sep)} { + if takes(s) { + found[s] = true + } + } + } + } + } + } + literal := "" + if len(found) == 1 { + for s := range found { + literal = strconv.Quote(s) + } + } + enumLiterals[t] = literal + return literal +} + +// camelWords splits a Go name into its words: LLMEval is LLM and Eval. +func camelWords(name string) []string { + var words []string + r := []rune(name) + start := 0 + for i := 1; i < len(r); i++ { + lower, upper := unicode.IsLower, unicode.IsUpper + if upper(r[i]) && (lower(r[i-1]) || unicode.IsDigit(r[i-1]) || (i+1 < len(r) && lower(r[i+1]) && upper(r[i-1]))) { + words = append(words, string(r[start:i])) + start = i + } + } + if start < len(r) { + words = append(words, string(r[start:])) + } + return words +} + +// shapeType sees through pointers and OptionalNullable[T] to the type a +// value is written as. +func shapeType(t reflect.Type) reflect.Type { + for { + switch { + case t.Kind() == reflect.Ptr: + t = t.Elem() + case t.Kind() == reflect.Map && t.Key().Kind() == reflect.Bool && t.Elem().Kind() == reflect.Ptr: + t = t.Elem().Elem() + default: + return t + } + } +} + +// optionalField reports whether field f may be left out of the JSON: the SDK +// leaves out an empty optional field, or fills in its default. A pointer +// alone is no sign; a required field may be null. +func optionalField(f reflect.StructField) bool { + return strings.Contains(f.Tag.Get("json"), ",omit") || f.Tag.Get("default") != "" +} diff --git a/internal/flagutil/shape_test.go b/internal/flagutil/shape_test.go new file mode 100644 index 00000000..b7eb0378 --- /dev/null +++ b/internal/flagutil/shape_test.go @@ -0,0 +1,56 @@ +// This file is not generated by Speakeasy. It covers shape.go against the +// SDK's own request types. + +package flagutil + +import ( + "reflect" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/sdk/models/components" +) + +func TestTypeShapeWritesTheKeysAndWhatTheyHold(t *testing.T) { + user := typeShape(reflect.TypeOf(components.StableTestTurnCreateRequestUser{}), "type") + if want := "{ testID: string, payload: { response: string, variableStates: string | [{ id: string, variableID: string | null, value: string | null }] } }"; user != want { + t.Errorf("user turn:\n got %s\nwant %s", user, want) + } + check := typeShape(reflect.TypeOf(components.StableTestCheckCreateRequestResponse{}), "type") + if want := `{ turnID: string, payload: { type: "equal", value: string } | { type: "llm_eval", prompt: string } }`; check != want { + t.Errorf("response check:\n got %s\nwant %s", check, want) + } + // Too long whole: the biggest nested objects are shortened, the small + // target is kept. + tool := typeShape(reflect.TypeOf(components.StableToolCreateRequestV2Function{}), "type") + if len(tool) > maxShape || !strings.Contains(tool, "target: { global?: boolean, playbookID?: string }") || !strings.Contains(tool, "{…}") { + t.Errorf("function tool (%d): %s", len(tool), tool) + } +} + +func TestEnumLiteralIsOnlyAValueTheDecoderTakes(t *testing.T) { + owner := reflect.TypeOf(components.SimulationTurnTestJudgeLLMEval{}) + field, _ := owner.FieldByName("Type") + if got := enumLiteral(field.Type, owner); got != `"llm_eval"` { + t.Errorf("llm eval: %s", got) + } + if got := enumLiteral(reflect.TypeOf(components.StableTestTurnCreateRequestTypeUser("")), owner); got != `"user"` { + t.Errorf("user: %s", got) + } + // Several values, or none the name gives: no literal. + if got := enumLiteral(reflect.TypeOf(components.StableTestCheckCreateRequestResourceType("")), owner); got != "" { + t.Errorf("resource type: %s", got) + } +} + +func TestCamelWords(t *testing.T) { + for name, want := range map[string]string{ + "SimulationTurnTestJudgeLLMEval": "Simulation Turn Test Judge LLM Eval", + "StableToolCreateRequestV2TypeFunction": "Stable Tool Create Request V2 Type Function", + "ID": "ID", + } { + if got := strings.Join(camelWords(name), " "); got != want { + t.Errorf("%s: %q", name, got) + } + } +} diff --git a/internal/flagutil/shorthands.go b/internal/flagutil/shorthands.go new file mode 100644 index 00000000..f1f12591 --- /dev/null +++ b/internal/flagutil/shorthands.go @@ -0,0 +1,72 @@ +// This file is not generated by Speakeasy. It gives -p and -e one meaning on +// every command: --project-id and --environment-alias. +// +// The generator gives a flag the first letter of its name as a shorthand, but +// only when no other flag on the command starts with that letter. So `agent +// update`, which also has --prompt and --playbooks, got no -p, and its +// --end-tool cost --environment-alias its -e. 47 commands with --project-id had +// no -p, and 36 with --environment-alias no -e: playbook get, tool list, +// transcript grep, event get, workflow create and more. Someone who learned +// `-p $P -e main` on one command got "unknown flag" on the next. +// +// Now --project-id and --environment-alias take -p and -e wherever no other +// flag of the command has the letter, which today is everywhere they appear. +// +// Commands without those flags keep their letters: -e is --evaluation-id in +// `vf evaluation`, --end-date in the workspace and organization analytics +// queries and --exclude in `document preview-sitemap`; -p is --phone-number-id +// in `phone-number get/update/delete/unassign` and --project-ids in the +// workspace analytics queries. None of them can take a project or an +// environment, and taking the letter away would break the scripts that use it. + +package flagutil + +import ( + "slices" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +// conventionalShorthands are the letters these flags have on every command +// where the letter is free. +var conventionalShorthands = map[string]string{ + "project-id": "p", + "environment-alias": "e", +} + +// withConventionalShorthands is meta with -p and -e given to --project-id and +// --environment-alias when they have no shorthand and no other flag of cmd's, +// a union form's included, has the letter. +func withConventionalShorthands(cmd *cobra.Command, meta []FlagMeta) []FlagMeta { + taken := map[string]bool{} + mark := func(f *pflag.Flag) { taken[f.Shorthand] = true } + cmd.Flags().VisitAll(mark) + cmd.InheritedFlags().VisitAll(mark) + var visit func(ms []FlagMeta) + visit = func(ms []FlagMeta) { + for _, m := range ms { + taken[m.Shorthand] = true + if m.Union != nil { + for _, v := range m.Union.Variants { + visit(v.Fields) + } + } + } + } + visit(meta) + + out, cloned := meta, false + for i, m := range meta { + letter, ok := conventionalShorthands[m.FlagName] + if !ok || m.Shorthand != "" || taken[letter] { + continue + } + if !cloned { + out, cloned = slices.Clone(meta), true // the generated metadata is shared; leave it as it is + } + out[i].Shorthand = letter + taken[letter] = true + } + return out +} diff --git a/internal/flagutil/standin.go b/internal/flagutil/standin.go new file mode 100644 index 00000000..e25e115a --- /dev/null +++ b/internal/flagutil/standin.go @@ -0,0 +1,55 @@ +// This file is not generated by Speakeasy. It lets one flag stand in for a +// required one. +// +// `conversation send --text hi` gives the action that --action otherwise +// gives as JSON. --action is required, so without a word about --text the +// help examples added `--action ` after --text, and help said +// --action was required outright, though --text alone is enough. + +package flagutil + +import ( + "slices" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +// StandsFor annotates a flag that gives the value of other flags, named in +// its value. A required flag is given when a flag that stands for it is. +const StandsFor = "vf:stands-for" + +// StandIn marks flag as giving each of others, and says so in their help. +func StandIn(cmd *cobra.Command, flag string, others ...string) { + if cmd.Flags().Lookup(flag) == nil { + return + } + _ = cmd.Flags().SetAnnotation(flag, StandsFor, others) + for _, name := range others { + if f := cmd.Flags().Lookup(name); f != nil { + f.Usage = strings.Replace(f.Usage, "[required]", "[required, or --"+flag+"]", 1) + } + } +} + +// StoodInFor reports whether one of names, the flags given, stands for name. +func StoodInFor(cmd *cobra.Command, names []string, name string) bool { + for _, n := range names { + if f := cmd.Flags().Lookup(n); f != nil && slices.Contains(f.Annotations[StandsFor], name) { + return true + } + } + return false +} + +// StandInFor is the flag that stands in for name on cmd, or "" when none does. +func StandInFor(cmd *cobra.Command, name string) string { + stand := "" + cmd.Flags().VisitAll(func(f *pflag.Flag) { + if stand == "" && slices.Contains(f.Annotations[StandsFor], name) { + stand = f.Name + } + }) + return stand +} diff --git a/internal/flagutil/unionform.go b/internal/flagutil/unionform.go index 419ba289..745ba83d 100644 --- a/internal/flagutil/unionform.go +++ b/internal/flagutil/unionform.go @@ -7,19 +7,38 @@ // value comes from any one of several flags: --body-param, or a variant's // --body-param.response, or that variant's field flags. So nothing told the // help examples to set it, and 7 of them failed as written. +// +// It also keeps a form's fields from reading as required outright. Each form +// marks the fields it needs [required], so help listed every form's under +// Required Flags: 15 on `evaluation create`, across its boolean, number and +// string forms, of which one is wanted. `test turn create` required the agent +// turn's fields, which a user turn doesn't have. Such a field now says +// "[required with --body-param.boolean.*]" among the optional flags, and is +// annotated with its form instead of speakeasy:required. A form given without +// one of them still fails, as before, naming it. +// +// And it lists such a union among the required flags. `conversation send` +// can't run without --action, but help showed it under Optional Flags, so +// people left it out and learned otherwise from the error. package flagutil -import "github.com/spf13/cobra" +import ( + "strings" + + "github.com/spf13/cobra" +) // UnionNeedsAForm annotates a union flag that must be given one of its forms. // Its value is the first variant's flag, or the union's own flag when its // variants have no flags of their own. const UnionNeedsAForm = "vf:union-needs-a-form" -// markUnionNeedsAForm annotates m's flag when the union isn't optional. +// markUnionNeedsAForm annotates m's flag when the union isn't optional, and +// marks it required, so help lists it among the required flags. func markUnionNeedsAForm(cmd *cobra.Command, m FlagMeta) { - if m.Union == nil || m.Union.Optional || cmd.Flags().Lookup(m.FlagName) == nil { + f := cmd.Flags().Lookup(m.FlagName) + if m.Union == nil || m.Union.Optional || f == nil { return } form := m.FlagName @@ -27,4 +46,41 @@ func markUnionNeedsAForm(cmd *cobra.Command, m FlagMeta) { form = m.Union.Variants[0].FlagName } _ = cmd.Flags().SetAnnotation(m.FlagName, UnionNeedsAForm, []string{form}) + _ = cmd.Flags().SetAnnotation(m.FlagName, "speakeasy:required", []string{"true"}) + if !strings.Contains(f.Usage, "[required") { + f.Usage = strings.TrimSpace(f.Usage + " " + requiredUnion(m)) + } +} + +// requiredUnion is the marker a required union's help ends with. One with +// forms is given by its own flag or by one form's flags. +func requiredUnion(m FlagMeta) string { + if len(m.Union.Variants) == 0 { + return "[required]" + } + return "[required: this, or one form's --" + m.FlagName + ".* flags]" +} + +// RequiredWithForm annotates a field a union's form requires. Its value is +// the form's flag, body-param.boolean: the field is required when the form is +// given through its flags, and not otherwise. +const RequiredWithForm = "vf:required-with-form" + +// markFormFields turns each of m's forms' required fields from required into +// required with that form, in its annotations and in its help. +func markFormFields(cmd *cobra.Command, m FlagMeta) { + if m.Union == nil { + return + } + for _, v := range m.Union.Variants { + for _, field := range v.Fields { + f := cmd.Flags().Lookup(field.FlagName) + if f == nil || len(f.Annotations["speakeasy:required"]) == 0 { + continue + } + delete(f.Annotations, "speakeasy:required") + _ = cmd.Flags().SetAnnotation(f.Name, RequiredWithForm, []string{v.FlagName}) + f.Usage = strings.Replace(f.Usage, "[required]", "[required with --"+v.FlagName+".*]", 1) + } + } } diff --git a/internal/flagutil/unknownkeys.go b/internal/flagutil/unknownkeys.go new file mode 100644 index 00000000..f7159d2e --- /dev/null +++ b/internal/flagutil/unknownkeys.go @@ -0,0 +1,325 @@ +// This file is not generated by Speakeasy. It warns about keys in a JSON +// body that the request has no field for. +// +// The SDK decodes a body into its request type and drops every key the type +// doesn't have, without a word. So `vf test create --body '{"name":…, +// "turns":[…]}'` made a test with no turns, a user turn given +// `"payload":{"text":"hi"}` was sent with an empty response, and a tool +// given `"target":{"type":"agent"}` was sent with `"target":{}`. Each +// command exited 0, and the agents that ran them believed they had built +// what they asked for. +// +// warnUnknownKeys compares the JSON a person gave with the type it was +// decoded into, and names on stderr each key that was dropped, with the keys +// that level takes. It doesn't fail the command. A key inside a union is +// checked against the form the SDK chose, a map takes any key, and a type +// that keeps extra keys (additionalProperties) keeps them. + +package flagutil + +import ( + "bytes" + "encoding/json" + "fmt" + "math/big" + "reflect" + "sort" + "strings" + "time" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/sdk/types" +) + +// unknownKey is a key the request type has no field for. +type unknownKey struct { + path string // payload.text + in reflect.Type // the type the key was looked for in +} + +// warnUnknownKeys warns on cmd's stderr about the keys in data that into, +// the value data was decoded into, has no field for. source names where +// data came from: --body, stdin or a JSON flag. +func warnUnknownKeys(cmd *cobra.Command, source string, data []byte, into reflect.Value) { + dec := json.NewDecoder(bytes.NewReader(data)) + dec.UseNumber() + var node any + if dec.Decode(&node) != nil || !into.IsValid() { + return + } + var found []unknownKey + seen := map[string]bool{} + walkKeys(node, into, into.Type(), "", func(k unknownKey) { + if !seen[k.path] { + seen[k.path] = true + found = append(found, k) + } + }) + if len(found) == 0 { + return + } + paths := make([]string, len(found)) + for i, k := range found { + paths[i] = k.path + } + w := Warning{ + Type: "unknown_body_keys", + Message: fmt.Sprintf("%s has keys %s doesn't take, so they weren't sent: %s", source, cmd.CommandPath(), strings.Join(paths, ", ")), + Keys: paths, + } + said := map[string]bool{} + for _, k := range found { + parent := "The top level" + if i := strings.LastIndex(k.path, "."); i >= 0 { + parent = k.path[:i] + } + if keys := keysOf(k.in); keys != "" && !said[parent] { + said[parent] = true + w.Hints = append(w.Hints, parent+" takes: "+keys) + } + } + w.Hints = append(w.Hints, helpListsFields(cmd)) + emitWarning(cmd, w) +} + +// bodyValue is the body in request v: the field at bodyFieldPath, or v +// itself when the request is the body. +func bodyValue(v reflect.Value, bodyFieldPath string) reflect.Value { + if bodyFieldPath == "" { + return v + } + field, err := navigateToField(v, bodyFieldPath) + if err != nil { + return reflect.Value{} + } + return field +} + +// bodySource names where a whole body came from: its flag, or stdin. +func bodySource(cmd *cobra.Command, flagName string) string { + if v, _ := GetStringFlag(cmd, flagName); FlagChanged(cmd, flagName) && strings.TrimSpace(v) != "-" { + return "--" + flagName + } + return "stdin" +} + +// walkKeys reports, through found, each key in node that t has no field for. +// v is node decoded into t, or invalid where nothing was decoded; it says +// which form of a union the SDK chose. +func walkKeys(node any, v reflect.Value, t reflect.Type, path string, found func(unknownKey)) { + if node == nil { + return + } + for { + if t.Kind() == reflect.Ptr { + t, v = t.Elem(), elem(v) + continue + } + // optionalnullable.OptionalNullable[T] is a map[bool]*T. + if t.Kind() == reflect.Map && t.Key().Kind() == reflect.Bool && t.Elem().Kind() == reflect.Ptr { + if v.IsValid() { + v = v.MapIndex(reflect.ValueOf(true)) + } + t, v = t.Elem().Elem(), elem(v) + continue + } + break + } + switch t.Kind() { + case reflect.Struct: + if isScalarStruct(t) { + return + } + if isUnion(t) { + if member, ok := chosenMember(v); ok { + walkKeys(node, member, member.Type(), path, found) + } + return + } + obj, ok := node.(map[string]any) + if !ok { + return + } + fields, open := jsonFields(t) + for _, key := range sortedKeys(obj) { + i, ok := fields[key] + if !ok && !implementsUnmarshaler(t) { + i, ok = fieldFold(fields, key) // encoding/json matches any case + } + switch { + case ok: + var fv reflect.Value + if v.IsValid() { + fv = v.Field(i) + } + walkKeys(obj[key], fv, t.Field(i).Type, joinPath(path, key), found) + case !open: + found(unknownKey{path: joinPath(path, key), in: t}) + } + } + case reflect.Map: + obj, ok := node.(map[string]any) + if !ok || t.Key().Kind() != reflect.String { + return + } + for _, key := range sortedKeys(obj) { + var ev reflect.Value + if v.IsValid() { + ev = v.MapIndex(reflect.ValueOf(key).Convert(t.Key())) + } + walkKeys(obj[key], ev, t.Elem(), joinPath(path, key), found) + } + case reflect.Slice, reflect.Array: + arr, ok := node.([]any) + if !ok || t.Elem().Kind() == reflect.Uint8 { + return + } + for i, item := range arr { + var ev reflect.Value + if v.IsValid() && i < v.Len() { + ev = v.Index(i) + } + walkKeys(item, ev, t.Elem(), path+"[]", found) + } + } +} + +// elem is what v points to, or invalid when v is invalid or nil. +func elem(v reflect.Value) reflect.Value { + if !v.IsValid() || v.IsNil() { + return reflect.Value{} + } + return v.Elem() +} + +// isScalarStruct reports whether t is a struct the SDK reads from a scalar. +func isScalarStruct(t reflect.Type) bool { + return t == reflect.TypeOf(time.Time{}) || t == reflect.TypeOf(big.Int{}) || t == reflect.TypeOf(types.Date{}) +} + +// isUnion reports whether t is a union: a struct whose fields are its forms. +func isUnion(t reflect.Type) bool { + for i := 0; i < t.NumField(); i++ { + if t.Field(i).Tag.Get("union") == "member" { + return true + } + } + return false +} + +// unionMembers are the fields of union t that hold its forms. +func unionMembers(t reflect.Type) []reflect.StructField { + var members []reflect.StructField + for i := 0; i < t.NumField(); i++ { + if f := t.Field(i); f.Tag.Get("union") == "member" { + members = append(members, f) + } + } + return members +} + +// chosenMember is the form union value v holds. +func chosenMember(v reflect.Value) (reflect.Value, bool) { + if !v.IsValid() { + return reflect.Value{}, false + } + for _, f := range unionMembers(v.Type()) { + fv := v.FieldByIndex(f.Index) + switch fv.Kind() { + case reflect.Ptr, reflect.Slice, reflect.Map, reflect.Interface: + if !fv.IsNil() { + return fv, true + } + } + } + return reflect.Value{}, false +} + +// jsonFields maps the JSON keys of struct t to its fields, named as the +// SDK's decoder names them. open reports whether t keeps keys it has no +// field for. +func jsonFields(t reflect.Type) (fields map[string]int, open bool) { + fields = map[string]int{} + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if f.Tag.Get("additionalProperties") == "true" { + open = true + continue + } + if !f.IsExported() { + continue + } + if name := jsonName(f); name != "-" { + fields[name] = i + } + } + return fields, open +} + +// jsonName is the key the SDK's decoder reads field f from. +func jsonName(f reflect.StructField) string { + name := f.Name + for _, part := range strings.Split(f.Tag.Get("json"), ",") { + if part != "" && part != "omitempty" && part != "omitzero" { + name = part + } + } + return name +} + +// fieldFold finds key in fields ignoring case. +func fieldFold(fields map[string]int, key string) (int, bool) { + for name, i := range fields { + if strings.EqualFold(name, key) { + return i, true + } + } + return 0, false +} + +func implementsUnmarshaler(t reflect.Type) bool { + return reflect.PointerTo(t).Implements(reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()) +} + +// keysOf lists the keys struct t takes, or each form's for a union. +func keysOf(t reflect.Type) string { + if isUnion(t) { + var forms []string + for _, f := range unionMembers(t) { + ft := f.Type + for ft.Kind() == reflect.Ptr { + ft = ft.Elem() + } + if ft.Kind() == reflect.Struct { + if keys := keysOf(ft); keys != "" { + forms = append(forms, "{"+keys+"}") + } + } + } + return strings.Join(forms, " or ") + } + var keys []string + for i := 0; i < t.NumField(); i++ { + if f := t.Field(i); f.IsExported() && f.Tag.Get("additionalProperties") != "true" && jsonName(f) != "-" { + keys = append(keys, jsonName(f)) + } + } + return strings.Join(keys, ", ") +} + +func joinPath(path, key string) string { + if path == "" { + return key + } + return path + "." + key +} + +func sortedKeys[V any](m map[string]V) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + return keys +} diff --git a/internal/flagutil/unknownkeys_test.go b/internal/flagutil/unknownkeys_test.go new file mode 100644 index 00000000..c7b605f4 --- /dev/null +++ b/internal/flagutil/unknownkeys_test.go @@ -0,0 +1,108 @@ +// This file is not generated by Speakeasy. It covers unknownkeys.go and +// warning.go against the SDK's own request types. + +package flagutil + +import ( + "bytes" + "encoding/json" + "reflect" + "strings" + "testing" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/sdk/models/components" +) + +// droppedKeys decodes data into a new T as the SDK does, and returns the +// keys warnUnknownKeys names, with what it wrote on stderr. +func droppedKeys[T any](t *testing.T, data string) ([]string, string) { + t.Helper() + var v T + if err := json.Unmarshal([]byte(data), &v); err != nil { + t.Fatalf("%s: %v", data, err) + } + cmd := &cobra.Command{Use: "create"} + var stderr bytes.Buffer + cmd.SetErr(&stderr) + var keys []string + walkKeys(mustDecode(t, data), reflect.ValueOf(v), reflect.TypeOf(v), "", func(k unknownKey) { keys = append(keys, k.path) }) + warnUnknownKeys(cmd, "--body", []byte(data), reflect.ValueOf(&v).Elem()) + return keys, stderr.String() +} + +func mustDecode(t *testing.T, data string) any { + t.Helper() + var node any + if err := json.Unmarshal([]byte(data), &node); err != nil { + t.Fatal(err) + } + return node +} + +// The keys the round-3 sweep lost: a test's turns, a user turn's +// payload.text and a tool's target.type. +func TestUnknownBodyKeysAreNamed(t *testing.T) { + keys, said := droppedKeys[components.StableTestCreateRequest](t, `{"name":"greets","turns":[{"type":"user"}]}`) + if !reflect.DeepEqual(keys, []string{"turns"}) || !strings.Contains(said, "Warning: --body has keys create doesn't take, so they weren't sent: turns\n The top level takes: name, settings") { + t.Errorf("test: %v\n%s", keys, said) + } + + keys, said = droppedKeys[components.StableTestTurnCreateRequest](t, `{"type":"user","testID":"t1","payload":{"text":"hi","response":"","variableStates":[]}}`) + if !reflect.DeepEqual(keys, []string{"payload.text"}) || !strings.Contains(said, "payload takes: response, variableStates") { + t.Errorf("user turn: %v\n%s", keys, said) + } + + keys, said = droppedKeys[components.StableToolCreateRequestV2](t, `{"type":"function","functionID":"f1","target":{"type":"agent"}}`) + if !reflect.DeepEqual(keys, []string{"target.type"}) || !strings.Contains(said, "target takes: global, playbookID") { + t.Errorf("tool: %v\n%s", keys, said) + } +} + +// Keys a type does take are never named: another form's fields are checked +// against the form the SDK chose, a map takes any key, and a type that keeps +// extra keys keeps them. +func TestKnownBodyKeysAreNotNamed(t *testing.T) { + for name, check := range map[string]func() ([]string, string){ + "an agent turn's own payload": func() ([]string, string) { + return droppedKeys[components.StableTestTurnCreateRequest](t, `{"type":"agent","testID":"t1","payload":{"sequential":true}}`) + }, + "variable states as a list": func() ([]string, string) { + return droppedKeys[components.StableTestTurnCreateRequest](t, `{"type":"user","testID":"t1","payload":{"response":"hi","variableStates":[{"variableID":"v1","value":"x"}]}}`) + }, + "a map's keys": func() ([]string, string) { + return droppedKeys[components.StableToolCreateRequestV2](t, `{"type":"function","functionID":"f1","target":{"global":true},"captureResponse":{"anyName":{"variableOrEntityID":"v1"}}}`) + }, + "extra keys a type keeps": func() ([]string, string) { + return droppedKeys[components.ActionRequest](t, `{"type":"action","anything":1,"metadata":{"k":"v"}}`) + }, + "null and empty values": func() ([]string, string) { + return droppedKeys[components.StableTestCreateRequest](t, `{"name":"n","settings":null}`) + }, + } { + if keys, said := check(); len(keys) > 0 || said != "" { + t.Errorf("%s: named %v\n%s", name, keys, said) + } + } +} + +// In agent mode the warning is a JSON object, so all of stderr parses. +func TestAnUnknownKeyWarningIsJSONInAgentMode(t *testing.T) { + saved := isAgentMode + isAgentMode = func() bool { return true } + t.Cleanup(func() { isAgentMode = saved }) + _, said := droppedKeys[components.StableTestCreateRequest](t, `{"name":"","turns":[]}`) + var event struct { + Warning string `json:"warning"` + Type string `json:"warning_type"` + Keys []string `json:"keys"` + Hints []string `json:"hints"` + } + if err := json.Unmarshal([]byte(said), &event); err != nil { + t.Fatalf("%v:\n%s", err, said) + } + if event.Type != "unknown_body_keys" || !reflect.DeepEqual(event.Keys, []string{"turns"}) || len(event.Hints) != 2 { + t.Errorf("got %+v", event) + } +} diff --git a/internal/flagutil/warning.go b/internal/flagutil/warning.go new file mode 100644 index 00000000..d9b56d5f --- /dev/null +++ b/internal/flagutil/warning.go @@ -0,0 +1,63 @@ +// This file is not generated by Speakeasy. It writes a warning on stderr: +// something vf noticed that didn't stop the command. +// +// A person reads a line and its hints. An agent reads a JSON object, as it +// does for progress events and errors, so every byte it reads from stderr +// parses. flagutil can't import output, which decides how a line is drawn, +// so output installs that with SetWarningLine. + +package flagutil + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "strings" + + "github.com/spf13/cobra" +) + +// Warning is something vf noticed that didn't stop the command. +type Warning struct { + Type string // warning_type, in agent mode + Message string // one line + Keys []string // what it is about, when that is a list of keys + Hints []string // what to do about it +} + +// warningLine draws a warning's first line for a person. +var warningLine = func(cmd *cobra.Command, w io.Writer, msg string) string { return "Warning: " + msg } + +// SetWarningLine installs the function that draws a warning's first line +// for a person. +func SetWarningLine(draw func(cmd *cobra.Command, w io.Writer, msg string) string) { + warningLine = draw +} + +// emitWarning writes w on cmd's stderr. +func emitWarning(cmd *cobra.Command, w Warning) { + out := cmd.ErrOrStderr() + if !isAgentMode() { + lines := []string{warningLine(cmd, out, w.Message)} + for _, h := range w.Hints { + lines = append(lines, " "+h) + } + fmt.Fprintln(out, strings.Join(lines, "\n")) + return + } + event := map[string]any{"warning": w.Message, "warning_type": w.Type} + if len(w.Keys) > 0 { + event["keys"] = w.Keys + } + if len(w.Hints) > 0 { + event["hints"] = w.Hints + } + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(false) + enc.SetIndent("", " ") + if enc.Encode(event) == nil { + _, _ = out.Write(buf.Bytes()) + } +} diff --git a/internal/interactive/confirm.go b/internal/interactive/confirm.go new file mode 100644 index 00000000..dd423671 --- /dev/null +++ b/internal/interactive/confirm.go @@ -0,0 +1,56 @@ +// This file is not generated by Speakeasy. It asks yes or no before vf does +// something it can't take back, in the form's own look, and remembers what +// each picked ID is called so the question can name it. +// internal/cli/confirm.go decides when to ask. + +package interactive + +import ( + "context" + "os" + + "github.com/charmbracelet/huh" + "golang.org/x/term" +) + +// AskYesNo shows title and note over Yes and No, with No chosen, and +// returns the answer: y and n answer at once, and Enter takes No unless the +// person moved to Yes. It draws on stderr, so stdout can still be piped +// (`-o json | jq`). +func AskYesNo(ctx context.Context, title, note string) (bool, error) { + width, _, err := term.GetSize(int(os.Stderr.Fd())) + if err != nil || width <= 0 { + width = 80 + } + yes := false + err = huh.NewForm(huh.NewGroup(huh.NewConfirm(). + Title(title). + Description(note). + Affirmative("Yes"). + Negative("No"). + Value(&yes))). + WithOutput(os.Stderr). + WithWidth(width). + WithTheme(formTheme()). + WithShowHelp(false). + RunWithContext(ctx) + return yes, err +} + +// pickedNames holds what each value picked in this run is called, by flag: +// the form is gone by the time a delete asks. +var pickedNames = map[string]map[string]string{} + +func rememberName(flag, value, name string) { + if name == "" || name == value { + return + } + if pickedNames[flag] == nil { + pickedNames[flag] = map[string]string{} + } + pickedNames[flag][value] = name +} + +// PickedName is what value was called when it was picked for flag in this +// run, or "" when it wasn't picked from a list. +func PickedName(flag, value string) string { return pickedNames[flag][value] } diff --git a/internal/interactive/confirm_test.go b/internal/interactive/confirm_test.go new file mode 100644 index 00000000..e6d8b1b4 --- /dev/null +++ b/internal/interactive/confirm_test.go @@ -0,0 +1,35 @@ +// This file is not generated by Speakeasy. It covers confirm.go: what a +// picker picked keeps its name for the question a delete asks. + +package interactive + +import "testing" + +func TestPickedNamesOutliveTheForm(t *testing.T) { + isolatePicks(t) + pickedNames = map[string]map[string]string{} + t.Cleanup(func() { pickedNames = map[string]map[string]string{} }) + + (&fakePicker{choices: []Choice{{Value: "p1", Name: "Help bot"}, {Value: "p2", Name: "Sales bot"}}}).register("project-id", "project") + s := newSession("delete", "project-id") + s.picks["Project"] = "p2" + if _, err := s.fill(fields("project-id")); err != nil { + t.Fatal(err) + } + if got := PickedName("project-id", "p2"); got != "Sales bot" { + t.Errorf("a value picked from a list should keep its name, got %q", got) + } + + (&fakePicker{choices: []Choice{{Value: "w1", Name: "Support"}}}).register("workspace-id", "workspace") + s = newSession("list", "workspace-id") + if _, err := s.fill(fields("workspace-id")); err != nil { + t.Fatal(err) + } + if got := PickedName("workspace-id", "w1"); got != "Support" { + t.Errorf("a lone value taken without asking should keep its name too, got %q", got) + } + + if got := PickedName("project-id", "p9"); got != "" { + t.Errorf("a value never picked has no name, got %q", got) + } +} diff --git a/internal/interactive/interactive.go b/internal/interactive/interactive.go index 7df9c7b6..ab54a3d5 100644 --- a/internal/interactive/interactive.go +++ b/internal/interactive/interactive.go @@ -597,6 +597,7 @@ func flagDisplayName(m flagutil.FlagMeta) string { // flagDescription returns a description combining the schema description // and the corresponding CLI flag name for reference. func flagDescription(m flagutil.FlagMeta) string { + m = flagutil.DescribeFlag(m) // flagutil/description.go: the words help gives it parts := []string{} if m.Description != "" { parts = append(parts, m.Description) diff --git a/internal/interactive/pickers.go b/internal/interactive/pickers.go index 71d82ea0..94ecc240 100644 --- a/internal/interactive/pickers.go +++ b/internal/interactive/pickers.go @@ -286,6 +286,7 @@ func (p *picking) pick(flag string, picker Picker, needs map[string]string) (str for _, c := range choices { if c.Value == value { p.names[flag] = c.Name + rememberName(flag, value, c.Name) // confirm.go: a delete's question names it p.using(picker, c.Name, value) } } @@ -297,6 +298,7 @@ func (p *picking) take(flag string, picker Picker, c Choice, why string) string fmt.Fprintln(p.out, p.u.Status(ui.StatusDone, "Using "+picker.Noun+" "+c.Name+" ("+c.Value+"), "+why)) savePick(flag, c.Value) p.names[flag] = c.Name + rememberName(flag, c.Value, c.Name) // confirm.go: a delete's question names it return c.Value } diff --git a/internal/oauth/present.go b/internal/oauth/present.go index d4eb40ac..757cff7f 100644 --- a/internal/oauth/present.go +++ b/internal/oauth/present.go @@ -122,7 +122,7 @@ func reportLoginError(u *ui.UI, out io.Writer, err error, interrupted bool, retr } fmt.Fprintln(out, u.Status(ui.StatusFailed, "Couldn't sign in")) fmt.Fprintln(out, u.Under(err.Error(), "Try again: "+u.Accent(retry))) - return output.AlreadyReported(err) + return output.WithExitCode(output.AlreadyReported(err), output.ExitAuth) // still not signed in } // writeSignedIn reports a finished login or signup: who and where, then only diff --git a/internal/output/agentmode.go b/internal/output/agentmode.go index f6963eea..b29795df 100644 --- a/internal/output/agentmode.go +++ b/internal/output/agentmode.go @@ -4,7 +4,6 @@ package output import ( - "encoding/json" "fmt" "os" "strings" @@ -165,31 +164,11 @@ func enrichAgentError(m map[string]interface{}, err error, statusCode int) { } // AgentModeError outputs a structured agent-mode error and returns a non-nil -// error for exit code 1. Used for CLI-level errors (not API errors) such as -// blocking the interactive configure command. +// error carrying errorType's exit code (exitcode.go). Used for CLI-level +// errors (not API errors) such as blocking the interactive configure command. // // Single-print contract: outputs structured JSON exactly once to stderr, // then returns the error. Callers must NOT print the error again. func AgentModeError(cmd *cobra.Command, errorType, message string, hints []string) error { - out := cmd.ErrOrStderr() - - envelope := map[string]interface{}{ - "error": message, - "error_type": errorType, - "message": message, - } - if len(hints) > 0 { - envelope["hints"] = hints - } - - jsonData, err := json.MarshalIndent(envelope, "", " ") - if err != nil { - fmt.Fprintln(out, message) - return AlreadyReported(fmt.Errorf("%s", message)) // see reported.go - } - - // No colorization in agent mode. - fmt.Fprintln(out, string(jsonData)) - - return AlreadyReported(fmt.Errorf("%s", message)) // see reported.go + return agentModeError(cmd, errorType, message, hints) // envelope.go: the JSON every error has } diff --git a/internal/output/apinames_test.go b/internal/output/apinames_test.go new file mode 100644 index 00000000..ac773264 --- /dev/null +++ b/internal/output/apinames_test.go @@ -0,0 +1,34 @@ +// This file is not generated by Speakeasy. It covers vfCommandNames in +// hintfit.go: a server message names vf's commands and flags, not the MCP +// tools and API fields it was written with (flagutil/apinames.go). + +package output + +import ( + "testing" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/session" +) + +func TestAServerMessageNamesVFCommandsAndFlags(t *testing.T) { + session.Stop() + root := &cobra.Command{Use: "vf"} + test := &cobra.Command{Use: "test"} + run := &cobra.Command{Use: "run"} + workflow := &cobra.Command{Use: "workflow"} + root.AddCommand(test, workflow) + test.AddCommand(run) + noop := func(*cobra.Command, []string) error { return nil } + wait := &cobra.Command{Use: "wait", RunE: noop} + run.AddCommand(wait, &cobra.Command{Use: "create", RunE: noop}) + workflow.AddCommand(&cobra.Command{Use: "list", RunE: noop}) + wait.Flags().String("run-ids", "", "") + wait.Flags().String("environment-alias", "", "") + + x := ExplainError(wait, apiError(404, `{"message":"Pass the run IDs vf_test_create_run returned, in environmentAlias. Copy a workflow ID from voiceflow_workflow.list."}`, nil)) + if want := "Pass the run IDs `vf test run create` returned, in --environment-alias. Copy a workflow ID from `vf workflow list`."; x.Message != want { + t.Errorf("message\n got %q\nwant %q", x.Message, want) + } +} diff --git a/internal/output/badbody.go b/internal/output/badbody.go index e1a44b6e..eecacc73 100644 --- a/internal/output/badbody.go +++ b/internal/output/badbody.go @@ -14,7 +14,9 @@ // that variableStates was missing. The chain's types name the path to the // field, each the root type's name plus the field's: Request → User → // Payload1 → VariableStates1 is user.payload.variableStates. vf now says -// that, and gives the cause in full. +// that, and gives the cause in full. The next step used to be "`--help` +// lists the body's fields", which it didn't; now it gives the JSON of the +// form the field is in, which help shows too (flagutil/forms.go). package output @@ -24,6 +26,8 @@ import ( "unicode" "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/flagutil" ) var ( @@ -63,6 +67,7 @@ func explainBadBody(cmd *cobra.Command, err error) (Explanation, bool) { } if path := marshalPath(root, append(types, m[1])); path != "" { x.Title = action(cmd) + ": the body has no value for " + path + x.Next = formShape(cmd, path, x.Next) // the form's JSON, where help gives it } else { x.Title = action(cmd) + ": the body is none of its forms" x.Why = []string{"The body takes one of several forms, and none was given, so the request wasn't sent.", said} @@ -72,6 +77,18 @@ func explainBadBody(cmd *cobra.Command, err error) (Explanation, bool) { return x, true } +// formShape leads next with the JSON of the form path starts in, when cmd +// has a flag for that form: user.payload.variableStates is in the user +// form, whose flag --body-param.user says what it takes. +func formShape(cmd *cobra.Command, path string, next []string) []string { + form, _, _ := strings.Cut(path, ".") + flag, help, ok := flagutil.FormHelp(cmd, form) + if !ok { + return next + } + return append([]string{"--" + flag + " takes " + strings.Replace(help, "The ", "the ", 1)}, "`"+cmd.CommandPath()+" --help` shows every form's fields") +} + // marshalPath turns a marshal chain's types into the path to the field they // lead to: under root StableTestTurnCreateRequest, the types …User, // …Payload1 and …VariableStates1 are user.payload.variableStates. A type diff --git a/internal/output/envelope.go b/internal/output/envelope.go new file mode 100644 index 00000000..18232685 --- /dev/null +++ b/internal/output/envelope.go @@ -0,0 +1,197 @@ +// This file is not generated by Speakeasy. It writes the one JSON shape every +// error has, in agent mode and with -o json or --jq, whether vf found the +// problem itself or the API answered with it. +// +// There were three shapes. An API error was its response body with vf's keys +// mixed in, so its top-level keys were whatever the API sent: path and +// timestamp on a 404, details on a 422, cause and errorCode on some 400s, and +// "error": "Bad Request" from some services. vf added status_code next to the +// body's own statusCode, and the two disagreed: the API answers some +// validation failures with HTTP 400 and "statusCode": 422 in the body. A local +// error had error, error_type and message, and AgentModeError a third set. +// With -o json outside agent mode, error_type was left out, and a local error +// was printed as text. A parser could rely on none of it. +// +// Now every error is one object, its keys in snake_case: +// +// error the headline a person sees: "Couldn't get project · HTTP 404 Not Found" +// error_type the kind of failure: not_found, missing_flag, validation_error, … +// exit_code the code the process exits with (exitcode.go) +// message what went wrong, in one line: the API's own message, or the headline +// hints what to do next; an empty list when there is nothing to add +// explanation why, when vf can tell +// details the fields a request was refused for: {field, flag, message, code}, +// or the required flags a command was run without +// docs_url the page that covers the command +// status_code the HTTP status, when a response came back +// body the response body as the API sent it, when one came back +// +// The first five are always there. The API's own keys, statusCode among them, +// are kept under body, so nothing it says is lost. + +package output + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "sort" + "strings" + + "github.com/spf13/cobra" +) + +// FieldError is one field a request was refused for. +type FieldError struct { + Field string `json:"field,omitempty"` // the body field's path: "data.displayName" + Flag string `json:"flag,omitempty"` // the flag that sets it: "--display-name" + Message string `json:"message"` + Code string `json:"code,omitempty"` // the API's name for the problem: "too_small" +} + +// String is the field error on one line: "take: Too small (--take)". +func (f FieldError) String() string { + line := strings.TrimPrefix(f.Field+": "+f.Message, ": ") + if f.Flag != "" { + line += " (" + f.Flag + ")" + } + return line +} + +// WantsJSONError reports whether cmd's errors are printed as the JSON +// envelope: in agent mode, and when the output is for a program, with +// -o json or --jq. +func WantsJSONError(cmd *cobra.Command) bool { + return IsAgentMode() || (cmd != nil && WantsRawJSON(cmd)) +} + +// ErrorEnvelope is the JSON object for err, explained as x. +func ErrorEnvelope(x Explanation, err error) map[string]interface{} { + hints := make([]string, 0, len(x.Next)) + for _, step := range x.Next { + hints = append(hints, Plain(step)) + } + errorType := x.Type + if errorType == "" { + errorType = "error" + } + m := map[string]interface{}{ + "error": x.Title, + "error_type": errorType, + "exit_code": exitCodeOf(x, err), + "message": envelopeMessage(x, err), + "hints": hints, + } + if why := strings.Join(x.Why, " "); why != "" { + m["explanation"] = Plain(why) + } + if len(x.Details) > 0 { + m["details"] = x.Details + } + if x.Docs != "" { + m["docs_url"] = x.Docs + } + if x.Status != 0 { + m["status_code"] = x.Status + if body := strings.TrimSpace(extractErrorBody(err)); body != "" { + var parsed interface{} + if json.Unmarshal([]byte(body), &parsed) == nil { + if fields, ok := parsed.(map[string]interface{}); ok { + parsed = readableFormats(fields) // fieldformat.go: a format in words, not its 300-character regex + } + m["body"] = parsed + } else { + m["body"] = body + } + } + } + return m +} + +// envelopeMessage is what went wrong, in one line: vf's reading of the +// server's message, the message a body vf made itself carries (the +// no-credential refusal), or the headline. +func envelopeMessage(x Explanation, err error) string { + if x.Message != "" { + return x.Message + } + if fields := parseObject(extractErrorBody(err)); fields != nil { + if msg, ok := fields["message"].(string); ok && strings.TrimSpace(msg) != "" && x.Status == 0 { + return msg + } + } + return x.Title +} + +// envelopeOrder is the order the envelope's keys are written in: what +// happened first, the response body last. Keys it doesn't name, such as a +// wait's bulkID, follow in alphabetical order. +var envelopeOrder = []string{ + "error", "error_type", "exit_code", "message", "explanation", "details", + "hints", "docs_url", "status_code", "body", +} + +// MarshalEnvelope is m as indented JSON, its keys in envelopeOrder, with +// "" left as written rather than escaped to "". +func MarshalEnvelope(m map[string]interface{}) []byte { + rank := map[string]int{} + for i, k := range envelopeOrder { + rank[k] = i + 1 + } + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Slice(keys, func(i, j int) bool { + ri, rj := rank[keys[i]], rank[keys[j]] + if ri == 0 || rj == 0 { + if ri != rj { + return ri != 0 + } + return keys[i] < keys[j] + } + return ri < rj + }) + + var b bytes.Buffer + b.WriteString("{") + for i, k := range keys { + if i > 0 { + b.WriteString(",") + } + b.WriteString("\n ") + b.Write(encodeJSON(k, "")) + b.WriteString(": ") + b.Write(encodeJSON(m[k], " ")) + } + b.WriteString("\n}") + return b.Bytes() +} + +// encodeJSON is v as indented JSON, each line after its first starting with +// prefix, and with no HTML escaping. +func encodeJSON(v interface{}, prefix string) []byte { + var b bytes.Buffer + enc := json.NewEncoder(&b) + enc.SetEscapeHTML(false) + enc.SetIndent(prefix, " ") + if enc.Encode(v) != nil { + return []byte("null") + } + return bytes.TrimRight(b.Bytes(), "\n") +} + +// writeEnvelope prints err, explained as x, as the JSON envelope. +func writeEnvelope(w io.Writer, x Explanation, err error) { + _, _ = w.Write(append(MarshalEnvelope(ErrorEnvelope(x, err)), '\n')) +} + +// agentModeError is AgentModeError: a failure vf found itself, of errorType, +// with the hints given, printed as the envelope. +func agentModeError(cmd *cobra.Command, errorType, message string, hints []string) error { + x := Explanation{Type: errorType, Title: message, Next: hints} + err := errors.New(message) + writeEnvelope(cmd.ErrOrStderr(), x, err) + return reported(x, err) +} diff --git a/internal/output/envelope_test.go b/internal/output/envelope_test.go new file mode 100644 index 00000000..e5ef7a71 --- /dev/null +++ b/internal/output/envelope_test.go @@ -0,0 +1,169 @@ +// This file is not generated by Speakeasy. It covers envelope.go: every +// error, local or from the API, is one JSON object with the same keys. + +package output + +import ( + "bytes" + "encoding/json" + "errors" + "regexp" + "strings" + "testing" + + "github.com/spf13/cobra" +) + +func inAgentMode(t *testing.T) { + t.Helper() + ResetAgentMode() + t.Setenv("FORCE_AGENT_MODE", "1") + InitAgentMode(&cobra.Command{Use: "vf"}) + t.Cleanup(ResetAgentMode) +} + +func decode(t *testing.T, stderr *bytes.Buffer) map[string]interface{} { + t.Helper() + var m map[string]interface{} + if err := json.Unmarshal(stderr.Bytes(), &m); err != nil { + t.Fatalf("stderr is not one JSON object: %v\n%s", err, stderr.String()) + } + return m +} + +// The API answers some validation failures with HTTP 400 and "statusCode": +// 422 in the body, and both used to be printed side by side. +func TestAnAPIErrorHasOneStatusCode(t *testing.T) { + inAgentMode(t) + cmd := projectGet(t) + var stderr bytes.Buffer + cmd.SetErr(&stderr) + body := `{"message":"Validation failed","details":[{"code":"too_small","message":"Too small","path":["take"]}],"statusCode":422,"statusText":"Unprocessable Entity"}` + _ = Error(cmd, apiError(400, body, nil)) + + m := decode(t, &stderr) + if m["status_code"] != float64(400) { + t.Errorf("status_code = %v, want the HTTP status, 400", m["status_code"]) + } + for _, key := range []string{"statusCode", "statusText"} { + if _, has := m[key]; has { + t.Errorf("%s belongs under body, not at the top level:\n%s", key, stderr.String()) + } + } + if b, _ := m["body"].(map[string]interface{}); b["statusCode"] != float64(422) || b["statusText"] != "Unprocessable Entity" { + t.Errorf("body should be the response as sent, got %v", m["body"]) + } + if m["error"] != "Couldn't get project · HTTP 400 Bad Request" || m["message"] != "Validation failed" { + t.Errorf("error = %q, message = %q", m["error"], m["message"]) + } + details, _ := m["details"].([]interface{}) + if d, _ := details[0].(map[string]interface{}); len(details) != 1 || d["field"] != "take" || d["message"] != "Too small" || d["code"] != "too_small" { + t.Errorf("details = %v", m["details"]) + } +} + +var snakeCase = regexp.MustCompile(`^[a-z]+(_[a-z]+)*$`) + +// Every error has error, error_type, exit_code, message and hints, and no +// key of the envelope's own is in another case. +func TestEveryErrorHasTheSameKeys(t *testing.T) { + inAgentMode(t) + for _, c := range []struct { + name string + run func(*cobra.Command) error + }{ + {"404", func(cmd *cobra.Command) error { + return Error(cmd, apiError(404, `{"message":"Not found","statusCode":404,"path":"/x","timestamp":"t"}`, nil)) + }}, + {"400 with its own error", func(cmd *cobra.Command) error { + return Error(cmd, apiError(400, `{"error":"Bad Request","message":"Alias taken","statusCode":400}`, nil)) + }}, + {"a body that isn't JSON", func(cmd *cobra.Command) error { + return Error(cmd, apiError(502, `502 Bad Gateway`, nil)) + }}, + {"a local error", func(cmd *cobra.Command) error { + return Report(cmd, Explanation{Type: "missing_flag", Title: "vf project get needs --project-id"}, errors.New("x")) + }}, + {"AgentModeError", func(cmd *cobra.Command) error { + return AgentModeError(cmd, "configure_blocked", "configure is interactive", nil) + }}, + } { + t.Run(c.name, func(t *testing.T) { + cmd := projectGet(t) + var stderr bytes.Buffer + cmd.SetErr(&stderr) + _ = c.run(cmd) + m := decode(t, &stderr) + for _, key := range []string{"error", "error_type", "exit_code", "message", "hints"} { + if _, has := m[key]; !has { + t.Errorf("no %s in\n%s", key, stderr.String()) + } + } + if _, ok := m["message"].(string); !ok { + t.Errorf("message should be a string, got %v", m["message"]) + } + if _, ok := m["hints"].([]interface{}); !ok { + t.Errorf("hints should be a list, got %v", m["hints"]) + } + for key := range m { + if !snakeCase.MatchString(key) { + t.Errorf("key %q isn't snake_case:\n%s", key, stderr.String()) + } + } + if !strings.HasPrefix(stderr.String(), "{\n \"error\": ") { + t.Errorf("error should come first:\n%s", stderr.String()) + } + }) + } +} + +// With -o json a local error is the envelope too, error_type included, +// though agent mode is off. +func TestJSONOutputGetsTheEnvelopeOutsideAgentMode(t *testing.T) { + ResetAgentMode() + t.Cleanup(ResetAgentMode) + cmd := projectGet(t) + cmd.Flags().StringP("output-format", "o", "pretty", "") + if err := cmd.Flags().Set("output-format", "json"); err != nil { + t.Fatal(err) + } + var stderr bytes.Buffer + cmd.SetErr(&stderr) + _ = Report(cmd, Explanation{Type: "missing_flag", Title: "vf project get needs --project-id", Next: []string{"Pass it: `vf project get --project-id `"}}, errors.New("x")) + + m := decode(t, &stderr) + if m["error_type"] != "missing_flag" || m["exit_code"] != float64(ExitUsage) { + t.Errorf("envelope = %v", m) + } + if !strings.Contains(stderr.String(), "") { + t.Errorf("angle brackets were escaped:\n%s", stderr.String()) + } + + stderr.Reset() + _ = Error(cmd, apiError(404, `{"message":"Project not found"}`, nil)) + if m := decode(t, &stderr); m["error_type"] != "not_found" || m["status_code"] != float64(404) { + t.Errorf("envelope = %v", m) + } +} + +// Agent mode names the flag a refused field is set with, as human mode does: +// "displayName: Required (--display-name)". +func TestAgentModeDetailsNameTheFlag(t *testing.T) { + inAgentMode(t) + cmd := projectGet(t) + var stderr bytes.Buffer + cmd.SetErr(&stderr) + body := `{"message":"Validation failed","details":[{"code":"invalid_type","message":"Required","path":["data","displayName"]},{"message":"Not a field vf knows","path":["other"]}]}` + _ = Error(cmd, apiError(422, body, nil)) + + details, _ := decode(t, &stderr)["details"].([]interface{}) + if len(details) != 2 { + t.Fatalf("details = %v", details) + } + if d, _ := details[0].(map[string]interface{}); d["field"] != "data.displayName" || d["flag"] != "--display-name" { + t.Errorf("details[0] = %v, want the field and its flag", d) + } + if d, _ := details[1].(map[string]interface{}); d["flag"] != nil { + t.Errorf("a field no flag sets has no flag, got %v", d) + } +} diff --git a/internal/output/exitcode.go b/internal/output/exitcode.go new file mode 100644 index 00000000..44ba2551 --- /dev/null +++ b/internal/output/exitcode.go @@ -0,0 +1,130 @@ +// This file is not generated by Speakeasy. It gives each kind of failure its +// own exit code, so a script can tell a typo from a missing resource, a +// timeout or a failed test without reading stderr. +// +// Every failure used to exit 1: cmd/vf/main.go exited 1 for any error. A CI +// step that wanted to retry a timeout, treat a 404 as "not there yet" and +// fail hard on a mistyped flag had to parse the error JSON instead. Now the +// code that reports an error decides its exit code, writes it into the JSON +// as exit_code, and returns the error carrying it, and main exits with it: +// +// 0 success +// 1 any other failure, including API errors not listed below +// 2 a usage error, caught before any request: an unknown or invalid flag, +// a missing required flag, a bad argument +// 3 authentication: not signed in, no token, a 401, an expired session +// 4 not found: a 404 +// 5 timed out: --timeout, or a wait's --max-wait ran out with runs still going +// 6 a test run didn't pass: test run wait, wait-suite, create-suite --wait + +package output + +import ( + "errors" + "strings" +) + +// The exit codes vf uses. ExitCodesHelp describes them. +const ( + ExitFailure = 1 + ExitUsage = 2 + ExitAuth = 3 + ExitNotFound = 4 + ExitTimeout = 5 + ExitNotPassed = 6 +) + +// ExitCodesHelp is the table above, for 'vf --help' and the docs. +var ExitCodesHelp = strings.Join([]string{ + " 0 Success", + " 1 Any other failure, including API errors not listed here", + " 2 Usage error, caught before any request: an unknown or invalid flag,", + " a missing required flag, a bad argument", + " 3 Authentication: not signed in, no token, HTTP 401, an expired session", + " 4 Not found: HTTP 404", + " 5 Timed out: --timeout, or a wait's --max-wait ran out with runs still going", + " 6 A test run didn't pass: test run wait, wait-suite, create-suite --wait", +}, "\n") + +// ExitCodeFor is the exit code for an error of errorType, the error_type the +// JSON reports, that got HTTP status back (0 for none). A type says more than +// a status, so it wins: a 404 that means the command's endpoint is missing is +// still not found, but a failed test is a failed test whatever the status. +func ExitCodeFor(errorType string, status int) int { + switch errorType { + case "missing_flag", "unknown_flag", "unknown_command", "invalid_flag_value", + "invalid_body", "usage_error", "stdin_empty", "stdin_timeout": + return ExitUsage + case "authentication_error", "auth_session_ended", "auth_session_renew_failed", + "auth_login_failed", "auth_signup_failed", "auth_login_interactive": + return ExitAuth + case "not_found", "test_runs_not_found": + return ExitNotFound + case "timeout", "test_runs_unfinished", "test_suite_unfinished": + return ExitTimeout + case "test_runs_failed", "test_suite_failed": + return ExitNotPassed + } + switch status { + case 401: + return ExitAuth + case 404: + return ExitNotFound + } + return ExitFailure +} + +// exitCoder is an error that knows the code the process exits with. +type exitCoder interface{ ExitCode() int } + +type exitCoded struct { + err error + code int +} + +func (e exitCoded) Error() string { return e.err.Error() } +func (e exitCoded) Unwrap() error { return e.err } +func (e exitCoded) ExitCode() int { return e.code } + +// WithExitCode marks err to make the process exit with code. Its message, +// and whether it has been reported, stay as they were. +func WithExitCode(err error, code int) error { + if err == nil { + return nil + } + return exitCoded{err: err, code: code} +} + +// ExitCode is the code the process exits with for err: 0 for none, the code +// it was marked with, or else what its HTTP status says, which is 1 for +// anything but a 401 or 404. +func ExitCode(err error) int { + if err == nil { + return 0 + } + var coded exitCoder + if errors.As(err, &coded) { + return coded.ExitCode() + } + for e := err; e != nil; e = errors.Unwrap(e) { + if status := extractErrorStatusCode(e); status != 0 { + return ExitCodeFor("", status) + } + } + return ExitFailure +} + +// exitCodeOf is the exit code for err, explained as x: the code err was +// marked with, if any, since what marked it knew best, or else x's. +func exitCodeOf(x Explanation, err error) int { + var coded exitCoder + if errors.As(err, &coded) { + return coded.ExitCode() + } + return ExitCodeFor(x.Type, x.Status) +} + +// reported marks err as printed, and as exiting with the code x gives it. +func reported(x Explanation, err error) error { + return WithExitCode(AlreadyReported(err), exitCodeOf(x, err)) +} diff --git a/internal/output/exitcode_test.go b/internal/output/exitcode_test.go new file mode 100644 index 00000000..a8690cd3 --- /dev/null +++ b/internal/output/exitcode_test.go @@ -0,0 +1,154 @@ +// This file is not generated by Speakeasy. It covers exitcode.go: each kind of +// failure exits with its own code, and the JSON says which. + +package output + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "testing" + + "github.com/spf13/cobra" +) + +func TestEachKindOfFailureHasItsOwnExitCode(t *testing.T) { + for _, c := range []struct { + errorType string + status int + want int + }{ + {"missing_flag", 0, ExitUsage}, + {"unknown_flag", 0, ExitUsage}, + {"unknown_command", 0, ExitUsage}, + {"invalid_flag_value", 0, ExitUsage}, + {"invalid_body", 0, ExitUsage}, + {"usage_error", 0, ExitUsage}, + {"authentication_error", 0, ExitAuth}, + {"authentication_error", 401, ExitAuth}, + {"auth_session_ended", 0, ExitAuth}, + {"not_found", 404, ExitNotFound}, + {"unsupported_command", 404, ExitNotFound}, + {"timeout", 0, ExitTimeout}, + {"test_runs_unfinished", 0, ExitTimeout}, + {"test_suite_unfinished", 0, ExitTimeout}, + {"test_runs_failed", 0, ExitNotPassed}, + {"test_suite_failed", 0, ExitNotPassed}, + {"test_runs_not_found", 0, ExitNotFound}, + {"validation_error", 400, ExitFailure}, + {"validation_error", 422, ExitFailure}, + {"authorization_error", 403, ExitFailure}, + {"server_error", 500, ExitFailure}, + {"rate_limit_error", 429, ExitFailure}, + {"connection_error", 0, ExitFailure}, + {"error", 0, ExitFailure}, + } { + if got := ExitCodeFor(c.errorType, c.status); got != c.want { + t.Errorf("ExitCodeFor(%q, %d) = %d, want %d", c.errorType, c.status, got, c.want) + } + } +} + +func TestExitCodeReadsTheMarkThroughWrapping(t *testing.T) { + cause := errors.New("x") + marked := WithExitCode(AlreadyReported(cause), ExitNotPassed) + if marked.Error() != "" { + t.Errorf("marking must keep the error reported, got %q", marked.Error()) + } + if !errors.Is(marked, cause) { + t.Error("marking must keep the cause reachable") + } + for _, err := range []error{marked, fmt.Errorf("wrapped: %w", marked)} { + if got := ExitCode(err); got != ExitNotPassed { + t.Errorf("ExitCode(%v) = %d, want %d", err, got, ExitNotPassed) + } + } + if ExitCode(nil) != 0 || ExitCode(errors.New("plain")) != ExitFailure { + t.Error("nil exits 0, and an unmarked error 1") + } + if WithExitCode(nil, ExitUsage) != nil { + t.Error("marking nil is nil") + } +} + +// An API error nothing marked still exits by its status. +func TestAnUnmarkedAPIErrorExitsByItsStatus(t *testing.T) { + for status, want := range map[int]int{401: ExitAuth, 404: ExitNotFound, 400: ExitFailure, 500: ExitFailure} { + if got := ExitCode(fmt.Errorf("call: %w", apiError(status, `{}`, nil))); got != want { + t.Errorf("HTTP %d: ExitCode = %d, want %d", status, got, want) + } + } +} + +// The code in the JSON is the code the process exits with, for an API error +// and for one vf found itself. +func TestTheEnvelopeCarriesTheExitCode(t *testing.T) { + ResetAgentMode() + t.Setenv("FORCE_AGENT_MODE", "1") + InitAgentMode(&cobra.Command{Use: "vf"}) + t.Cleanup(ResetAgentMode) + + envelope := func(t *testing.T, stderr *bytes.Buffer) map[string]interface{} { + t.Helper() + var m map[string]interface{} + if err := json.Unmarshal(stderr.Bytes(), &m); err != nil { + t.Fatalf("stderr is not one JSON object: %v\n%s", err, stderr.String()) + } + return m + } + for _, c := range []struct { + name string + run func(cmd *cobra.Command) error + want int + }{ + {"404", func(cmd *cobra.Command) error { + return Error(cmd, apiError(404, `{"statusCode":404,"message":"Project not found"}`, nil)) + }, ExitNotFound}, + {"401", func(cmd *cobra.Command) error { return Error(cmd, apiError(401, `{"message":"Unauthorized"}`, nil)) }, ExitAuth}, + {"422", func(cmd *cobra.Command) error { + return Error(cmd, apiError(422, `{"message":"Validation failed"}`, nil)) + }, ExitFailure}, + {"timeout", func(cmd *cobra.Command) error { return Error(cmd, fmt.Errorf("call: %w", context.DeadlineExceeded)) }, ExitTimeout}, + {"missing flag", func(cmd *cobra.Command) error { + return Report(cmd, Explanation{Type: "missing_flag", Title: "vf project get needs --project-id"}, errors.New("missing")) + }, ExitUsage}, + {"marked", func(cmd *cobra.Command) error { + return Report(cmd, Explanation{Type: "error", Title: "2 of 2 runs did not pass"}, WithExitCode(errors.New("x"), ExitNotPassed)) + }, ExitNotPassed}, + {"agent-mode error", func(cmd *cobra.Command) error { + return AgentModeError(cmd, "test_suite_unfinished", "still going", nil) + }, ExitTimeout}, + } { + t.Run(c.name, func(t *testing.T) { + cmd := projectGet(t) + var stderr bytes.Buffer + cmd.SetErr(&stderr) + err := c.run(cmd) + if got := ExitCode(err); got != c.want { + t.Errorf("exits %d, want %d", got, c.want) + } + if got := envelope(t, &stderr)["exit_code"]; got != float64(c.want) { + t.Errorf("exit_code = %v, want %d\n%s", got, c.want, stderr.String()) + } + if err.Error() != "" { + t.Errorf("the error should be marked as reported, got %q", err.Error()) + } + }) + } +} + +// Off agent mode, a person sees no code, but the process still exits with it. +func TestHumanModeExitsWithTheSameCode(t *testing.T) { + ResetAgentMode() + t.Cleanup(ResetAgentMode) + cmd := projectGet(t) + cmd.SetErr(&bytes.Buffer{}) + if got := ExitCode(Error(cmd, apiError(404, `{"message":"Project not found"}`, nil))); got != ExitNotFound { + t.Errorf("404 exits %d, want %d", got, ExitNotFound) + } + if got := ExitCode(Report(cmd, Explanation{Type: "unknown_flag", Title: "t"}, errors.New("x"))); got != ExitUsage { + t.Errorf("unknown flag exits %d, want %d", got, ExitUsage) + } +} diff --git a/internal/output/explain.go b/internal/output/explain.go index e18ffbcf..03b0c253 100644 --- a/internal/output/explain.go +++ b/internal/output/explain.go @@ -11,8 +11,9 @@ // vf project list lists the projects you can use // Docs: https://www.voiceflow.com/docs/cli/commands/project // -// and Envelope adds the same content to the JSON error an agent or a script -// reads, as explanation, hints (the next steps) and docs_url. +// and the same content is the JSON error an agent or a script reads +// (envelope.go): error, message, explanation, hints (the next steps), details +// and docs_url, with the code the process exits with as exit_code. // // Steps name commands in `backticks`: Render draws them in Accent, and the // JSON gets them in 'single quotes', the convention every other hint uses. @@ -44,13 +45,14 @@ import ( // Explanation is what vf tells someone about a failure. type Explanation struct { - Type string // error_type, for machines: authentication_error, not_found, … - Title string // what happened, on one line - Message string // the server's own message, when it says more than the status - Why []string // the likely cause, most likely first - Details []string // field errors from the response: "name: Required (--name)" - Next []string // what to do, each a step someone can take - Docs string // the page that covers the command + Type string // error_type, for machines: authentication_error, not_found, … + Title string // what happened, on one line + Message string // the server's own message, when it says more than the status + Why []string // the likely cause, most likely first + Details []FieldError // field errors from the response: "name: Required" + Next []string // what to do, each a step someone can take + Docs string // the page that covers the command + Status int // the HTTP status that came back, or 0 when none did } // Credential is what vf signs its requests with, so a 401 or 403 can be @@ -179,8 +181,9 @@ func explainAPI(cmd *cobra.Command, err error, status int, body string, headers Type: classifyErrorType(status), Title: action(cmd) + " · HTTP " + strconv.Itoa(status) + " " + http.StatusText(status), Message: vfCommandNames(cmd, serverMessage(status, fields, body)), // hintfit.go - Details: fieldErrors(cmd, fields), + Details: fieldErrors(cmd, readableFormats(fields)), // fieldformat.go: a format, not its regex Docs: docsFor(cmd), + Status: status, } cred := DescribeCredential(cmd) @@ -451,32 +454,6 @@ func explainTransport(cmd *cobra.Command, err error) (Explanation, bool) { return x, true } -// Envelope adds an explanation to a JSON error object, keeping every key the -// response already has: a server's own hints and docs win. -func Envelope(m map[string]interface{}, x Explanation) { - if _, has := m["error_type"]; !has && x.Type != "" && IsAgentMode() { - m["error_type"] = x.Type - } - if _, has := m["message"]; !has && x.Title != "" { - m["message"] = x.Title - } - if why := strings.Join(x.Why, " "); why != "" { - if _, has := m["explanation"]; !has { - m["explanation"] = Plain(why) - } - } - if _, has := m["hints"]; !has && len(x.Next) > 0 { - hints := make([]string, len(x.Next)) - for i, step := range x.Next { - hints[i] = Plain(step) - } - m["hints"] = hints - } - if _, has := m["docs_url"]; !has && x.Docs != "" { - m["docs_url"] = x.Docs - } -} - // Render writes x for a person: // // ✗ @@ -502,7 +479,9 @@ func Render(cmd *cobra.Command, x Explanation) { under = append(under, forPeople(x.Message)) } under = append(under, x.Why...) - under = append(under, x.Details...) + for _, d := range x.Details { + under = append(under, d.String()) + } if len(under) > 0 { fmt.Fprintln(w, u.Under(under...)) } @@ -517,28 +496,16 @@ func Render(cmd *cobra.Command, x Explanation) { } } -// Report prints x where it belongs, as JSON in agent mode and for a person -// otherwise, and returns err marked as reported. +// Report prints x where it belongs, as the JSON envelope in agent mode or +// with -o json or --jq (envelope.go), and for a person otherwise, and returns +// err marked as reported and with its exit code. func Report(cmd *cobra.Command, x Explanation, err error) error { - if IsAgentMode() { - m := map[string]interface{}{"error": x.Title} - if x.Message != "" { - m["message"] = x.Title + ": " + x.Message - } - Envelope(m, x) - if len(x.Details) > 0 { - m["details"] = x.Details - } - // No HTML escaping: a step such as "--project-id <value>" should - // read as written, not as "\u003cvalue\u003e". - enc := json.NewEncoder(cmd.ErrOrStderr()) - enc.SetEscapeHTML(false) - enc.SetIndent("", " ") - _ = enc.Encode(m) - return AlreadyReported(err) + if WantsJSONError(cmd) { + writeEnvelope(cmd.ErrOrStderr(), x, err) + return reported(x, err) } Render(cmd, x) - return AlreadyReported(err) + return reported(x, err) } var codeSpan = regexp.MustCompile("`([^`]+)`") @@ -707,11 +674,11 @@ func serverMessage(status int, fields map[string]interface{}, body string) strin // fieldErrors lists the per-field errors a response carries, each with the // flag that sets the field when cmd has one. -func fieldErrors(cmd *cobra.Command, fields map[string]interface{}) []string { +func fieldErrors(cmd *cobra.Command, fields map[string]interface{}) []FieldError { if fields == nil { return nil } - var out []string + var out []FieldError if list, ok := fields["details"].([]interface{}); ok { for _, item := range list { d, ok := item.(map[string]interface{}) @@ -726,17 +693,14 @@ func fieldErrors(cmd *cobra.Command, fields map[string]interface{}) []string { if path == "" && msg == "" { continue } - line := strings.TrimPrefix(path+": "+msg, ": ") - if flag := flagForField(cmd, path); flag != "" { - line += " (" + flag + ")" - } - out = append(out, line) + code, _ := d["code"].(string) + out = append(out, FieldError{Field: path, Flag: flagForField(cmd, path), Message: msg, Code: code}) } } if list, ok := fields["message"].([]interface{}); ok { for _, item := range list { if s, ok := item.(string); ok { - out = append(out, s) + out = append(out, FieldError{Message: s}) } } } diff --git a/internal/output/explain_test.go b/internal/output/explain_test.go index c5a8f5bb..f7803912 100644 --- a/internal/output/explain_test.go +++ b/internal/output/explain_test.go @@ -60,7 +60,11 @@ func withCredential(t *testing.T, c Credential) { } func joined(x Explanation) string { - return strings.Join(append(append(append([]string{x.Title, x.Message}, x.Why...), x.Details...), x.Next...), "\n") + lines := append([]string{x.Title, x.Message}, x.Why...) + for _, d := range x.Details { + lines = append(lines, d.String()) + } + return strings.Join(append(lines, x.Next...), "\n") } func TestEveryStatusSaysWhyAndWhatNext(t *testing.T) { @@ -147,7 +151,7 @@ func TestServerMessagesThatSayNothingAreDropped(t *testing.T) { } } got := fieldErrors(nil, parseObject(`{"message":["name must be a string","type is required"]}`)) - if len(got) != 2 || got[0] != "name must be a string" { + if len(got) != 2 || got[0].String() != "name must be a string" { t.Errorf("NestJS validation messages should become field errors, got %q", got) } } @@ -381,14 +385,6 @@ func TestReportInAgentModeIsOneJSONObject(t *testing.T) { } } -func TestEnvelopeKeepsWhatTheResponseSays(t *testing.T) { - m := map[string]interface{}{"message": "Project not found", "hints": []string{"server hint"}} - Envelope(m, Explanation{Title: "t", Why: []string{"why"}, Next: []string{"`vf x`"}, Docs: "d"}) - if m["message"] != "Project not found" || fmt.Sprint(m["hints"]) != "[server hint]" || m["explanation"] != "why" || m["docs_url"] != "d" { - t.Errorf("envelope = %v", m) - } -} - func TestWaitStepReadsRetryAfter(t *testing.T) { if got := waitStep("17"); got != "Wait 17s (Retry-After: 17), then run it again" { t.Errorf("seconds: %q", got) diff --git a/internal/output/fieldformat.go b/internal/output/fieldformat.go new file mode 100644 index 00000000..fec4e9a8 --- /dev/null +++ b/internal/output/fieldformat.go @@ -0,0 +1,73 @@ +// This file is not generated by Speakeasy. It names the format a field +// takes when the API says only which regex the value failed. +// +// An analytics query given a day, the usual way to ask for one, came back +// with two errors for each date: +// +// endDate: Invalid ISO datetime (--end-date) +// endDate: Invalid string: must match pattern /^(?:(?:\d\d[2468][048]|…/ +// +// The regex runs to 300 characters and says, to someone who can read it, +// "a UTC time". In agent mode the response's details were passed on whole, +// each regex twice. Now each field gets one line saying that: +// +// endDate: expected a UTC time such as 2026-06-01T09:30:00Z (--end-date) + +package output + +import "strings" + +// longPattern is the longest regex a field error keeps; past it, the +// regex is no help to a reader. +const longPattern = 80 + +// readableFormats gives each of fields' details that failed a format the +// format in words, in place of its regex, and drops a second detail that +// says the same of the same field. +func readableFormats(fields map[string]interface{}) map[string]interface{} { + list, ok := fields["details"].([]interface{}) + if !ok { + return fields + } + seen := map[string]bool{} + kept := make([]interface{}, 0, len(list)) + for _, item := range list { + d, ok := item.(map[string]interface{}) + if !ok || d["code"] != "invalid_format" { + kept = append(kept, item) + continue + } + pattern, _ := d["pattern"].(string) + format, _ := d["format"].(string) + msg, _ := d["message"].(string) + switch { + case format == "datetime" || strings.Contains(pattern, `\d{4}-`) && strings.Contains(pattern, ")T(?:"): + msg = "expected a UTC time such as 2026-06-01T09:30:00Z" + case format == "date" || strings.Contains(pattern, `\d{4}-`): + msg = "expected a day such as 2026-06-01" + case len(pattern) > longPattern: + before, _, _ := strings.Cut(msg, " /") + msg = before + " that `--debug` shows" + } + key := fieldPath(d["path"]) + "\x00" + msg + if seen[key] { + continue + } + seen[key] = true + c := make(map[string]interface{}, len(d)) + for k, v := range d { + c[k] = v + } + c["message"] = msg + if len(pattern) > longPattern { + delete(c, "pattern") // the message says it; `--debug` shows it + } + kept = append(kept, c) + } + out := make(map[string]interface{}, len(fields)) + for k, v := range fields { + out[k] = v + } + out["details"] = kept + return out +} diff --git a/internal/output/flagwarning.go b/internal/output/flagwarning.go new file mode 100644 index 00000000..35277238 --- /dev/null +++ b/internal/output/flagwarning.go @@ -0,0 +1,21 @@ +// This file is not generated by Speakeasy. It draws flagutil's warnings the +// way vf draws every status line: a glyph at a terminal, "Warning:" +// elsewhere. flagutil can't import this package to ask (this package +// imports flagutil), so the drawing is installed there. + +package output + +import ( + "io" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/ui" +) + +func init() { + flagutil.SetWarningLine(func(cmd *cobra.Command, w io.Writer, msg string) string { + return UI(cmd, w).Status(ui.StatusWarn, msg) + }) +} diff --git a/internal/output/hintfit.go b/internal/output/hintfit.go index b61005c9..aad9b46a 100644 --- a/internal/output/hintfit.go +++ b/internal/output/hintfit.go @@ -31,6 +31,7 @@ import ( "github.com/spf13/cobra" "github.com/spf13/pflag" + "github.com/voiceflow/cli/internal/flagutil" "github.com/voiceflow/cli/internal/session" ) @@ -174,23 +175,10 @@ func withScope(cmd *cobra.Command, next string) string { return next } -// snakeName is an MCP tool's name in a server message: search_instructions. -var snakeName = regexp.MustCompile("`?\\b[a-z]+(?:_[a-z]+)+\\b`?") - -// vfCommandNames rewrites the MCP tool names in a server message as the vf -// commands beside cmd that do the same: "Use search_instructions" becomes -// "Use `vf agent search-instructions`". Names with no such command stay. +// vfCommandNames rewrites the MCP tool and API field names in a server +// message as vf's commands and cmd's flags: "Use search_instructions" becomes +// "Use `vf agent search-instructions`", vf_test_create_run `vf test run +// create`, oldString --old-string. Names with no such command or flag stay. func vfCommandNames(cmd *cobra.Command, message string) string { - if cmd == nil || !cmd.HasParent() { - return message - } - return snakeName.ReplaceAllStringFunc(message, func(name string) string { - kebab := strings.ReplaceAll(strings.Trim(name, "`"), "_", "-") - for _, sibling := range cmd.Parent().Commands() { - if sibling.Name() == kebab { - return "`" + sibling.CommandPath() + "`" - } - } - return name - }) + return flagutil.VFNamesInMessage(cmd, message) // flagutil/apinames.go } diff --git a/internal/output/jq.go b/internal/output/jq.go index 25c8a3d7..fa044629 100644 --- a/internal/output/jq.go +++ b/internal/output/jq.go @@ -40,7 +40,7 @@ func ApplyJqFilter(content interface{}, expression string) ([]interface{}, error break } if err, isErr := v.(error); isErr { - return nil, fmt.Errorf("jq error: %w", err) + return nil, jqRunFailed(data, err) // jqfail.go: keeps what the filter ran on, to show it } results = append(results, v) } diff --git a/internal/output/jqfail.go b/internal/output/jqfail.go new file mode 100644 index 00000000..da9777e7 --- /dev/null +++ b/internal/output/jqfail.go @@ -0,0 +1,142 @@ +// This file is not generated by Speakeasy. It says, when a --jq filter fails +// on a response, that the request itself succeeded, and shows what came back. +// +// A filter that parses can still fail on the data: `.variable.id.foo` on a +// string. That error came after the request had run, and read like any +// other: exit 1, `error_type: "error"`, `jq error: expected an object but got: +// string ("6b0d…")`. Nothing said the variable had been created, and the +// response was gone. An agent treats exit 1 as "nothing happened" and runs +// it again, which gets a 409 for a name that is now taken, or makes a second +// test or document where names needn't be unique. +// +// Now the error says the request succeeded and, for a command that makes or +// changes something, not to run it again. It gives the response's ID, or the +// response itself. Like every error under --jq it is the JSON envelope, with +// `error_type: "jq_error"`, `request_succeeded`, `id` and `response`. The +// command still exits non-zero: the output it was asked for wasn't printed. +// +// A filter that cannot parse or compile is refused before anything is sent; +// see validate.go. + +package output + +import ( + "errors" + "fmt" + "net/http" + "strings" + + "github.com/spf13/cobra" +) + +// jqRunError is a --jq filter that failed on the data it was given. +type jqRunError struct { + input interface{} // what the filter ran on, as decoded JSON + err error +} + +func (e *jqRunError) Error() string { return "jq error: " + e.err.Error() } +func (e *jqRunError) Unwrap() error { return e.err } + +// ExitCode is 1, a failure of no listed kind. gojq's error() and halt_error +// carry jq's own codes, and error()'s 5 is vf's "timed out" (exitcode.go), +// which a pipeline might retry, repeating a write that went through. +func (e *jqRunError) ExitCode() int { return ExitFailure } + +// jqRunFailed keeps what a filter ran on with the error it failed with. +func jqRunFailed(input interface{}, err error) error { + return &jqRunError{input: input, err: err} +} + +// readVerbs start the names of commands that only read, whatever their +// request's method: `test run wait` and `transcript search` send a POST. +var readVerbs = []string{"get", "list", "search", "query", "wait", "read", "export", "diff", "grep", "files", "preview"} + +// reportJqFailure reports err when it is a --jq filter that failed on the +// response to res, and returns it marked as reported. Any other err is +// returned as it is. +func reportJqFailure(cmd *cobra.Command, res interface{}, err error) error { + var failed *jqRunError + if !errors.As(err, &failed) { + return err + } + var method, status string + if resp := extractHTTPResponse(res); resp != nil { + status = fmt.Sprintf(" (HTTP %d)", resp.StatusCode) + if resp.Request != nil { + method = resp.Request.Method + } + } + write := !isReadCommand(cmd, method) + id := responseID(failed.input) + + x := Explanation{ + Type: "jq_error", + Title: "--jq failed on the response: " + failed.err.Error(), + Docs: docsFor(cmd), + } + if write { + x.Why = []string{"The request itself succeeded" + status + ": `" + cmd.CommandPath() + "` went through, and only the filter failed."} + x.Next = []string{"Don't run it again to get the output: that would do it twice"} + } else { + x.Why = []string{"The request itself succeeded" + status + "; only the filter failed."} + } + if id != "" { + x.Why = append(x.Why, "Its id: "+id) + } + x.Next = append(x.Next, "Fix the filter; `--jq .` prints the whole response to start from") + + // --jq makes every error the JSON envelope (envelope.go), this one too. + m := ErrorEnvelope(x, err) + m["request_succeeded"] = true + if id != "" { + m["id"] = id + } + if write { + m["response"] = failed.input + } + _, _ = cmd.ErrOrStderr().Write(append(MarshalEnvelope(m), '\n')) + return reported(x, err) +} + +// isReadCommand reports whether cmd only reads: its request was a GET, or +// its name starts with a verb that reads. +func isReadCommand(cmd *cobra.Command, method string) bool { + if method == http.MethodGet || method == http.MethodHead { + return true + } + if cmd == nil { + return false + } + verb, _, _ := strings.Cut(cmd.Name(), "-") + for _, v := range readVerbs { + if verb == v { + return true + } + } + return false +} + +// responseID is the id of what a response holds: its own "id", or the "id" +// of the one object it wraps ({"variable": {"id": …}}). Empty when there is +// no single one. +func responseID(input interface{}) string { + m, ok := input.(map[string]interface{}) + if !ok { + return "" + } + if id, ok := m["id"].(string); ok { + return id + } + if len(m) != 1 { + return "" + } + for _, v := range m { + if inner, ok := v.(map[string]interface{}); ok { + if id, ok := inner["id"].(string); ok { + return id + } + } + } + return "" +} diff --git a/internal/output/jqraw.go b/internal/output/jqraw.go new file mode 100644 index 00000000..fa9c9b8a --- /dev/null +++ b/internal/output/jqraw.go @@ -0,0 +1,44 @@ +// This file is not generated by Speakeasy. It prints a --jq result that is a +// string as the string itself, as `jq -r` and `gh --jq` do. +// +// Every result used to print as JSON, so a string kept its quotes. +// `ID=$(vf test create … --jq .test.id)` captured "6b0d…" quotes and all, and +// the next call failed with `No test exists with ID "\"6b0d…\""`. Text came +// out on one line with its newlines as \n. Every script needed `| jq -r .` +// or `| tr -d '"'`, the extra tool --jq is there to replace. The help said +// none of this, nor that --jq ignores -o. +// +// Now a string prints raw, one per line. An object, an array, a number, a +// boolean or null still prints as JSON, so `--jq .project` stays parseable. +// That is the same in agent mode and whatever -o says, and --jq's help says +// so. + +package output + +import ( + "encoding/json" + "fmt" + "io" +) + +// JqUsage is --jq's help. +const JqUsage = "Filter the response with a jq expression, e.g. '.project.id' or '.items[] | .id'. " + + "A string prints raw, as jq -r prints it; anything else prints as JSON ('| tojson' keeps a string quoted). " + + "Overrides -o: the filter reads the JSON response, and its output is the same whatever -o says" + +// WriteJqResults prints each result of a --jq filter on its own line: a +// string as itself, anything else as indented JSON. +func WriteJqResults(out io.Writer, results []interface{}, colorize bool) error { + for _, result := range results { + if s, ok := result.(string); ok { + fmt.Fprintln(out, s) + continue + } + data, err := json.MarshalIndent(result, "", " ") + if err != nil { + return fmt.Errorf("failed to marshal jq result: %w", err) + } + printJSON(out, data, colorize) + } + return nil +} diff --git a/internal/output/output.go b/internal/output/output.go index ee185f72..4b117dd1 100644 --- a/internal/output/output.go +++ b/internal/output/output.go @@ -148,10 +148,11 @@ func ValidateGlobalServerName(cmd *cobra.Command, validNames map[string]string) } // Result formats and outputs the response based on the --output-format flag. -func Result(cmd *cobra.Command, res interface{}) error { +func Result(cmd *cobra.Command, res interface{}) (err error) { defer afterResult(cmd, res)() // created.go: what was made, then what to do next out, done := ResultWriter(cmd) // fold.go: folds a long result inside the home prompt defer done() + defer func() { err = reportJqFailure(cmd, res, err) }() // jqfail.go: a filter that fails says the request succeeded colorFlag, _ := flagutil.GetStringFlag(cmd, "color") colorize := ShouldColorize(colorFlag) jqExpr, _ := flagutil.GetStringFlag(cmd, "jq") @@ -264,7 +265,7 @@ func Result(cmd *cobra.Command, res interface{}) error { } fmt.Fprint(out, string(data)) case "table": - if err := printTableOf(out, content); err != nil { // tableview.go: the rows a response wraps, or why not + if err := printTableOf(cmd, out, content); err != nil { // tableview.go: the rows a response wraps, or why not return err } case "toon": @@ -411,8 +412,9 @@ func Error(cmd *cobra.Command, err error) error { } } - Render(cmd, explain(cmd, err, statusCode, body)) // explain.go: what happened, why, and what to do next - return AlreadyReported(err) // see reported.go + explained := explain(cmd, err, statusCode, body) // explain.go: what happened, why, and what to do next + Render(cmd, explained) + return reported(explained, err) // exitcode.go: marked as printed, with its exit code } out := cmd.ErrOrStderr() @@ -420,67 +422,7 @@ func Error(cmd *cobra.Command, err error) error { colorize := ShouldColorize(colorFlag) explained := explain(cmd, err, statusCode, body) // explain.go: added to the JSON as explanation, hints and docs_url - // Try to extract the raw body from error types via reflection. - // Works with APIError and typed SDK errors that have a Body field. - var jsonData []byte - - if body != "" && isValidJSON(body) { - // Error body is valid JSON — parse it to inject metadata. - jsonData = []byte(body) - var parsed interface{} - if parseErr := json.Unmarshal(jsonData, &parsed); parseErr == nil { - if m, ok := parsed.(map[string]interface{}); ok { - if statusCode != 0 { - if _, hasStatus := m["status_code"]; !hasStatus { - m["status_code"] = statusCode - } - } - Envelope(m, explained) // explain.go - if IsAgentMode() { - enrichAgentError(m, err, statusCode) - } - if enriched, mergeErr := json.MarshalIndent(m, "", " "); mergeErr == nil { - jsonData = enriched - } - } else { - // Non-object JSON body (array, primitive) — wrap in envelope to inject metadata - envelope := map[string]interface{}{ - "error": err.Error(), - "body": parsed, - } - if statusCode != 0 { - envelope["status_code"] = statusCode - } - Envelope(envelope, explained) // explain.go - if IsAgentMode() { - enrichAgentError(envelope, err, statusCode) - } - if enriched, mergeErr := json.MarshalIndent(envelope, "", " "); mergeErr == nil { - jsonData = enriched - } - } - } - } else { - // Fallback: wrap error info in a consistent JSON envelope - envelope := map[string]interface{}{ - "error": explained.Title, // explain.go: the SDK's message repeats the whole body - } - if statusCode != 0 { - envelope["status_code"] = statusCode - } - if body != "" { - envelope["body"] = body - } - Envelope(envelope, explained) // explain.go - if IsAgentMode() { - enrichAgentError(envelope, err, statusCode) - } - var marshalErr error - jsonData, marshalErr = json.MarshalIndent(envelope, "", " ") - if marshalErr != nil { - return err - } - } + jsonData := MarshalEnvelope(ErrorEnvelope(explained, err)) // envelope.go: one shape for every error, with the response body under body // Inject response headers if --include-headers is set if includeHeaders { @@ -498,7 +440,7 @@ func Error(cmd *cobra.Command, err error) error { printJSON(out, jsonData, colorize) - return AlreadyReported(err) // see reported.go + return reported(explained, err) // exitcode.go: marked as printed, with its exit code } // derefToStruct dereferences pointer/interface values and validates the result @@ -795,16 +737,9 @@ func printResponseHeadersPretty(w io.Writer, headers http.Header, colorize bool) } } -// outputJqResults marshals and prints each jq filter result as indented JSON. +// outputJqResults prints each jq filter result. func outputJqResults(out io.Writer, results []interface{}, colorize bool) error { - for _, result := range results { - data, err := json.MarshalIndent(result, "", " ") - if err != nil { - return fmt.Errorf("failed to marshal jq result: %w", err) - } - printJSON(out, data, colorize) - } - return nil + return WriteJqResults(out, results, colorize) // jqraw.go: a string prints raw, as jq -r prints it } // applyJqToRawJSON applies a jq expression to raw JSON bytes. diff --git a/internal/output/tableview.go b/internal/output/tableview.go index 94314c98..1faaa9f5 100644 --- a/internal/output/tableview.go +++ b/internal/output/tableview.go @@ -1,5 +1,6 @@ // This file is not generated by Speakeasy. It has -o table show the rows a -// response holds, and fail when it can't, rather than print part of it. +// response holds, with columns a person can use, and fail when it can't +// rather than print part of it. // // The generated table printer only knew three shapes: a list, a record and a // map. But almost every response wraps its data in an object: @@ -13,65 +14,141 @@ // the response's other plain fields under it. A wrapper around one record is // printed as that record. A response that holds more than one list fails, and // says which lists and what to use instead, so no rows are dropped unseen. +// +// The generated printer also read columns off the Go structs, which goes +// wrong in three ways. A list whose items are one of several kinds is a +// Speakeasy union, a Go struct with a pointer per kind, so `tool list`, +// `conversation send` and `test run get` printed its wrapper fields, +// `UNKNOWNRAW TYPE`, with no ID and no text. A field that is an object was +// skipped, so `document list` showed only ID and FOLDERID: a document's name +// and type are under "data" and its status under "status". And a time is a +// Go struct too, so no CREATEDAT column ever appeared. +// +// So the table is now built from the response's JSON, as -o json prints it: +// a union is the kind the API returned. Its columns are every row's plain +// fields, in the order the API sends them, plus the name, title, type, +// status, message or text of a field that is an object, one level down. +// `status: {"type": "SUCCESS"}` is a STATUS column. A column no row has a +// value for is left out, and id, name, type, status and message come first. +// +// And the table never looked at the terminal. At 72, 100 and 160 columns +// its rows wrapped mid-word, a description with a newline pushed the rows +// below it out of their columns, headers ran together (REQUESTNAME, +// GOESTO), a project ID was repeated on every row and credits read +// 1.0150000000000001. Now, at a terminal, the widest columns are cut with +// "…" until the table fits, an ID never is, and the last columns are left +// out, and named under the table, when even cut they don't fit. Anywhere, +// a cell is one line, a number keeps at most four decimals (more for a +// small one), headers are words (REQUEST NAME), and a project, workspace or +// environment that every row shares isn't a column. package output import ( + "bytes" + "encoding/json" "fmt" "io" + "math" "reflect" + "sort" + "strconv" "strings" + "unicode" + + "github.com/charmbracelet/x/ansi" + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/ui" ) // printTableOf prints content as a table, looking through the object a -// response wraps its data in. -func printTableOf(out io.Writer, content any) error { - v := reflect.ValueOf(content) - for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface { - if v.IsNil() { - return printTable(out, content) - } - v = v.Elem() +// response wraps its data in, and fitting a terminal's width. +func printTableOf(cmd *cobra.Command, out io.Writer, content any) error { + return writeTableOf(out, content, tableWidth(cmd)) +} + +// tableWidth is the width a table must fit in: the terminal's, when a +// person is reading one, and 0, no limit, anywhere else. +func tableWidth(cmd *cobra.Command) int { + stdout := cmd.OutOrStdout() + if !UI(cmd, stdout).Decorated() { + return 0 + } + return ui.TerminalWidth(stdout) +} + +// writeTableOf prints content as a table width columns wide; 0 is no limit. +func writeTableOf(out io.Writer, content any, width int) error { + data, err := marshalJSON(content) + if err != nil { + return err } - if v.Kind() != reflect.Struct { - return tableError(printTable(out, content)) + value, err := orderedJSON(data) + if err != nil { + return err } + orderByType(value, reflect.TypeOf(content)) + return printTableValue(out, value, reflect.TypeOf(content), width) +} - var lists, records []int - for i := 0; i < v.NumField(); i++ { - f := v.Type().Field(i) - if !f.IsExported() { - continue +// printTableValue prints a decoded response. t is its Go type, when known, +// which says whether an empty list would hold rows. +func printTableValue(out io.Writer, value any, t reflect.Type, width int) error { + switch v := value.(type) { + case []any: + return tableError(printRows(out, v, width)) + case *jsonObject: + types := fieldTypes(v, t) + var lists, records []string + for _, key := range v.keys { + switch field := v.values[key].(type) { + case *jsonObject: + records = append(records, key) + case []any, nil: + if items, _ := field.([]any); isRowList(items, types[key]) { + lists = append(lists, key) + } + } } - switch t := derefType(f.Type); { - case (t.Kind() == reflect.Slice || t.Kind() == reflect.Array) && isRowType(t.Elem()): - lists = append(lists, i) - case t.Kind() == reflect.Struct || t.Kind() == reflect.Map: - records = append(records, i) + switch { + case len(lists) > 1: + return fmt.Errorf("-o table shows one list, and this response holds %d: %s. Use -o json or -o yaml to see them all", len(lists), strings.Join(lists, ", ")) + case len(lists) == 1: + rows, _ := v.values[lists[0]].([]any) + if err := tableError(printRows(out, rows, width)); err != nil { + return err + } + footer := recordFields(v, types, lists) + if len(footer) == 0 { + return nil + } + fmt.Fprintln(out) + return printRecord(out, footer, width) + case len(records) == 1 && !hasPlainFields(v, types): + return printTableValue(out, v.values[records[0]], types[records[0]], width) } + return tableError(printRecord(out, recordFields(v, types, nil), width)) + case nil: + return tableError(fmt.Errorf("nil value, nothing to display as table")) } - plain := collectTableColumns(v.Type()) + fmt.Fprintln(out, cellText(value)) + return nil +} - switch { - case len(lists) > 1: - names := make([]string, len(lists)) - for i, field := range lists { - names[i] = jsonName(v.Type().Field(field)) - } - return fmt.Errorf("-o table shows one list, and this response holds %d: %s. Use -o json or -o yaml to see them all", len(lists), strings.Join(names, ", ")) - case len(lists) == 1: - if err := tableError(printTableRows(out, v.Field(lists[0]))); err != nil { - return err - } - if len(plain) == 0 { - return nil +// isRowList reports whether a field holds rows: objects, or nothing yet in +// a field whose Go type is a list of objects. +func isRowList(items []any, t reflect.Type) bool { + for _, item := range items { + if _, ok := item.(*jsonObject); ok { + return true } - fmt.Fprintln(out) - return printTableSingle(out, v) - case len(records) == 1 && len(plain) == 0: - return printTableOf(out, v.Field(records[0]).Interface()) } - return tableError(printTable(out, content)) + if len(items) > 0 || t == nil { + return false + } + t = derefType(t) + return (t.Kind() == reflect.Slice || t.Kind() == reflect.Array) && isRowType(t.Elem()) } // isRowType reports whether a list of t prints as rows: a list of objects. @@ -87,6 +164,16 @@ func derefType(t reflect.Type) reflect.Type { return t } +// fieldTypes maps obj's JSON field names to their Go types, when t, its +// type, is a struct. +func fieldTypes(obj *jsonObject, t reflect.Type) map[string]reflect.Type { + if t == nil || derefType(t).Kind() != reflect.Struct { + return nil + } + _, types := structFields(unionKind(obj, derefType(t))) + return types +} + func jsonName(f reflect.StructField) string { if name, _, _ := strings.Cut(f.Tag.Get("json"), ","); name != "" && name != "-" { return name @@ -102,3 +189,610 @@ func tableError(err error) error { } return fmt.Errorf("-o table can't show this response: %w. Use -o json or -o yaml", err) } + +// A column is a plain field of a row, by its path: ["id"], or ["status", +// "type"] for a field one object down. +type column struct { + path []string + header string +} + +// promoted are the fields of an object field that get a column of their +// own, in the order they are shown. +var promoted = []string{"name", "title", "type", "status", "message", "text"} + +// promotedFields are the fields of obj that get a column of their own. +func promotedFields(obj *jsonObject) []string { + var fields []string + for _, name := range promoted { + if value := obj.values[name]; value != nil && isPlain(value) { + fields = append(fields, name) + } + } + return fields +} + +// containers are object fields that only hold the row's content, so their +// "type" is the row's type, not theirs. +var containers = map[string]bool{"data": true, "payload": true} + +// firstColumns come before the rest, in this order. +var firstColumns = []string{"id", "name", "title", "type", "status", "message", "text"} + +// scopeFields say where a row lives. When every row has the same one, it is +// what the command was asked about, not a column. +var scopeFields = []string{"organizationID", "workspaceID", "projectID", "environmentID", "environmentAlias"} + +const ( + columnGap = 2 // spaces between columns + minCell = 16 // the narrowest a column is cut to, unless its header is wider +) + +// printRows prints a list of objects as rows, and a list of anything else one +// item per line. +func printRows(out io.Writer, items []any, width int) error { + if len(items) == 0 { + fmt.Fprintln(out, "(empty)") + return nil + } + var rows []*jsonObject + for _, item := range items { + if row, ok := item.(*jsonObject); ok { + rows = append(rows, row) + } + } + if len(rows) == 0 { + for _, item := range items { + fmt.Fprintln(out, cellText(item)) + } + return nil + } + + // The rows of a union are of several kinds, so each row adds the + // columns it has. + var cols []column + seen := map[string]bool{} + for _, row := range rows { + for _, c := range plainColumns(row, nil, nil) { + if key := strings.Join(c.path, "\x00"); !seen[key] { + seen[key] = true + cols = append(cols, c) + } + } + } + + // A column no row has a value for says nothing, and nor does a scope + // every row shares. + kept := cols[:0] + for _, c := range cols { + if len(rows) > 1 && len(c.path) == 1 && contains(scopeFields, c.path[0]) && sameInEveryRow(rows, c.path) { + continue + } + for _, row := range rows { + if cell(row, c.path) != "" { + kept = append(kept, c) + break + } + } + } + cols = orderColumns(nameColumns(kept)) + if len(cols) == 0 { + return fmt.Errorf("no displayable columns found") + } + + table := make([][]string, 0, len(rows)+1) + headers := make([]string, len(cols)) + for i, c := range cols { + headers[i] = c.header + } + table = append(table, headers) + for _, row := range rows { + cells := make([]string, len(cols)) + for i, c := range cols { + cells[i] = cell(row, c.path) + } + table = append(table, cells) + } + + natural := naturalWidths(table) + floors := make([]int, len(cols)) + for i, c := range cols { + floors[i] = natural[i] + if !isIDColumn(c) { + floors[i] = min(natural[i], max(ansi.StringWidth(c.header), minCell)) + } + } + widths := fitWidths(natural, floors, width, 1) + if err := writeTable(out, table, widths); err != nil { + return err + } + if hidden := headers[len(widths):]; len(hidden) > 0 { + note := fmt.Sprintf("(Left out to fit %d columns: %s. -o json shows everything)", width, strings.Join(hidden, ", ")) + _, err := fmt.Fprintln(out, ansi.Wordwrap(note, width, "")) + return err + } + return nil +} + +// sameInEveryRow reports whether every row has the same value at path. +func sameInEveryRow(rows []*jsonObject, path []string) bool { + for _, row := range rows[1:] { + if cell(row, path) != cell(rows[0], path) { + return false + } + } + return true +} + +// isIDColumn reports whether c holds IDs, which are never cut: a cut ID +// can't be pasted into the next command. +func isIDColumn(c column) bool { + leaf := c.path[len(c.path)-1] + return leaf == "id" || strings.HasSuffix(leaf, "ID") || strings.HasSuffix(leaf, "Id") +} + +// hasPlainFields reports whether obj has a field of its own a cell can show: +// not an object, and not a list of rows. +func hasPlainFields(obj *jsonObject, types map[string]reflect.Type) bool { + for _, c := range plainColumns(obj, types, nil) { + if len(c.path) == 1 { + return true + } + } + return false +} + +// plainColumns are obj's columns: its plain fields, and the promoted fields +// of its object fields. types, when known, says which empty lists hold rows; +// skip names fields left out, such as the list printed above them. +func plainColumns(obj *jsonObject, types map[string]reflect.Type, skip []string) []column { + var cols []column + for _, key := range obj.keys { + if contains(skip, key) { + continue + } + switch v := obj.values[key].(type) { + case *jsonObject: + for _, leaf := range promotedFields(v) { + cols = append(cols, column{path: []string{key, leaf}}) + } + case []any: + if isPlainList(v) && !isRowList(v, types[key]) { + cols = append(cols, column{path: []string{key}}) + } + default: + cols = append(cols, column{path: []string{key}}) + } + } + return cols +} + +// recordFields are a record's columns, each with its header and cell. skip +// names fields left out. +func recordFields(obj *jsonObject, types map[string]reflect.Type, skip []string) [][2]string { + cols := orderColumns(nameColumns(plainColumns(obj, types, skip))) + fields := make([][2]string, len(cols)) + for i, c := range cols { + fields[i] = [2]string{c.header, cell(obj, c.path)} + } + return fields +} + +// printRecord prints fields as a vertical, two-column table, with the values +// cut to fit width. +func printRecord(out io.Writer, fields [][2]string, width int) error { + if len(fields) == 0 { + return fmt.Errorf("no displayable fields found") + } + table := make([][]string, len(fields)) + for i, f := range fields { + table[i] = []string{f[0], f[1]} + } + natural := naturalWidths(table) + floors := []int{natural[0], min(natural[1], minCell)} + return writeTable(out, table, fitWidths(natural, floors, width, 2)) +} + +// nameColumns gives each column its header. A field one object down is +// named by its own name, or by its object's when it is the object's type +// (status.type is STATUS); when that is taken, by both. +func nameColumns(cols []column) []column { + taken := map[string]bool{} + for i, c := range cols { + if len(c.path) == 1 { + cols[i].header = headerText(c.path[0]) + taken[cols[i].header] = true + } + } + for i, c := range cols { + if len(c.path) == 1 { + continue + } + parent, leaf := c.path[0], c.path[1] + name := leaf + if leaf == "type" && !containers[parent] { + name = parent + } + header := headerText(name) + if taken[header] { + header = headerText(parent) + " " + headerText(leaf) + } + cols[i].header = header + taken[header] = true + } + return cols +} + +// orderColumns puts the id, name, type, status and message columns first, +// and keeps the API's order for the rest. +func orderColumns(cols []column) []column { + rank := func(c column) int { + leaf := c.path[len(c.path)-1] + for i, name := range firstColumns { + if strings.EqualFold(leaf, name) { + return i + } + } + return len(firstColumns) + } + sort.SliceStable(cols, func(i, j int) bool { return rank(cols[i]) < rank(cols[j]) }) + return cols +} + +// headerText is a field's name as a header, in words: requestName is +// REQUEST NAME, turnID TURN ID. +func headerText(name string) string { + var b strings.Builder + runes := []rune(name) + for i, r := range runes { + if r == '_' || r == '-' || r == '.' { + b.WriteRune(' ') + continue + } + if i > 0 && unicode.IsUpper(r) { + prev := runes[i-1] + nextLower := i+1 < len(runes) && unicode.IsLower(runes[i+1]) + if unicode.IsLower(prev) || unicode.IsDigit(prev) || (unicode.IsUpper(prev) && nextLower) { + b.WriteRune(' ') + } + } + b.WriteRune(unicode.ToUpper(r)) + } + return b.String() +} + +// naturalWidths is each column's widest cell. +func naturalWidths(table [][]string) []int { + var widths []int + for _, row := range table { + for i, c := range row { + if i == len(widths) { + widths = append(widths, 0) + } + widths[i] = max(widths[i], ansi.StringWidth(c)) + } + } + return widths +} + +// fitWidths is how wide each column is so that the table fits in width: the +// widest columns are cut first, none below its floor. When even the floors +// don't fit, the last columns are left out, keeping at least keep of them. +// The result has a width for each column that fits. A width of 0 fits +// everything. +func fitWidths(natural, floors []int, width, keep int) []int { + n := len(natural) + if width <= 0 { + return natural + } + total := func(widths []int) int { + sum := columnGap * (len(widths) - 1) + for _, w := range widths { + sum += w + } + return sum + } + for n > keep && total(floors[:n]) > width { + n-- + } + widths := append([]int(nil), natural[:n]...) + for excess := total(widths) - width; excess > 0; excess-- { + widest := -1 + for i, w := range widths { + if w > floors[i] && (widest < 0 || w > widths[widest]) { + widest = i + } + } + if widest < 0 { + break + } + widths[widest]-- + } + return widths +} + +// writeTable prints the first len(widths) cells of each row, each cut to its +// width with "…" and padded, two spaces apart. +func writeTable(out io.Writer, table [][]string, widths []int) error { + gap := strings.Repeat(" ", columnGap) + for _, row := range table { + var b strings.Builder + for i, w := range widths { + text := ansi.Truncate(row[i], w, "…") + if i > 0 { + b.WriteString(gap) + } + b.WriteString(text) + b.WriteString(strings.Repeat(" ", w-ansi.StringWidth(text))) + } + if _, err := fmt.Fprintln(out, strings.TrimRight(b.String(), " ")); err != nil { + return err + } + } + return nil +} + +// cell is the text of the field at path in row: empty when it is missing or +// null. +func cell(row *jsonObject, path []string) string { + var value any = row + for _, key := range path { + obj, ok := value.(*jsonObject) + if !ok { + return "" + } + value = obj.values[key] + } + return cellText(value) +} + +// cellText is a value as a cell shows it, on one line: a list of plain +// values joined by commas, and an object as compact JSON. +func cellText(value any) string { + switch v := value.(type) { + case nil: + return "" + case string: + if strings.ContainsAny(v, "\n\r\t") { + return strings.Join(strings.Fields(v), " ") + } + return v + case json.Number: + return numberText(v) + case bool: + if v { + return "true" + } + return "false" + case []any: + if !isPlainList(v) { + return compactJSON(v) + } + parts := make([]string, len(v)) + for i, item := range v { + parts[i] = cellText(item) + } + return strings.Join(parts, ", ") + case *jsonObject: + return compactJSON(v) + } + return fmt.Sprint(value) +} + +// numberText is n as written when it is a whole number, and otherwise +// rounded to four decimals, or to three significant digits when it is +// smaller: 1.0150000000000001 is 1.015, 0.000012345 is 0.0000123. +func numberText(n json.Number) string { + literal := n.String() + f, err := n.Float64() + if !strings.ContainsAny(literal, ".eE") || err != nil { + return literal + } + decimals := 4 + if a := math.Abs(f); a > 0 && a < 1 { + decimals = max(decimals, int(-math.Floor(math.Log10(a)))+2) + } + scale := math.Pow(10, float64(decimals)) + return strconv.FormatFloat(math.Round(f*scale)/scale, 'f', -1, 64) +} + +// compactJSON is value as one line of JSON. +func compactJSON(value any) string { + var b bytes.Buffer + enc := json.NewEncoder(&b) + enc.SetEscapeHTML(false) + if err := enc.Encode(value); err != nil { + return fmt.Sprint(value) + } + return strings.TrimSpace(b.String()) +} + +// isPlain reports whether a value fits in a cell as it is: not a list or an +// object. +func isPlain(value any) bool { + switch value.(type) { + case *jsonObject, []any: + return false + } + return true +} + +// isPlainList reports whether every item of a list is plain. +func isPlainList(items []any) bool { + for _, item := range items { + if !isPlain(item) { + return false + } + } + return true +} + +// jsonObject is a JSON object with its keys in order, so columns come in +// the API's order. +type jsonObject struct { + keys []string + values map[string]any +} + +// MarshalJSON writes the object with its keys in order. +func (o *jsonObject) MarshalJSON() ([]byte, error) { + var b bytes.Buffer + b.WriteByte('{') + for i, key := range o.keys { + if i > 0 { + b.WriteByte(',') + } + k, err := json.Marshal(key) + if err != nil { + return nil, err + } + b.Write(k) + b.WriteByte(':') + v, err := json.Marshal(o.values[key]) + if err != nil { + return nil, err + } + b.Write(v) + } + b.WriteByte('}') + return b.Bytes(), nil +} + +// orderByType puts each object's keys in the order of t's fields, which is +// the API's order: the SDK marshals through a map, so its JSON comes sorted. +// A union's object follows the kind whose fields it has, and keys t doesn't +// name stay last. +func orderByType(value any, t reflect.Type) { + if t == nil { + return + } + t = derefType(t) + switch v := value.(type) { + case []any: + if t.Kind() == reflect.Slice || t.Kind() == reflect.Array { + for _, item := range v { + orderByType(item, t.Elem()) + } + } + case *jsonObject: + switch t.Kind() { + case reflect.Map: + for _, key := range v.keys { + orderByType(v.values[key], t.Elem()) + } + case reflect.Struct: + t = unionKind(v, t) + names, types := structFields(t) + sort.SliceStable(v.keys, func(i, j int) bool { + return fieldIndex(names, v.keys[i]) < fieldIndex(names, v.keys[j]) + }) + for _, key := range v.keys { + orderByType(v.values[key], types[key]) + } + } + } +} + +// structFields lists a struct's JSON field names in order, with their types. +func structFields(t reflect.Type) ([]string, map[string]reflect.Type) { + var names []string + types := map[string]reflect.Type{} + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if !f.IsExported() || f.Tag.Get("json") == "-" { + continue + } + name := jsonName(f) + names = append(names, name) + types[name] = f.Type + } + return names, types +} + +func fieldIndex(names []string, key string) int { + for i, name := range names { + if name == key { + return i + } + } + return len(names) +} + +// unionKind is the kind of union t that obj is: the member with most of +// obj's keys. t itself when it isn't a union. +func unionKind(obj *jsonObject, t reflect.Type) reflect.Type { + best, bestHits := t, 0 + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if f.Tag.Get("union") != "member" { + continue + } + member := derefType(f.Type) + if member.Kind() != reflect.Struct { + continue + } + _, types := structFields(member) + hits := 0 + for _, key := range obj.keys { + if _, ok := types[key]; ok { + hits++ + } + } + if hits > bestHits { + best, bestHits = member, hits + } + } + return best +} + +// orderedJSON decodes JSON with each object's keys kept in order and each +// number as written. +func orderedJSON(data []byte) (any, error) { + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + value, err := decodeOrdered(decoder) + if err != nil { + return nil, fmt.Errorf("failed to decode response JSON: %w", err) + } + return value, nil +} + +func decodeOrdered(decoder *json.Decoder) (any, error) { + token, err := decoder.Token() + if err != nil { + return nil, err + } + switch token { + case json.Delim('{'): + obj := &jsonObject{values: map[string]any{}} + for decoder.More() { + keyToken, err := decoder.Token() + if err != nil { + return nil, err + } + key, _ := keyToken.(string) + value, err := decodeOrdered(decoder) + if err != nil { + return nil, err + } + if _, dup := obj.values[key]; !dup { + obj.keys = append(obj.keys, key) + } + obj.values[key] = value + } + _, err = decoder.Token() // } + return obj, err + case json.Delim('['): + list := []any{} + for decoder.More() { + value, err := decodeOrdered(decoder) + if err != nil { + return nil, err + } + list = append(list, value) + } + _, err = decoder.Token() // ] + return list, err + } + return token, nil +} diff --git a/internal/output/tableview_test.go b/internal/output/tableview_test.go index ee0807ba..e652f0ad 100644 --- a/internal/output/tableview_test.go +++ b/internal/output/tableview_test.go @@ -4,6 +4,8 @@ package output import ( "bytes" + "encoding/json" + "regexp" "strings" "testing" @@ -11,12 +13,23 @@ import ( ) func table(t *testing.T, content any) (string, error) { + return tableAt(t, content, 0) +} + +// tableAt prints content as a table width columns wide. +func tableAt(t *testing.T, content any, width int) (string, error) { t.Helper() var out bytes.Buffer - err := printTableOf(&out, content) + err := writeTableOf(&out, content, width) return out.String(), err } +// columnsOf splits a table line into its cells: columns are two or more +// spaces apart, and a header's words one. +func columnsOf(line string) []string { + return regexp.MustCompile(` {2,}`).Split(strings.TrimSpace(line), -1) +} + // {"environments": [...]} prints its environments as rows. func TestATableShowsTheListAResponseWraps(t *testing.T) { out, err := table(t, &components.StableEnvironmentListResponse{Environments: []components.StableEnvironment{ @@ -41,7 +54,7 @@ func TestATableShowsTheRowsAndThePlainFieldsUnderThem(t *testing.T) { t.Fatal(err) } rows, footer, ok := strings.Cut(out, "\n\n") - if !ok || !strings.Contains(rows, "6b0c-transcript") || !strings.Contains(footer, "HASMORE") { + if !ok || !strings.Contains(rows, "6b0c-transcript") || !strings.Contains(footer, "HAS MORE") { t.Errorf("want the rows, a blank line, then returned and hasMore; got:\n%s", out) } } @@ -65,3 +78,152 @@ func TestATableOfTwoListsFailsAndSaysWhatToUse(t *testing.T) { t.Errorf("got %v", err) } } + +// The SDK marshals through a map, so its JSON comes with sorted keys. The +// columns follow the Go type's fields instead, which is the API's order, +// with the id and name first. +func TestATableKeepsTheAPIsColumnOrder(t *testing.T) { + description := "Fired when a parcel ships" + out, err := table(t, &components.StableEventListResponse{Events: []components.StableEvent{ + {ID: "6b0d-event", Name: "Order Shipped", RequestName: "Order_Shipped", Description: &description}, + }}) + if err != nil { + t.Fatal(err) + } + header := columnsOf(strings.SplitN(out, "\n", 2)[0]) + want := []string{"ID", "NAME", "REQUEST NAME", "DESCRIPTION", "IS SYSTEM", "CREATED AT", "UPDATED AT"} + if strings.Join(header, "|") != strings.Join(want, "|") { + t.Errorf("header %q, want %q", header, want) + } +} + +// An empty list still prints as a table's rows, and a record's empty list +// of rows isn't a column. +func TestATableOfAnEmptyListSaysEmpty(t *testing.T) { + out, err := table(t, &components.StableEnvironmentListResponse{Environments: []components.StableEnvironment{}}) + if err != nil || strings.TrimSpace(out) != "(empty)" { + t.Errorf("got %v:\n%s", err, out) + } + out, err = table(t, &components.StableEnvironmentListResponse{Environments: []components.StableEnvironment{{Alias: "main", Name: "Main"}}}) + if err != nil || strings.Contains(out, "RELEASES") { + t.Errorf("an environment's empty releases aren't a column: %v\n%s", err, out) + } +} + +// human-poweruser:F1's events, whose rows wrapped mid-word at 72, 100 and +// 160 columns. +func wideEvents() *components.StableEventListResponse { + long := "Fired by the shop backend when a parcel leaves the warehouse and gets a tracking number" + short := "Line one\nline two" + workflow := "6b0dafba297e8fc83d5487ff" + return &components.StableEventListResponse{Events: []components.StableEvent{ + {ID: "6b0dafba297e8fc83d548802", Name: "Order Shipped", RequestName: "Order_Shipped", Description: &long}, + {ID: "6b0dafba297e8fc83d548803", Name: "Refund", RequestName: "Refund", Description: &short, WorkflowID: &workflow, IsSystem: true}, + }} +} + +// At a terminal, the table fits: the widest columns are cut with "…", an ID +// never is, and columns that don't fit even cut are named under it. +func TestATableFitsTheTerminalsWidth(t *testing.T) { + for _, width := range []int{72, 100, 160} { + out, err := tableAt(t, wideEvents(), width) + if err != nil { + t.Fatal(err) + } + lines := strings.Split(strings.TrimRight(out, "\n"), "\n") + for _, line := range lines { + if n := len([]rune(line)); n > width { + t.Errorf("at %d columns, a line is %d wide:\n%s", width, n, out) + } + } + for _, id := range []string{"6b0dafba297e8fc83d548802", "6b0dafba297e8fc83d548803"} { + if !strings.Contains(out, id) { + t.Errorf("at %d columns, ID %s was cut:\n%s", width, id, out) + } + } + if !strings.Contains(out, "Fired by the sh") || !strings.Contains(out, "…") { + t.Errorf("at %d columns, the description should be cut, not dropped:\n%s", width, out) + } + if width == 72 && !strings.Contains(out, "(Left out to fit 72 columns: WORKFLOW ID, IS SYSTEM,") { + t.Errorf("at 72 columns, the columns left out should be named:\n%s", out) + } + } + + // Off a terminal nothing is cut. + out, err := table(t, wideEvents()) + if err != nil || strings.Contains(out, "…") || !strings.Contains(out, "gets a tracking number") || strings.Contains(out, "Left out") { + t.Errorf("with no width, nothing is cut: %v\n%s", err, out) + } +} + +// A cell is one line, so a description with a newline doesn't push the rows +// below it out of their columns. +func TestATableCellIsOneLine(t *testing.T) { + out, err := table(t, wideEvents()) + if err != nil { + t.Fatal(err) + } + lines := strings.Split(strings.TrimRight(out, "\n"), "\n") + if len(lines) != 3 || !strings.Contains(lines[2], "Line one line two") { + t.Errorf("want a header and two rows:\n%s", out) + } +} + +// Credits read 0.9714999999999999. A number keeps at most four decimals, a +// small one three significant digits, and a whole number every digit. +func TestATableRoundsNumbers(t *testing.T) { + for literal, want := range map[string]string{ + "0.9714999999999999": "0.9715", + "1.0150000000000001": "1.015", + "0.000012345": "0.0000123", + "1796059460997": "1796059460997", + "9007199254740993": "9007199254740993", + "2.5e-7": "0.00000025", + "42.0": "42", + } { + if got := cellText(json.Number(literal)); got != want { + t.Errorf("%s shows as %s, want %s", literal, got, want) + } + } + out, err := table(t, &components.StableTestRunResponse{Run: components.StableTestRun{ID: "R1", TotalCredits: 0.9714999999999999}}) + if err != nil || !strings.Contains(out, "0.9715") || strings.Contains(out, "0.97149") { + t.Errorf("got %v:\n%s", err, out) + } +} + +// The project every row is in is what was asked about, not a column; it is +// when rows differ. +func TestATableLeavesOutTheProjectEveryRowShares(t *testing.T) { + list := func(projects ...string) *components.StableTranscriptPropertyListResponse { + res := &components.StableTranscriptPropertyListResponse{} + for i, p := range projects { + res.Properties = append(res.Properties, components.StableTranscriptProperty{ID: string(rune('a' + i)), Name: "rating", ProjectID: p}) + } + return res + } + out, err := table(t, list("p1", "p1")) + if err != nil || strings.Contains(out, "PROJECT ID") { + t.Errorf("one project: %v\n%s", err, out) + } + out, err = table(t, list("p1", "p2")) + if err != nil || !strings.Contains(out, "PROJECT ID") { + t.Errorf("two projects: %v\n%s", err, out) + } +} + +// A record's values are cut to fit too. +func TestATableRecordFitsTheTerminalsWidth(t *testing.T) { + description := strings.Repeat("A coffee shop agent that takes orders. ", 5) + out, err := tableAt(t, &components.StableProjectResponse{Project: components.StableProject{ID: "6b0c-project", Name: "Coffee", Description: &description}}, 60) + if err != nil { + t.Fatal(err) + } + for _, line := range strings.Split(strings.TrimRight(out, "\n"), "\n") { + if n := len([]rune(line)); n > 60 { + t.Errorf("a line is %d wide:\n%s", n, out) + } + } + if !strings.Contains(out, "A coffee shop agent") || !strings.Contains(out, "…") { + t.Errorf("the description should be cut:\n%s", out) + } +} diff --git a/internal/output/validate.go b/internal/output/validate.go index 067ea514..be3148b5 100644 --- a/internal/output/validate.go +++ b/internal/output/validate.go @@ -6,6 +6,13 @@ // the variable and then reported an error, and running it again made a // second one. An unknown --output-format was never reported at all: Result // fell through to its YAML-like default and exited 0. +// +// PrepareCallOpts checks both before the command's own request. But forms, +// pickers, a draft's compile and `vf docs search` come earlier or don't call +// it, and `test run create-suite --wait` kept a copy of the check. So the +// root command now checks --jq before any command runs, and the copy calls +// CompileJq. A filter that parses and still fails on the response is +// jqfail.go's. package output @@ -35,20 +42,31 @@ func ValidateOutputFlags(cmd *cobra.Command) error { if format != "" && !contains(OutputFormats, format) { return fmt.Errorf("invalid value for %s: %q; valid options: %s", source, format, strings.Join(OutputFormats, ", ")) } + return ValidateJq(cmd) +} + +// ValidateJq rejects a --jq expression that cannot run. The root command +// calls it before any command runs, so a typo fails before a form opens or +// a request is sent: a picker's list, a draft's compile, a docs search. +func ValidateJq(cmd *cobra.Command) error { if expr, _ := flagutil.GetStringFlag(cmd, "jq"); expr != "" { - // Compiling as well as parsing catches a function that does not - // exist, which parses fine. - query, err := gojq.Parse(expr) - if err == nil { - _, err = gojq.Compile(query) - } - if err != nil { + if err := CompileJq(expr); err != nil { return fmt.Errorf("invalid --jq expression %q: %w", expr, err) } } return nil } +// CompileJq reports why expr cannot run, or nil. Compiling as well as +// parsing catches a function that does not exist, which parses fine. +func CompileJq(expr string) error { + query, err := gojq.Parse(expr) + if err == nil { + _, err = gojq.Compile(query) + } + return err +} + func contains(list []string, s string) bool { for _, v := range list { if v == s { diff --git a/internal/ui/DESIGN.md b/internal/ui/DESIGN.md index 30579988..87db592b 100644 --- a/internal/ui/DESIGN.md +++ b/internal/ui/DESIGN.md @@ -469,10 +469,13 @@ never both: command doesn't fail the same way. - **Off a terminal** it is `Error: …` and `-`, with commands in 'quotes', so CI logs stay greppable and steps stay pasteable. -- **In agent mode** the same content is one JSON object on stderr: - `error_type`, `message`, `explanation` (why), `hints` (the next steps, with - commands in 'quotes'), `docs_url`, plus every key the response carried. A - server's own `hints` and `docs_url` win over vf's. +- **In agent mode**, and with `-o json` or `--jq`, the same content is one + JSON object on stderr with the same keys for every error + (internal/output/envelope.go): `error` (the headline), `error_type`, + `exit_code`, `message`, `explanation` (why), `details`, `hints` (the next + steps, with commands in 'quotes'), `docs_url`, and for an API error + `status_code` and the response itself under `body`. A server's own `hints` + and `docs_url` win over vf's. - **Unknown words** suggest the nearest: `Did you mean 'vf workspace list'?`, `Did you mean '--name'?`. - **Fail before sending** whatever can be checked locally: a missing diff --git a/internal/usage/extra_flags.go b/internal/usage/extra_flags.go index 9b78a883..3d3ddd79 100644 --- a/internal/usage/extra_flags.go +++ b/internal/usage/extra_flags.go @@ -7,6 +7,7 @@ package usage import ( "fmt" "regexp" + "slices" "strings" ) @@ -49,12 +50,15 @@ func addFlagsToSchema(schema string, path []string, flags []UsageFlag) string { var stack []usageCmd for _, line := range lines { if m := usageCmdLine.FindStringSubmatch(line); m != nil { - stack = append(stack, usageCmd{indent: m[1], name: m[2]}) + stack = append(stack, usageCmd{indent: m[1], name: m[2], start: len(out)}) } else if m := usageCloseLine.FindStringSubmatch(line); m != nil && len(stack) > 0 && stack[len(stack)-1].indent == m[1] { if stackMatches(stack, path) { + // Only this command's own lines say whether it has the flag: + // a sibling with the same flag (every delete's --yes) doesn't. + block := out[stack[len(stack)-1].start:] for _, flag := range flags { flagLine := fmt.Sprintf("%s flag %q help=%q", m[1], flag.Spec, flag.Help) - if !strings.Contains(schema, flagLine) { + if !slices.Contains(block, flagLine) { out = append(out, flagLine) } } @@ -69,6 +73,7 @@ func addFlagsToSchema(schema string, path []string, flags []UsageFlag) string { type usageCmd struct { indent string name string + start int // where its lines start in the output } func stackMatches(stack []usageCmd, path []string) bool { diff --git a/internal/usage/extra_flags_test.go b/internal/usage/extra_flags_test.go new file mode 100644 index 00000000..0537f655 --- /dev/null +++ b/internal/usage/extra_flags_test.go @@ -0,0 +1,26 @@ +// This file is not generated by Speakeasy. It covers extra_flags.go. + +package usage + +import ( + "strings" + "testing" +) + +// Every delete gets the same --yes line. The second one used to be dropped, +// because the check for a flag already there looked at the whole schema +// rather than the command's own lines. +func TestAFlagSiblingsShareIsAddedToEach(t *testing.T) { + schema := "cmd \"project\" {\n cmd \"delete\" {\n }\n}\ncmd \"secret\" {\n cmd \"delete\" {\n }\n}" + yes := UsageFlag{Spec: "-y --yes", Help: "Delete without asking first."} + line := ` flag "-y --yes" help="Delete without asking first."` + + s := addFlagsToSchema(schema, []string{"project", "delete"}, []UsageFlag{yes}) + s = addFlagsToSchema(s, []string{"secret", "delete"}, []UsageFlag{yes}) + if n := strings.Count(s, line); n != 2 { + t.Errorf("both deletes should list --yes, found %d:\n%s", n, s) + } + if again := addFlagsToSchema(s, []string{"project", "delete"}, []UsageFlag{yes}); again != s { + t.Errorf("adding a flag a command already lists should change nothing:\n%s", again) + } +} diff --git a/internal/usage/ownhelp.go b/internal/usage/ownhelp.go new file mode 100644 index 00000000..f28a1481 --- /dev/null +++ b/internal/usage/ownhelp.go @@ -0,0 +1,110 @@ +// This file is not generated by Speakeasy. It lets a flag whose help vf +// writes at startup show that help in --usage too. +// +// The schemas in schema.go are fixed text from the API spec. A union's +// forms appear there as `{ type: string, testID: string, payload: object }`, +// and the flags that take each form (--body-param.user) not at all, so +// `--usage` couldn't say what a test turn's payload holds. flagutil writes +// each form's JSON into its flag's help (flagutil/forms.go) and marks the +// flag; when --usage is asked for, the schema takes the help from the flag, +// and gains a line for each marked flag it lacks. + +package usage + +import ( + "fmt" + "regexp" + "strconv" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +// OwnHelp marks a flag whose help --usage takes from the flag itself. +const OwnHelp = "vf:usage-own-help" + +var usageFlagLine = regexp.MustCompile(`^(\s*)flag "(?:-\S )?(--[^\s"]+)`) + +// withOwnHelp gives schema, cmd's --usage, the help of each marked flag. +func withOwnHelp(cmd *cobra.Command, schema string) string { + type block struct { + cmd *cobra.Command + indent string + has map[string]bool + } + var stack []block + lines := strings.Split(schema, "\n") + out := make([]string, 0, len(lines)) + for _, line := range lines { + if m := usageCmdLine.FindStringSubmatch(line); m != nil { + var c *cobra.Command + switch { + case len(stack) > 0: + c = subcommand(stack[len(stack)-1].cmd, m[2]) + case cmd.HasParent(): + c = cmd // a command's own schema starts with itself + default: + c = subcommand(cmd, m[2]) // the root's starts with its children + } + stack = append(stack, block{cmd: c, indent: m[1], has: map[string]bool{}}) + } else if m := usageFlagLine.FindStringSubmatch(line); m != nil && len(stack) > 0 { + top := stack[len(stack)-1] + top.has[m[2]] = true + if f := ownHelpFlag(top.cmd, m[2]); f != nil { + line = replaceHelp(line, f.Usage) + } + } else if m := usageCloseLine.FindStringSubmatch(line); m != nil && len(stack) > 0 && stack[len(stack)-1].indent == m[1] { + top := stack[len(stack)-1] + if top.cmd != nil { + top.cmd.LocalFlags().VisitAll(func(f *pflag.Flag) { + if len(f.Annotations[OwnHelp]) > 0 && !f.Hidden && !top.has["--"+f.Name] { + out = append(out, fmt.Sprintf("%s flag %q help=%q", m[1], "--"+f.Name+" <"+strings.NewReplacer("-", "_", ".", "_").Replace(f.Name)+">", f.Usage)) + } + }) + } + stack = stack[:len(stack)-1] + } + out = append(out, line) + } + return strings.Join(out, "\n") +} + +// subcommand is parent's command named name, or nil. +func subcommand(parent *cobra.Command, name string) *cobra.Command { + if parent == nil { + return nil + } + for _, c := range parent.Commands() { + if c.Name() == name { + return c + } + } + return nil +} + +// ownHelpFlag is cmd's flag name when it is marked, or nil. +func ownHelpFlag(cmd *cobra.Command, name string) *pflag.Flag { + if cmd == nil { + return nil + } + f := cmd.LocalFlags().Lookup(strings.TrimPrefix(name, "--")) + if f == nil || len(f.Annotations[OwnHelp]) == 0 { + return nil + } + return f +} + +// replaceHelp gives a flag line help instead of the help it has. +func replaceHelp(line, help string) string { + i := strings.Index(line, ` help="`) + if i < 0 { + return line + } + start := i + len(` help=`) + quoted, err := strconv.QuotedPrefix(line[start:]) + if err != nil { + return line + } + return line[:start] + strconv.Quote(help) + line[start+len(quoted):] +} diff --git a/internal/usage/schema.go b/internal/usage/schema.go index bf8010b0..7c5ec4bf 100644 --- a/internal/usage/schema.go +++ b/internal/usage/schema.go @@ -11,7 +11,7 @@ import ( ) var usageSchemas = map[string]string{ - "": "name \"vf\"\nbin \"vf\"\nabout \"Build, test, and operate Voiceflow AI agents from your terminal\"\nversion \"0.2.349\"\nconfig {\n file \"~/.config/vf/config.yaml\"\n}\nflag \"--usage\" help=\"Print the CLI Usage schema in KDL format\" global=#true\nflag \"-o --output-format <format>\" help=\"Specify the output format. Options: pretty, json, yaml, table, toon.\" global=#true config=\"output_format\" default=\"pretty\"\nflag \"--color <color>\" help=\"Control colored output: auto (color when output is a TTY), always, or never. Respects NO_COLOR and FORCE_COLOR env vars.\" global=#true default=\"auto\"\nflag \"-q --jq <jq>\" help=\"Filter and transform output using a jq expression (e.g., '.name', '.items[] | .id')\" global=#true\nflag \"--server-url <url>\" help=\"Override the default server URL\" global=#true\nflag \"--server <server>\" help=\"Select a server by index (for indexed servers) or name (for named servers)\" global=#true\nflag \"-H --header <header...>\" help=\"Set a custom HTTP request header (format: \\\"Key: Value\\\"). Can be specified multiple times.\" global=#true var=#true\nflag \"--include-headers\" help=\"Include HTTP response headers in the output\" global=#true default=#false\nflag \"--timeout <duration>\" help=\"HTTP request timeout (e.g., 30s, 5m, 100ms)\" global=#true config=\"timeout\"\nflag \"--dry-run\" help=\"Preview the request that would be sent without executing it (output to stderr)\" global=#true default=#false\nflag \"-d --debug\" help=\"Log request and response diagnostics to stderr\" global=#true default=#false\nflag \"--agent-mode\" help=\"Enable structured errors and default TOON output for AI coding agents. Automatically enabled when a known agent environment is detected (CLAUDE_CODE, CURSOR_AGENT, etc.). Use --agent-mode=false to disable.\" global=#true default=#false\nflag \"--token <token>\" help=\"Voiceflow bearer token\" global=#true env=\"VF_TOKEN\" config=\"security.token\"\ncmd \"agent\" help=\"Configure the agent's instructions, prompt and voice\" {\n cmd \"get\" help=\"Get agent\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--include-instructions\" help=\"boolean flag\" default=#false\n flag \"--include-prompt\" help=\"boolean flag\" default=#false\n }\n cmd \"update\" help=\"Update agent\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--prompt <prompt>\" help=\"string value\"\n flag \"--end-tool <end_tool>\" help=\"JSON object\"\n flag \"--card-tool <card_tool>\" help=\"JSON object\"\n flag \"--playbooks <playbooks>\" help=\"Playbooks available for the agent to invoke. This list REPLACES the registry: send the complete list you want, or omit the field to leave routing untouched. An agent with no playbooks AND no workflows registered cannot run - the runtime fails the conversation - so never send an empty list unless `workflows` still holds at least one.\"\n flag \"--workflows <workflows>\" help=\"Workflows available for the agent to invoke. This list REPLACES the registry: send the complete list you want, or omit the field to leave routing untouched. An agent with no workflows AND no playbooks registered cannot run, so never send an empty list unless `playbooks` still holds at least one.\"\n flag \"--button-tool <button_tool>\" help=\"JSON object\"\n flag \"--carousel-tool <carousel_tool>\" help=\"JSON object\"\n flag \"--instructions <instructions>\" help=\"string value\"\n flag \"--skip-turn-tool <skip_turn_tool>\" help=\"JSON object\"\n flag \"--path-tool-order <path_tool_order...>\" help=\"The ordered list of path tool IDs that controls the order of the agent exit paths.\" var=#true\n flag \"--web-search-tool <web_search_tool>\" help=\"JSON object\"\n flag \"--call-forward-tool <call_forward_tool>\" help=\"JSON object\"\n flag \"--knowledge-base-tool <knowledge_base_tool>\" help=\"JSON object\"\n flag \"--include-guidelines\" help=\"Whether to append the default prompting guidelines to the global prompt.\"\n flag \"--llm <llm>\" help=\"JSON object\"\n flag \"--voice <voice>\" help=\"JSON object\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"add-workflow\" help=\"Add agent workflow\" {\n alias \"aw\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--condition <condition>\" help=\"The agent can run the workflow only while this condition holds. Leave it out for a workflow it can always run.\"\n flag \"--description <description>\" help=\"When the agent should run this workflow. The agent reads it to choose between its playbooks and workflows. [required]\"\n flag \"--required-variables <required_variables>\" help=\"Variables the agent fills from the conversation before it runs the workflow, each with a description of what it holds.\"\n flag \"--workflow-id <workflow_id>\" help=\"The workflow to add. Copy its ID from voiceflow_workflow.list. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"update-workflow\" help=\"Update agent workflow\" {\n alias \"uw\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--condition <condition>\" help=\"The agent can run the workflow only while this condition holds. Leave it out for a workflow it can always run.\"\n flag \"--description <description>\" help=\"When the agent should run this workflow. The agent reads it to choose between its playbooks and workflows.\"\n flag \"--required-variables <required_variables>\" help=\"Replaces the stored list. Keep the id of each variable you keep, as read with voiceflow_agent.get. Leave the field out to keep the stored required variables.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"remove-workflow\" help=\"Remove agent workflow\" {\n alias \"rw\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"read-instructions\" help=\"Read agent instructions\" {\n alias \"ri\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--offset <offset>\" help=\"integer value\" default=1\n flag \"--limit <limit>\" help=\"integer value\" default=400\n }\n cmd \"patch-instructions\" help=\"Patch agent instructions\" {\n alias \"pi\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--old-string <old_string>\" help=\"The exact text to replace, copied verbatim from a read or search result. Matching is literal — whitespace, punctuation and case must match. Do not include the line numbers a read adds. [required]\"\n flag \"--new-string <new_string>\" help=\"The text to put in its place. May be empty to delete. [required]\"\n flag \"--replace-all\" help=\"Replace every occurrence. When false, more than one match is an error rather than a guess.\" default=#false\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"search-instructions\" help=\"Search agent instructions\" {\n alias \"si\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--pattern <pattern>\" help=\"A JavaScript regular expression, evaluated against each line on its own. [required]\"\n flag \"--ignore-case\" help=\"Match case-insensitively. Defaults to false, like grep.\" default=#false\n flag \"--context-lines <context_lines>\" help=\"How many lines either side of each match to return.\" default=0\n flag \"--limit <limit>\" help=\"The maximum number of matching LINES to return. The reported totals cover the whole document.\" default=50\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"read-prompt\" help=\"Read the global prompt\" {\n alias \"rp\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--offset <offset>\" help=\"integer value\" default=1\n flag \"--limit <limit>\" help=\"integer value\" default=400\n }\n cmd \"patch-prompt\" help=\"Patch the global prompt\" {\n alias \"pp\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--old-string <old_string>\" help=\"The exact text to replace, copied verbatim from a read or search result. Matching is literal — whitespace, punctuation and case must match. Do not include the line numbers a read adds. [required]\"\n flag \"--new-string <new_string>\" help=\"The text to put in its place. May be empty to delete. [required]\"\n flag \"--replace-all\" help=\"Replace every occurrence. When false, more than one match is an error rather than a guess.\" default=#false\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"search-prompt\" help=\"Search the global prompt\" {\n alias \"sp\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--pattern <pattern>\" help=\"A JavaScript regular expression, evaluated against each line on its own. [required]\"\n flag \"--ignore-case\" help=\"Match case-insensitively. Defaults to false, like grep.\" default=#false\n flag \"--context-lines <context_lines>\" help=\"How many lines either side of each match to return.\" default=0\n flag \"--limit <limit>\" help=\"The maximum number of matching LINES to return. The reported totals cover the whole document.\" default=50\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"add-tool-message\" help=\"Add agent tool message\" {\n alias \"atm\"\n flag \"--project-id <project_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--environment-alias <environment_alias>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--slot <slot>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: delay, failure, execution, completion) [required]\"\n flag \"--tool-id <tool_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected.\"\n flag \"--native-tool <native_tool>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: endTool, cardTool, buttonTool, carouselTool, webSearchTool, callForwardTool, knowledgeBaseTool)\"\n flag \"--body-param <body_param>\" help=\"{ type: string, examples: string[] } | { type: string, messageID: string }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"update-tool-message\" help=\"Update agent tool message\" {\n alias \"utm\"\n flag \"--project-id <project_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--environment-alias <environment_alias>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--slot <slot>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: delay, failure, execution, completion) [required]\"\n flag \"--tool-id <tool_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected.\"\n flag \"--native-tool <native_tool>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: endTool, cardTool, buttonTool, carouselTool, webSearchTool, callForwardTool, knowledgeBaseTool)\"\n flag \"--body-param <body_param>\" help=\"{ type: string, examples: string[] } | { type: string, messageID: string }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete-tool-message\" help=\"Delete agent tool message\" {\n alias \"dtm\"\n flag \"--project-id <project_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--environment-alias <environment_alias>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--slot <slot>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: delay, failure, execution, completion) [required]\"\n flag \"--tool-id <tool_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected.\"\n flag \"--native-tool <native_tool>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: endTool, cardTool, buttonTool, carouselTool, webSearchTool, callForwardTool, knowledgeBaseTool)\"\n }\n cmd \"patch-pronunciation\" help=\"Patch pronunciation dictionary\" {\n alias \"ppr\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--set <set>\" help=\"Words to add, or to change when the dictionary already has them. `from` is the written word and `to` is how the voice says it; an empty `to` makes the voice skip the word.\"\n flag \"--remove <remove...>\" help=\"Written words whose entries to delete.\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"search-voices\" help=\"Search voices\" {\n alias \"sv\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--search <search>\" help=\"string value\"\n flag \"--language <language>\" help=\"string value\"\n flag \"--provider <provider>\" help=\"A TTS provider whose voices are in the voice catalog. (options: elevenlabs, cartesia)\"\n flag \"--gender <gender>\" help=\"How the vendor describes the voice. (options: male, female, neutral)\"\n flag \"--limit <limit>\" help=\"integer value\" default=10\n flag \"--offset <offset>\" help=\"integer value\" default=0\n }\n cmd \"patch-voices\" help=\"Patch voices\" {\n alias \"pv\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--primary <primary>\" help=\"The default voice: the one a conversation speaks with unless a language voice matches its locale.\"\n flag \"--set-overrides <set_overrides>\" help=\"Language voices to add, or to change when the agent already has one for that locale.\"\n flag \"--remove-overrides <remove_overrides...>\" help=\"Locales whose language voice to delete, as stored. They match ignoring case and _, as the runtime matches them.\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get-initialization-workflow\" help=\"Get initialization workflow\" {\n alias \"giw\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"set-initialization-workflow\" help=\"Set initialization workflow\" {\n alias \"siw\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--workflow-id <workflow_id>\" help=\"The workflow to run before the user's first turn, or null to run none. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n}\ncmd \"workflow\" help=\"Build workflows: blocks, steps, branches and links\" {\n cmd \"list\" help=\"List workflows\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--folder-id <folder_id>\" help=\"string value\"\n flag \"--cursor <cursor>\" help=\"string value\"\n flag \"--limit <limit>\" help=\"integer value\"\n }\n cmd \"create\" help=\"Create workflow\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"[required]\"\n flag \"--description <description>\" help=\"string value\"\n flag \"--folder-id <folder_id>\" help=\"string value\"\n flag \"--entry <entry>\" help=\"string value\"\n flag \"--blocks <blocks>\" help=\"list of values\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get workflow\" {\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--cursor <cursor>\" help=\"string value\"\n }\n cmd \"update\" help=\"Update workflow\" {\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"string value\"\n flag \"--description <description>\" help=\"string value\"\n flag \"--folder-id <folder_id>\" help=\"A workflow folder in this environment, or null for the top level.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete workflow\" {\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"get-step\" help=\"Get workflow step\" {\n alias \"gs\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--step-id <step_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update-step\" help=\"Update workflow step\" {\n alias \"us\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--step-id <step_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ kind: string, content: object }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete-step\" help=\"Delete workflow step\" {\n alias \"ds\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--step-id <step_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--expected-steps <expected_steps...>\" help=\"[required]\" var=#true\n }\n cmd \"get-raw\" help=\"Get raw workflow\" {\n alias \"gr\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--block-ids <block_ids...>\" help=\"list of values\" var=#true\n }\n cmd \"duplicate\" help=\"Duplicate workflow\" {\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the copy. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"link\" help=\"Link a port\" {\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--step-id <step_id>\" help=\"[required]\"\n flag \"--port-key <port_key>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--to-block-id <to_block_id>\" help=\"The block the port will lead to. Links point at blocks, never at a step inside one. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"unlink\" help=\"Unlink a port\" {\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--step-id <step_id>\" help=\"[required]\"\n flag \"--port-key <port_key>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"link-many\" help=\"Link many ports\" {\n alias \"lm\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--links <links>\" help=\"1 to 50 ports to link, each once. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"create-block\" help=\"Create block\" {\n alias \"cb\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"[required]\"\n flag \"--color-param <color_param>\" help=\"string value\"\n flag \"--placement <placement>\" help=\"Place the new block to the right of this block. Without it, the block goes next to the block of from.stepID, or right of the right-most block.\"\n flag \"--from <from>\" help=\"Also link this port to the new block in the same call, with the same checks as voiceflow_workflow.link.\"\n flag \"--steps <steps>\" help=\"[required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"add-blocks\" help=\"Add workflow blocks\" {\n alias \"ab\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--blocks <blocks>\" help=\"The new blocks. A step's links and a branch's to name a block key from this call or an existing block ID. [required]\"\n flag \"--from <from>\" help=\"Existing ports to link to new blocks in the same call, with the same checks as voiceflow_workflow.link.\"\n flag \"--placement <placement>\" help=\"Place the new blocks to the right of this block. Without it, they go right of the block of the first from step, or right of the right-most block.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"update-block\" help=\"Update block\" {\n alias \"ub\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--block-id <block_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"string value\"\n flag \"--color-param <color_param>\" help=\"string value\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete-block\" help=\"Delete workflow block\" {\n alias \"db\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--block-id <block_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--expected-steps <expected_steps...>\" help=\"[required]\" var=#true\n }\n cmd \"arrange-blocks\" help=\"Arrange workflow blocks\" {\n alias \"abl\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--block-ids <block_ids...>\" help=\"Move only these blocks, as a group laid out by the links between them. Leave it out to arrange every block from the Start.\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"split-block\" help=\"Split workflow block\" {\n alias \"sb\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--block-id <block_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--at-step-id <at_step_id>\" help=\"The step that starts the new block. It and every step below it move there, and the step above it becomes the last step of the block. To make step X the last step, so that its fail and path ports run, send the step below X. It must not be the first step. [required]\"\n flag \"--name <name>\" help=\"The new block name. Default: the block name with \\\" (continued)\\\".\"\n flag \"--expected-steps <expected_steps...>\" help=\"The block's step IDs exactly as your last read returned them. If the block changed, nothing is written. [required]\" var=#true\n flag \"--acknowledge-rewire\" help=\"Required when the step that becomes the last step has hidden links or actions. The split keeps them, so they start to run. An action list on its next exit is deleted, because next links to the new block.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"insert-step\" help=\"Insert workflow step\" {\n alias \"is\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--block-id <block_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--after-step-id <after_step_id>\" help=\"Insert right after this step of the block. Send this or atStart.\"\n flag \"--at-start\" help=\"Insert as the first step of the block. Send this or afterStepID.\"\n flag \"--step <step>\" help=\"{ kind: string, key: string, content: value, links: object } | { kind: string, key: string, content: object, links: object }\"\n flag \"--expected-steps <expected_steps...>\" help=\"The block's step IDs exactly as your last read returned them. If the block changed, nothing is written. [required]\" var=#true\n flag \"--acknowledge-rewire\" help=\"Required when the insert makes the last step stop being last and that step has exits that would stop running: a Tool or Code fail or path link is cleared, and actions on such an exit are deleted. Also required when you append a step that has no next port, such as End or Go to block: the old last step's next link cannot move to it, so it is cleared.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"add-branch\" help=\"Add workflow branch\" {\n alias \"abr\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--step-id <step_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ label: string, matchAll: boolean, assertions: object[], to: string, ... } | { label: string, url: string, to: string, kind: string } | { label: string, url: string, to: string, kind: string, ... } | { label: string, to: string, kind: string } | { name: string, description: string, requiredVariables: object[], messages: object, ... }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"update-branch\" help=\"Update workflow branch\" {\n alias \"ubr\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--step-id <step_id>\" help=\"[required]\"\n flag \"--branch-id <branch_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ label: string, matchAll: boolean, assertions: object[], kind: string } | { label: string, url: string, kind: string } | { label: string, kind: string } | { name: string, description: string, requiredVariables: object[], kind: string }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete-branch\" help=\"Delete workflow branch\" {\n alias \"dbr\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--step-id <step_id>\" help=\"[required]\"\n flag \"--branch-id <branch_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"add-actions\" help=\"Add port actions\" {\n alias \"aa\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--step-id <step_id>\" help=\"[required]\"\n flag \"--port-key <port_key>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--actions <actions>\" help=\"1 to 10 actions to add, in run order. [required]\"\n flag \"--after-action-id <after_action_id>\" help=\"Add them after this action. Leave out afterActionID and atStart to add them at the end, before an action that ends the path.\"\n flag \"--at-start\" help=\"Add them before every other action on this exit.\"\n flag \"--expected-actions <expected_actions...>\" help=\"The IDs in this exit's actions from your last read, in order. Send [] when it has none. [required]\" var=#true\n flag \"--to <to>\" help=\"The block the path goes to after the actions. Leave it out to keep the current one. Send null to clear it.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"reorder-actions\" help=\"Reorder port actions\" {\n alias \"ra\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--step-id <step_id>\" help=\"[required]\"\n flag \"--port-key <port_key>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--order <order...>\" help=\"Every action ID of this exit, in the new order. [required]\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"replace-action\" help=\"Replace port action\" {\n alias \"rac\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--action-id <action_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--action <action>\" help=\"{ kind: string, content: object }\"\n flag \"--expected-actions <expected_actions...>\" help=\"The IDs in this exit's actions from your last read, in order. [required]\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n}\ncmd \"playbook\" help=\"Build playbooks: instructions, tools and exit paths\" {\n cmd \"list\" help=\"List playbooks\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--include-instructions\" help=\"boolean flag\" default=#false\n }\n cmd \"create\" help=\"Create playbook\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"[required]\"\n flag \"--description <description>\" help=\"A human-readable description of what the playbook does.\"\n flag \"--instructions <instructions>\" help=\"string value\"\n flag \"--end-tool <end_tool>\" help=\"JSON object\"\n flag \"--card-tool <card_tool>\" help=\"JSON object\"\n flag \"--button-tool <button_tool>\" help=\"JSON object\"\n flag \"--carousel-tool <carousel_tool>\" help=\"JSON object\"\n flag \"--skip-turn-tool <skip_turn_tool>\" help=\"JSON object\"\n flag \"--web-search-tool <web_search_tool>\" help=\"JSON object\"\n flag \"--call-forward-tool <call_forward_tool>\" help=\"JSON object\"\n flag \"--knowledge-base-tool <knowledge_base_tool>\" help=\"JSON object\"\n flag \"--settings <settings>\" help=\"JSON object\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get playbook\" {\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--include-instructions\" help=\"boolean flag\" default=#false\n }\n cmd \"update\" help=\"Update playbook\" {\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"string value\"\n flag \"--settings <settings>\" help=\"JSON object\"\n flag \"--description <description>\" help=\"A human-readable description of what the playbook does.\"\n flag \"--instructions <instructions>\" help=\"string value\"\n flag \"--end-tool <end_tool>\" help=\"JSON object\"\n flag \"--card-tool <card_tool>\" help=\"JSON object\"\n flag \"--button-tool <button_tool>\" help=\"JSON object\"\n flag \"--carousel-tool <carousel_tool>\" help=\"JSON object\"\n flag \"--skip-turn-tool <skip_turn_tool>\" help=\"JSON object\"\n flag \"--web-search-tool <web_search_tool>\" help=\"JSON object\"\n flag \"--call-forward-tool <call_forward_tool>\" help=\"JSON object\"\n flag \"--knowledge-base-tool <knowledge_base_tool>\" help=\"JSON object\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete playbook\" {\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"read-instructions\" help=\"Read playbook instructions\" {\n alias \"ri\"\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--offset <offset>\" help=\"integer value\" default=1\n flag \"--limit <limit>\" help=\"integer value\" default=400\n }\n cmd \"patch-instructions\" help=\"Patch playbook instructions\" {\n alias \"pi\"\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--old-string <old_string>\" help=\"The exact text to replace, copied verbatim from a read or search result. Matching is literal — whitespace, punctuation and case must match. Do not include the line numbers a read adds. [required]\"\n flag \"--new-string <new_string>\" help=\"The text to put in its place. May be empty to delete. [required]\"\n flag \"--replace-all\" help=\"Replace every occurrence. When false, more than one match is an error rather than a guess.\" default=#false\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"search-instructions\" help=\"Search playbook instructions\" {\n alias \"si\"\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--pattern <pattern>\" help=\"A JavaScript regular expression, evaluated against each line on its own. [required]\"\n flag \"--ignore-case\" help=\"Match case-insensitively. Defaults to false, like grep.\" default=#false\n flag \"--context-lines <context_lines>\" help=\"How many lines either side of each match to return.\" default=0\n flag \"--limit <limit>\" help=\"The maximum number of matching LINES to return. The reported totals cover the whole document.\" default=50\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"duplicate\" help=\"Duplicate playbook\" {\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the copy. Leave it out to use the original's name with \\\" copy\\\" added.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"add-tool-message\" help=\"Add playbook tool message\" {\n alias \"atm\"\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--environment-alias <environment_alias>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--slot <slot>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: delay, failure, execution, completion) [required]\"\n flag \"--tool-id <tool_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected.\"\n flag \"--native-tool <native_tool>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: endTool, cardTool, buttonTool, carouselTool, webSearchTool, callForwardTool, knowledgeBaseTool)\"\n flag \"--body-param <body_param>\" help=\"{ type: string, examples: string[] } | { type: string, messageID: string }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"update-tool-message\" help=\"Update playbook tool message\" {\n alias \"utm\"\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--environment-alias <environment_alias>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--slot <slot>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: delay, failure, execution, completion) [required]\"\n flag \"--tool-id <tool_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected.\"\n flag \"--native-tool <native_tool>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: endTool, cardTool, buttonTool, carouselTool, webSearchTool, callForwardTool, knowledgeBaseTool)\"\n flag \"--body-param <body_param>\" help=\"{ type: string, examples: string[] } | { type: string, messageID: string }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete-tool-message\" help=\"Delete playbook tool message\" {\n alias \"dtm\"\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--environment-alias <environment_alias>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--slot <slot>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: delay, failure, execution, completion) [required]\"\n flag \"--tool-id <tool_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected.\"\n flag \"--native-tool <native_tool>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: endTool, cardTool, buttonTool, carouselTool, webSearchTool, callForwardTool, knowledgeBaseTool)\"\n }\n cmd \"path\" help=\"Manage a playbook's exit paths\" {\n cmd \"list\" help=\"List exit paths\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create exit path\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--playbook-id <playbook_id>\" help=\"The ID of the playbook to add the exit path to. [required]\"\n flag \"--name <name>\" help=\"The name of the exit path, trimmed. Use Latin letters, digits, spaces, hyphens and underscores, as the editor does: the runtime turns the name into the snake_case name of the exit tool the model calls. [required]\"\n flag \"--description <description>\" help=\"The exit condition: the model reads it to decide when to leave the playbook through this path.\"\n flag \"--required-variables <required_variables>\" help=\"The variables or entities the model must fill before it can leave through this path, in order.\"\n flag \"--messages <messages>\" help=\"What the agent says as it leaves through this path. Send only a message ID that nothing else uses: no other step in any workflow, no reprompt, no agent and no playbook. For the same words in a second place, create a new message with that text.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"update\" help=\"Update exit path\" {\n flag \"--path-id <path_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the exit path, trimmed. Use Latin letters, digits, spaces, hyphens and underscores, as the editor does: the runtime turns the name into the snake_case name of the exit tool the model calls.\"\n flag \"--description <description>\" help=\"The exit condition: the model reads it to decide when to leave the playbook through this path.\"\n flag \"--required-variables <required_variables>\" help=\"Replaces the stored list, in order. Leave it out to keep it; send [] to remove every one.\"\n flag \"--messages <messages>\" help=\"Replaces the stored messages whole. Send null to remove them; leave it out to keep them. Send only a message ID that nothing else uses: no other step in any workflow, no reprompt, no agent and no playbook. For the same words in a second place, create a new message with that text.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete exit path\" {\n flag \"--path-id <path_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n }\n }\n}\ncmd \"tool\" help=\"Manage the tools an agent and its playbooks use\" {\n cmd \"list\" help=\"List tools\" {\n flag \"--global\" help=\"boolean flag\"\n flag \"--playbook-id <playbook_id>\" help=\"string value\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--type <type>\" help=\"When provided, only tools of this type are returned. `workflow` returns the workflow tools. (options: api, mcp, function, integration, workflow)\"\n }\n cmd \"create\" help=\"Create tool\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ description: string, target: object, messages: object, captureInputVariables: object, ... }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get tool\" {\n flag \"--tool-id <tool_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--type <type>\" help=\"The type of the tool to fetch. (options: api, mcp, function, integration, workflow) [required]\"\n }\n cmd \"update\" help=\"Update tool\" {\n flag \"--tool-id <tool_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ description: string, messages: object, toolSound: object, captureInputVariables: object, ... }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete tool\" {\n flag \"--tool-id <tool_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--type <type>\" help=\"The type of the tool to delete. `workflow` removes a workflow tool; the workflow stays. (options: api, mcp, function, integration, workflow) [required]\"\n }\n cmd \"move\" help=\"Move tool\" {\n flag \"--tool-id <tool_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--type <type>\" help=\"The type of the tool to move. `workflow` is refused: a workflow tool is never moved. (options: api, mcp, function, integration, workflow) [required]\"\n flag \"--target <target>\" help=\"[required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n}\ncmd \"workspace\" help=\"Create, list and manage workspaces\" {\n cmd \"list\" help=\"List workspaces\"\n cmd \"create\" help=\"Create workspace\" {\n flag \"--name <name>\" help=\"[required]\"\n flag \"--organization-id <organization_id>\" help=\"The ID of the organization the workspace belongs to. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get workspace\" {\n flag \"--workspace-id <workspace_id>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update workspace\" {\n flag \"--workspace-id <workspace_id>\" help=\"[required]\"\n flag \"--name <name>\" help=\"string value\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete workspace\" {\n flag \"--workspace-id <workspace_id>\" help=\"[required]\"\n }\n}\ncmd \"project\" help=\"Create, list and manage projects\" {\n cmd \"list\" help=\"List projects\" {\n flag \"--workspace-id <workspace_id>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create project\" {\n flag \"--name <name>\" help=\"[required]\"\n flag \"--workspace-id <workspace_id>\" help=\"The ID of the workspace the project belongs to. [required]\"\n flag \"--type <type>\" help=\"The channel type of the project to create. (options: webchat, phone-call) [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get project\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update project\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--name <name>\" help=\"string value\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete project\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n}\ncmd \"environment\" help=\"Publish, clone, merge and compare environments\" {\n cmd \"list\" help=\"List environments\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"merge\" help=\"Merge environments\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--source-environment-alias <source_environment_alias>\" help=\"The alias of the environment whose changes are merged. [required]\"\n flag \"--target-environment-alias <target_environment_alias>\" help=\"The alias of the environment that receives the merged changes. [required]\"\n flag \"--remove-source-environment\" help=\"If true, the source environment is deleted after the merge.\" default=#false\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"update-traffic-split\" help=\"Update traffic split\" {\n alias \"uts\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--traffic <traffic>\" help=\"Map of environmentAlias → traffic percentage (0-100). Values must sum to 100. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get environment\" {\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update environment\" {\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--name <name>\" help=\"string value\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete environment\" {\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"diff\" help=\"Diff environment\" {\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"audit-wiring\" help=\"Audit environment wiring\" {\n alias \"aw\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"search-text\" help=\"Search project text\" {\n alias \"st\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--pattern <pattern>\" help=\"The word, phrase or ID to find. With regex, a JavaScript regular expression. [required]\"\n flag \"--regex\" help=\"Read pattern as a regular expression. Default false: literal text.\"\n flag \"--ignore-case\" help=\"Ignore case. Default true.\"\n flag \"--whole-word\" help=\"Match only where no letter, digit or underscore touches the match on either side. Default false.\"\n flag \"--resource-types <resource_types...>\" help=\"Search only these kinds of resource. Default: all of them.\" var=#true\n flag \"--limit <limit>\" help=\"Hits per page. Default 50.\"\n flag \"--offset <offset>\" help=\"Hits to skip: nextOffset from the previous page.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"compile\" help=\"Compile environment\" {\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"clone\" help=\"Clone environment\" {\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The display name of the new environment. [required]\"\n flag \"--alias <alias>\" help=\"Short URL-safe identifier; cannot be 'main' (reserved). [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"publish\" help=\"Publish environment\" {\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the release created by publishing. [required]\"\n flag \"--description <description>\" help=\"An optional description of what changed in this release.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n}\ncmd \"message\" help=\"Manage reusable messages and their variants\" {\n cmd \"get-many\" help=\"Get many messages\" {\n alias \"gm\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--ids <ids...>\" help=\"Message IDs to read. Duplicates are ignored; at most 50 distinct IDs. [required]\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get message\" {\n flag \"--message-id <message_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"delete\" help=\"Delete message\" {\n flag \"--message-id <message_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Reorder message variants\" {\n flag \"--message-id <message_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--variant-order <variant_order...>\" help=\"Every variant ID of the message, each exactly once, in the new order. [required]\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"create\" help=\"Create message\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--variants <variants>\" help=\"The variants, in stored order. They are alternatives: the runtime says one of them each time. The first variant cannot carry a condition. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"add-variant\" help=\"Add message variant\" {\n alias \"av\"\n flag \"--message-id <message_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--text <text>\" help=\"Message text shown to the end user. Limited markdown: **bold**, _italic_, <u>underline</u>, ~~strikethrough~~, [label](url). {variable_name} inserts a variable or entity, {variable_name.path} a field of a variable. Escape a literal { or \\\\ with a backslash. A name matching neither is stored as literal text and reported in unresolvedReferences; secrets are not available here. [required]\"\n flag \"--delay <delay>\" help=\"Milliseconds to wait before this variant is sent.\"\n flag \"--condition <condition>\" help=\"{ type: string, matchAll: boolean, assertions: object[] } | { type: string, code: string }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"update-variant\" help=\"Update message variant\" {\n alias \"uv\"\n flag \"--message-id <message_id>\" help=\"[required]\"\n flag \"--variant-id <variant_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--text <text>\" help=\"string value\"\n flag \"--delay <delay>\" help=\"Milliseconds to wait before this variant is sent. null removes the delay.\"\n flag \"--condition <condition>\" help=\"{ type: string, matchAll: boolean, assertions: object[] } | { type: string, code: string }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete-variant\" help=\"Delete message variant\" {\n alias \"dv\"\n flag \"--message-id <message_id>\" help=\"[required]\"\n flag \"--variant-id <variant_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n}\ncmd \"prompt\" help=\"Manage reusable prompts and their settings\" {\n cmd \"get-many\" help=\"Get many prompts\" {\n alias \"gm\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--ids <ids...>\" help=\"Prompt IDs to read. Duplicates are ignored; at most 50 distinct IDs. [required]\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get prompt\" {\n flag \"--prompt-id <prompt_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update prompt\" {\n flag \"--prompt-id <prompt_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"string value\"\n flag \"--system <system>\" help=\"string value\"\n flag \"--settings <settings>\" help=\"JSON object\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete prompt\" {\n flag \"--prompt-id <prompt_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create prompt\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"Defaults to \\\"Untitled prompt\\\", as the editor names one.\"\n flag \"--system <system>\" help=\"Plain text; markdown is not interpreted. {variable_name} inserts a variable or entity, {variable_name.path} a field of a variable. Escape a literal { or \\\\ with a backslash. A name matching neither is stored as literal text and reported in unresolvedReferences; secrets are not available here. [required]\"\n flag \"--settings <settings>\" help=\"JSON object\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"update-settings\" help=\"Update prompt settings\" {\n alias \"us\"\n flag \"--prompt-id <prompt_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--model <model>\" help=\"options: gpt-3.5-turbo-1106, gpt-3.5-turbo, gpt-4, gpt-4o, gpt-4o-mini, gpt-4.1-2025-04-14, gpt-4.1-mini-2025-04-14, gpt-4.1-nano-2025-04-14, gpt-o3-mini, o3-2025-04-16, o4-mini-2025-04-16, gpt-5, gpt-5-mini, gpt-5-nano, gpt-5.2, gpt-5.4, gpt-5.4-mini, gpt-5.5, gpt-5.6-sol, gpt-5.6-terra, gpt-5.6-luna, gpt-6-sol, gpt-6-luna, gpt-6.1-sol, gpt-realtime, gpt-live-1, claude-4-opus, claude-4-sonnet, claude-4.5-sonnet, claude-4.6-sonnet, claude-4.5-haiku, claude-4.5-opus, claude-4.7-opus, bedrock-claude-4-sonnet, bedrock-claude-4.5-sonnet, bedrock-claude-4.6-sonnet, bedrock-claude-5-sonnet, bedrock-claude-5.5-sonnet, bedrock-claude-4.5-haiku, bedrock-claude-5.5-haiku, bedrock-claude-4.5-opus, bedrock-claude-4.7-opus, bedrock-claude-4.8-opus, voiceflow-core-4.0, voiceflow-core-4.1, voiceflow-core-4.2, voiceflow-flash-4.2, gemini-2.5-pro, gemini-2.5-flash, gemini-live-2.5-flash, gemini-3-flash, gemini-3.5-flash, gemini-3.1-pro, gpt-oss-20b, gpt-oss-120b, llama-guard-4, llama-3.1-instant, llama-3.3-versatile, qwen3.6-27b, grok-4.6, voiceflow-flash-4.1, kimi-k3, gemini-flash-2, gpt-4-turbo, claude-3.5-haiku, claude-3-opus, claude-3.7-sonnet, claude-v2, llama-3.2-1b-preview, gemini-pro-1.5, claude-3-haiku, claude-3-sonnet, text-davinci-003, claude-v1, claude-instant-v1, deep-seek-r1-distill-llama-70B, claude-3.5-sonnet\"\n flag \"--max-tokens <max_tokens>\" help=\"number value\"\n flag \"--temperature <temperature>\" help=\"number value\"\n flag \"--response-format <response_format>\" help=\"string value\"\n flag \"--reasoning-effort <reasoning_effort>\" help=\"options: off, adaptive, minimal, low, medium, high\"\n flag \"--service-tier <service_tier>\" help=\"options: default, flex, priority\"\n flag \"--use-structured-output\" help=\"boolean flag\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n}\ncmd \"variable\" help=\"Manage the variables an agent reads and sets\" {\n cmd \"list\" help=\"List variables\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create variable\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the variable. Letters, digits and underscores only, at most 64 characters — this is what a {token} in a text field binds to. Must not already be used by a variable or an entity in this environment. When updating, omit this field unless you are renaming: a variable stored before this rule can hold a name outside the grammar, and echoing that name back would be rejected. [required]\"\n flag \"--color-param <color_param>\" help=\"The display color of the variable in the Voiceflow editor, as a hex code from the editor's color picker. Use #515A63 (the editor's default) unless the user asks for a color; otherwise pick the closest of #5B9FD7, #CB627B, #56B365, #DC8879, #9A63BC. Do not invent other hex codes. [required]\"\n flag \"--description <description>\" help=\"A short description of what the variable stores.\"\n flag \"--default-value <default_value>\" help=\"The initial value of the variable at the start of a conversation.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get variable\" {\n flag \"--variable-id <variable_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update variable\" {\n flag \"--variable-id <variable_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the variable. Letters, digits and underscores only, at most 64 characters — this is what a {token} in a text field binds to. Must not already be used by a variable or an entity in this environment. When updating, omit this field unless you are renaming: a variable stored before this rule can hold a name outside the grammar, and echoing that name back would be rejected.\"\n flag \"--color-param <color_param>\" help=\"The display color of the variable in the Voiceflow editor, as a hex code from the editor's color picker. Use #515A63 (the editor's default) unless the user asks for a color; otherwise pick the closest of #5B9FD7, #CB627B, #56B365, #DC8879, #9A63BC. Do not invent other hex codes.\"\n flag \"--description <description>\" help=\"A short description of what the variable stores.\"\n flag \"--default-value <default_value>\" help=\"The initial value of the variable at the start of a conversation.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete variable\" {\n flag \"--variable-id <variable_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n}\ncmd \"api-tool\" help=\"Manage API tools: HTTP requests the agent can make\" {\n alias \"at\"\n cmd \"list\" help=\"List API tools\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create API tool\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--url <url>\" help=\"string value\"\n flag \"--name <name>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ type: string, contentType: string, content: string } | { type: string, formData: object[] } | { type: string, params: object[] }\"\n flag \"--settings <settings>\" help=\"JSON object\"\n flag \"--http-method <http_method>\" help=\"options: get, put, post, patch, delete [required]\"\n flag \"--description <description>\" help=\"A description of what the API tool does, used by the agent to decide when to call it.\"\n flag \"--headers <headers>\" help=\"list of values\"\n flag \"--query-parameters <query_parameters>\" help=\"list of values\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get API tool\" {\n flag \"--tool-id <tool_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update API tool\" {\n flag \"--tool-id <tool_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--url <url>\" help=\"string value\"\n flag \"--name <name>\" help=\"string value\"\n flag \"--body-param <body_param>\" help=\"{ type: string, contentType: string, content: string } | { type: string, formData: object[] } | { type: string, params: object[] }\"\n flag \"--headers <headers>\" help=\"list of values\"\n flag \"--settings <settings>\" help=\"JSON object\"\n flag \"--http-method <http_method>\" help=\"options: get, put, post, patch, delete\"\n flag \"--description <description>\" help=\"A description of what the API tool does, used by the agent to decide when to call it.\"\n flag \"--query-parameters <query_parameters>\" help=\"list of values\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete API tool\" {\n flag \"--tool-id <tool_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"get-schema\" help=\"Get API tool schema\" {\n alias \"gs\"\n flag \"--tool-id <tool_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"execute\" help=\"Execute API tool\" {\n flag \"--tool-id <tool_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--inputs <inputs>\" help=\"A value for each of the API tool's input variables, keyed by input name. Each value replaces the tool's {input_name} placeholder in the URL, headers, query and body. Every declared input needs a value, and a name the tool does not declare is refused. List them with get_schema.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"variable\" help=\"Manage an API tool's variables\" {\n cmd \"list\" help=\"List variables\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--api-tool-id <api_tool_id>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create variable\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the variable, referenced within the API tool request as {name}. Letters, digits and underscores only, at most 64 characters. [required]\"\n flag \"--api-tool-id <api_tool_id>\" help=\"The ID of the API tool this variable belongs to. [required]\"\n flag \"--description <description>\" help=\"A description of the variable, used by the agent to determine what value to provide.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get variable\" {\n flag \"--variable-id <variable_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update variable\" {\n flag \"--variable-id <variable_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the variable, referenced within the API tool request as {name}. Letters, digits and underscores only, at most 64 characters.\"\n flag \"--description <description>\" help=\"A description of the variable, used by the agent to determine what value to provide.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete variable\" {\n flag \"--variable-id <variable_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n }\n}\ncmd \"transcript\" help=\"Search and read conversation transcripts\" {\n cmd \"search\" help=\"Search transcripts\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--take <take>\" help=\"Page size, 1 to 50. There is no `limit`. Page with `skip` while `hasMore` is true.\" default=20\n flag \"--skip <skip>\" help=\"The number of results to skip, used for pagination.\" default=0\n flag \"--start-date <start_date>\" help=\"Only transcripts created at or after this day (`2026-06-01`, from 00:00 UTC) or ISO 8601 timestamp.\"\n flag \"--end-date <end_date>\" help=\"Only transcripts created at or before this day (`2026-06-30`, to 23:59:59.999 UTC) or ISO 8601 timestamp.\"\n flag \"--version-param <version_param>\" help=\"When provided, only transcripts from the draft or published version of the environment are returned. `published` covers the current release and every past release. Applies within a single environment; the main environment is used when `environmentAlias` is omitted. (options: draft, published)\"\n flag \"--filters <filters>\" help=\"list of values\"\n flag \"--session-id <session_id>\" help=\"When provided, only transcripts from this conversation session are returned.\"\n flag \"--environment-alias <environment_alias>\" help=\"When provided, only transcripts from the environment with this alias are returned.\"\n flag \"--release-name <release_name>\" help=\"When provided, only transcripts from the release with this exact name (e.g. `V1.02`) are returned, as listed in the `releases` of the environment. When several releases share the name, transcripts from all of them are returned. Applies within a single environment; the main environment is used when `environmentAlias` is omitted. Cannot be combined with `version: \\\"draft\\\"`.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"grep\" help=\"Grep transcripts\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--pattern <pattern>\" help=\"Regex (case-insensitive) or plain text to find in the dialogue. A pattern may hold one open quantifier (*, +, ?, {n,} or {n,m}), no backreference and no alternation inside a group. Use exact counts such as \\\\d{3}, or put the alternation at the top level: refund|return. Any other pattern runs as plain text, and the result says so. [required]\"\n flag \"--transcript-ids <transcript_ids...>\" help=\"Transcripts to scan. Leave it out to scan the newest transcripts in the date range.\" var=#true\n flag \"--start-date <start_date>\" help=\"Lower bound when no transcriptIDs are given: a day or a timestamp.\"\n flag \"--end-date <end_date>\" help=\"Upper bound when no transcriptIDs are given: a day or a timestamp.\"\n flag \"--environment-alias <environment_alias>\" help=\"Only transcripts from this environment, when no transcriptIDs are given.\"\n flag \"--limit <limit>\" help=\"How many transcripts to scan at most, 1 to 60.\" default=25\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get transcript\" {\n flag \"--transcript-id <transcript_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--format-param <format_param>\" help=\"`summary` (default): the turns, the tool calls and a turn count. `formatted`: every turn with the debug traces and the first system prompt of each agent. `logs`: the raw log entries, which can be very large. (options: summary, formatted, logs)\" default=\"summary\"\n flag \"--filter-conversation\" help=\"boolean flag\"\n flag \"--custom-trace-types <custom_trace_types>\" help=\"string | array of string\"\n }\n cmd \"files\" help=\"List transcript files\" {\n flag \"--transcript-id <transcript_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"query-logs\" help=\"Query transcript logs\" {\n alias \"ql\"\n flag \"--transcript-id <transcript_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--kinds <kinds...>\" help=\"Keep only entries of these kinds. Omit to keep every kind.\" var=#true\n flag \"--levels <levels...>\" help=\"Keep only entries at these levels, for example [\\\"fatal\\\", \\\"error\\\", \\\"warn\\\"] for what went wrong.\" var=#true\n flag \"--debug-kinds <debug_kinds...>\" help=\"Keep only debug entries of these kinds. Setting it leaves out every entry that is not a debug log.\" var=#true\n flag \"--turns <turns>\" help=\"Keep only entries of these turns. Turn 0 holds anything logged before the first input.\"\n flag \"--search <search>\" help=\"Keep only entries whose message or recorded data contains this text, ignoring case. It is plain text, not a regular expression. Separate alternatives with |, as in \\\"timeout|denied\\\", to keep entries that contain any of them.\"\n flag \"--detail <detail>\" help=\"options: summary, full\" default=\"summary\"\n flag \"--limit <limit>\" help=\"The most entries to return in one page.\" default=50\n flag \"--offset <offset>\" help=\"How many matching entries to skip, for paging.\" default=0\n flag \"--order <order>\" help=\"options: asc, desc\" default=\"asc\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"property\" help=\"Manage the properties that tag transcripts\" {\n cmd \"list\" help=\"List properties\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create property\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--name <name>\" help=\"[required]\"\n flag \"--type <type>\" help=\"The type of value the property holds. (options: boolean, number, string) [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get property\" {\n flag \"--property-id <property_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update property\" {\n flag \"--property-id <property_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--name <name>\" help=\"string value\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete property\" {\n flag \"--property-id <property_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"set-value\" help=\"Set property value\" {\n alias \"sv\"\n flag \"--property-id <property_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--value <value>\" help=\"The value to set for the property on the transcript. [required]\"\n flag \"--transcript-id <transcript_id>\" help=\"The ID of the transcript to set the property value on. [required]\"\n flag \"--metadata <metadata>\" help=\"Additional structured data to record alongside the value. Omit or pass `null` to record none.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n }\n}\ncmd \"function\" help=\"Write, run and manage functions\" {\n cmd \"list\" help=\"List functions\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create function\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"[required]\"\n flag \"--code <code>\" help=\"The JavaScript source code executed when the function runs. [required]\"\n flag \"--settings <settings>\" help=\"JSON object\"\n flag \"--description <description>\" help=\"A human-readable description of what the function does.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get function\" {\n flag \"--function-id <function_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update function\" {\n flag \"--function-id <function_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"string value\"\n flag \"--code <code>\" help=\"The JavaScript source code executed when the function runs.\"\n flag \"--settings <settings>\" help=\"JSON object\"\n flag \"--path-order <path_order...>\" help=\"An ordered list of path IDs controlling the display order of the function's exit paths.\" var=#true\n flag \"--description <description>\" help=\"A human-readable description of what the function does.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete function\" {\n flag \"--function-id <function_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"patch-code\" help=\"Patch function code\" {\n alias \"pc\"\n flag \"--function-id <function_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--old-string <old_string>\" help=\"The exact code to replace, copied verbatim from the function's code as a get returned it. Matching is literal: whitespace, indentation, quotes and case must match. Include enough neighbouring code that it occurs once. [required]\"\n flag \"--new-string <new_string>\" help=\"The code to put in its place. May be empty to delete. [required]\"\n flag \"--replace-all\" help=\"Replace every occurrence. When false, more than one match is an error rather than a guess.\" default=#false\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get-schema\" help=\"Get function schema\" {\n alias \"gs\"\n flag \"--function-id <function_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"execute\" help=\"Execute function\" {\n flag \"--function-id <function_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--inputs <inputs>\" help=\"A value for each of the function's input variables, keyed by input name. Every declared input needs a value, and a name the function does not declare is refused. List them with get_schema.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"check\" help=\"Check function\" {\n flag \"--function-id <function_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--cases <cases>\" help=\"[required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"variable\" help=\"Manage a function's variables\" {\n cmd \"list\" help=\"List variables\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--function-id <function_id>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create variable\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name used to reference the variable in the function code. [required]\"\n flag \"--type <type>\" help=\"options: input, output [required]\"\n flag \"--function-id <function_id>\" help=\"The ID of the function this variable belongs to. [required]\"\n flag \"--description <description>\" help=\"A human-readable description of what the variable holds.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get variable\" {\n flag \"--variable-id <variable_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update variable\" {\n flag \"--variable-id <variable_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name used to reference the variable in the function code.\"\n flag \"--description <description>\" help=\"A human-readable description of what the variable holds.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete variable\" {\n flag \"--variable-id <variable_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n }\n cmd \"path\" help=\"Manage a function's paths\" {\n cmd \"list\" help=\"List paths\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--function-id <function_id>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create path\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the exit path, referenced by the function code when returning which path to take. [required]\"\n flag \"--function-id <function_id>\" help=\"The ID of the function this path belongs to. [required]\"\n flag \"--label <label>\" help=\"The display label shown for this path in the Voiceflow UI; falls back to `name` when null.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get path\" {\n flag \"--path-id <path_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update path\" {\n flag \"--path-id <path_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the exit path, referenced by the function code when returning which path to take.\"\n flag \"--label <label>\" help=\"The display label shown for this path in the Voiceflow UI; falls back to `name` when null.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete path\" {\n flag \"--path-id <path_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n }\n}\ncmd \"evaluation\" help=\"Create and run evaluations that score transcripts\" {\n cmd \"list\" help=\"List evaluations\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create evaluation\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ type: string, truePrompt: string, falsePrompt: string, name: string, ... } | { type: string, minimumValue: number, maximumValue: number, minimumPrompt: string, ... } | { type: string, name: string, prompt: string, enabled: boolean, ... } | { type: string, options: object[], name: string, prompt: string, ... }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get evaluation\" {\n flag \"--evaluation-id <evaluation_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update evaluation\" {\n flag \"--evaluation-id <evaluation_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ truePrompt: string, falsePrompt: string, name: string, prompt: string, ... } | { minimumValue: number, maximumValue: number, minimumPrompt: string, maximumPrompt: string, ... } | { name: string, prompt: string, enabled: boolean, settings: object, ... } | { options: object[], name: string, prompt: string, enabled: boolean, ... }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete evaluation\" {\n flag \"--evaluation-id <evaluation_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"run\" help=\"Run evaluation\" {\n flag \"--evaluation-id <evaluation_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--transcript-id <transcript_id>\" help=\"The ID of the transcript to run the evaluation against. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"queue-runs\" help=\"Queue evaluation runs\" {\n alias \"qr\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--evaluation-ids <evaluation_ids...>\" help=\"The evaluations to run, 1 to 10. Every evaluation runs against every transcript. [required]\" var=#true\n flag \"--transcript-ids <transcript_ids...>\" help=\"The transcripts to score, 1 to 100. [required]\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n}\ncmd \"document\" help=\"Manage knowledge base documents and sitemaps\" {\n cmd \"list\" help=\"List documents\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--sitemap-document-id <sitemap_document_id>\" help=\"string value\"\n }\n cmd \"list-changes\" help=\"List document changes\" {\n alias \"lc\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--from <from>\" help=\"[required]\"\n flag \"--to <to>\" help=\"[required]\"\n flag \"--sitemap-document-id <sitemap_document_id>\" help=\"string value\"\n flag \"--type <type>\" help=\"options: added, updated, removed\"\n flag \"--cursor <cursor>\" help=\"string value\"\n flag \"--limit <limit>\" help=\"integer value\"\n }\n cmd \"create-url\" help=\"Create URL document\" {\n alias \"cu\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--max-chunk-size <max_chunk_size>\" help=\"string | number\"\n flag \"--overwrite <overwrite>\" help=\"boolean | StableDocumentController_createURL_overwrite_enum\"\n flag \"--markdown-conversion <markdown_conversion>\" help=\"boolean | StableDocumentController_createURL_markdownConversion_enum\"\n flag \"--llm-based-chunks <llm_based_chunks>\" help=\"boolean | StableDocumentController_createURL_llmBasedChunks_enum\"\n flag \"--llm-generated-q <llm_generated_q>\" help=\"boolean | StableDocumentController_createURL_llmGeneratedQ_enum\"\n flag \"--llm-content-summarization <llm_content_summarization>\" help=\"boolean | StableDocumentController_createURL_llmContentSummarization_enum\"\n flag \"--llm-prepend-context <llm_prepend_context>\" help=\"boolean | StableDocumentController_createURL_llmPrependContext_enum\"\n flag \"--single-chunk <single_chunk>\" help=\"boolean | StableDocumentController_createURL_singleChunk_enum\"\n flag \"--url <url>\" help=\"The URL of the web page to crawl and ingest into the knowledge base. [required]\"\n flag \"--metadata <metadata>\" help=\"Metadata tags attached to the document, used to filter knowledge base retrieval at runtime.\"\n flag \"--refresh-rate <refresh_rate>\" help=\"How often the URL is automatically re-crawled to refresh the document content. (options: daily, weekly, monthly, never)\"\n flag \"--folder-id <folder_id>\" help=\"The ID of the Knowledge Base folder to file the document under. Without it, a new document starts at the top level and a document this overwrites keeps its folder; move one to the top level with `folderID: null` on the document update. File names and URLs are unique across the whole Knowledge Base, not per folder, so an overwrite replaces the one document with that name or URL and, with `folderID`, moves it into this folder.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"create-text\" help=\"Create text document\" {\n alias \"cte\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--max-chunk-size <max_chunk_size>\" help=\"string | number\"\n flag \"--overwrite <overwrite>\" help=\"boolean | StableDocumentController_createText_overwrite_enum\"\n flag \"--markdown-conversion <markdown_conversion>\" help=\"boolean | StableDocumentController_createText_markdownConversion_enum\"\n flag \"--llm-based-chunks <llm_based_chunks>\" help=\"boolean | StableDocumentController_createText_llmBasedChunks_enum\"\n flag \"--llm-generated-q <llm_generated_q>\" help=\"boolean | StableDocumentController_createText_llmGeneratedQ_enum\"\n flag \"--llm-content-summarization <llm_content_summarization>\" help=\"boolean | StableDocumentController_createText_llmContentSummarization_enum\"\n flag \"--llm-prepend-context <llm_prepend_context>\" help=\"boolean | StableDocumentController_createText_llmPrependContext_enum\"\n flag \"--single-chunk <single_chunk>\" help=\"boolean | StableDocumentController_createText_singleChunk_enum\"\n flag \"--url <url>\" help=\"An optional source URL to associate with the uploaded document.\"\n flag \"--can-edit\" help=\"If true, the document content can be edited in the Creator after upload.\" default=#false\n flag \"--metadata <metadata>\" help=\"A JSON-encoded array of `{ key, values }` metadata tags attached to the document, used to filter knowledge base retrieval at runtime.\"\n flag \"--folder-id <folder_id>\" help=\"The ID of the Knowledge Base folder to file the document under. Without it, a new document starts at the top level and a document this overwrites keeps its folder; move one to the top level with `folderID: null` on the document update. File names and URLs are unique across the whole Knowledge Base, not per folder, so an overwrite replaces the one document with that name or URL and, with `folderID`, moves it into this folder.\"\n flag \"--file <file>\" help=\"Path to file to upload\"\n }\n cmd \"create-table\" help=\"Create table document\" {\n alias \"ct\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--max-chunk-size <max_chunk_size>\" help=\"string | number\"\n flag \"--overwrite <overwrite>\" help=\"boolean | StableDocumentController_createTable_overwrite_enum\"\n flag \"--markdown-conversion <markdown_conversion>\" help=\"boolean | StableDocumentController_createTable_markdownConversion_enum\"\n flag \"--llm-based-chunks <llm_based_chunks>\" help=\"boolean | StableDocumentController_createTable_llmBasedChunks_enum\"\n flag \"--llm-generated-q <llm_generated_q>\" help=\"boolean | StableDocumentController_createTable_llmGeneratedQ_enum\"\n flag \"--llm-content-summarization <llm_content_summarization>\" help=\"boolean | StableDocumentController_createTable_llmContentSummarization_enum\"\n flag \"--llm-prepend-context <llm_prepend_context>\" help=\"boolean | StableDocumentController_createTable_llmPrependContext_enum\"\n flag \"--single-chunk <single_chunk>\" help=\"boolean | StableDocumentController_createTable_singleChunk_enum\"\n flag \"--url <url>\" help=\"An optional source URL to associate with the table document.\"\n flag \"--name <name>\" help=\"[required]\"\n flag \"--items <items>\" help=\"The table rows to ingest; each row is a flat object and becomes its own chunk. [required]\"\n flag \"--schema <schema>\" help=\"Declares which top-level keys of each row are full-text searchable versus row-level metadata. [required]\"\n flag \"--metadata <metadata>\" help=\"Metadata tags attached to the document, used to filter knowledge base retrieval at runtime.\"\n flag \"--folder-id <folder_id>\" help=\"The ID of the Knowledge Base folder to file the document under. Without it, a new document starts at the top level and a document this overwrites keeps its folder; move one to the top level with `folderID: null` on the document update. File names and URLs are unique across the whole Knowledge Base, not per folder, so an overwrite replaces the one document with that name or URL and, with `folderID`, moves it into this folder.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"preview-sitemap\" help=\"Preview sitemap URLs\" {\n alias \"ps\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--sitemap-url <sitemap_url>\" help=\"The HTTPS URL of the sitemap to read. A bare site URL works too — when it does not end in `.xml`, `/sitemap.xml`, `/sitemap_index.xml` and `/sitemap/sitemap.xml` are probed in turn. [required]\"\n flag \"--exclude <exclude...>\" help=\"Patterns that drop a URL from the import when any one of them matches. Matching is case-insensitive and unanchored: a pattern with no `*` matches any URL containing it as a substring (`/blog/`), while `*` matches any run of characters (`*/tag/*`, `*.pdf`).\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"create-sitemap\" help=\"Create documents from sitemap\" {\n alias \"cs\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--markdown-conversion <markdown_conversion>\" help=\"boolean | StableDocumentController_createSitemap_markdownConversion_enum\"\n flag \"--llm-based-chunks <llm_based_chunks>\" help=\"boolean | StableDocumentController_createSitemap_llmBasedChunks_enum\"\n flag \"--llm-generated-q <llm_generated_q>\" help=\"boolean | StableDocumentController_createSitemap_llmGeneratedQ_enum\"\n flag \"--llm-content-summarization <llm_content_summarization>\" help=\"boolean | StableDocumentController_createSitemap_llmContentSummarization_enum\"\n flag \"--llm-prepend-context <llm_prepend_context>\" help=\"boolean | StableDocumentController_createSitemap_llmPrependContext_enum\"\n flag \"--single-chunk <single_chunk>\" help=\"boolean | StableDocumentController_createSitemap_singleChunk_enum\"\n flag \"--sitemap-url <sitemap_url>\" help=\"The HTTPS URL of the sitemap to read. A bare site URL works too — when it does not end in `.xml`, `/sitemap.xml`, `/sitemap_index.xml` and `/sitemap/sitemap.xml` are probed in turn. [required]\"\n flag \"--exclude <exclude...>\" help=\"Patterns that drop a URL from the import when any one of them matches. Matching is case-insensitive and unanchored: a pattern with no `*` matches any URL containing it as a substring (`/blog/`), while `*` matches any run of characters (`*/tag/*`, `*.pdf`).\" var=#true\n flag \"--metadata <metadata>\" help=\"Metadata tags attached to the document, used to filter knowledge base retrieval at runtime.\"\n flag \"--refresh-rate <refresh_rate>\" help=\"How often the URL is automatically re-crawled to refresh the document content. (options: daily, weekly, monthly, never)\" default=\"never\"\n flag \"--folder-id <folder_id>\" help=\"The ID of the Knowledge Base folder to file every document the import creates or reuses under. Without it, new documents start at the top level and reused ones keep their folder.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"create-managed-sitemap\" help=\"Create managed sitemap\" {\n alias \"cms\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--markdown-conversion <markdown_conversion>\" help=\"boolean | StableDocumentController_createManagedSitemap_markdownConversion_enum\"\n flag \"--llm-based-chunks <llm_based_chunks>\" help=\"boolean | StableDocumentController_createManagedSitemap_llmBasedChunks_enum\"\n flag \"--llm-generated-q <llm_generated_q>\" help=\"boolean | StableDocumentController_createManagedSitemap_llmGeneratedQ_enum\"\n flag \"--llm-content-summarization <llm_content_summarization>\" help=\"boolean | StableDocumentController_createManagedSitemap_llmContentSummarization_enum\"\n flag \"--llm-prepend-context <llm_prepend_context>\" help=\"boolean | StableDocumentController_createManagedSitemap_llmPrependContext_enum\"\n flag \"--single-chunk <single_chunk>\" help=\"boolean | StableDocumentController_createManagedSitemap_singleChunk_enum\"\n flag \"--sitemap-url <sitemap_url>\" help=\"The HTTPS URL of the sitemap to read. A bare site URL works too — when it does not end in `.xml`, `/sitemap.xml`, `/sitemap_index.xml` and `/sitemap/sitemap.xml` are probed in turn. [required]\"\n flag \"--patterns <patterns>\" help=\"Which of the pages the sitemap lists it keeps. Matching is case-insensitive and unanchored: a pattern with no `*` matches any URL containing it as a substring (`/blog/`), while `*` matches any run of characters (`*/tag/*`, `*.pdf`).\"\n flag \"--refresh-rate <refresh_rate>\" help=\"How often the sitemap is re-read to add the pages it newly lists and remove the ones it no longer does. Its pages are re-crawled on the same schedule. (options: daily, weekly, monthly, never)\" default=\"never\"\n flag \"--metadata <metadata>\" help=\"Metadata tags attached to the sitemap and to every page it imports, used to filter knowledge base retrieval at runtime.\"\n flag \"--folder-id <folder_id>\" help=\"The ID of the Knowledge Base folder to file the sitemap and the pages it imports under. Omit to create them at the top level.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"update-managed-sitemap\" help=\"Update managed sitemap\" {\n alias \"ums\"\n flag \"--document-id <document_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--patterns <patterns>\" help=\"Replaces the stored patterns whole, so send both lists even when changing one. Matching is case-insensitive and unanchored: a pattern with no `*` matches any URL containing it as a substring (`/blog/`), while `*` matches any run of characters (`*/tag/*`, `*.pdf`).\"\n flag \"--refresh-rate <refresh_rate>\" help=\"How often the sitemap is re-read to add the pages it newly lists and remove the ones it no longer does. Its pages are re-crawled on the same schedule. Also applied to the pages it has already imported. (options: daily, weekly, monthly, never)\"\n flag \"--markdown-conversion <markdown_conversion>\" help=\"boolean | StableDocumentUpdateManagedSitemapRequest_markdownConversion_enum\"\n flag \"--llm-based-chunks <llm_based_chunks>\" help=\"boolean | StableDocumentUpdateManagedSitemapRequest_llmBasedChunks_enum\"\n flag \"--llm-generated-q <llm_generated_q>\" help=\"boolean | StableDocumentUpdateManagedSitemapRequest_llmGeneratedQ_enum\"\n flag \"--llm-content-summarization <llm_content_summarization>\" help=\"boolean | StableDocumentUpdateManagedSitemapRequest_llmContentSummarization_enum\"\n flag \"--llm-prepend-context <llm_prepend_context>\" help=\"boolean | StableDocumentUpdateManagedSitemapRequest_llmPrependContext_enum\"\n flag \"--single-chunk <single_chunk>\" help=\"boolean | StableDocumentUpdateManagedSitemapRequest_singleChunk_enum\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get document\" {\n flag \"--document-id <document_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"delete\" help=\"Delete document\" {\n flag \"--document-id <document_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update document\" {\n flag \"--document-id <document_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--metadata <metadata>\" help=\"Replaces the document's metadata tags. Leave it out to keep them.\"\n flag \"--folder-id <folder_id>\" help=\"The ID of the Knowledge Base folder to move the document into, or null to move it to the top level. Leave it out to keep its folder.\"\n flag \"--content <content>\" help=\"The whole new text of a text or markdown document. It replaces the stored text; the document keeps its ID and name and is processed again. Refused for every other document type.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"folder\" help=\"Organize knowledge base documents into folders\" {\n cmd \"list\" help=\"List document folders\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create document folder\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the folder. [required]\"\n flag \"--parent-id <parent_id>\" help=\"The ID of the folder to nest this folder in. Omit or pass null for a top-level folder.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"update\" help=\"Update document folder\" {\n flag \"--folder-id <folder_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the folder.\"\n flag \"--parent-id <parent_id>\" help=\"The ID of the folder to move this folder into, or null to move it to the top level. Omit it to keep the folder where it is.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete document folder\" {\n flag \"--folder-id <folder_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n }\n}\ncmd \"integration\" help=\"Connect integrations and use their tools\" {\n cmd \"list\" help=\"List integrations\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"connect\" help=\"Connect integration\" {\n flag \"--integration <integration>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ integration: string, credentials: string } | { integration: string, credentials: object } | { integration: string }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"disconnect\" help=\"Disconnect integration\" {\n flag \"--integration <integration>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"get-schema\" help=\"Get integration tool schemas\" {\n alias \"gs\"\n flag \"--integration <integration>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"add-tool\" help=\"Add integration tool\" {\n alias \"at\"\n flag \"--integration <integration>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--tool-name <tool_name>\" help=\"The catalog tool to add, as get_schema lists it, such as `google_sheets_update_spreadsheet`. It must belong to the integration in the path. (options: example_dynamic_schema, zendesk_find_user, zendesk_find_group, zendesk_find_ticket, zendesk_create_ticket, zendesk_update_ticket, zendesk_add_ticket_comment, zendesk_update_organization, zendesk_find_latest_comment, salesforce_create_lead, salesforce_update_lead, salesforce_create_contact, salesforce_update_contact, salesforce_create_case, salesforce_update_case, salesforce_add_comment_to_case, shopify_get_products, shopify_get_order, shopify_cancel_order, shopify_update_order, google_sheets_create_spreadsheet, google_sheets_update_spreadsheet, google_sheets_read_spreadsheet, google_sheets_append_spreadsheet, google_sheets_read_row, google_gmail_send_email, airtable_create_records, airtable_delete_records, airtable_get_record, airtable_list_records, airtable_update_records, make_run_scenario, twilio_send_sms, hubspot_create_contact, hubspot_create_lead, hubspot_create_ticket, kustomer_find_customer, kustomer_create_customer, kustomer_update_customer, kustomer_find_conversation, kustomer_find_customer_conversations, kustomer_create_conversation, kustomer_update_conversation, kustomer_add_conversation_note, kustomer_add_conversation_tags, kustomer_find_latest_message, kustomer_find_team, kustomer_update_company) [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"execute\" help=\"Execute integration tool\" {\n flag \"--integration <integration>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--tool-name <tool_name>\" help=\"The catalog tool to run, as get_schema lists it, such as `zendesk_find_ticket`. It must belong to the integration in the path. (options: example_dynamic_schema, zendesk_find_user, zendesk_find_group, zendesk_find_ticket, zendesk_create_ticket, zendesk_update_ticket, zendesk_add_ticket_comment, zendesk_update_organization, zendesk_find_latest_comment, salesforce_create_lead, salesforce_update_lead, salesforce_create_contact, salesforce_update_contact, salesforce_create_case, salesforce_update_case, salesforce_add_comment_to_case, shopify_get_products, shopify_get_order, shopify_cancel_order, shopify_update_order, google_sheets_create_spreadsheet, google_sheets_update_spreadsheet, google_sheets_read_spreadsheet, google_sheets_append_spreadsheet, google_sheets_read_row, google_gmail_send_email, airtable_create_records, airtable_delete_records, airtable_get_record, airtable_list_records, airtable_update_records, make_run_scenario, twilio_send_sms, hubspot_create_contact, hubspot_create_lead, hubspot_create_ticket, kustomer_find_customer, kustomer_create_customer, kustomer_update_customer, kustomer_find_conversation, kustomer_find_customer_conversations, kustomer_create_conversation, kustomer_update_conversation, kustomer_add_conversation_note, kustomer_add_conversation_tags, kustomer_find_latest_message, kustomer_find_team, kustomer_update_company) [required]\"\n flag \"--inputs <inputs>\" help=\"The tool's inputs, keyed by input name and typed as get_schema says. A top-level string value follows the ExecuteInputString rules, so {secret_name} inserts a project secret. Secrets work only at the top level: inside a nested object or array, {secret_name} is sent as written and no secret is filled in.\"\n flag \"--extended-input-variables <extended_input_variables>\" help=\"Provider metadata the tool editor stored for this tool, such as Zendesk custom field IDs. Omit it unless you are replaying an editor run.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n}\ncmd \"mcp-server\" help=\"Manage the MCP servers an agent connects to\" {\n alias \"ms\"\n cmd \"list\" help=\"List MCP servers\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create MCP server\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"[required]\"\n flag \"--description <description>\" help=\"A human-readable description of what the MCP server provides.\"\n flag \"--url <url>\" help=\"Plain text resolved at runtime and never shown to a model. {variable_name} inserts a variable or entity, {secret_name} a project secret, {variable_name.path} a field of a variable. Escape a literal { or \\\\ with a backslash. When a name is both a variable and a secret, the secret wins. A name matching none is stored as literal text and reported in unresolvedReferences. Where the field is sent to an upstream system, an unresolved placeholder may be sent as literal text; on an MCP server it is re-resolved by name at connect time, so a literal that matches a real secret binds. [required]\"\n flag \"--headers <headers>\" help=\"list of values\"\n flag \"--specification <specification>\" help=\"options: 2025-03-26, 2025-06-18\" default=\"2025-06-18\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get MCP server\" {\n flag \"--server-id <server_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update MCP server\" {\n flag \"--server-id <server_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"string value\"\n flag \"--description <description>\" help=\"A human-readable description of what the MCP server provides.\"\n flag \"--specification <specification>\" help=\"options: 2025-03-26, 2025-06-18\"\n flag \"--url <url>\" help=\"string value\"\n flag \"--headers <headers>\" help=\"list of values\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete MCP server\" {\n flag \"--server-id <server_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"sync\" help=\"Sync MCP server\" {\n flag \"--server-id <server_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n}\ncmd \"mcp-tool\" help=\"List, inspect and run MCP server tools\" {\n alias \"mt\"\n cmd \"list\" help=\"List MCP tools\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--server-id <server_id>\" help=\"string value\"\n }\n cmd \"get\" help=\"Get MCP tool\" {\n flag \"--tool-id <tool_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"get-schema\" help=\"Get MCP tool schema\" {\n alias \"gs\"\n flag \"--tool-id <tool_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"execute\" help=\"Execute MCP tool\" {\n flag \"--tool-id <tool_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--inputs <inputs>\" help=\"The tool's arguments, keyed by argument name and typed as its JSON Schema says; see get_schema. A top-level string value follows the ExecuteInputString rules, so {secret_name} inserts a project secret. Secrets work only at the top level: inside a nested object or array, {secret_name} is sent as written and no secret is filled in.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n}\ncmd \"secret\" help=\"Manage secrets and their values\" {\n cmd \"list\" help=\"List secrets\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create secret\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the secret. Letters, digits and underscores only, at most 64 characters — this is what a {token} in a default-value field binds to. Must be unique within the project. [required]\"\n flag \"--default-value <default_value>\" help=\"The secret's value, written to the `main` environment's published version, the one serving live traffic. It cannot be empty. Omit it to create the secret as a placeholder with no value — a teammate can fill it in later through the Voiceflow UI or CLI.\"\n flag \"--visibility <visibility>\" help=\"Whether the value can be revealed in the Voiceflow UI. `restricted` secrets can never be read back by anyone. (options: restricted, masked)\" default=\"masked\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"list-overrides\" help=\"List secret overrides\" {\n alias \"lo\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"delete\" help=\"Delete secret\" {\n flag \"--secret-id <secret_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"set-value\" help=\"Set secret value\" {\n alias \"sv\"\n flag \"--secret-id <secret_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--value <value>\" help=\"The secret value to store. Write-only — it can never be read back through this API. [required]\"\n flag \"--environment-alias <environment_alias>\" help=\"The alias of the environment to write (e.g. `staging`). Without it the value goes to the `main` environment. Requires `versionVariant`.\"\n flag \"--version-variant <version_variant>\" help=\"Which version of the environment to write: `published`, the version serving live traffic, or `draft`, the one used when testing. Required with `environmentAlias`. Without `environmentAlias` it defaults to `published`, and `draft` writes the `main` environment's draft version; a project with no `main` environment has no draft version, so the request is then handled as if `versionVariant` were omitted. (options: draft, published)\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n}\ncmd \"knowledge-base\" help=\"Query the knowledge base\" {\n alias \"kb\"\n cmd \"query\" help=\"Query knowledge base\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--version-param <version_param>\" help=\"Whether to query the draft or the published version of the knowledge base. (options: draft, published) [required]\"\n flag \"--filters <filters>\" help=\"Metadata filters used to narrow down which document chunks are searched.\"\n flag \"--question <question>\" help=\"The natural-language question to ask the knowledge base. [required]\"\n flag \"--settings <settings>\" help=\"JSON object\"\n flag \"--synthesis\" help=\"Whether to synthesize an answer from the retrieved chunks; when false, only raw chunks are returned.\"\n flag \"--chunk-limit <chunk_limit>\" help=\"The maximum number of document chunks to retrieve.\"\n flag \"--instruction <instruction>\" help=\"An additional instruction applied when synthesizing the answer from the retrieved chunks.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n}\ncmd \"conversation\" help=\"Talk to an agent: send messages, run scripts\" {\n cmd \"send\" help=\"Send\" {\n flag \"--user-id <user_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--action <action>\" help=\"{ type: string, payload: object, diagramID: string, time: number, ... } | { type: string, payload: string, diagramID: string, time: number, ... } | { type: string, diagramID: string, time: number, metadata: object, ... } | { type: string, payload: value, diagramID: string, time: number, ... }\"\n flag \"--version-param <version_param>\" help=\"Whether to run the conversation against the draft or published version of the environment. (options: draft, published) [required]\"\n flag \"--session-id <session_id>\" help=\"The unique ID of the conversation session to continue.\"\n flag \"--config-param <config_param>\" help=\"Options controlling how the response is shaped.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"run-script\" help=\"Run script\" {\n alias \"rs\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--messages <messages>\" help=\"The user messages to send, in order, after the launch. A message is typed text, as a string or { \\\"text\\\": \\\"…\\\" }, or a button press, as { \\\"button\\\": \\\"<label>\\\" }, for a button the reply before offered. The digest shows offered buttons as \\\"[buttons: Yes | No]\\\". [required]\"\n flag \"--variables <variables>\" help=\"Variable values to set before the launch, keyed by variable name, to start as a known caller. Next to messages, not inside launch.\"\n flag \"--version-param <version_param>\" help=\"Whether to talk to the draft or the published version of the environment. Draft unless you pass it. (options: draft, published)\" default=\"draft\"\n flag \"--launch <launch>\" help=\"How the conversation starts; payload is its only field. Leave it out for a plain launch.\"\n flag \"--user-id <user_id>\" help=\"The conversation user ID to run as; the agent reads it as the user_id variable. Use it when the agent expects a caller ID of a known shape, such as a phone number, and make one up: never a real customer's ID. Draft version only. Leave it out to run as a new user each time. A reused ID keeps the variables an earlier conversation with it left.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"state\" help=\"Read and change a user's conversation state\" {\n cmd \"get\" help=\"Get state\" {\n flag \"--user-id <user_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--version-param <version_param>\" help=\"options: draft, published [required]\"\n }\n cmd \"update\" help=\"Update state\" {\n flag \"--user-id <user_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--version-param <version_param>\" help=\"options: draft, published [required]\"\n flag \"--stack <stack>\" help=\"The execution stack for the conversation, from root to innermost frame. [required]\"\n flag \"--storage <storage>\" help=\"Internal runtime storage persisted across turns of the session. [required]\"\n flag \"--variables <variables>\" help=\"The current values of the agent variables for this session. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete state\" {\n flag \"--user-id <user_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--version-param <version_param>\" help=\"options: draft, published [required]\"\n }\n cmd \"update-variables\" help=\"Update variables\" {\n alias \"uv\"\n flag \"--user-id <user_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--version-param <version_param>\" help=\"options: draft, published [required]\"\n flag \"--variables <variables>\" help=\"Variable values to set on the conversation session, keyed by variable name. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n }\n}\ncmd \"credits\" help=\"Check whether a project has credits left to run\" {\n cmd \"get\" help=\"Get credits\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n}\ncmd \"analytics\" help=\"See how agents are used: calls, tokens, tools\" {\n cmd \"query\" help=\"Query calls, token use, and tool and document use\" {\n cmd \"call-count\" help=\"Query call count\" {\n alias \"cc\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--interval <interval>\" help=\"options: hour, day, week, month [required]\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"call-duration\" help=\"Query call duration\" {\n alias \"cd\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--interval <interval>\" help=\"options: hour, day, week, month [required]\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"workspace-transcript-count\" help=\"Query workspace transcript count\" {\n alias \"wtc\"\n flag \"--workspace-id <workspace_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--project-ids <project_ids...>\" help=\"The IDs of the projects to filter results by. Defaults to all projects in the workspace.\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"project-transcript-count\" help=\"Query project transcript count\" {\n alias \"ptco\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--interval <interval>\" help=\"options: hour, day, week, month [required]\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"project-transcript-cost\" help=\"Query transcript cost\" {\n alias \"ptc\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--interval <interval>\" help=\"options: hour, day, week, month [required]\"\n flag \"--usage-class <usage_class>\" help=\"options: Host, Build, Test, Monitor\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"workspace-interaction-count\" help=\"Query workspace interaction count\" {\n alias \"wic\"\n flag \"--workspace-id <workspace_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--project-ids <project_ids...>\" help=\"The IDs of the projects to filter results by. Defaults to all projects in the workspace.\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"project-interaction-count\" help=\"Query project interaction count\" {\n alias \"pic\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--interval <interval>\" help=\"options: hour, day, week, month [required]\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"organization-token-usage\" help=\"Query organization token usage\" {\n alias \"otu\"\n flag \"--organization-id <organization_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--workspace-ids <workspace_ids...>\" help=\"list of values\" var=#true\n flag \"--project-ids <project_ids...>\" help=\"The IDs of the projects to filter results by. Defaults to all projects in the workspace.\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"workspace-token-usage\" help=\"Query workspace token usage\" {\n alias \"wtu\"\n flag \"--workspace-id <workspace_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--project-ids <project_ids...>\" help=\"The IDs of the projects to filter results by. Defaults to all projects in the workspace.\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"project-token-usage\" help=\"Query project token usage\" {\n alias \"ptu\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--interval <interval>\" help=\"options: hour, day, week, month [required]\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"hourly-organization-token-usage\" help=\"Query hourly organization token usage\" {\n alias \"hotu\"\n flag \"--organization-id <organization_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--workspace-ids <workspace_ids...>\" help=\"list of values\" var=#true\n flag \"--project-ids <project_ids...>\" help=\"The IDs of the projects to filter results by. Defaults to all projects in the workspace.\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"hourly-project-token-usage\" help=\"Query hourly project token usage\" {\n alias \"hptu\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--interval <interval>\" help=\"options: hour, day, week, month [required]\"\n flag \"--usage-class <usage_class>\" help=\"options: Host, Build, Test, Monitor\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"daily-token-usage\" help=\"Query daily token usage\" {\n alias \"dtu\"\n flag \"--organization-id <organization_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--workspace-ids <workspace_ids...>\" help=\"list of values\" var=#true\n flag \"--project-ids <project_ids...>\" help=\"The IDs of the projects to filter results by. Defaults to all projects in the workspace.\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"entity-token-usage\" help=\"Query entity token usage\" {\n alias \"etu\"\n flag \"--organization-id <organization_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"category-token-usage\" help=\"Query category token usage\" {\n alias \"ctu\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--interval <interval>\" help=\"options: hour, day, week, month [required]\"\n flag \"--usage-class <usage_class>\" help=\"options: Host, Build, Test, Monitor\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"playbook-usage\" help=\"Query playbook usage\" {\n alias \"pu\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--exclude-id <exclude_id...>\" help=\"list of values\" var=#true\n flag \"--limit <limit>\" help=\"number value\" default=10\n flag \"--order-direction <order_direction>\" help=\"options: ASC, DESC\"\n flag \"--order-by <order_by>\" help=\"options: count, averageLatencyMS\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"workflow-usage\" help=\"Query workflow usage\" {\n alias \"wu\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--exclude-id <exclude_id...>\" help=\"list of values\" var=#true\n flag \"--limit <limit>\" help=\"number value\" default=10\n flag \"--order-direction <order_direction>\" help=\"options: ASC, DESC\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"prompt-usage\" help=\"Query prompt usage\" {\n alias \"pus\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--exclude-id <exclude_id...>\" help=\"list of values\" var=#true\n flag \"--limit <limit>\" help=\"number value\" default=10\n flag \"--order-direction <order_direction>\" help=\"options: ASC, DESC\"\n flag \"--order-by <order_by>\" help=\"options: count, averageLatencyMS\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"intent-usage\" help=\"Query intent usage\" {\n alias \"ius\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--exclude-id <exclude_id...>\" help=\"list of values\" var=#true\n flag \"--limit <limit>\" help=\"number value\" default=10\n flag \"--order-direction <order_direction>\" help=\"options: ASC, DESC\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"function-usage\" help=\"Query function usage\" {\n alias \"fu\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--exclude-id <exclude_id...>\" help=\"list of values\" var=#true\n flag \"--limit <limit>\" help=\"number value\" default=10\n flag \"--order-direction <order_direction>\" help=\"options: ASC, DESC\"\n flag \"--order-by <order_by>\" help=\"options: count, averageLatencyMS\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"api-tool-usage\" help=\"Query API tool usage\" {\n alias \"atu\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--exclude-id <exclude_id...>\" help=\"list of values\" var=#true\n flag \"--limit <limit>\" help=\"number value\" default=10\n flag \"--order-direction <order_direction>\" help=\"options: ASC, DESC\"\n flag \"--order-by <order_by>\" help=\"options: count, averageLatencyMS\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"mcp-tool-usage\" help=\"Query MCP tool usage\" {\n alias \"mtu\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--exclude-id <exclude_id...>\" help=\"list of values\" var=#true\n flag \"--limit <limit>\" help=\"number value\" default=10\n flag \"--order-direction <order_direction>\" help=\"options: ASC, DESC\"\n flag \"--order-by <order_by>\" help=\"options: count, averageLatencyMS\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"knowledge-base-document-usage\" help=\"Query knowledge base document usage\" {\n alias \"kbdu\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--exclude-id <exclude_id...>\" help=\"list of values\" var=#true\n flag \"--limit <limit>\" help=\"number value\" default=10\n flag \"--order-direction <order_direction>\" help=\"options: ASC, DESC\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"integration-usage\" help=\"Query integration usage\" {\n alias \"iu\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--exclude-id <exclude_id...>\" help=\"list of values\" var=#true\n flag \"--limit <limit>\" help=\"number value\" default=10\n flag \"--order-direction <order_direction>\" help=\"options: ASC, DESC\"\n flag \"--order-by <order_by>\" help=\"options: count, averageLatencyMS\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"unique-user-count\" help=\"Query unique user count\" {\n alias \"uuc\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--interval <interval>\" help=\"options: hour, day, week, month [required]\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"objective-metrics\" help=\"Query objective metrics\" {\n alias \"om\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--interfaces <interfaces...>\" help=\"The channels to filter results by. Defaults to all channels.\" var=#true\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n }\n}\ncmd \"test\" help=\"Build and run agent tests\" {\n cmd \"list\" help=\"List tests\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create test\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"[required]\"\n flag \"--settings <settings>\" help=\"JSON object\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get test\" {\n flag \"--test-id <test_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update test\" {\n flag \"--test-id <test_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"string value\"\n flag \"--settings <settings>\" help=\"JSON object\"\n flag \"--turn-order <turn_order...>\" help=\"The IDs of the test's turns, in execution order.\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete test\" {\n flag \"--test-id <test_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"turn\" help=\"Manage the turns of a test conversation\" {\n cmd \"list\" help=\"List turns\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--test-id <test_id>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create turn\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ type: string, testID: string, payload: object }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get turn\" {\n flag \"--turn-id <turn_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update turn\" {\n flag \"--turn-id <turn_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ type: string, payload: object } | { type: string, payload: object, checkOrder: string[] }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete turn\" {\n flag \"--turn-id <turn_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n }\n cmd \"check\" help=\"Manage the checks a test makes\" {\n cmd \"list\" help=\"List checks\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--turn-id <turn_id>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create check\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ type: string, turnID: string, payload: value } | { type: string, turnID: string, payload: object }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get check\" {\n flag \"--check-id <check_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update check\" {\n flag \"--check-id <check_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ type: string, payload: value } | { type: string, payload: object }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete check\" {\n flag \"--check-id <check_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n }\n cmd \"folder\" help=\"List the folders tests are kept in\" {\n cmd \"list\" help=\"List test folders\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n }\n cmd \"run\" help=\"Run tests, wait for results and read their logs\" {\n cmd \"search\" help=\"Search runs\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--take <take>\" help=\"The maximum number of results to return, used for pagination.\" default=20\n flag \"--skip <skip>\" help=\"The number of results to skip, used for pagination.\" default=0\n flag \"--test-id <test_id>\" help=\"Restrict results to runs of this test. Omit to search across all tests.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"create\" help=\"Create run\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--test-id <test_id>\" help=\"The ID of the test to run. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"create-suite\" help=\"Run test suite\" {\n alias \"cs\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--all\" help=\"Run every test in the environment. Pass exactly one of `all`, `testIDs` and `folderIDs`.\"\n flag \"--test-ids <test_ids...>\" help=\"Run these tests, one run each, with no limit on how many. Pass exactly one of `all`, `testIDs` and `folderIDs`.\" var=#true\n flag \"--folder-ids <folder_ids...>\" help=\"Run every test in these folders and in every folder nested under them. Pass exactly one of `all`, `testIDs` and `folderIDs`.\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"cancel\" help=\"Cancel runs\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--run-ids <run_ids...>\" help=\"The IDs of the runs to cancel. [required]\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"wait\" help=\"Wait for runs\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--run-ids <run_ids...>\" help=\"The runs to wait for: the IDs create_run or create_many_runs returned (each run's `id`, not its `testID`). [required]\" var=#true\n flag \"--timeout-seconds <timeout_seconds>\" help=\"How long to wait at most, in seconds: 45 by default, 120 at most.\" default=45\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"wait-suite\" help=\"Wait for test suite\" {\n alias \"ws\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--bulk-id <bulk_id>\" help=\"The `bulkID` that starting the suite returned. [required]\"\n flag \"--timeout-seconds <timeout_seconds>\" help=\"How long to wait at most, in seconds: 45 by default, 120 at most.\" default=45\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get run\" {\n flag \"--run-id <run_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"query-logs\" help=\"Query run logs\" {\n alias \"ql\"\n flag \"--run-id <run_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--kinds <kinds...>\" help=\"Keep only entries of these kinds. Omit to keep every kind.\" var=#true\n flag \"--levels <levels...>\" help=\"Keep only entries at these levels, for example [\\\"fatal\\\", \\\"error\\\", \\\"warn\\\"] for what went wrong.\" var=#true\n flag \"--debug-kinds <debug_kinds...>\" help=\"Keep only debug entries of these kinds. Setting it leaves out every entry that is not a debug log.\" var=#true\n flag \"--turns <turns>\" help=\"Keep only entries of these turns. Turn 0 holds anything logged before the first input.\"\n flag \"--search <search>\" help=\"Keep only entries whose message or recorded data contains this text, ignoring case. It is plain text, not a regular expression. Separate alternatives with |, as in \\\"timeout|denied\\\", to keep entries that contain any of them.\"\n flag \"--detail <detail>\" help=\"options: summary, full\" default=\"summary\"\n flag \"--limit <limit>\" help=\"The most entries to return in one page.\" default=50\n flag \"--offset <offset>\" help=\"How many matching entries to skip, for paging.\" default=0\n flag \"--order <order>\" help=\"options: asc, desc\" default=\"asc\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n }\n}\ncmd \"persona\" help=\"Manage personas, sets of preset variable values\" {\n cmd \"list\" help=\"List personas\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create persona\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the persona. Must not already be used by another persona in this environment. [required]\"\n flag \"--items <items>\" help=\"The variable values this persona presets. On update this replaces the whole list: send every item the persona should keep. An item read back with a null variable cannot be kept: leave it out, or name an existing variable in its place.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get persona\" {\n flag \"--persona-id <persona_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update persona\" {\n flag \"--persona-id <persona_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the persona. Must not already be used by another persona in this environment.\"\n flag \"--items <items>\" help=\"The variable values this persona presets. On update this replaces the whole list: send every item the persona should keep. An item read back with a null variable cannot be kept: leave it out, or name an existing variable in its place.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete persona\" {\n flag \"--persona-id <persona_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n}\ncmd \"widget\" help=\"Configure the web chat widget and get its snippet\" {\n cmd \"get\" help=\"Get widget\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update widget\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--type <type>\" help=\"Switches the embed between the text `chat` surface and the click-to-call `voice` surface. The surface you switch away from is kept as it was, so switching back later restores it. (options: chat, voice)\"\n flag \"--chat <chat>\" help=\"Chat-surface fields to change, merged one level deep into the stored `chat` block: what you send replaces its stored counterpart and everything else is kept. A nested object (`banner`, `headerImage`, `disclaimer`, `csat`, …) replaces the stored one outright, so send it complete. `placeholderText` and `aiDisclaimer` need the Webchat Premium entitlement and `disclaimer` the widget-security one: without it the whole request is refused with 403 and nothing is written, including the other fields sent alongside it.\"\n flag \"--voice <voice>\" help=\"Voice-surface fields to change, merged one level deep into the stored `voice` block. `content` is a nested object: it replaces the stored one outright, so send every line of call-screen copy, not just the one you are changing.\"\n flag \"--common <common>\" help=\"Shared-chrome fields to change, merged one level deep into the stored `common` block. A nested object (`launcher`, `footerLink`) replaces the stored one outright, so send it complete. `primaryColor` is the exception and merges too: send `color` on its own to recolor the widget and the shade palette is regenerated from it, send `palette` on its own to hand-tune the shades against the stored color, or send both together. `poweredBy`, `fontFamily`, `footerLink` and `primaryColor.palette` need the Webchat Premium entitlement — `primaryColor.color` on its own does not — and without it the whole request is refused with 403 and nothing is written, including the other fields sent alongside it.\"\n flag \"--security <security>\" help=\"Replaces the stored security block in full — unlike the other blocks it has no partial form. Requires a plan entitlement: without one the whole request is refused with 403 and nothing is written, including the other fields sent alongside it.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get-snippet\" help=\"Get widget snippet\" {\n alias \"gs\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--version-param <version_param>\" help=\"Pins the embed to one version of the environment: `draft`, the version used when testing, or `published`, the version serving live traffic. Omit it to pin the snippet to `published`. (options: draft, published)\" default=\"published\"\n }\n}\ncmd \"phone-number\" help=\"Manage phone numbers and assign them to projects\" {\n alias \"pn\"\n cmd \"list\" help=\"List phone numbers\" {\n flag \"--project-id <project_id>\" help=\"string value\"\n flag \"--workspace-id <workspace_id>\" help=\"string value\"\n }\n cmd \"create\" help=\"Create phone number\" {\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get phone number\" {\n flag \"--phone-number-id <phone_number_id>\" help=\"[required]\"\n flag \"--workspace-id <workspace_id>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update phone number\" {\n flag \"--phone-number-id <phone_number_id>\" help=\"[required]\"\n flag \"--workspace-id <workspace_id>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The display name of the number within the workspace. Callers never see it. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete phone number\" {\n flag \"--phone-number-id <phone_number_id>\" help=\"[required]\"\n flag \"--workspace-id <workspace_id>\" help=\"[required]\"\n }\n cmd \"assign\" help=\"Assign phone number\" {\n flag \"--phone-number-id <phone_number_id>\" help=\"[required]\"\n flag \"--workspace-id <workspace_id>\" help=\"[required]\"\n flag \"--target <target>\" help=\"Which side of the number to point at the project: `voice` for incoming calls, `sms` for incoming SMS. The other side is left as it was. (options: sms, voice) [required]\"\n flag \"--version-param <version_param>\" help=\"Which version of the environment answers: `published`, the one serving live traffic, or `draft`, the working copy. Requires `environmentAlias`. Defaults to `published`. (options: draft, published)\"\n flag \"--project-id <project_id>\" help=\"The ID of the project the number should reach. [required]\"\n flag \"--environment-alias <environment_alias>\" help=\"The alias of the environment that should answer (e.g. `main`). Omit it to assign the number to the project without pinning an environment, which also clears a pin a previous assign set.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"unassign\" help=\"Unassign phone number\" {\n flag \"--phone-number-id <phone_number_id>\" help=\"[required]\"\n flag \"--workspace-id <workspace_id>\" help=\"[required]\"\n flag \"--target <target>\" help=\"Which side of the number to clear: `voice` or `sms`. Omit it to clear both. Clearing a side that is not assigned is refused. (options: sms, voice)\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n}\ncmd \"event\" help=\"Manage the events clients can send to the agent\" {\n cmd \"list\" help=\"List events\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create event\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--description <description>\" help=\"What the event is for. Null when none was written.\"\n flag \"--name <name>\" help=\"The display name of the event. Must not match another event in this environment, ignoring case. [required]\"\n flag \"--request-name <request_name>\" help=\"The name a client sends to trigger the event, as payload.event.name of an `event` request. Letters, digits, underscores and $ only, at most 64 characters. Must not be used by another event in this environment. Defaults to the name with spaces turned into underscores and other characters dropped.\"\n flag \"--goes-to <goes_to>\" help=\"What the agent does when the event arrives. `flow` runs the workflow named by workflowID. `global_agent` hands the conversation back to the agent to decide what to do next, and is only valid in an agent project. `continue` carries on the conversation where it was, for an event that only updates user info. (options: flow, global_agent, continue) [required]\"\n flag \"--workflow-id <workflow_id>\" help=\"The workflow to run, as a workflow ID from voiceflow_workflow.list. Required when goesTo is `flow`; leave it out for any other goesTo.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get event\" {\n flag \"--event-id <event_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update event\" {\n flag \"--event-id <event_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--description <description>\" help=\"What the event is for. Null when none was written.\"\n flag \"--name <name>\" help=\"The display name of the event. Must not match another event in this environment, ignoring case. Renaming does not change requestName.\"\n flag \"--request-name <request_name>\" help=\"The name a client sends to trigger the event. Letters, digits, underscores and $ only, at most 64 characters. Must not be used by another event in this environment. Changing it breaks any client still sending the old name.\"\n flag \"--goes-to <goes_to>\" help=\"options: flow, global_agent, continue\"\n flag \"--workflow-id <workflow_id>\" help=\"The workflow to run, as a workflow ID from voiceflow_workflow.list. Only valid while goesTo is `flow`. Changing goesTo away from `flow` clears it.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete event\" {\n flag \"--event-id <event_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n}\ncmd \"billing\" help=\"Check an organization's plan, limits and credits\" {\n cmd \"subscription\" help=\"Get an organization's subscription and plan\" {\n cmd \"get\" help=\"Get subscription\" {\n flag \"--organization-id <organization_id>\" help=\"[required]\"\n }\n }\n cmd \"credits\" help=\"Check credits used this billing period\" {\n cmd \"get\" help=\"Get credits\" {\n flag \"--organization-id <organization_id>\" help=\"[required]\"\n }\n }\n cmd \"limits\" help=\"Check plan limits against current usage\" {\n cmd \"get\" help=\"Get limits\" {\n flag \"--organization-id <organization_id>\" help=\"[required]\"\n }\n }\n}\ncmd \"configure\" help=\"Configure authentication credentials and preferences\"\ncmd \"whoami\" help=\"Display current authentication configuration\"\ncmd \"version\" help=\"Print the CLI version\"\n", + "": "name \"vf\"\nbin \"vf\"\nabout \"Build, test, and operate Voiceflow AI agents from your terminal\"\nversion \"0.2.349\"\nconfig {\n file \"~/.config/vf/config.yaml\"\n}\nflag \"--usage\" help=\"Print the CLI Usage schema in KDL format\" global=#true\nflag \"-o --output-format <format>\" help=\"Specify the output format. Options: pretty, json, yaml, table, toon.\" global=#true config=\"output_format\" default=\"pretty\"\nflag \"--color <color>\" help=\"Control colored output: auto (color when output is a TTY), always, or never. Respects NO_COLOR and FORCE_COLOR env vars.\" global=#true default=\"auto\"\nflag \"-q --jq <jq>\" help=\"Filter the response with a jq expression, e.g. '.project.id' or '.items[] | .id'. A string prints raw, as jq -r prints it; anything else prints as JSON ('| tojson' keeps a string quoted). Overrides -o: the filter reads the JSON response, and its output is the same whatever -o says\" global=#true\nflag \"--server-url <url>\" help=\"Override the default server URL\" global=#true\nflag \"--server <server>\" help=\"Select a server by index (for indexed servers) or name (for named servers)\" global=#true\nflag \"-H --header <header...>\" help=\"Set a custom HTTP request header (format: \\\"Key: Value\\\"). Can be specified multiple times.\" global=#true var=#true\nflag \"--include-headers\" help=\"Include HTTP response headers in the output\" global=#true default=#false\nflag \"--timeout <duration>\" help=\"HTTP request timeout (e.g., 30s, 5m, 100ms)\" global=#true config=\"timeout\"\nflag \"--dry-run\" help=\"Preview the request that would be sent without executing it (output to stderr)\" global=#true default=#false\nflag \"-d --debug\" help=\"Log request and response diagnostics to stderr\" global=#true default=#false\nflag \"--agent-mode\" help=\"Enable structured errors and default TOON output for AI coding agents. Automatically enabled when a known agent environment is detected (CLAUDE_CODE, CURSOR_AGENT, etc.). Use --agent-mode=false to disable.\" global=#true default=#false\nflag \"--token <token>\" help=\"Voiceflow bearer token\" global=#true env=\"VF_TOKEN\" config=\"security.token\"\ncmd \"agent\" help=\"Configure the agent's instructions, prompt and voice\" {\n cmd \"get\" help=\"Get agent\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--include-instructions\" help=\"boolean flag\" default=#false\n flag \"--include-prompt\" help=\"boolean flag\" default=#false\n }\n cmd \"update\" help=\"Update agent\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--prompt <prompt>\" help=\"string value\"\n flag \"--end-tool <end_tool>\" help=\"JSON object\"\n flag \"--card-tool <card_tool>\" help=\"JSON object\"\n flag \"--playbooks <playbooks>\" help=\"Playbooks available for the agent to invoke. This list REPLACES the registry: send the complete list you want, or omit the field to leave routing untouched. An agent with no playbooks AND no workflows registered cannot run - the runtime fails the conversation - so never send an empty list unless `workflows` still holds at least one.\"\n flag \"--workflows <workflows>\" help=\"Workflows available for the agent to invoke. This list REPLACES the registry: send the complete list you want, or omit the field to leave routing untouched. An agent with no workflows AND no playbooks registered cannot run, so never send an empty list unless `playbooks` still holds at least one.\"\n flag \"--button-tool <button_tool>\" help=\"JSON object\"\n flag \"--carousel-tool <carousel_tool>\" help=\"JSON object\"\n flag \"--instructions <instructions>\" help=\"string value\"\n flag \"--skip-turn-tool <skip_turn_tool>\" help=\"JSON object\"\n flag \"--path-tool-order <path_tool_order...>\" help=\"The ordered list of path tool IDs that controls the order of the agent exit paths.\" var=#true\n flag \"--web-search-tool <web_search_tool>\" help=\"JSON object\"\n flag \"--call-forward-tool <call_forward_tool>\" help=\"JSON object\"\n flag \"--knowledge-base-tool <knowledge_base_tool>\" help=\"JSON object\"\n flag \"--include-guidelines\" help=\"Whether to append the default prompting guidelines to the global prompt.\"\n flag \"--llm <llm>\" help=\"JSON object\"\n flag \"--voice <voice>\" help=\"JSON object\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"add-workflow\" help=\"Add agent workflow\" {\n alias \"aw\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--condition <condition>\" help=\"The agent can run the workflow only while this condition holds. Leave it out for a workflow it can always run.\"\n flag \"--description <description>\" help=\"When the agent should run this workflow. The agent reads it to choose between its playbooks and workflows. [required]\"\n flag \"--required-variables <required_variables>\" help=\"Variables the agent fills from the conversation before it runs the workflow, each with a description of what it holds.\"\n flag \"--workflow-id <workflow_id>\" help=\"The workflow to add. Copy its ID from voiceflow_workflow.list. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"update-workflow\" help=\"Update agent workflow\" {\n alias \"uw\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--condition <condition>\" help=\"The agent can run the workflow only while this condition holds. Leave it out for a workflow it can always run.\"\n flag \"--description <description>\" help=\"When the agent should run this workflow. The agent reads it to choose between its playbooks and workflows.\"\n flag \"--required-variables <required_variables>\" help=\"Replaces the stored list. Keep the id of each variable you keep, as read with voiceflow_agent.get. Leave the field out to keep the stored required variables.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"remove-workflow\" help=\"Remove agent workflow\" {\n alias \"rw\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"read-instructions\" help=\"Read agent instructions\" {\n alias \"ri\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--offset <offset>\" help=\"integer value\" default=1\n flag \"--limit <limit>\" help=\"integer value\" default=400\n }\n cmd \"patch-instructions\" help=\"Patch agent instructions\" {\n alias \"pi\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--old-string <old_string>\" help=\"The exact text to replace, copied verbatim from a read or search result. Matching is literal — whitespace, punctuation and case must match. Do not include the line numbers a read adds. [required]\"\n flag \"--new-string <new_string>\" help=\"The text to put in its place. May be empty to delete. [required]\"\n flag \"--replace-all\" help=\"Replace every occurrence. When false, more than one match is an error rather than a guess.\" default=#false\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"search-instructions\" help=\"Search agent instructions\" {\n alias \"si\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--pattern <pattern>\" help=\"A JavaScript regular expression, evaluated against each line on its own. [required]\"\n flag \"--ignore-case\" help=\"Match case-insensitively. Defaults to false, like grep.\" default=#false\n flag \"--context-lines <context_lines>\" help=\"How many lines either side of each match to return.\" default=0\n flag \"--limit <limit>\" help=\"The maximum number of matching LINES to return. The reported totals cover the whole document.\" default=50\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"read-prompt\" help=\"Read the global prompt\" {\n alias \"rp\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--offset <offset>\" help=\"integer value\" default=1\n flag \"--limit <limit>\" help=\"integer value\" default=400\n }\n cmd \"patch-prompt\" help=\"Patch the global prompt\" {\n alias \"pp\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--old-string <old_string>\" help=\"The exact text to replace, copied verbatim from a read or search result. Matching is literal — whitespace, punctuation and case must match. Do not include the line numbers a read adds. [required]\"\n flag \"--new-string <new_string>\" help=\"The text to put in its place. May be empty to delete. [required]\"\n flag \"--replace-all\" help=\"Replace every occurrence. When false, more than one match is an error rather than a guess.\" default=#false\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"search-prompt\" help=\"Search the global prompt\" {\n alias \"sp\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--pattern <pattern>\" help=\"A JavaScript regular expression, evaluated against each line on its own. [required]\"\n flag \"--ignore-case\" help=\"Match case-insensitively. Defaults to false, like grep.\" default=#false\n flag \"--context-lines <context_lines>\" help=\"How many lines either side of each match to return.\" default=0\n flag \"--limit <limit>\" help=\"The maximum number of matching LINES to return. The reported totals cover the whole document.\" default=50\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"add-tool-message\" help=\"Add agent tool message\" {\n alias \"atm\"\n flag \"--project-id <project_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--environment-alias <environment_alias>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--slot <slot>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: delay, failure, execution, completion) [required]\"\n flag \"--tool-id <tool_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected.\"\n flag \"--native-tool <native_tool>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: endTool, cardTool, buttonTool, carouselTool, webSearchTool, callForwardTool, knowledgeBaseTool)\"\n flag \"--body-param <body_param>\" help=\"{ type: string, examples: string[] } | { type: string, messageID: string }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"update-tool-message\" help=\"Update agent tool message\" {\n alias \"utm\"\n flag \"--project-id <project_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--environment-alias <environment_alias>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--slot <slot>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: delay, failure, execution, completion) [required]\"\n flag \"--tool-id <tool_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected.\"\n flag \"--native-tool <native_tool>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: endTool, cardTool, buttonTool, carouselTool, webSearchTool, callForwardTool, knowledgeBaseTool)\"\n flag \"--body-param <body_param>\" help=\"{ type: string, examples: string[] } | { type: string, messageID: string }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete-tool-message\" help=\"Delete agent tool message\" {\n alias \"dtm\"\n flag \"--project-id <project_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--environment-alias <environment_alias>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--slot <slot>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: delay, failure, execution, completion) [required]\"\n flag \"--tool-id <tool_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected.\"\n flag \"--native-tool <native_tool>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: endTool, cardTool, buttonTool, carouselTool, webSearchTool, callForwardTool, knowledgeBaseTool)\"\n }\n cmd \"patch-pronunciation\" help=\"Patch pronunciation dictionary\" {\n alias \"ppr\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--set <set>\" help=\"Words to add, or to change when the dictionary already has them. `from` is the written word and `to` is how the voice says it; an empty `to` makes the voice skip the word.\"\n flag \"--remove <remove...>\" help=\"Written words whose entries to delete.\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"search-voices\" help=\"Search voices\" {\n alias \"sv\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--search <search>\" help=\"string value\"\n flag \"--language <language>\" help=\"string value\"\n flag \"--provider <provider>\" help=\"A TTS provider whose voices are in the voice catalog. (options: elevenlabs, cartesia)\"\n flag \"--gender <gender>\" help=\"How the vendor describes the voice. (options: male, female, neutral)\"\n flag \"--limit <limit>\" help=\"integer value\" default=10\n flag \"--offset <offset>\" help=\"integer value\" default=0\n }\n cmd \"patch-voices\" help=\"Patch voices\" {\n alias \"pv\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--primary <primary>\" help=\"The default voice: the one a conversation speaks with unless a language voice matches its locale.\"\n flag \"--set-overrides <set_overrides>\" help=\"Language voices to add, or to change when the agent already has one for that locale.\"\n flag \"--remove-overrides <remove_overrides...>\" help=\"Locales whose language voice to delete, as stored. They match ignoring case and _, as the runtime matches them.\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get-initialization-workflow\" help=\"Get initialization workflow\" {\n alias \"giw\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"set-initialization-workflow\" help=\"Set initialization workflow\" {\n alias \"siw\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--workflow-id <workflow_id>\" help=\"The workflow to run before the user's first turn, or null to run none. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n}\ncmd \"workflow\" help=\"Build workflows: blocks, steps, branches and links\" {\n cmd \"list\" help=\"List workflows\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--folder-id <folder_id>\" help=\"string value\"\n flag \"--cursor <cursor>\" help=\"string value\"\n flag \"--limit <limit>\" help=\"integer value\"\n }\n cmd \"create\" help=\"Create workflow\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"[required]\"\n flag \"--description <description>\" help=\"string value\"\n flag \"--folder-id <folder_id>\" help=\"string value\"\n flag \"--entry <entry>\" help=\"string value\"\n flag \"--blocks <blocks>\" help=\"list of values\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get workflow\" {\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--cursor <cursor>\" help=\"string value\"\n }\n cmd \"update\" help=\"Update workflow\" {\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"string value\"\n flag \"--description <description>\" help=\"string value\"\n flag \"--folder-id <folder_id>\" help=\"A workflow folder in this environment, or null for the top level.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete workflow\" {\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"get-step\" help=\"Get workflow step\" {\n alias \"gs\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--step-id <step_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update-step\" help=\"Update workflow step\" {\n alias \"us\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--step-id <step_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ kind: string, content: object }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete-step\" help=\"Delete workflow step\" {\n alias \"ds\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--step-id <step_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--expected-steps <expected_steps...>\" help=\"[required]\" var=#true\n }\n cmd \"get-raw\" help=\"Get raw workflow\" {\n alias \"gr\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--block-ids <block_ids...>\" help=\"list of values\" var=#true\n }\n cmd \"duplicate\" help=\"Duplicate workflow\" {\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the copy. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"link\" help=\"Link a port\" {\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--step-id <step_id>\" help=\"[required]\"\n flag \"--port-key <port_key>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--to-block-id <to_block_id>\" help=\"The block the port will lead to. Links point at blocks, never at a step inside one. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"unlink\" help=\"Unlink a port\" {\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--step-id <step_id>\" help=\"[required]\"\n flag \"--port-key <port_key>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"link-many\" help=\"Link many ports\" {\n alias \"lm\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--links <links>\" help=\"1 to 50 ports to link, each once. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"create-block\" help=\"Create block\" {\n alias \"cb\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"[required]\"\n flag \"--color-param <color_param>\" help=\"string value\"\n flag \"--placement <placement>\" help=\"Place the new block to the right of this block. Without it, the block goes next to the block of from.stepID, or right of the right-most block.\"\n flag \"--from <from>\" help=\"Also link this port to the new block in the same call, with the same checks as voiceflow_workflow.link.\"\n flag \"--steps <steps>\" help=\"[required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"add-blocks\" help=\"Add workflow blocks\" {\n alias \"ab\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--blocks <blocks>\" help=\"The new blocks. A step's links and a branch's to name a block key from this call or an existing block ID. [required]\"\n flag \"--from <from>\" help=\"Existing ports to link to new blocks in the same call, with the same checks as voiceflow_workflow.link.\"\n flag \"--placement <placement>\" help=\"Place the new blocks to the right of this block. Without it, they go right of the block of the first from step, or right of the right-most block.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"update-block\" help=\"Update block\" {\n alias \"ub\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--block-id <block_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"string value\"\n flag \"--color-param <color_param>\" help=\"string value\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete-block\" help=\"Delete workflow block\" {\n alias \"db\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--block-id <block_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--expected-steps <expected_steps...>\" help=\"[required]\" var=#true\n }\n cmd \"arrange-blocks\" help=\"Arrange workflow blocks\" {\n alias \"abl\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--block-ids <block_ids...>\" help=\"Move only these blocks, as a group laid out by the links between them. Leave it out to arrange every block from the Start.\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"split-block\" help=\"Split workflow block\" {\n alias \"sb\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--block-id <block_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--at-step-id <at_step_id>\" help=\"The step that starts the new block. It and every step below it move there, and the step above it becomes the last step of the block. To make step X the last step, so that its fail and path ports run, send the step below X. It must not be the first step. [required]\"\n flag \"--name <name>\" help=\"The new block name. Default: the block name with \\\" (continued)\\\".\"\n flag \"--expected-steps <expected_steps...>\" help=\"The block's step IDs exactly as your last read returned them. If the block changed, nothing is written. [required]\" var=#true\n flag \"--acknowledge-rewire\" help=\"Required when the step that becomes the last step has hidden links or actions. The split keeps them, so they start to run. An action list on its next exit is deleted, because next links to the new block.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"insert-step\" help=\"Insert workflow step\" {\n alias \"is\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--block-id <block_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--after-step-id <after_step_id>\" help=\"Insert right after this step of the block. Send this or atStart.\"\n flag \"--at-start\" help=\"Insert as the first step of the block. Send this or afterStepID.\"\n flag \"--step <step>\" help=\"{ kind: string, key: string, content: value, links: object } | { kind: string, key: string, content: object, links: object }\"\n flag \"--expected-steps <expected_steps...>\" help=\"The block's step IDs exactly as your last read returned them. If the block changed, nothing is written. [required]\" var=#true\n flag \"--acknowledge-rewire\" help=\"Required when the insert makes the last step stop being last and that step has exits that would stop running: a Tool or Code fail or path link is cleared, and actions on such an exit are deleted. Also required when you append a step that has no next port, such as End or Go to block: the old last step's next link cannot move to it, so it is cleared.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"add-branch\" help=\"Add workflow branch\" {\n alias \"abr\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--step-id <step_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ label: string, matchAll: boolean, assertions: object[], to: string, ... } | { label: string, url: string, to: string, kind: string } | { label: string, url: string, to: string, kind: string, ... } | { label: string, to: string, kind: string } | { name: string, description: string, requiredVariables: object[], messages: object, ... }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"update-branch\" help=\"Update workflow branch\" {\n alias \"ubr\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--step-id <step_id>\" help=\"[required]\"\n flag \"--branch-id <branch_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ label: string, matchAll: boolean, assertions: object[], kind: string } | { label: string, url: string, kind: string } | { label: string, kind: string } | { name: string, description: string, requiredVariables: object[], kind: string }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete-branch\" help=\"Delete workflow branch\" {\n alias \"dbr\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--step-id <step_id>\" help=\"[required]\"\n flag \"--branch-id <branch_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"add-actions\" help=\"Add port actions\" {\n alias \"aa\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--step-id <step_id>\" help=\"[required]\"\n flag \"--port-key <port_key>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--actions <actions>\" help=\"1 to 10 actions to add, in run order. [required]\"\n flag \"--after-action-id <after_action_id>\" help=\"Add them after this action. Leave out afterActionID and atStart to add them at the end, before an action that ends the path.\"\n flag \"--at-start\" help=\"Add them before every other action on this exit.\"\n flag \"--expected-actions <expected_actions...>\" help=\"The IDs in this exit's actions from your last read, in order. Send [] when it has none. [required]\" var=#true\n flag \"--to <to>\" help=\"The block the path goes to after the actions. Leave it out to keep the current one. Send null to clear it.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"reorder-actions\" help=\"Reorder port actions\" {\n alias \"ra\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--step-id <step_id>\" help=\"[required]\"\n flag \"--port-key <port_key>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--order <order...>\" help=\"Every action ID of this exit, in the new order. [required]\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"replace-action\" help=\"Replace port action\" {\n alias \"rac\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--action-id <action_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--action <action>\" help=\"{ kind: string, content: object }\"\n flag \"--expected-actions <expected_actions...>\" help=\"The IDs in this exit's actions from your last read, in order. [required]\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n}\ncmd \"playbook\" help=\"Build playbooks: instructions, tools and exit paths\" {\n cmd \"list\" help=\"List playbooks\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--include-instructions\" help=\"boolean flag\" default=#false\n }\n cmd \"create\" help=\"Create playbook\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"[required]\"\n flag \"--description <description>\" help=\"A human-readable description of what the playbook does.\"\n flag \"--instructions <instructions>\" help=\"string value\"\n flag \"--end-tool <end_tool>\" help=\"JSON object\"\n flag \"--card-tool <card_tool>\" help=\"JSON object\"\n flag \"--button-tool <button_tool>\" help=\"JSON object\"\n flag \"--carousel-tool <carousel_tool>\" help=\"JSON object\"\n flag \"--skip-turn-tool <skip_turn_tool>\" help=\"JSON object\"\n flag \"--web-search-tool <web_search_tool>\" help=\"JSON object\"\n flag \"--call-forward-tool <call_forward_tool>\" help=\"JSON object\"\n flag \"--knowledge-base-tool <knowledge_base_tool>\" help=\"JSON object\"\n flag \"--settings <settings>\" help=\"JSON object\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get playbook\" {\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--include-instructions\" help=\"boolean flag\" default=#false\n }\n cmd \"update\" help=\"Update playbook\" {\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"string value\"\n flag \"--settings <settings>\" help=\"JSON object\"\n flag \"--description <description>\" help=\"A human-readable description of what the playbook does.\"\n flag \"--instructions <instructions>\" help=\"string value\"\n flag \"--end-tool <end_tool>\" help=\"JSON object\"\n flag \"--card-tool <card_tool>\" help=\"JSON object\"\n flag \"--button-tool <button_tool>\" help=\"JSON object\"\n flag \"--carousel-tool <carousel_tool>\" help=\"JSON object\"\n flag \"--skip-turn-tool <skip_turn_tool>\" help=\"JSON object\"\n flag \"--web-search-tool <web_search_tool>\" help=\"JSON object\"\n flag \"--call-forward-tool <call_forward_tool>\" help=\"JSON object\"\n flag \"--knowledge-base-tool <knowledge_base_tool>\" help=\"JSON object\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete playbook\" {\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"read-instructions\" help=\"Read playbook instructions\" {\n alias \"ri\"\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--offset <offset>\" help=\"integer value\" default=1\n flag \"--limit <limit>\" help=\"integer value\" default=400\n }\n cmd \"patch-instructions\" help=\"Patch playbook instructions\" {\n alias \"pi\"\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--old-string <old_string>\" help=\"The exact text to replace, copied verbatim from a read or search result. Matching is literal — whitespace, punctuation and case must match. Do not include the line numbers a read adds. [required]\"\n flag \"--new-string <new_string>\" help=\"The text to put in its place. May be empty to delete. [required]\"\n flag \"--replace-all\" help=\"Replace every occurrence. When false, more than one match is an error rather than a guess.\" default=#false\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"search-instructions\" help=\"Search playbook instructions\" {\n alias \"si\"\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--pattern <pattern>\" help=\"A JavaScript regular expression, evaluated against each line on its own. [required]\"\n flag \"--ignore-case\" help=\"Match case-insensitively. Defaults to false, like grep.\" default=#false\n flag \"--context-lines <context_lines>\" help=\"How many lines either side of each match to return.\" default=0\n flag \"--limit <limit>\" help=\"The maximum number of matching LINES to return. The reported totals cover the whole document.\" default=50\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"duplicate\" help=\"Duplicate playbook\" {\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the copy. Leave it out to use the original's name with \\\" copy\\\" added.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"add-tool-message\" help=\"Add playbook tool message\" {\n alias \"atm\"\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--environment-alias <environment_alias>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--slot <slot>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: delay, failure, execution, completion) [required]\"\n flag \"--tool-id <tool_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected.\"\n flag \"--native-tool <native_tool>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: endTool, cardTool, buttonTool, carouselTool, webSearchTool, callForwardTool, knowledgeBaseTool)\"\n flag \"--body-param <body_param>\" help=\"{ type: string, examples: string[] } | { type: string, messageID: string }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"update-tool-message\" help=\"Update playbook tool message\" {\n alias \"utm\"\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--environment-alias <environment_alias>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--slot <slot>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: delay, failure, execution, completion) [required]\"\n flag \"--tool-id <tool_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected.\"\n flag \"--native-tool <native_tool>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: endTool, cardTool, buttonTool, carouselTool, webSearchTool, callForwardTool, knowledgeBaseTool)\"\n flag \"--body-param <body_param>\" help=\"{ type: string, examples: string[] } | { type: string, messageID: string }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete-tool-message\" help=\"Delete playbook tool message\" {\n alias \"dtm\"\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--environment-alias <environment_alias>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--slot <slot>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: delay, failure, execution, completion) [required]\"\n flag \"--tool-id <tool_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected.\"\n flag \"--native-tool <native_tool>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: endTool, cardTool, buttonTool, carouselTool, webSearchTool, callForwardTool, knowledgeBaseTool)\"\n }\n cmd \"path\" help=\"Manage a playbook's exit paths\" {\n cmd \"list\" help=\"List exit paths\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create exit path\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--playbook-id <playbook_id>\" help=\"The ID of the playbook to add the exit path to. [required]\"\n flag \"--name <name>\" help=\"The name of the exit path, trimmed. Use Latin letters, digits, spaces, hyphens and underscores, as the editor does: the runtime turns the name into the snake_case name of the exit tool the model calls. [required]\"\n flag \"--description <description>\" help=\"The exit condition: the model reads it to decide when to leave the playbook through this path.\"\n flag \"--required-variables <required_variables>\" help=\"The variables or entities the model must fill before it can leave through this path, in order.\"\n flag \"--messages <messages>\" help=\"What the agent says as it leaves through this path. Send only a message ID that nothing else uses: no other step in any workflow, no reprompt, no agent and no playbook. For the same words in a second place, create a new message with that text.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"update\" help=\"Update exit path\" {\n flag \"--path-id <path_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the exit path, trimmed. Use Latin letters, digits, spaces, hyphens and underscores, as the editor does: the runtime turns the name into the snake_case name of the exit tool the model calls.\"\n flag \"--description <description>\" help=\"The exit condition: the model reads it to decide when to leave the playbook through this path.\"\n flag \"--required-variables <required_variables>\" help=\"Replaces the stored list, in order. Leave it out to keep it; send [] to remove every one.\"\n flag \"--messages <messages>\" help=\"Replaces the stored messages whole. Send null to remove them; leave it out to keep them. Send only a message ID that nothing else uses: no other step in any workflow, no reprompt, no agent and no playbook. For the same words in a second place, create a new message with that text.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete exit path\" {\n flag \"--path-id <path_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--playbook-id <playbook_id>\" help=\"[required]\"\n }\n }\n}\ncmd \"tool\" help=\"Manage the tools an agent and its playbooks use\" {\n cmd \"list\" help=\"List tools\" {\n flag \"--global\" help=\"boolean flag\"\n flag \"--playbook-id <playbook_id>\" help=\"string value\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--type <type>\" help=\"When provided, only tools of this type are returned. `workflow` returns the workflow tools. (options: api, mcp, function, integration, workflow)\"\n }\n cmd \"create\" help=\"Create tool\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ description: string, target: object, messages: object, captureInputVariables: object, ... }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get tool\" {\n flag \"--tool-id <tool_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--type <type>\" help=\"The type of the tool to fetch. (options: api, mcp, function, integration, workflow) [required]\"\n }\n cmd \"update\" help=\"Update tool\" {\n flag \"--tool-id <tool_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ description: string, messages: object, toolSound: object, captureInputVariables: object, ... }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete tool\" {\n flag \"--tool-id <tool_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--type <type>\" help=\"The type of the tool to delete. `workflow` removes a workflow tool; the workflow stays. (options: api, mcp, function, integration, workflow) [required]\"\n }\n cmd \"move\" help=\"Move tool\" {\n flag \"--tool-id <tool_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--type <type>\" help=\"The type of the tool to move. `workflow` is refused: a workflow tool is never moved. (options: api, mcp, function, integration, workflow) [required]\"\n flag \"--target <target>\" help=\"[required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n}\ncmd \"workspace\" help=\"Create, list and manage workspaces\" {\n cmd \"list\" help=\"List workspaces\"\n cmd \"create\" help=\"Create workspace\" {\n flag \"--name <name>\" help=\"[required]\"\n flag \"--organization-id <organization_id>\" help=\"The ID of the organization the workspace belongs to. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get workspace\" {\n flag \"--workspace-id <workspace_id>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update workspace\" {\n flag \"--workspace-id <workspace_id>\" help=\"[required]\"\n flag \"--name <name>\" help=\"string value\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete workspace\" {\n flag \"--workspace-id <workspace_id>\" help=\"[required]\"\n }\n}\ncmd \"project\" help=\"Create, list and manage projects\" {\n cmd \"list\" help=\"List projects\" {\n flag \"--workspace-id <workspace_id>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create project\" {\n flag \"--name <name>\" help=\"[required]\"\n flag \"--workspace-id <workspace_id>\" help=\"The ID of the workspace the project belongs to. [required]\"\n flag \"--type <type>\" help=\"The channel type of the project to create. (options: webchat, phone-call) [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get project\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update project\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--name <name>\" help=\"string value\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete project\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n}\ncmd \"environment\" help=\"Publish, clone, merge and compare environments\" {\n cmd \"list\" help=\"List environments\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"merge\" help=\"Merge environments\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--source-environment-alias <source_environment_alias>\" help=\"The alias of the environment whose changes are merged. [required]\"\n flag \"--target-environment-alias <target_environment_alias>\" help=\"The alias of the environment that receives the merged changes. [required]\"\n flag \"--remove-source-environment\" help=\"If true, the source environment is deleted after the merge.\" default=#false\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"update-traffic-split\" help=\"Update traffic split\" {\n alias \"uts\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--traffic <traffic>\" help=\"Map of environmentAlias → traffic percentage (0-100). Values must sum to 100. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get environment\" {\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update environment\" {\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--name <name>\" help=\"string value\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete environment\" {\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"diff\" help=\"Diff environment\" {\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"audit-wiring\" help=\"Audit environment wiring\" {\n alias \"aw\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"search-text\" help=\"Search project text\" {\n alias \"st\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--pattern <pattern>\" help=\"The word, phrase or ID to find. With regex, a JavaScript regular expression. [required]\"\n flag \"--regex\" help=\"Read pattern as a regular expression. Default false: literal text.\"\n flag \"--ignore-case\" help=\"Ignore case. Default true.\"\n flag \"--whole-word\" help=\"Match only where no letter, digit or underscore touches the match on either side. Default false.\"\n flag \"--resource-types <resource_types...>\" help=\"Search only these kinds of resource. Default: all of them.\" var=#true\n flag \"--limit <limit>\" help=\"Hits per page. Default 50.\"\n flag \"--offset <offset>\" help=\"Hits to skip: nextOffset from the previous page.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"compile\" help=\"Compile environment\" {\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"clone\" help=\"Clone environment\" {\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The display name of the new environment. [required]\"\n flag \"--alias <alias>\" help=\"Short URL-safe identifier; cannot be 'main' (reserved). [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"publish\" help=\"Publish environment\" {\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the release created by publishing. [required]\"\n flag \"--description <description>\" help=\"An optional description of what changed in this release.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n}\ncmd \"message\" help=\"Manage reusable messages and their variants\" {\n cmd \"get-many\" help=\"Get many messages\" {\n alias \"gm\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--ids <ids...>\" help=\"Message IDs to read. Duplicates are ignored; at most 50 distinct IDs. [required]\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get message\" {\n flag \"--message-id <message_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"delete\" help=\"Delete message\" {\n flag \"--message-id <message_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Reorder message variants\" {\n flag \"--message-id <message_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--variant-order <variant_order...>\" help=\"Every variant ID of the message, each exactly once, in the new order. [required]\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"create\" help=\"Create message\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--variants <variants>\" help=\"The variants, in stored order. They are alternatives: the runtime says one of them each time. The first variant cannot carry a condition. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"add-variant\" help=\"Add message variant\" {\n alias \"av\"\n flag \"--message-id <message_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--text <text>\" help=\"Message text shown to the end user. Limited markdown: **bold**, _italic_, <u>underline</u>, ~~strikethrough~~, [label](url). {variable_name} inserts a variable or entity, {variable_name.path} a field of a variable. Escape a literal { or \\\\ with a backslash. A name matching neither is stored as literal text and reported in unresolvedReferences; secrets are not available here. [required]\"\n flag \"--delay <delay>\" help=\"Milliseconds to wait before this variant is sent.\"\n flag \"--condition <condition>\" help=\"{ type: string, matchAll: boolean, assertions: object[] } | { type: string, code: string }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"update-variant\" help=\"Update message variant\" {\n alias \"uv\"\n flag \"--message-id <message_id>\" help=\"[required]\"\n flag \"--variant-id <variant_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--text <text>\" help=\"string value\"\n flag \"--delay <delay>\" help=\"Milliseconds to wait before this variant is sent. null removes the delay.\"\n flag \"--condition <condition>\" help=\"{ type: string, matchAll: boolean, assertions: object[] } | { type: string, code: string }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete-variant\" help=\"Delete message variant\" {\n alias \"dv\"\n flag \"--message-id <message_id>\" help=\"[required]\"\n flag \"--variant-id <variant_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n}\ncmd \"prompt\" help=\"Manage reusable prompts and their settings\" {\n cmd \"get-many\" help=\"Get many prompts\" {\n alias \"gm\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--ids <ids...>\" help=\"Prompt IDs to read. Duplicates are ignored; at most 50 distinct IDs. [required]\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get prompt\" {\n flag \"--prompt-id <prompt_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update prompt\" {\n flag \"--prompt-id <prompt_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"string value\"\n flag \"--system <system>\" help=\"string value\"\n flag \"--settings <settings>\" help=\"JSON object\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete prompt\" {\n flag \"--prompt-id <prompt_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create prompt\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"Defaults to \\\"Untitled prompt\\\", as the editor names one.\"\n flag \"--system <system>\" help=\"Plain text; markdown is not interpreted. {variable_name} inserts a variable or entity, {variable_name.path} a field of a variable. Escape a literal { or \\\\ with a backslash. A name matching neither is stored as literal text and reported in unresolvedReferences; secrets are not available here. [required]\"\n flag \"--settings <settings>\" help=\"JSON object\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"update-settings\" help=\"Update prompt settings\" {\n alias \"us\"\n flag \"--prompt-id <prompt_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--model <model>\" help=\"options: gpt-3.5-turbo-1106, gpt-3.5-turbo, gpt-4, gpt-4o, gpt-4o-mini, gpt-4.1-2025-04-14, gpt-4.1-mini-2025-04-14, gpt-4.1-nano-2025-04-14, gpt-o3-mini, o3-2025-04-16, o4-mini-2025-04-16, gpt-5, gpt-5-mini, gpt-5-nano, gpt-5.2, gpt-5.4, gpt-5.4-mini, gpt-5.5, gpt-5.6-sol, gpt-5.6-terra, gpt-5.6-luna, gpt-6-sol, gpt-6-luna, gpt-6.1-sol, gpt-realtime, gpt-live-1, claude-4-opus, claude-4-sonnet, claude-4.5-sonnet, claude-4.6-sonnet, claude-4.5-haiku, claude-4.5-opus, claude-4.7-opus, bedrock-claude-4-sonnet, bedrock-claude-4.5-sonnet, bedrock-claude-4.6-sonnet, bedrock-claude-5-sonnet, bedrock-claude-5.5-sonnet, bedrock-claude-4.5-haiku, bedrock-claude-5.5-haiku, bedrock-claude-4.5-opus, bedrock-claude-4.7-opus, bedrock-claude-4.8-opus, voiceflow-core-4.0, voiceflow-core-4.1, voiceflow-core-4.2, voiceflow-flash-4.2, gemini-2.5-pro, gemini-2.5-flash, gemini-live-2.5-flash, gemini-3-flash, gemini-3.5-flash, gemini-3.1-pro, gpt-oss-20b, gpt-oss-120b, llama-guard-4, llama-3.1-instant, llama-3.3-versatile, qwen3.6-27b, grok-4.6, voiceflow-flash-4.1, kimi-k3, gemini-flash-2, gpt-4-turbo, claude-3.5-haiku, claude-3-opus, claude-3.7-sonnet, claude-v2, llama-3.2-1b-preview, gemini-pro-1.5, claude-3-haiku, claude-3-sonnet, text-davinci-003, claude-v1, claude-instant-v1, deep-seek-r1-distill-llama-70B, claude-3.5-sonnet\"\n flag \"--max-tokens <max_tokens>\" help=\"number value\"\n flag \"--temperature <temperature>\" help=\"number value\"\n flag \"--response-format <response_format>\" help=\"string value\"\n flag \"--reasoning-effort <reasoning_effort>\" help=\"options: off, adaptive, minimal, low, medium, high\"\n flag \"--service-tier <service_tier>\" help=\"options: default, flex, priority\"\n flag \"--use-structured-output\" help=\"boolean flag\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n}\ncmd \"variable\" help=\"Manage the variables an agent reads and sets\" {\n cmd \"list\" help=\"List variables\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create variable\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the variable. Letters, digits and underscores only, at most 64 characters — this is what a {token} in a text field binds to. Must not already be used by a variable or an entity in this environment. When updating, omit this field unless you are renaming: a variable stored before this rule can hold a name outside the grammar, and echoing that name back would be rejected. [required]\"\n flag \"--color-param <color_param>\" help=\"The display color of the variable in the Voiceflow editor, as a hex code from the editor's color picker. Use #515A63 (the editor's default) unless the user asks for a color; otherwise pick the closest of #5B9FD7, #CB627B, #56B365, #DC8879, #9A63BC. Do not invent other hex codes. [required]\"\n flag \"--description <description>\" help=\"A short description of what the variable stores.\"\n flag \"--default-value <default_value>\" help=\"The initial value of the variable at the start of a conversation.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get variable\" {\n flag \"--variable-id <variable_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update variable\" {\n flag \"--variable-id <variable_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the variable. Letters, digits and underscores only, at most 64 characters — this is what a {token} in a text field binds to. Must not already be used by a variable or an entity in this environment. When updating, omit this field unless you are renaming: a variable stored before this rule can hold a name outside the grammar, and echoing that name back would be rejected.\"\n flag \"--color-param <color_param>\" help=\"The display color of the variable in the Voiceflow editor, as a hex code from the editor's color picker. Use #515A63 (the editor's default) unless the user asks for a color; otherwise pick the closest of #5B9FD7, #CB627B, #56B365, #DC8879, #9A63BC. Do not invent other hex codes.\"\n flag \"--description <description>\" help=\"A short description of what the variable stores.\"\n flag \"--default-value <default_value>\" help=\"The initial value of the variable at the start of a conversation.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete variable\" {\n flag \"--variable-id <variable_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n}\ncmd \"api-tool\" help=\"Manage API tools: HTTP requests the agent can make\" {\n alias \"at\"\n cmd \"list\" help=\"List API tools\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create API tool\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--url <url>\" help=\"string value\"\n flag \"--name <name>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ type: string, contentType: string, content: string } | { type: string, formData: object[] } | { type: string, params: object[] }\"\n flag \"--settings <settings>\" help=\"JSON object\"\n flag \"--http-method <http_method>\" help=\"options: get, put, post, patch, delete [required]\"\n flag \"--description <description>\" help=\"A description of what the API tool does, used by the agent to decide when to call it.\"\n flag \"--headers <headers>\" help=\"list of values\"\n flag \"--query-parameters <query_parameters>\" help=\"list of values\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get API tool\" {\n flag \"--tool-id <tool_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update API tool\" {\n flag \"--tool-id <tool_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--url <url>\" help=\"string value\"\n flag \"--name <name>\" help=\"string value\"\n flag \"--body-param <body_param>\" help=\"{ type: string, contentType: string, content: string } | { type: string, formData: object[] } | { type: string, params: object[] }\"\n flag \"--headers <headers>\" help=\"list of values\"\n flag \"--settings <settings>\" help=\"JSON object\"\n flag \"--http-method <http_method>\" help=\"options: get, put, post, patch, delete\"\n flag \"--description <description>\" help=\"A description of what the API tool does, used by the agent to decide when to call it.\"\n flag \"--query-parameters <query_parameters>\" help=\"list of values\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete API tool\" {\n flag \"--tool-id <tool_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"get-schema\" help=\"Get API tool schema\" {\n alias \"gs\"\n flag \"--tool-id <tool_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"execute\" help=\"Execute API tool\" {\n flag \"--tool-id <tool_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--inputs <inputs>\" help=\"A value for each of the API tool's input variables, keyed by input name. Each value replaces the tool's {input_name} placeholder in the URL, headers, query and body. Every declared input needs a value, and a name the tool does not declare is refused. List them with get_schema.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"variable\" help=\"Manage an API tool's variables\" {\n cmd \"list\" help=\"List variables\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--api-tool-id <api_tool_id>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create variable\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the variable, referenced within the API tool request as {name}. Letters, digits and underscores only, at most 64 characters. [required]\"\n flag \"--api-tool-id <api_tool_id>\" help=\"The ID of the API tool this variable belongs to. [required]\"\n flag \"--description <description>\" help=\"A description of the variable, used by the agent to determine what value to provide.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get variable\" {\n flag \"--variable-id <variable_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update variable\" {\n flag \"--variable-id <variable_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the variable, referenced within the API tool request as {name}. Letters, digits and underscores only, at most 64 characters.\"\n flag \"--description <description>\" help=\"A description of the variable, used by the agent to determine what value to provide.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete variable\" {\n flag \"--variable-id <variable_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n }\n}\ncmd \"transcript\" help=\"Search and read conversation transcripts\" {\n cmd \"search\" help=\"Search transcripts\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--take <take>\" help=\"Page size, 1 to 50. There is no `limit`. Page with `skip` while `hasMore` is true.\" default=20\n flag \"--skip <skip>\" help=\"The number of results to skip, used for pagination.\" default=0\n flag \"--start-date <start_date>\" help=\"Only transcripts created at or after this day (`2026-06-01`, from 00:00 UTC) or ISO 8601 timestamp.\"\n flag \"--end-date <end_date>\" help=\"Only transcripts created at or before this day (`2026-06-30`, to 23:59:59.999 UTC) or ISO 8601 timestamp.\"\n flag \"--version-param <version_param>\" help=\"When provided, only transcripts from the draft or published version of the environment are returned. `published` covers the current release and every past release. Applies within a single environment; the main environment is used when `environmentAlias` is omitted. (options: draft, published)\"\n flag \"--filters <filters>\" help=\"list of values\"\n flag \"--session-id <session_id>\" help=\"When provided, only transcripts from this conversation session are returned.\"\n flag \"--environment-alias <environment_alias>\" help=\"When provided, only transcripts from the environment with this alias are returned.\"\n flag \"--release-name <release_name>\" help=\"When provided, only transcripts from the release with this exact name (e.g. `V1.02`) are returned, as listed in the `releases` of the environment. When several releases share the name, transcripts from all of them are returned. Applies within a single environment; the main environment is used when `environmentAlias` is omitted. Cannot be combined with `version: \\\"draft\\\"`.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"grep\" help=\"Grep transcripts\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--pattern <pattern>\" help=\"Regex (case-insensitive) or plain text to find in the dialogue. A pattern may hold one open quantifier (*, +, ?, {n,} or {n,m}), no backreference and no alternation inside a group. Use exact counts such as \\\\d{3}, or put the alternation at the top level: refund|return. Any other pattern runs as plain text, and the result says so. [required]\"\n flag \"--transcript-ids <transcript_ids...>\" help=\"Transcripts to scan. Leave it out to scan the newest transcripts in the date range.\" var=#true\n flag \"--start-date <start_date>\" help=\"Lower bound when no transcriptIDs are given: a day or a timestamp.\"\n flag \"--end-date <end_date>\" help=\"Upper bound when no transcriptIDs are given: a day or a timestamp.\"\n flag \"--environment-alias <environment_alias>\" help=\"Only transcripts from this environment, when no transcriptIDs are given.\"\n flag \"--limit <limit>\" help=\"How many transcripts to scan at most, 1 to 60.\" default=25\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get transcript\" {\n flag \"--transcript-id <transcript_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--format-param <format_param>\" help=\"`summary` (default): the turns, the tool calls and a turn count. `formatted`: every turn with the debug traces and the first system prompt of each agent. `logs`: the raw log entries, which can be very large. (options: summary, formatted, logs)\" default=\"summary\"\n flag \"--filter-conversation\" help=\"boolean flag\"\n flag \"--custom-trace-types <custom_trace_types>\" help=\"string | array of string\"\n }\n cmd \"files\" help=\"List transcript files\" {\n flag \"--transcript-id <transcript_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"query-logs\" help=\"Query transcript logs\" {\n alias \"ql\"\n flag \"--transcript-id <transcript_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--kinds <kinds...>\" help=\"Keep only entries of these kinds. Omit to keep every kind.\" var=#true\n flag \"--levels <levels...>\" help=\"Keep only entries at these levels, for example [\\\"fatal\\\", \\\"error\\\", \\\"warn\\\"] for what went wrong.\" var=#true\n flag \"--debug-kinds <debug_kinds...>\" help=\"Keep only debug entries of these kinds. Setting it leaves out every entry that is not a debug log.\" var=#true\n flag \"--turns <turns>\" help=\"Keep only entries of these turns. Turn 0 holds anything logged before the first input.\"\n flag \"--search <search>\" help=\"Keep only entries whose message or recorded data contains this text, ignoring case. It is plain text, not a regular expression. Separate alternatives with |, as in \\\"timeout|denied\\\", to keep entries that contain any of them.\"\n flag \"--detail <detail>\" help=\"options: summary, full\" default=\"summary\"\n flag \"--limit <limit>\" help=\"The most entries to return in one page.\" default=50\n flag \"--offset <offset>\" help=\"How many matching entries to skip, for paging.\" default=0\n flag \"--order <order>\" help=\"options: asc, desc\" default=\"asc\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"property\" help=\"Manage the properties that tag transcripts\" {\n cmd \"list\" help=\"List properties\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create property\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--name <name>\" help=\"[required]\"\n flag \"--type <type>\" help=\"The type of value the property holds. (options: boolean, number, string) [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get property\" {\n flag \"--property-id <property_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update property\" {\n flag \"--property-id <property_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--name <name>\" help=\"string value\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete property\" {\n flag \"--property-id <property_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"set-value\" help=\"Set property value\" {\n alias \"sv\"\n flag \"--property-id <property_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--value <value>\" help=\"The value to set for the property on the transcript. [required]\"\n flag \"--transcript-id <transcript_id>\" help=\"The ID of the transcript to set the property value on. [required]\"\n flag \"--metadata <metadata>\" help=\"Additional structured data to record alongside the value. Omit or pass `null` to record none.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n }\n}\ncmd \"function\" help=\"Write, run and manage functions\" {\n cmd \"list\" help=\"List functions\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create function\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"[required]\"\n flag \"--code <code>\" help=\"The JavaScript source code executed when the function runs. [required]\"\n flag \"--settings <settings>\" help=\"JSON object\"\n flag \"--description <description>\" help=\"A human-readable description of what the function does.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get function\" {\n flag \"--function-id <function_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update function\" {\n flag \"--function-id <function_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"string value\"\n flag \"--code <code>\" help=\"The JavaScript source code executed when the function runs.\"\n flag \"--settings <settings>\" help=\"JSON object\"\n flag \"--path-order <path_order...>\" help=\"An ordered list of path IDs controlling the display order of the function's exit paths.\" var=#true\n flag \"--description <description>\" help=\"A human-readable description of what the function does.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete function\" {\n flag \"--function-id <function_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"patch-code\" help=\"Patch function code\" {\n alias \"pc\"\n flag \"--function-id <function_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--old-string <old_string>\" help=\"The exact code to replace, copied verbatim from the function's code as a get returned it. Matching is literal: whitespace, indentation, quotes and case must match. Include enough neighbouring code that it occurs once. [required]\"\n flag \"--new-string <new_string>\" help=\"The code to put in its place. May be empty to delete. [required]\"\n flag \"--replace-all\" help=\"Replace every occurrence. When false, more than one match is an error rather than a guess.\" default=#false\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get-schema\" help=\"Get function schema\" {\n alias \"gs\"\n flag \"--function-id <function_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"execute\" help=\"Execute function\" {\n flag \"--function-id <function_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--inputs <inputs>\" help=\"A value for each of the function's input variables, keyed by input name. Every declared input needs a value, and a name the function does not declare is refused. List them with get_schema.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"check\" help=\"Check function\" {\n flag \"--function-id <function_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--cases <cases>\" help=\"[required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"variable\" help=\"Manage a function's variables\" {\n cmd \"list\" help=\"List variables\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--function-id <function_id>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create variable\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name used to reference the variable in the function code. [required]\"\n flag \"--type <type>\" help=\"options: input, output [required]\"\n flag \"--function-id <function_id>\" help=\"The ID of the function this variable belongs to. [required]\"\n flag \"--description <description>\" help=\"A human-readable description of what the variable holds.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get variable\" {\n flag \"--variable-id <variable_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update variable\" {\n flag \"--variable-id <variable_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name used to reference the variable in the function code.\"\n flag \"--description <description>\" help=\"A human-readable description of what the variable holds.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete variable\" {\n flag \"--variable-id <variable_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n }\n cmd \"path\" help=\"Manage a function's paths\" {\n cmd \"list\" help=\"List paths\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--function-id <function_id>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create path\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the exit path, referenced by the function code when returning which path to take. [required]\"\n flag \"--function-id <function_id>\" help=\"The ID of the function this path belongs to. [required]\"\n flag \"--label <label>\" help=\"The display label shown for this path in the Voiceflow UI; falls back to `name` when null.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get path\" {\n flag \"--path-id <path_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update path\" {\n flag \"--path-id <path_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the exit path, referenced by the function code when returning which path to take.\"\n flag \"--label <label>\" help=\"The display label shown for this path in the Voiceflow UI; falls back to `name` when null.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete path\" {\n flag \"--path-id <path_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n }\n}\ncmd \"evaluation\" help=\"Create and run evaluations that score transcripts\" {\n cmd \"list\" help=\"List evaluations\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create evaluation\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ type: string, truePrompt: string, falsePrompt: string, name: string, ... } | { type: string, minimumValue: number, maximumValue: number, minimumPrompt: string, ... } | { type: string, name: string, prompt: string, enabled: boolean, ... } | { type: string, options: object[], name: string, prompt: string, ... }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get evaluation\" {\n flag \"--evaluation-id <evaluation_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update evaluation\" {\n flag \"--evaluation-id <evaluation_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ truePrompt: string, falsePrompt: string, name: string, prompt: string, ... } | { minimumValue: number, maximumValue: number, minimumPrompt: string, maximumPrompt: string, ... } | { name: string, prompt: string, enabled: boolean, settings: object, ... } | { options: object[], name: string, prompt: string, enabled: boolean, ... }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete evaluation\" {\n flag \"--evaluation-id <evaluation_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"run\" help=\"Run evaluation\" {\n flag \"--evaluation-id <evaluation_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--transcript-id <transcript_id>\" help=\"The ID of the transcript to run the evaluation against. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"queue-runs\" help=\"Queue evaluation runs\" {\n alias \"qr\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--evaluation-ids <evaluation_ids...>\" help=\"The evaluations to run, 1 to 10. Every evaluation runs against every transcript. [required]\" var=#true\n flag \"--transcript-ids <transcript_ids...>\" help=\"The transcripts to score, 1 to 100. [required]\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n}\ncmd \"document\" help=\"Manage knowledge base documents and sitemaps\" {\n cmd \"list\" help=\"List documents\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--sitemap-document-id <sitemap_document_id>\" help=\"string value\"\n }\n cmd \"list-changes\" help=\"List document changes\" {\n alias \"lc\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--from <from>\" help=\"[required]\"\n flag \"--to <to>\" help=\"[required]\"\n flag \"--sitemap-document-id <sitemap_document_id>\" help=\"string value\"\n flag \"--type <type>\" help=\"options: added, updated, removed\"\n flag \"--cursor <cursor>\" help=\"string value\"\n flag \"--limit <limit>\" help=\"integer value\"\n }\n cmd \"create-url\" help=\"Create URL document\" {\n alias \"cu\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--max-chunk-size <max_chunk_size>\" help=\"string | number\"\n flag \"--overwrite <overwrite>\" help=\"boolean | StableDocumentController_createURL_overwrite_enum\"\n flag \"--markdown-conversion <markdown_conversion>\" help=\"boolean | StableDocumentController_createURL_markdownConversion_enum\"\n flag \"--llm-based-chunks <llm_based_chunks>\" help=\"boolean | StableDocumentController_createURL_llmBasedChunks_enum\"\n flag \"--llm-generated-q <llm_generated_q>\" help=\"boolean | StableDocumentController_createURL_llmGeneratedQ_enum\"\n flag \"--llm-content-summarization <llm_content_summarization>\" help=\"boolean | StableDocumentController_createURL_llmContentSummarization_enum\"\n flag \"--llm-prepend-context <llm_prepend_context>\" help=\"boolean | StableDocumentController_createURL_llmPrependContext_enum\"\n flag \"--single-chunk <single_chunk>\" help=\"boolean | StableDocumentController_createURL_singleChunk_enum\"\n flag \"--url <url>\" help=\"The URL of the web page to crawl and ingest into the knowledge base. [required]\"\n flag \"--metadata <metadata>\" help=\"Metadata tags attached to the document, used to filter knowledge base retrieval at runtime.\"\n flag \"--refresh-rate <refresh_rate>\" help=\"How often the URL is automatically re-crawled to refresh the document content. (options: daily, weekly, monthly, never)\"\n flag \"--folder-id <folder_id>\" help=\"The ID of the Knowledge Base folder to file the document under. Without it, a new document starts at the top level and a document this overwrites keeps its folder; move one to the top level with `folderID: null` on the document update. File names and URLs are unique across the whole Knowledge Base, not per folder, so an overwrite replaces the one document with that name or URL and, with `folderID`, moves it into this folder.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"create-text\" help=\"Create text document\" {\n alias \"cte\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--max-chunk-size <max_chunk_size>\" help=\"string | number\"\n flag \"--overwrite <overwrite>\" help=\"boolean | StableDocumentController_createText_overwrite_enum\"\n flag \"--markdown-conversion <markdown_conversion>\" help=\"boolean | StableDocumentController_createText_markdownConversion_enum\"\n flag \"--llm-based-chunks <llm_based_chunks>\" help=\"boolean | StableDocumentController_createText_llmBasedChunks_enum\"\n flag \"--llm-generated-q <llm_generated_q>\" help=\"boolean | StableDocumentController_createText_llmGeneratedQ_enum\"\n flag \"--llm-content-summarization <llm_content_summarization>\" help=\"boolean | StableDocumentController_createText_llmContentSummarization_enum\"\n flag \"--llm-prepend-context <llm_prepend_context>\" help=\"boolean | StableDocumentController_createText_llmPrependContext_enum\"\n flag \"--single-chunk <single_chunk>\" help=\"boolean | StableDocumentController_createText_singleChunk_enum\"\n flag \"--url <url>\" help=\"An optional source URL to associate with the uploaded document.\"\n flag \"--can-edit\" help=\"If true, the document content can be edited in the Creator after upload.\" default=#false\n flag \"--metadata <metadata>\" help=\"A JSON-encoded array of `{ key, values }` metadata tags attached to the document, used to filter knowledge base retrieval at runtime.\"\n flag \"--folder-id <folder_id>\" help=\"The ID of the Knowledge Base folder to file the document under. Without it, a new document starts at the top level and a document this overwrites keeps its folder; move one to the top level with `folderID: null` on the document update. File names and URLs are unique across the whole Knowledge Base, not per folder, so an overwrite replaces the one document with that name or URL and, with `folderID`, moves it into this folder.\"\n flag \"--file <file>\" help=\"Path to file to upload\"\n }\n cmd \"create-table\" help=\"Create table document\" {\n alias \"ct\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--max-chunk-size <max_chunk_size>\" help=\"string | number\"\n flag \"--overwrite <overwrite>\" help=\"boolean | StableDocumentController_createTable_overwrite_enum\"\n flag \"--markdown-conversion <markdown_conversion>\" help=\"boolean | StableDocumentController_createTable_markdownConversion_enum\"\n flag \"--llm-based-chunks <llm_based_chunks>\" help=\"boolean | StableDocumentController_createTable_llmBasedChunks_enum\"\n flag \"--llm-generated-q <llm_generated_q>\" help=\"boolean | StableDocumentController_createTable_llmGeneratedQ_enum\"\n flag \"--llm-content-summarization <llm_content_summarization>\" help=\"boolean | StableDocumentController_createTable_llmContentSummarization_enum\"\n flag \"--llm-prepend-context <llm_prepend_context>\" help=\"boolean | StableDocumentController_createTable_llmPrependContext_enum\"\n flag \"--single-chunk <single_chunk>\" help=\"boolean | StableDocumentController_createTable_singleChunk_enum\"\n flag \"--url <url>\" help=\"An optional source URL to associate with the table document.\"\n flag \"--name <name>\" help=\"[required]\"\n flag \"--items <items>\" help=\"The table rows to ingest; each row is a flat object and becomes its own chunk. [required]\"\n flag \"--schema <schema>\" help=\"Declares which top-level keys of each row are full-text searchable versus row-level metadata. [required]\"\n flag \"--metadata <metadata>\" help=\"Metadata tags attached to the document, used to filter knowledge base retrieval at runtime.\"\n flag \"--folder-id <folder_id>\" help=\"The ID of the Knowledge Base folder to file the document under. Without it, a new document starts at the top level and a document this overwrites keeps its folder; move one to the top level with `folderID: null` on the document update. File names and URLs are unique across the whole Knowledge Base, not per folder, so an overwrite replaces the one document with that name or URL and, with `folderID`, moves it into this folder.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"preview-sitemap\" help=\"Preview sitemap URLs\" {\n alias \"ps\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--sitemap-url <sitemap_url>\" help=\"The HTTPS URL of the sitemap to read. A bare site URL works too — when it does not end in `.xml`, `/sitemap.xml`, `/sitemap_index.xml` and `/sitemap/sitemap.xml` are probed in turn. [required]\"\n flag \"--exclude <exclude...>\" help=\"Patterns that drop a URL from the import when any one of them matches. Matching is case-insensitive and unanchored: a pattern with no `*` matches any URL containing it as a substring (`/blog/`), while `*` matches any run of characters (`*/tag/*`, `*.pdf`).\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"create-sitemap\" help=\"Create documents from sitemap\" {\n alias \"cs\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--markdown-conversion <markdown_conversion>\" help=\"boolean | StableDocumentController_createSitemap_markdownConversion_enum\"\n flag \"--llm-based-chunks <llm_based_chunks>\" help=\"boolean | StableDocumentController_createSitemap_llmBasedChunks_enum\"\n flag \"--llm-generated-q <llm_generated_q>\" help=\"boolean | StableDocumentController_createSitemap_llmGeneratedQ_enum\"\n flag \"--llm-content-summarization <llm_content_summarization>\" help=\"boolean | StableDocumentController_createSitemap_llmContentSummarization_enum\"\n flag \"--llm-prepend-context <llm_prepend_context>\" help=\"boolean | StableDocumentController_createSitemap_llmPrependContext_enum\"\n flag \"--single-chunk <single_chunk>\" help=\"boolean | StableDocumentController_createSitemap_singleChunk_enum\"\n flag \"--sitemap-url <sitemap_url>\" help=\"The HTTPS URL of the sitemap to read. A bare site URL works too — when it does not end in `.xml`, `/sitemap.xml`, `/sitemap_index.xml` and `/sitemap/sitemap.xml` are probed in turn. [required]\"\n flag \"--exclude <exclude...>\" help=\"Patterns that drop a URL from the import when any one of them matches. Matching is case-insensitive and unanchored: a pattern with no `*` matches any URL containing it as a substring (`/blog/`), while `*` matches any run of characters (`*/tag/*`, `*.pdf`).\" var=#true\n flag \"--metadata <metadata>\" help=\"Metadata tags attached to the document, used to filter knowledge base retrieval at runtime.\"\n flag \"--refresh-rate <refresh_rate>\" help=\"How often the URL is automatically re-crawled to refresh the document content. (options: daily, weekly, monthly, never)\" default=\"never\"\n flag \"--folder-id <folder_id>\" help=\"The ID of the Knowledge Base folder to file every document the import creates or reuses under. Without it, new documents start at the top level and reused ones keep their folder.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"create-managed-sitemap\" help=\"Create managed sitemap\" {\n alias \"cms\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--markdown-conversion <markdown_conversion>\" help=\"boolean | StableDocumentController_createManagedSitemap_markdownConversion_enum\"\n flag \"--llm-based-chunks <llm_based_chunks>\" help=\"boolean | StableDocumentController_createManagedSitemap_llmBasedChunks_enum\"\n flag \"--llm-generated-q <llm_generated_q>\" help=\"boolean | StableDocumentController_createManagedSitemap_llmGeneratedQ_enum\"\n flag \"--llm-content-summarization <llm_content_summarization>\" help=\"boolean | StableDocumentController_createManagedSitemap_llmContentSummarization_enum\"\n flag \"--llm-prepend-context <llm_prepend_context>\" help=\"boolean | StableDocumentController_createManagedSitemap_llmPrependContext_enum\"\n flag \"--single-chunk <single_chunk>\" help=\"boolean | StableDocumentController_createManagedSitemap_singleChunk_enum\"\n flag \"--sitemap-url <sitemap_url>\" help=\"The HTTPS URL of the sitemap to read. A bare site URL works too — when it does not end in `.xml`, `/sitemap.xml`, `/sitemap_index.xml` and `/sitemap/sitemap.xml` are probed in turn. [required]\"\n flag \"--patterns <patterns>\" help=\"Which of the pages the sitemap lists it keeps. Matching is case-insensitive and unanchored: a pattern with no `*` matches any URL containing it as a substring (`/blog/`), while `*` matches any run of characters (`*/tag/*`, `*.pdf`).\"\n flag \"--refresh-rate <refresh_rate>\" help=\"How often the sitemap is re-read to add the pages it newly lists and remove the ones it no longer does. Its pages are re-crawled on the same schedule. (options: daily, weekly, monthly, never)\" default=\"never\"\n flag \"--metadata <metadata>\" help=\"Metadata tags attached to the sitemap and to every page it imports, used to filter knowledge base retrieval at runtime.\"\n flag \"--folder-id <folder_id>\" help=\"The ID of the Knowledge Base folder to file the sitemap and the pages it imports under. Omit to create them at the top level.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"update-managed-sitemap\" help=\"Update managed sitemap\" {\n alias \"ums\"\n flag \"--document-id <document_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--patterns <patterns>\" help=\"Replaces the stored patterns whole, so send both lists even when changing one. Matching is case-insensitive and unanchored: a pattern with no `*` matches any URL containing it as a substring (`/blog/`), while `*` matches any run of characters (`*/tag/*`, `*.pdf`).\"\n flag \"--refresh-rate <refresh_rate>\" help=\"How often the sitemap is re-read to add the pages it newly lists and remove the ones it no longer does. Its pages are re-crawled on the same schedule. Also applied to the pages it has already imported. (options: daily, weekly, monthly, never)\"\n flag \"--markdown-conversion <markdown_conversion>\" help=\"boolean | StableDocumentUpdateManagedSitemapRequest_markdownConversion_enum\"\n flag \"--llm-based-chunks <llm_based_chunks>\" help=\"boolean | StableDocumentUpdateManagedSitemapRequest_llmBasedChunks_enum\"\n flag \"--llm-generated-q <llm_generated_q>\" help=\"boolean | StableDocumentUpdateManagedSitemapRequest_llmGeneratedQ_enum\"\n flag \"--llm-content-summarization <llm_content_summarization>\" help=\"boolean | StableDocumentUpdateManagedSitemapRequest_llmContentSummarization_enum\"\n flag \"--llm-prepend-context <llm_prepend_context>\" help=\"boolean | StableDocumentUpdateManagedSitemapRequest_llmPrependContext_enum\"\n flag \"--single-chunk <single_chunk>\" help=\"boolean | StableDocumentUpdateManagedSitemapRequest_singleChunk_enum\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get document\" {\n flag \"--document-id <document_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"delete\" help=\"Delete document\" {\n flag \"--document-id <document_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update document\" {\n flag \"--document-id <document_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--metadata <metadata>\" help=\"Replaces the document's metadata tags. Leave it out to keep them.\"\n flag \"--folder-id <folder_id>\" help=\"The ID of the Knowledge Base folder to move the document into, or null to move it to the top level. Leave it out to keep its folder.\"\n flag \"--content <content>\" help=\"The whole new text of a text or markdown document. It replaces the stored text; the document keeps its ID and name and is processed again. Refused for every other document type.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"folder\" help=\"Organize knowledge base documents into folders\" {\n cmd \"list\" help=\"List document folders\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create document folder\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the folder. [required]\"\n flag \"--parent-id <parent_id>\" help=\"The ID of the folder to nest this folder in. Omit or pass null for a top-level folder.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"update\" help=\"Update document folder\" {\n flag \"--folder-id <folder_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the folder.\"\n flag \"--parent-id <parent_id>\" help=\"The ID of the folder to move this folder into, or null to move it to the top level. Omit it to keep the folder where it is.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete document folder\" {\n flag \"--folder-id <folder_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n }\n}\ncmd \"integration\" help=\"Connect integrations and use their tools\" {\n cmd \"list\" help=\"List integrations\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"connect\" help=\"Connect integration\" {\n flag \"--integration <integration>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ integration: string, credentials: string } | { integration: string, credentials: object } | { integration: string }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"disconnect\" help=\"Disconnect integration\" {\n flag \"--integration <integration>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"get-schema\" help=\"Get integration tool schemas\" {\n alias \"gs\"\n flag \"--integration <integration>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"add-tool\" help=\"Add integration tool\" {\n alias \"at\"\n flag \"--integration <integration>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--tool-name <tool_name>\" help=\"The catalog tool to add, as get_schema lists it, such as `google_sheets_update_spreadsheet`. It must belong to the integration in the path. (options: example_dynamic_schema, zendesk_find_user, zendesk_find_group, zendesk_find_ticket, zendesk_create_ticket, zendesk_update_ticket, zendesk_add_ticket_comment, zendesk_update_organization, zendesk_find_latest_comment, salesforce_create_lead, salesforce_update_lead, salesforce_create_contact, salesforce_update_contact, salesforce_create_case, salesforce_update_case, salesforce_add_comment_to_case, shopify_get_products, shopify_get_order, shopify_cancel_order, shopify_update_order, google_sheets_create_spreadsheet, google_sheets_update_spreadsheet, google_sheets_read_spreadsheet, google_sheets_append_spreadsheet, google_sheets_read_row, google_gmail_send_email, airtable_create_records, airtable_delete_records, airtable_get_record, airtable_list_records, airtable_update_records, make_run_scenario, twilio_send_sms, hubspot_create_contact, hubspot_create_lead, hubspot_create_ticket, kustomer_find_customer, kustomer_create_customer, kustomer_update_customer, kustomer_find_conversation, kustomer_find_customer_conversations, kustomer_create_conversation, kustomer_update_conversation, kustomer_add_conversation_note, kustomer_add_conversation_tags, kustomer_find_latest_message, kustomer_find_team, kustomer_update_company) [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"execute\" help=\"Execute integration tool\" {\n flag \"--integration <integration>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--tool-name <tool_name>\" help=\"The catalog tool to run, as get_schema lists it, such as `zendesk_find_ticket`. It must belong to the integration in the path. (options: example_dynamic_schema, zendesk_find_user, zendesk_find_group, zendesk_find_ticket, zendesk_create_ticket, zendesk_update_ticket, zendesk_add_ticket_comment, zendesk_update_organization, zendesk_find_latest_comment, salesforce_create_lead, salesforce_update_lead, salesforce_create_contact, salesforce_update_contact, salesforce_create_case, salesforce_update_case, salesforce_add_comment_to_case, shopify_get_products, shopify_get_order, shopify_cancel_order, shopify_update_order, google_sheets_create_spreadsheet, google_sheets_update_spreadsheet, google_sheets_read_spreadsheet, google_sheets_append_spreadsheet, google_sheets_read_row, google_gmail_send_email, airtable_create_records, airtable_delete_records, airtable_get_record, airtable_list_records, airtable_update_records, make_run_scenario, twilio_send_sms, hubspot_create_contact, hubspot_create_lead, hubspot_create_ticket, kustomer_find_customer, kustomer_create_customer, kustomer_update_customer, kustomer_find_conversation, kustomer_find_customer_conversations, kustomer_create_conversation, kustomer_update_conversation, kustomer_add_conversation_note, kustomer_add_conversation_tags, kustomer_find_latest_message, kustomer_find_team, kustomer_update_company) [required]\"\n flag \"--inputs <inputs>\" help=\"The tool's inputs, keyed by input name and typed as get_schema says. A top-level string value follows the ExecuteInputString rules, so {secret_name} inserts a project secret. Secrets work only at the top level: inside a nested object or array, {secret_name} is sent as written and no secret is filled in.\"\n flag \"--extended-input-variables <extended_input_variables>\" help=\"Provider metadata the tool editor stored for this tool, such as Zendesk custom field IDs. Omit it unless you are replaying an editor run.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n}\ncmd \"mcp-server\" help=\"Manage the MCP servers an agent connects to\" {\n alias \"ms\"\n cmd \"list\" help=\"List MCP servers\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create MCP server\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"[required]\"\n flag \"--description <description>\" help=\"A human-readable description of what the MCP server provides.\"\n flag \"--url <url>\" help=\"Plain text resolved at runtime and never shown to a model. {variable_name} inserts a variable or entity, {secret_name} a project secret, {variable_name.path} a field of a variable. Escape a literal { or \\\\ with a backslash. When a name is both a variable and a secret, the secret wins. A name matching none is stored as literal text and reported in unresolvedReferences. Where the field is sent to an upstream system, an unresolved placeholder may be sent as literal text; on an MCP server it is re-resolved by name at connect time, so a literal that matches a real secret binds. [required]\"\n flag \"--headers <headers>\" help=\"list of values\"\n flag \"--specification <specification>\" help=\"options: 2025-03-26, 2025-06-18\" default=\"2025-06-18\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get MCP server\" {\n flag \"--server-id <server_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update MCP server\" {\n flag \"--server-id <server_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"string value\"\n flag \"--description <description>\" help=\"A human-readable description of what the MCP server provides.\"\n flag \"--specification <specification>\" help=\"options: 2025-03-26, 2025-06-18\"\n flag \"--url <url>\" help=\"string value\"\n flag \"--headers <headers>\" help=\"list of values\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete MCP server\" {\n flag \"--server-id <server_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"sync\" help=\"Sync MCP server\" {\n flag \"--server-id <server_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n}\ncmd \"mcp-tool\" help=\"List, inspect and run MCP server tools\" {\n alias \"mt\"\n cmd \"list\" help=\"List MCP tools\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--server-id <server_id>\" help=\"string value\"\n }\n cmd \"get\" help=\"Get MCP tool\" {\n flag \"--tool-id <tool_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"get-schema\" help=\"Get MCP tool schema\" {\n alias \"gs\"\n flag \"--tool-id <tool_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"execute\" help=\"Execute MCP tool\" {\n flag \"--tool-id <tool_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--inputs <inputs>\" help=\"The tool's arguments, keyed by argument name and typed as its JSON Schema says; see get_schema. A top-level string value follows the ExecuteInputString rules, so {secret_name} inserts a project secret. Secrets work only at the top level: inside a nested object or array, {secret_name} is sent as written and no secret is filled in.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n}\ncmd \"secret\" help=\"Manage secrets and their values\" {\n cmd \"list\" help=\"List secrets\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create secret\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the secret. Letters, digits and underscores only, at most 64 characters — this is what a {token} in a default-value field binds to. Must be unique within the project. [required]\"\n flag \"--default-value <default_value>\" help=\"The secret's value, written to the `main` environment's published version, the one serving live traffic. It cannot be empty. Omit it to create the secret as a placeholder with no value — a teammate can fill it in later through the Voiceflow UI or CLI.\"\n flag \"--visibility <visibility>\" help=\"Whether the value can be revealed in the Voiceflow UI. `restricted` secrets can never be read back by anyone. (options: restricted, masked)\" default=\"masked\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"list-overrides\" help=\"List secret overrides\" {\n alias \"lo\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"delete\" help=\"Delete secret\" {\n flag \"--secret-id <secret_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n cmd \"set-value\" help=\"Set secret value\" {\n alias \"sv\"\n flag \"--secret-id <secret_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--value <value>\" help=\"The secret value to store. Write-only — it can never be read back through this API. [required]\"\n flag \"--environment-alias <environment_alias>\" help=\"The alias of the environment to write (e.g. `staging`). Without it the value goes to the `main` environment. Requires `versionVariant`.\"\n flag \"--version-variant <version_variant>\" help=\"Which version of the environment to write: `published`, the version serving live traffic, or `draft`, the one used when testing. Required with `environmentAlias`. Without `environmentAlias` it defaults to `published`, and `draft` writes the `main` environment's draft version; a project with no `main` environment has no draft version, so the request is then handled as if `versionVariant` were omitted. (options: draft, published)\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n}\ncmd \"knowledge-base\" help=\"Query the knowledge base\" {\n alias \"kb\"\n cmd \"query\" help=\"Query knowledge base\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--version-param <version_param>\" help=\"Whether to query the draft or the published version of the knowledge base. (options: draft, published) [required]\"\n flag \"--filters <filters>\" help=\"Metadata filters used to narrow down which document chunks are searched.\"\n flag \"--question <question>\" help=\"The natural-language question to ask the knowledge base. [required]\"\n flag \"--settings <settings>\" help=\"JSON object\"\n flag \"--synthesis\" help=\"Whether to synthesize an answer from the retrieved chunks; when false, only raw chunks are returned.\"\n flag \"--chunk-limit <chunk_limit>\" help=\"The maximum number of document chunks to retrieve.\"\n flag \"--instruction <instruction>\" help=\"An additional instruction applied when synthesizing the answer from the retrieved chunks.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n}\ncmd \"conversation\" help=\"Talk to an agent: send messages, run scripts\" {\n cmd \"send\" help=\"Send\" {\n flag \"--user-id <user_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--action <action>\" help=\"{ type: string, payload: object, diagramID: string, time: number, ... } | { type: string, payload: string, diagramID: string, time: number, ... } | { type: string, diagramID: string, time: number, metadata: object, ... } | { type: string, payload: value, diagramID: string, time: number, ... }\"\n flag \"--version-param <version_param>\" help=\"Whether to run the conversation against the draft or published version of the environment. (options: draft, published) [required]\"\n flag \"--session-id <session_id>\" help=\"The unique ID of the conversation session to continue.\"\n flag \"--config-param <config_param>\" help=\"Options controlling how the response is shaped.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"run-script\" help=\"Run script\" {\n alias \"rs\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--messages <messages>\" help=\"The user messages to send, in order, after the launch. A message is typed text, as a string or { \\\"text\\\": \\\"…\\\" }, or a button press, as { \\\"button\\\": \\\"<label>\\\" }, for a button the reply before offered. The digest shows offered buttons as \\\"[buttons: Yes | No]\\\". [required]\"\n flag \"--variables <variables>\" help=\"Variable values to set before the launch, keyed by variable name, to start as a known caller. Next to messages, not inside launch.\"\n flag \"--version-param <version_param>\" help=\"Whether to talk to the draft or the published version of the environment. Draft unless you pass it. (options: draft, published)\" default=\"draft\"\n flag \"--launch <launch>\" help=\"How the conversation starts; payload is its only field. Leave it out for a plain launch.\"\n flag \"--user-id <user_id>\" help=\"The conversation user ID to run as; the agent reads it as the user_id variable. Use it when the agent expects a caller ID of a known shape, such as a phone number, and make one up: never a real customer's ID. Draft version only. Leave it out to run as a new user each time. A reused ID keeps the variables an earlier conversation with it left.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"state\" help=\"Read and change a user's conversation state\" {\n cmd \"get\" help=\"Get state\" {\n flag \"--user-id <user_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--version-param <version_param>\" help=\"options: draft, published [required]\"\n }\n cmd \"update\" help=\"Update state\" {\n flag \"--user-id <user_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--version-param <version_param>\" help=\"options: draft, published [required]\"\n flag \"--stack <stack>\" help=\"The execution stack for the conversation, from root to innermost frame. [required]\"\n flag \"--storage <storage>\" help=\"Internal runtime storage persisted across turns of the session. [required]\"\n flag \"--variables <variables>\" help=\"The current values of the agent variables for this session. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete state\" {\n flag \"--user-id <user_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--version-param <version_param>\" help=\"options: draft, published [required]\"\n }\n cmd \"update-variables\" help=\"Update variables\" {\n alias \"uv\"\n flag \"--user-id <user_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--version-param <version_param>\" help=\"options: draft, published [required]\"\n flag \"--variables <variables>\" help=\"Variable values to set on the conversation session, keyed by variable name. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n }\n}\ncmd \"credits\" help=\"Check whether a project has credits left to run\" {\n cmd \"get\" help=\"Get credits\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n }\n}\ncmd \"analytics\" help=\"See how agents are used: calls, tokens, tools\" {\n cmd \"query\" help=\"Query calls, token use, and tool and document use\" {\n cmd \"call-count\" help=\"Query call count\" {\n alias \"cc\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--interval <interval>\" help=\"options: hour, day, week, month [required]\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"call-duration\" help=\"Query call duration\" {\n alias \"cd\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--interval <interval>\" help=\"options: hour, day, week, month [required]\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"workspace-transcript-count\" help=\"Query workspace transcript count\" {\n alias \"wtc\"\n flag \"--workspace-id <workspace_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--project-ids <project_ids...>\" help=\"The IDs of the projects to filter results by. Defaults to all projects in the workspace.\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"project-transcript-count\" help=\"Query project transcript count\" {\n alias \"ptco\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--interval <interval>\" help=\"options: hour, day, week, month [required]\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"project-transcript-cost\" help=\"Query transcript cost\" {\n alias \"ptc\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--interval <interval>\" help=\"options: hour, day, week, month [required]\"\n flag \"--usage-class <usage_class>\" help=\"options: Host, Build, Test, Monitor\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"workspace-interaction-count\" help=\"Query workspace interaction count\" {\n alias \"wic\"\n flag \"--workspace-id <workspace_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--project-ids <project_ids...>\" help=\"The IDs of the projects to filter results by. Defaults to all projects in the workspace.\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"project-interaction-count\" help=\"Query project interaction count\" {\n alias \"pic\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--interval <interval>\" help=\"options: hour, day, week, month [required]\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"organization-token-usage\" help=\"Query organization token usage\" {\n alias \"otu\"\n flag \"--organization-id <organization_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--workspace-ids <workspace_ids...>\" help=\"list of values\" var=#true\n flag \"--project-ids <project_ids...>\" help=\"The IDs of the projects to filter results by. Defaults to all projects in the workspace.\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"workspace-token-usage\" help=\"Query workspace token usage\" {\n alias \"wtu\"\n flag \"--workspace-id <workspace_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--project-ids <project_ids...>\" help=\"The IDs of the projects to filter results by. Defaults to all projects in the workspace.\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"project-token-usage\" help=\"Query project token usage\" {\n alias \"ptu\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--interval <interval>\" help=\"options: hour, day, week, month [required]\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"hourly-organization-token-usage\" help=\"Query hourly organization token usage\" {\n alias \"hotu\"\n flag \"--organization-id <organization_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--workspace-ids <workspace_ids...>\" help=\"list of values\" var=#true\n flag \"--project-ids <project_ids...>\" help=\"The IDs of the projects to filter results by. Defaults to all projects in the workspace.\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"hourly-project-token-usage\" help=\"Query hourly project token usage\" {\n alias \"hptu\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--interval <interval>\" help=\"options: hour, day, week, month [required]\"\n flag \"--usage-class <usage_class>\" help=\"options: Host, Build, Test, Monitor\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"daily-token-usage\" help=\"Query daily token usage\" {\n alias \"dtu\"\n flag \"--organization-id <organization_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--workspace-ids <workspace_ids...>\" help=\"list of values\" var=#true\n flag \"--project-ids <project_ids...>\" help=\"The IDs of the projects to filter results by. Defaults to all projects in the workspace.\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"entity-token-usage\" help=\"Query entity token usage\" {\n alias \"etu\"\n flag \"--organization-id <organization_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"category-token-usage\" help=\"Query category token usage\" {\n alias \"ctu\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--interval <interval>\" help=\"options: hour, day, week, month [required]\"\n flag \"--usage-class <usage_class>\" help=\"options: Host, Build, Test, Monitor\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"playbook-usage\" help=\"Query playbook usage\" {\n alias \"pu\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--exclude-id <exclude_id...>\" help=\"list of values\" var=#true\n flag \"--limit <limit>\" help=\"number value\" default=10\n flag \"--order-direction <order_direction>\" help=\"options: ASC, DESC\"\n flag \"--order-by <order_by>\" help=\"options: count, averageLatencyMS\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"workflow-usage\" help=\"Query workflow usage\" {\n alias \"wu\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--exclude-id <exclude_id...>\" help=\"list of values\" var=#true\n flag \"--limit <limit>\" help=\"number value\" default=10\n flag \"--order-direction <order_direction>\" help=\"options: ASC, DESC\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"prompt-usage\" help=\"Query prompt usage\" {\n alias \"pus\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--exclude-id <exclude_id...>\" help=\"list of values\" var=#true\n flag \"--limit <limit>\" help=\"number value\" default=10\n flag \"--order-direction <order_direction>\" help=\"options: ASC, DESC\"\n flag \"--order-by <order_by>\" help=\"options: count, averageLatencyMS\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"intent-usage\" help=\"Query intent usage\" {\n alias \"ius\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--exclude-id <exclude_id...>\" help=\"list of values\" var=#true\n flag \"--limit <limit>\" help=\"number value\" default=10\n flag \"--order-direction <order_direction>\" help=\"options: ASC, DESC\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"function-usage\" help=\"Query function usage\" {\n alias \"fu\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--exclude-id <exclude_id...>\" help=\"list of values\" var=#true\n flag \"--limit <limit>\" help=\"number value\" default=10\n flag \"--order-direction <order_direction>\" help=\"options: ASC, DESC\"\n flag \"--order-by <order_by>\" help=\"options: count, averageLatencyMS\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"api-tool-usage\" help=\"Query API tool usage\" {\n alias \"atu\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--exclude-id <exclude_id...>\" help=\"list of values\" var=#true\n flag \"--limit <limit>\" help=\"number value\" default=10\n flag \"--order-direction <order_direction>\" help=\"options: ASC, DESC\"\n flag \"--order-by <order_by>\" help=\"options: count, averageLatencyMS\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"mcp-tool-usage\" help=\"Query MCP tool usage\" {\n alias \"mtu\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--exclude-id <exclude_id...>\" help=\"list of values\" var=#true\n flag \"--limit <limit>\" help=\"number value\" default=10\n flag \"--order-direction <order_direction>\" help=\"options: ASC, DESC\"\n flag \"--order-by <order_by>\" help=\"options: count, averageLatencyMS\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"knowledge-base-document-usage\" help=\"Query knowledge base document usage\" {\n alias \"kbdu\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--exclude-id <exclude_id...>\" help=\"list of values\" var=#true\n flag \"--limit <limit>\" help=\"number value\" default=10\n flag \"--order-direction <order_direction>\" help=\"options: ASC, DESC\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"integration-usage\" help=\"Query integration usage\" {\n alias \"iu\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--exclude-id <exclude_id...>\" help=\"list of values\" var=#true\n flag \"--limit <limit>\" help=\"number value\" default=10\n flag \"--order-direction <order_direction>\" help=\"options: ASC, DESC\"\n flag \"--order-by <order_by>\" help=\"options: count, averageLatencyMS\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"unique-user-count\" help=\"Query unique user count\" {\n alias \"uuc\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--interval <interval>\" help=\"options: hour, day, week, month [required]\"\n flag \"--version-param <version_param>\" help=\"Filters results to the draft or published version of the environment. Defaults to both. (options: draft, published)\"\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"objective-metrics\" help=\"Query objective metrics\" {\n alias \"om\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--end-date <end_date>\" help=\"[required]\"\n flag \"--start-date <start_date>\" help=\"[required]\"\n flag \"--timezone <timezone>\" help=\"string value\"\n flag \"--version-scope <version_scope>\" help=\"Restrict the results to published versions: the live version and release history of `projectEnvironmentID`, or of every environment when it is omitted. The server resolves the versions, so the request size does not grow with each publish. Takes precedence over `versionIDs` and `environmentID` when the agent has published versions. (options: published)\"\n flag \"--interfaces <interfaces...>\" help=\"The channels to filter results by. Defaults to all channels.\" var=#true\n flag \"--environment-alias <environment_alias>\" help=\"The ID or alias of the environment to filter results by. Defaults to all environments.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n }\n}\ncmd \"test\" help=\"Build and run agent tests\" {\n cmd \"list\" help=\"List tests\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create test\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"[required]\"\n flag \"--settings <settings>\" help=\"JSON object\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get test\" {\n flag \"--test-id <test_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update test\" {\n flag \"--test-id <test_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"string value\"\n flag \"--settings <settings>\" help=\"JSON object\"\n flag \"--turn-order <turn_order...>\" help=\"The IDs of the test's turns, in execution order.\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete test\" {\n flag \"--test-id <test_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"turn\" help=\"Manage the turns of a test conversation\" {\n cmd \"list\" help=\"List turns\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--test-id <test_id>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create turn\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ type: string, testID: string, payload: object }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get turn\" {\n flag \"--turn-id <turn_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update turn\" {\n flag \"--turn-id <turn_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ type: string, payload: object } | { type: string, payload: object, checkOrder: string[] }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete turn\" {\n flag \"--turn-id <turn_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n }\n cmd \"check\" help=\"Manage the checks a test makes\" {\n cmd \"list\" help=\"List checks\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--turn-id <turn_id>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create check\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ type: string, turnID: string, payload: value } | { type: string, turnID: string, payload: object }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get check\" {\n flag \"--check-id <check_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update check\" {\n flag \"--check-id <check_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--body-param <body_param>\" help=\"{ type: string, payload: value } | { type: string, payload: object }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete check\" {\n flag \"--check-id <check_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n }\n cmd \"folder\" help=\"List the folders tests are kept in\" {\n cmd \"list\" help=\"List test folders\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n }\n cmd \"run\" help=\"Run tests, wait for results and read their logs\" {\n cmd \"search\" help=\"Search runs\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--take <take>\" help=\"The maximum number of results to return, used for pagination.\" default=20\n flag \"--skip <skip>\" help=\"The number of results to skip, used for pagination.\" default=0\n flag \"--test-id <test_id>\" help=\"Restrict results to runs of this test. Omit to search across all tests.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"create\" help=\"Create run\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--test-id <test_id>\" help=\"The ID of the test to run. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"create-suite\" help=\"Run test suite\" {\n alias \"cs\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--all\" help=\"Run every test in the environment. Pass exactly one of `all`, `testIDs` and `folderIDs`.\"\n flag \"--test-ids <test_ids...>\" help=\"Run these tests, one run each, with no limit on how many. Pass exactly one of `all`, `testIDs` and `folderIDs`.\" var=#true\n flag \"--folder-ids <folder_ids...>\" help=\"Run every test in these folders and in every folder nested under them. Pass exactly one of `all`, `testIDs` and `folderIDs`.\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"cancel\" help=\"Cancel runs\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--run-ids <run_ids...>\" help=\"The IDs of the runs to cancel. [required]\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"wait\" help=\"Wait for runs\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--run-ids <run_ids...>\" help=\"The runs to wait for: the IDs create_run or create_many_runs returned (each run's `id`, not its `testID`). [required]\" var=#true\n flag \"--timeout-seconds <timeout_seconds>\" help=\"How long to wait at most, in seconds: 45 by default, 120 at most.\" default=45\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"wait-suite\" help=\"Wait for test suite\" {\n alias \"ws\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--bulk-id <bulk_id>\" help=\"The `bulkID` that starting the suite returned. [required]\"\n flag \"--timeout-seconds <timeout_seconds>\" help=\"How long to wait at most, in seconds: 45 by default, 120 at most.\" default=45\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get run\" {\n flag \"--run-id <run_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"query-logs\" help=\"Query run logs\" {\n alias \"ql\"\n flag \"--run-id <run_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--kinds <kinds...>\" help=\"Keep only entries of these kinds. Omit to keep every kind.\" var=#true\n flag \"--levels <levels...>\" help=\"Keep only entries at these levels, for example [\\\"fatal\\\", \\\"error\\\", \\\"warn\\\"] for what went wrong.\" var=#true\n flag \"--debug-kinds <debug_kinds...>\" help=\"Keep only debug entries of these kinds. Setting it leaves out every entry that is not a debug log.\" var=#true\n flag \"--turns <turns>\" help=\"Keep only entries of these turns. Turn 0 holds anything logged before the first input.\"\n flag \"--search <search>\" help=\"Keep only entries whose message or recorded data contains this text, ignoring case. It is plain text, not a regular expression. Separate alternatives with |, as in \\\"timeout|denied\\\", to keep entries that contain any of them.\"\n flag \"--detail <detail>\" help=\"options: summary, full\" default=\"summary\"\n flag \"--limit <limit>\" help=\"The most entries to return in one page.\" default=50\n flag \"--offset <offset>\" help=\"How many matching entries to skip, for paging.\" default=0\n flag \"--order <order>\" help=\"options: asc, desc\" default=\"asc\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n }\n}\ncmd \"persona\" help=\"Manage personas, sets of preset variable values\" {\n cmd \"list\" help=\"List personas\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create persona\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the persona. Must not already be used by another persona in this environment. [required]\"\n flag \"--items <items>\" help=\"The variable values this persona presets. On update this replaces the whole list: send every item the persona should keep. An item read back with a null variable cannot be kept: leave it out, or name an existing variable in its place.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get persona\" {\n flag \"--persona-id <persona_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update persona\" {\n flag \"--persona-id <persona_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The name of the persona. Must not already be used by another persona in this environment.\"\n flag \"--items <items>\" help=\"The variable values this persona presets. On update this replaces the whole list: send every item the persona should keep. An item read back with a null variable cannot be kept: leave it out, or name an existing variable in its place.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete persona\" {\n flag \"--persona-id <persona_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n}\ncmd \"widget\" help=\"Configure the web chat widget and get its snippet\" {\n cmd \"get\" help=\"Get widget\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update widget\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--type <type>\" help=\"Switches the embed between the text `chat` surface and the click-to-call `voice` surface. The surface you switch away from is kept as it was, so switching back later restores it. (options: chat, voice)\"\n flag \"--chat <chat>\" help=\"Chat-surface fields to change, merged one level deep into the stored `chat` block: what you send replaces its stored counterpart and everything else is kept. A nested object (`banner`, `headerImage`, `disclaimer`, `csat`, …) replaces the stored one outright, so send it complete. `placeholderText` and `aiDisclaimer` need the Webchat Premium entitlement and `disclaimer` the widget-security one: without it the whole request is refused with 403 and nothing is written, including the other fields sent alongside it.\"\n flag \"--voice <voice>\" help=\"Voice-surface fields to change, merged one level deep into the stored `voice` block. `content` is a nested object: it replaces the stored one outright, so send every line of call-screen copy, not just the one you are changing.\"\n flag \"--common <common>\" help=\"Shared-chrome fields to change, merged one level deep into the stored `common` block. A nested object (`launcher`, `footerLink`) replaces the stored one outright, so send it complete. `primaryColor` is the exception and merges too: send `color` on its own to recolor the widget and the shade palette is regenerated from it, send `palette` on its own to hand-tune the shades against the stored color, or send both together. `poweredBy`, `fontFamily`, `footerLink` and `primaryColor.palette` need the Webchat Premium entitlement — `primaryColor.color` on its own does not — and without it the whole request is refused with 403 and nothing is written, including the other fields sent alongside it.\"\n flag \"--security <security>\" help=\"Replaces the stored security block in full — unlike the other blocks it has no partial form. Requires a plan entitlement: without one the whole request is refused with 403 and nothing is written, including the other fields sent alongside it.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get-snippet\" help=\"Get widget snippet\" {\n alias \"gs\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--version-param <version_param>\" help=\"Pins the embed to one version of the environment: `draft`, the version used when testing, or `published`, the version serving live traffic. Omit it to pin the snippet to `published`. (options: draft, published)\" default=\"published\"\n }\n}\ncmd \"phone-number\" help=\"Manage phone numbers and assign them to projects\" {\n alias \"pn\"\n cmd \"list\" help=\"List phone numbers\" {\n flag \"--project-id <project_id>\" help=\"string value\"\n flag \"--workspace-id <workspace_id>\" help=\"string value\"\n }\n cmd \"create\" help=\"Create phone number\" {\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get phone number\" {\n flag \"--phone-number-id <phone_number_id>\" help=\"[required]\"\n flag \"--workspace-id <workspace_id>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update phone number\" {\n flag \"--phone-number-id <phone_number_id>\" help=\"[required]\"\n flag \"--workspace-id <workspace_id>\" help=\"[required]\"\n flag \"--name <name>\" help=\"The display name of the number within the workspace. Callers never see it. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete phone number\" {\n flag \"--phone-number-id <phone_number_id>\" help=\"[required]\"\n flag \"--workspace-id <workspace_id>\" help=\"[required]\"\n }\n cmd \"assign\" help=\"Assign phone number\" {\n flag \"--phone-number-id <phone_number_id>\" help=\"[required]\"\n flag \"--workspace-id <workspace_id>\" help=\"[required]\"\n flag \"--target <target>\" help=\"Which side of the number to point at the project: `voice` for incoming calls, `sms` for incoming SMS. The other side is left as it was. (options: sms, voice) [required]\"\n flag \"--version-param <version_param>\" help=\"Which version of the environment answers: `published`, the one serving live traffic, or `draft`, the working copy. Requires `environmentAlias`. Defaults to `published`. (options: draft, published)\"\n flag \"--project-id <project_id>\" help=\"The ID of the project the number should reach. [required]\"\n flag \"--environment-alias <environment_alias>\" help=\"The alias of the environment that should answer (e.g. `main`). Omit it to assign the number to the project without pinning an environment, which also clears a pin a previous assign set.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"unassign\" help=\"Unassign phone number\" {\n flag \"--phone-number-id <phone_number_id>\" help=\"[required]\"\n flag \"--workspace-id <workspace_id>\" help=\"[required]\"\n flag \"--target <target>\" help=\"Which side of the number to clear: `voice` or `sms`. Omit it to clear both. Clearing a side that is not assigned is refused. (options: sms, voice)\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n}\ncmd \"event\" help=\"Manage the events clients can send to the agent\" {\n cmd \"list\" help=\"List events\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"create\" help=\"Create event\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--description <description>\" help=\"What the event is for. Null when none was written.\"\n flag \"--name <name>\" help=\"The display name of the event. Must not match another event in this environment, ignoring case. [required]\"\n flag \"--request-name <request_name>\" help=\"The name a client sends to trigger the event, as payload.event.name of an `event` request. Letters, digits, underscores and $ only, at most 64 characters. Must not be used by another event in this environment. Defaults to the name with spaces turned into underscores and other characters dropped.\"\n flag \"--goes-to <goes_to>\" help=\"What the agent does when the event arrives. `flow` runs the workflow named by workflowID. `global_agent` hands the conversation back to the agent to decide what to do next, and is only valid in an agent project. `continue` carries on the conversation where it was, for an event that only updates user info. (options: flow, global_agent, continue) [required]\"\n flag \"--workflow-id <workflow_id>\" help=\"The workflow to run, as a workflow ID from voiceflow_workflow.list. Required when goesTo is `flow`; leave it out for any other goesTo.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get\" help=\"Get event\" {\n flag \"--event-id <event_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"update\" help=\"Update event\" {\n flag \"--event-id <event_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--description <description>\" help=\"What the event is for. Null when none was written.\"\n flag \"--name <name>\" help=\"The display name of the event. Must not match another event in this environment, ignoring case. Renaming does not change requestName.\"\n flag \"--request-name <request_name>\" help=\"The name a client sends to trigger the event. Letters, digits, underscores and $ only, at most 64 characters. Must not be used by another event in this environment. Changing it breaks any client still sending the old name.\"\n flag \"--goes-to <goes_to>\" help=\"options: flow, global_agent, continue\"\n flag \"--workflow-id <workflow_id>\" help=\"The workflow to run, as a workflow ID from voiceflow_workflow.list. Only valid while goesTo is `flow`. Changing goesTo away from `flow` clears it.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete\" help=\"Delete event\" {\n flag \"--event-id <event_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n}\ncmd \"billing\" help=\"Check an organization's plan, limits and credits\" {\n cmd \"subscription\" help=\"Get an organization's subscription and plan\" {\n cmd \"get\" help=\"Get subscription\" {\n flag \"--organization-id <organization_id>\" help=\"[required]\"\n }\n }\n cmd \"credits\" help=\"Check credits used this billing period\" {\n cmd \"get\" help=\"Get credits\" {\n flag \"--organization-id <organization_id>\" help=\"[required]\"\n }\n }\n cmd \"limits\" help=\"Check plan limits against current usage\" {\n cmd \"get\" help=\"Get limits\" {\n flag \"--organization-id <organization_id>\" help=\"[required]\"\n }\n }\n}\ncmd \"configure\" help=\"Configure authentication credentials and preferences\"\ncmd \"whoami\" help=\"Display current authentication configuration\"\ncmd \"version\" help=\"Print the CLI version\"\n", "agent": "cmd \"agent\" help=\"Configure the agent's instructions, prompt and voice\" {\n cmd \"get\" help=\"Get agent\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--include-instructions\" help=\"boolean flag\" default=#false\n flag \"--include-prompt\" help=\"boolean flag\" default=#false\n }\n cmd \"update\" help=\"Update agent\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--prompt <prompt>\" help=\"string value\"\n flag \"--end-tool <end_tool>\" help=\"JSON object\"\n flag \"--card-tool <card_tool>\" help=\"JSON object\"\n flag \"--playbooks <playbooks>\" help=\"Playbooks available for the agent to invoke. This list REPLACES the registry: send the complete list you want, or omit the field to leave routing untouched. An agent with no playbooks AND no workflows registered cannot run - the runtime fails the conversation - so never send an empty list unless `workflows` still holds at least one.\"\n flag \"--workflows <workflows>\" help=\"Workflows available for the agent to invoke. This list REPLACES the registry: send the complete list you want, or omit the field to leave routing untouched. An agent with no workflows AND no playbooks registered cannot run, so never send an empty list unless `playbooks` still holds at least one.\"\n flag \"--button-tool <button_tool>\" help=\"JSON object\"\n flag \"--carousel-tool <carousel_tool>\" help=\"JSON object\"\n flag \"--instructions <instructions>\" help=\"string value\"\n flag \"--skip-turn-tool <skip_turn_tool>\" help=\"JSON object\"\n flag \"--path-tool-order <path_tool_order...>\" help=\"The ordered list of path tool IDs that controls the order of the agent exit paths.\" var=#true\n flag \"--web-search-tool <web_search_tool>\" help=\"JSON object\"\n flag \"--call-forward-tool <call_forward_tool>\" help=\"JSON object\"\n flag \"--knowledge-base-tool <knowledge_base_tool>\" help=\"JSON object\"\n flag \"--include-guidelines\" help=\"Whether to append the default prompting guidelines to the global prompt.\"\n flag \"--llm <llm>\" help=\"JSON object\"\n flag \"--voice <voice>\" help=\"JSON object\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"add-workflow\" help=\"Add agent workflow\" {\n alias \"aw\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--condition <condition>\" help=\"The agent can run the workflow only while this condition holds. Leave it out for a workflow it can always run.\"\n flag \"--description <description>\" help=\"When the agent should run this workflow. The agent reads it to choose between its playbooks and workflows. [required]\"\n flag \"--required-variables <required_variables>\" help=\"Variables the agent fills from the conversation before it runs the workflow, each with a description of what it holds.\"\n flag \"--workflow-id <workflow_id>\" help=\"The workflow to add. Copy its ID from voiceflow_workflow.list. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"update-workflow\" help=\"Update agent workflow\" {\n alias \"uw\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--condition <condition>\" help=\"The agent can run the workflow only while this condition holds. Leave it out for a workflow it can always run.\"\n flag \"--description <description>\" help=\"When the agent should run this workflow. The agent reads it to choose between its playbooks and workflows.\"\n flag \"--required-variables <required_variables>\" help=\"Replaces the stored list. Keep the id of each variable you keep, as read with voiceflow_agent.get. Leave the field out to keep the stored required variables.\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"remove-workflow\" help=\"Remove agent workflow\" {\n alias \"rw\"\n flag \"--workflow-id <workflow_id>\" help=\"[required]\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"read-instructions\" help=\"Read agent instructions\" {\n alias \"ri\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--offset <offset>\" help=\"integer value\" default=1\n flag \"--limit <limit>\" help=\"integer value\" default=400\n }\n cmd \"patch-instructions\" help=\"Patch agent instructions\" {\n alias \"pi\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--old-string <old_string>\" help=\"The exact text to replace, copied verbatim from a read or search result. Matching is literal — whitespace, punctuation and case must match. Do not include the line numbers a read adds. [required]\"\n flag \"--new-string <new_string>\" help=\"The text to put in its place. May be empty to delete. [required]\"\n flag \"--replace-all\" help=\"Replace every occurrence. When false, more than one match is an error rather than a guess.\" default=#false\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"search-instructions\" help=\"Search agent instructions\" {\n alias \"si\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--pattern <pattern>\" help=\"A JavaScript regular expression, evaluated against each line on its own. [required]\"\n flag \"--ignore-case\" help=\"Match case-insensitively. Defaults to false, like grep.\" default=#false\n flag \"--context-lines <context_lines>\" help=\"How many lines either side of each match to return.\" default=0\n flag \"--limit <limit>\" help=\"The maximum number of matching LINES to return. The reported totals cover the whole document.\" default=50\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"read-prompt\" help=\"Read the global prompt\" {\n alias \"rp\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--offset <offset>\" help=\"integer value\" default=1\n flag \"--limit <limit>\" help=\"integer value\" default=400\n }\n cmd \"patch-prompt\" help=\"Patch the global prompt\" {\n alias \"pp\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--old-string <old_string>\" help=\"The exact text to replace, copied verbatim from a read or search result. Matching is literal — whitespace, punctuation and case must match. Do not include the line numbers a read adds. [required]\"\n flag \"--new-string <new_string>\" help=\"The text to put in its place. May be empty to delete. [required]\"\n flag \"--replace-all\" help=\"Replace every occurrence. When false, more than one match is an error rather than a guess.\" default=#false\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"search-prompt\" help=\"Search the global prompt\" {\n alias \"sp\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--pattern <pattern>\" help=\"A JavaScript regular expression, evaluated against each line on its own. [required]\"\n flag \"--ignore-case\" help=\"Match case-insensitively. Defaults to false, like grep.\" default=#false\n flag \"--context-lines <context_lines>\" help=\"How many lines either side of each match to return.\" default=0\n flag \"--limit <limit>\" help=\"The maximum number of matching LINES to return. The reported totals cover the whole document.\" default=50\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"add-tool-message\" help=\"Add agent tool message\" {\n alias \"atm\"\n flag \"--project-id <project_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--environment-alias <environment_alias>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--slot <slot>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: delay, failure, execution, completion) [required]\"\n flag \"--tool-id <tool_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected.\"\n flag \"--native-tool <native_tool>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: endTool, cardTool, buttonTool, carouselTool, webSearchTool, callForwardTool, knowledgeBaseTool)\"\n flag \"--body-param <body_param>\" help=\"{ type: string, examples: string[] } | { type: string, messageID: string }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"update-tool-message\" help=\"Update agent tool message\" {\n alias \"utm\"\n flag \"--project-id <project_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--environment-alias <environment_alias>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--slot <slot>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: delay, failure, execution, completion) [required]\"\n flag \"--tool-id <tool_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected.\"\n flag \"--native-tool <native_tool>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: endTool, cardTool, buttonTool, carouselTool, webSearchTool, callForwardTool, knowledgeBaseTool)\"\n flag \"--body-param <body_param>\" help=\"{ type: string, examples: string[] } | { type: string, messageID: string }\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"delete-tool-message\" help=\"Delete agent tool message\" {\n alias \"dtm\"\n flag \"--project-id <project_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--environment-alias <environment_alias>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. [required]\"\n flag \"--slot <slot>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: delay, failure, execution, completion) [required]\"\n flag \"--tool-id <tool_id>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected.\"\n flag \"--native-tool <native_tool>\" help=\"Addresses one message on one tool. Exactly one of toolID and nativeTool is required; sending neither or both is rejected. (options: endTool, cardTool, buttonTool, carouselTool, webSearchTool, callForwardTool, knowledgeBaseTool)\"\n }\n cmd \"patch-pronunciation\" help=\"Patch pronunciation dictionary\" {\n alias \"ppr\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--set <set>\" help=\"Words to add, or to change when the dictionary already has them. `from` is the written word and `to` is how the voice says it; an empty `to` makes the voice skip the word.\"\n flag \"--remove <remove...>\" help=\"Written words whose entries to delete.\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"search-voices\" help=\"Search voices\" {\n alias \"sv\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--search <search>\" help=\"string value\"\n flag \"--language <language>\" help=\"string value\"\n flag \"--provider <provider>\" help=\"A TTS provider whose voices are in the voice catalog. (options: elevenlabs, cartesia)\"\n flag \"--gender <gender>\" help=\"How the vendor describes the voice. (options: male, female, neutral)\"\n flag \"--limit <limit>\" help=\"integer value\" default=10\n flag \"--offset <offset>\" help=\"integer value\" default=0\n }\n cmd \"patch-voices\" help=\"Patch voices\" {\n alias \"pv\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--primary <primary>\" help=\"The default voice: the one a conversation speaks with unless a language voice matches its locale.\"\n flag \"--set-overrides <set_overrides>\" help=\"Language voices to add, or to change when the agent already has one for that locale.\"\n flag \"--remove-overrides <remove_overrides...>\" help=\"Locales whose language voice to delete, as stored. They match ignoring case and _, as the runtime matches them.\" var=#true\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n cmd \"get-initialization-workflow\" help=\"Get initialization workflow\" {\n alias \"giw\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n }\n cmd \"set-initialization-workflow\" help=\"Set initialization workflow\" {\n alias \"siw\"\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--workflow-id <workflow_id>\" help=\"The workflow to run before the user's first turn, or null to run none. [required]\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n }\n}\n", "agent get": "cmd \"get\" help=\"Get agent\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--include-instructions\" help=\"boolean flag\" default=#false\n flag \"--include-prompt\" help=\"boolean flag\" default=#false\n}\n", "agent update": "cmd \"update\" help=\"Update agent\" {\n flag \"--project-id <project_id>\" help=\"[required]\"\n flag \"--environment-alias <environment_alias>\" help=\"[required]\"\n flag \"--prompt <prompt>\" help=\"string value\"\n flag \"--end-tool <end_tool>\" help=\"JSON object\"\n flag \"--card-tool <card_tool>\" help=\"JSON object\"\n flag \"--playbooks <playbooks>\" help=\"Playbooks available for the agent to invoke. This list REPLACES the registry: send the complete list you want, or omit the field to leave routing untouched. An agent with no playbooks AND no workflows registered cannot run - the runtime fails the conversation - so never send an empty list unless `workflows` still holds at least one.\"\n flag \"--workflows <workflows>\" help=\"Workflows available for the agent to invoke. This list REPLACES the registry: send the complete list you want, or omit the field to leave routing untouched. An agent with no workflows AND no playbooks registered cannot run, so never send an empty list unless `playbooks` still holds at least one.\"\n flag \"--button-tool <button_tool>\" help=\"JSON object\"\n flag \"--carousel-tool <carousel_tool>\" help=\"JSON object\"\n flag \"--instructions <instructions>\" help=\"string value\"\n flag \"--skip-turn-tool <skip_turn_tool>\" help=\"JSON object\"\n flag \"--path-tool-order <path_tool_order...>\" help=\"The ordered list of path tool IDs that controls the order of the agent exit paths.\" var=#true\n flag \"--web-search-tool <web_search_tool>\" help=\"JSON object\"\n flag \"--call-forward-tool <call_forward_tool>\" help=\"JSON object\"\n flag \"--knowledge-base-tool <knowledge_base_tool>\" help=\"JSON object\"\n flag \"--include-guidelines\" help=\"Whether to append the default prompting guidelines to the global prompt.\"\n flag \"--llm <llm>\" help=\"JSON object\"\n flag \"--voice <voice>\" help=\"JSON object\"\n flag \"--body <body>\" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin.\"\n}\n", @@ -477,6 +477,7 @@ func selectedCommandPath(cmd *cobra.Command) []string { func EmitSchema(cmd *cobra.Command, w io.Writer) error { path := strings.Join(selectedCommandPath(cmd), " ") if schema, ok := usageSchemas[path]; ok { + schema = withOwnHelp(cmd, schema) // ownhelp.go: flags whose help vf writes _, err := io.WriteString(w, schema) return err } diff --git a/test/agent-mode-flag.test.ts b/test/agent-mode-flag.test.ts index 3e72c5eb..d7cba61a 100644 --- a/test/agent-mode-flag.test.ts +++ b/test/agent-mode-flag.test.ts @@ -66,7 +66,7 @@ describe('--agent-mode', () => { it('turns agent mode off under an agent', async () => { const result = await run([...NO_TOKEN, '--agent-mode=false'], { CLAUDECODE: '1' }); - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(3); // not signed in expect(isEnvelope(result.stderr), result.stderr).toBe(false); expect(result.stderr).toContain("you're not signed in"); }); @@ -74,7 +74,7 @@ describe('--agent-mode', () => { it('turns agent mode on outside an agent', async () => { const result = await run([...NO_TOKEN, '--agent-mode']); - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(3); // not signed in expect(isEnvelope(result.stderr), result.stderr).toBe(true); expect(JSON.parse(result.stderr).error_type).toBe('authentication_error'); }); @@ -96,7 +96,7 @@ describe('--agent-mode', () => { { CLAUDECODE: '1' }, ); - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(2); // a usage error expect(isEnvelope(result.stderr), result.stderr).toBe(false); expect(result.stderr).toContain('invalid value for --llm'); }); diff --git a/test/docs-command.test.ts b/test/docs-command.test.ts index 98e975b7..2fc63660 100644 --- a/test/docs-command.test.ts +++ b/test/docs-command.test.ts @@ -57,7 +57,7 @@ describe('vf docs get', () => { it('refuses non-voiceflow URLs', async () => { const result = await $vf(['docs', 'get', 'https://example.com/docs/page']); - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(2); // a bad argument, refused before any request expect(result.stderr).toContain('voiceflow.com/docs'); }); @@ -73,7 +73,7 @@ describe('vf docs get', () => { ]; for (const url of hostile) { const result = await $vf(['docs', 'get', url]); - expect(result.exitCode, `must block: ${url}`).toBe(1); + expect(result.exitCode, `must block: ${url}`).toBe(2); expect(result.stderr, `must not fetch: ${url}`).not.toContain('GOTCHA'); } }); diff --git a/test/dry-run.test.ts b/test/dry-run.test.ts index 9a355911..46897c15 100644 --- a/test/dry-run.test.ts +++ b/test/dry-run.test.ts @@ -109,7 +109,7 @@ describe('--dry-run', () => { it('still fails when the request cannot be built', async () => { const result = await dryRun(['tool', 'create', '--project-id', 'p', '--environment-alias', 'main']); - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(2); // a usage error: nothing was sent expect(result.stderr).not.toContain(PREVIEWED); expect(result.stderr).toContain("the request wasn't sent"); }); diff --git a/test/error-envelope.test.ts b/test/error-envelope.test.ts new file mode 100644 index 00000000..ef10cdf5 --- /dev/null +++ b/test/error-envelope.test.ts @@ -0,0 +1,183 @@ +// Tests for the one JSON shape every error has (internal/output/envelope.go), +// in agent mode and with -o json, whether vf found the problem itself or the +// API answered with it. +// +// An API error used to be its response body with vf's keys mixed in, so the +// top-level keys were whatever the API sent, and vf's status_code sat next to +// the body's own statusCode: "statusCode": 422 beside "status_code": 400 on +// every validation failure the API answers with HTTP 400. Local errors had +// their own keys, and with -o json outside agent mode they were plain text. +// +// Uses a local mock API. Requires: go build -o vf ./cmd/vf + +import { execa } from 'execa'; +import * as http from 'node:http'; +import type { AddressInfo } from 'node:net'; +import * as path from 'node:path'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +const VF = path.resolve(__dirname, '..', 'vf'); + +// Mirrors the list in internal/output/agentmode.go. +const AGENT_ENV_VARS = [ + 'CLAUDECODE', 'CLAUDE_CODE', 'CURSOR_AGENT', 'CODEX', 'AIDER', 'CLINE', + 'WINDSURF_AGENT', 'GITHUB_COPILOT', 'AMAZON_Q', 'GEMINI_CODE_ASSIST', + 'SRC_CODY', 'FORCE_AGENT_MODE', +]; + +// Keys every error has, and the only other keys the envelope itself uses. +const ALWAYS = ['error', 'error_type', 'exit_code', 'message', 'hints']; +const SOMETIMES = ['explanation', 'details', 'docs_url', 'status_code', 'body']; + +let server: http.Server; +let serverURL: string; + +beforeAll(async () => { + server = http.createServer((req, res) => { + req.resume(); + const reply = (status: number, body: object) => { + res.writeHead(status, { 'content-type': 'application/json' }); + res.end(JSON.stringify(body)); + }; + const url = req.url ?? ''; + if (url.includes('/transcript')) { + // What the API sends for --take 0: HTTP 400, and 422 in the body. + return reply(400, { + message: 'Validation failed', + details: [{ code: 'too_small', message: 'Too small: expected number to be >=1', path: ['take'] }], + statusCode: 422, + statusText: 'Unprocessable Entity', + }); + } + if (url.includes('/environment')) { + return reply(400, { error: 'Bad Request', message: "Alias 'staging' is already in use by another environment", statusCode: 400 }); + } + return reply(404, { message: 'Project not found', statusCode: 404, statusText: 'Not Found', path: '/v1/x', timestamp: '2026-11-30T00:00:00Z' }); + }); + await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve)); + serverURL = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; +}); + +afterAll(async () => { + await new Promise<void>((resolve) => server.close(() => resolve())); +}); + +function vf(args: string[], opts: { agentMode: boolean; token?: string }) { + const env: Record<string, string | undefined> = Object.fromEntries(AGENT_ENV_VARS.map((name) => [name, undefined])); + if (opts.agentMode) env.CLAUDECODE = '1'; + env.VF_TOKEN = opts.token ?? 'vfp_x'; + return execa({ reject: false, timeout: 20_000, stdin: 'ignore', env, extendEnv: true })(VF, [ + ...args, + '--server-url', serverURL, + '--no-interactive', + ]); +} + +const cases: Array<[name: string, args: string[], token?: string]> = [ + ['an API validation error', ['transcript', 'search', '--project-id', 'p1', '--take', '0']], + ['an API error whose body has its own "error"', ['environment', 'list', '--project-id', 'p1']], + ['an API 404', ['project', 'get', '--project-id', 'p1']], + ['a missing flag', ['project', 'get']], + ['an unknown flag', ['project', 'get', '--nosuch']], + ['an invalid flag value', ['agent', 'update', '--project-id', 'p', '--environment-alias', 'main', '--llm', 'not json', '--dry-run']], + ['a bad --body', ['project', 'update', '--project-id', 'p1', '--body', '{bad']], + ['no credential', ['project', 'get', '--project-id', 'p1'], ''], +]; + +describe('every error has one JSON shape', () => { + for (const [name, args, token] of cases) { + for (const mode of ['agent mode', '-o json'] as const) { + it(`${name}, in ${mode}`, async () => { + const result = mode === 'agent mode' + ? await vf(args, { agentMode: true, token }) + : await vf([...args, '--agent-mode=false', '-o', 'json'], { agentMode: false, token }); + + expect(result.exitCode).not.toBe(0); + const envelope = JSON.parse(result.stderr); + for (const key of ALWAYS) expect(envelope, `${key} in\n${result.stderr}`).toHaveProperty(key); + for (const key of Object.keys(envelope)) expect([...ALWAYS, ...SOMETIMES], `unexpected key ${key}`).toContain(key); + expect(typeof envelope.error).toBe('string'); + expect(typeof envelope.message).toBe('string'); + expect(Array.isArray(envelope.hints)).toBe(true); + expect(envelope.exit_code).toBe(result.exitCode); + }); + } + } +}); + +describe('malformed JSON input', () => { + // These said "Go value of type components.StableProjectUpdateRequest", + // "int64", or "error unmarshalling json response body" for the user's own + // flag value, and never which field was wrong. + const inputs: Array<[args: string[], error: string, type: string]> = [ + [['transcript', 'search', '--project-id', 'p1', '--body', '{"take":"ten"}'], 'invalid --body: take should be a whole number, not "ten"', 'invalid_body'], + [['project', 'update', '--project-id', 'p1', '--body', '[1,2]'], 'invalid --body: it should be an object, not a list', 'invalid_body'], + [['document', 'create-text', '--project-id', 'p1', '--environment-alias', 'main', '--max-chunk-size', 'big'], 'invalid value for --max-chunk-size: it isn\'t JSON', 'invalid_flag_value'], + [['document', 'create-text', '--project-id', 'p1', '--environment-alias', 'main', '--max-chunk-size', '{"a":1}'], 'invalid value for --max-chunk-size: it isn\'t any of the forms --max-chunk-size takes', 'invalid_flag_value'], + ]; + for (const [args, error, type] of inputs) { + it(`${args.at(-2)} ${args.at(-1)}: ${error}`, async () => { + const result = await vf([...args, '--dry-run'], { agentMode: true }); + expect(result.exitCode).toBe(2); + const envelope = JSON.parse(result.stderr); + expect(envelope.error).toBe(error); + expect(envelope.error_type).toBe(type); + expect(JSON.stringify(envelope.hints)).toMatch(/takes (an object|JSON, one of: string \| number)/); + for (const internal of ['Go value', 'response body', 'union types', 'components.', 'int64']) { + expect(result.stderr).not.toContain(internal); + } + }); + } +}); + +describe('an API error', () => { + it('has one status code, the HTTP status, and keeps the body as the API sent it', async () => { + const result = await vf(['transcript', 'search', '--project-id', 'p1', '--take', '0'], { agentMode: true }); + const envelope = JSON.parse(result.stderr); + + expect(envelope.status_code).toBe(400); + expect(envelope).not.toHaveProperty('statusCode'); + expect(envelope).not.toHaveProperty('statusText'); + expect(envelope.body).toMatchObject({ statusCode: 422, statusText: 'Unprocessable Entity', message: 'Validation failed' }); + expect(envelope.error_type).toBe('validation_error'); + expect(envelope.message).toBe('Validation failed'); + expect(envelope.details).toEqual([ + expect.objectContaining({ field: 'take', message: 'Too small: expected number to be >=1', code: 'too_small' }), + ]); + }); + + it('names the flag a refused field is set with, and the headline, as human mode does', async () => { + const args = ['transcript', 'search', '--project-id', 'p1', '--take', '0']; + const human = await vf([...args, '--agent-mode=false'], { agentMode: false }); + expect(human.stderr).toContain("Couldn't search transcripts | HTTP 400 Bad Request"); + expect(human.stderr).toContain('take: Too small: expected number to be >=1 (--take)'); + + const envelope = JSON.parse((await vf(args, { agentMode: true })).stderr); + expect(envelope.error).toBe("Couldn't search transcripts · HTTP 400 Bad Request"); + expect(envelope.details[0]).toMatchObject({ field: 'take', flag: '--take' }); + }); + + it('puts the headline in error, not the body\'s "Bad Request"', async () => { + const result = await vf(['environment', 'list', '--project-id', 'p1'], { agentMode: true }); + const envelope = JSON.parse(result.stderr); + + expect(envelope.error).toMatch(/^Couldn't .* · HTTP 400 Bad Request$/); + expect(envelope.message).toBe("Alias 'staging' is already in use by another environment"); + expect(envelope.body.error).toBe('Bad Request'); + }); + + it('keeps path and timestamp out of the top level', async () => { + const result = await vf(['project', 'get', '--project-id', 'p1'], { agentMode: true }); + const envelope = JSON.parse(result.stderr); + + expect(envelope).not.toHaveProperty('path'); + expect(envelope).not.toHaveProperty('timestamp'); + expect(envelope.body).toMatchObject({ path: '/v1/x', timestamp: '2026-11-30T00:00:00Z' }); + }); + + it('leaves <value> unescaped', async () => { + const result = await vf(['project', 'get'], { agentMode: true }); + expect(result.stderr).toContain('<value>'); + expect(result.stderr).not.toContain('\\u003c'); + }); +}); diff --git a/test/errors-teach.test.ts b/test/errors-teach.test.ts index f76fcdb9..8502d5a2 100644 --- a/test/errors-teach.test.ts +++ b/test/errors-teach.test.ts @@ -64,7 +64,7 @@ afterAll(() => { describe('no-token preflight', () => { it('fails before any network call with setup guidance', async () => { const result = await $vf(['workspace', 'list', '--server-url', 'http://127.0.0.1:1']); // unroutable — must not be contacted - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(3); // not signed in const envelope = parseEnvelope(result.stderr); expect(envelope.error_type).toBe('authentication_error'); @@ -86,7 +86,7 @@ describe('no-token preflight', () => { const result = await execa({ reject: false, env: { CLAUDECODE: '1', CLAUDE_CODE: '', VF_TOKEN: '' }, stdin: 'ignore' })( VF, ['workspace', 'list', '--server-url', 'http://127.0.0.1:1'], ); - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(3); const envelope = parseEnvelope(result.stderr); // agent-mode structured envelope, not pretty output expect(envelope.error_type).toBe('authentication_error'); }); @@ -110,7 +110,7 @@ describe('required-flag preflight', () => { it('fails locally with the exact flag name when a required path param is missing', async () => { // Unroutable server: proves the request never leaves the machine. const result = await $vf(['project', 'get', '--token', 'vfp_x', '--server-url', 'http://127.0.0.1:1']); - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(2); // a usage error const envelope = parseEnvelope(result.stderr); expect(envelope.error_type).toBe('missing_flag'); expect(envelope.error).toBe('vf project get needs --project-id'); @@ -118,11 +118,30 @@ describe('required-flag preflight', () => { expect(result.stderr).not.toContain('statusCode'); // no server round-trip happened }); + it('names every missing flag in one run, with one command line that gives them', async () => { + // It used to take a run per flag: --environment-alias, then --color-param. + const args = ['variable', 'create', '-p', 'p1', '-n', 'hi', '--token', 'vfp_x', '--server-url', 'http://127.0.0.1:1']; + const result = await $vf(args); + expect(result.exitCode).toBe(2); + const envelope = parseEnvelope(result.stderr); + expect(envelope.error).toBe('vf variable create needs --environment-alias and --color-param'); + expect(envelope.details).toEqual([ + { flag: '--environment-alias', message: 'required' }, + { flag: '--color-param', message: 'required' }, + ]); + const lines = (envelope.hints as string[]).filter((h) => h.startsWith('Pass')); + expect(lines).toEqual(["Pass them: 'vf variable create --name hi --project-id p1 --environment-alias <value> --color-param <value>'"]); + + const human = await $vf([...args, '--agent-mode=false', '--no-interactive']); + expect(human.exitCode).toBe(2); + expect(human.stderr).toContain('Error: vf variable create needs --environment-alias and --color-param'); + }); + it('is not bypassed by piped stdin on params-only commands', async () => { const result = await execa({ reject: false, env: { ...AGENT_ENV }, input: '{}' })( VF, ['project', 'get', '--token', 'vfp_x', '--server-url', 'http://127.0.0.1:1'], ); - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(2); expect(result.stderr).toContain('needs --project-id'); expect(result.stderr).not.toContain('statusCode'); }); @@ -135,14 +154,14 @@ describe('required-flag preflight', () => { ]); // The mock replies 401 — reaching it proves the body path was not blocked locally. const envelope = parseEnvelope(result.stderr); - expect(envelope.statusCode).toBe(401); + expect(envelope.status_code).toBe(401); }); }); describe('error hint injection', () => { it('injects a list-command hint and docs_url on 404', async () => { const result = await $vf(['project', 'get', '--project-id', 'missing', '--token', 'vfp_x', '--server-url', mockURL]); - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(4); // not found const envelope = parseEnvelope(result.stderr); expect(envelope.error_type).toBe('not_found'); @@ -221,7 +240,7 @@ describe('human-mode errors print once', () => { it('prints an API error once, with why and what next', async () => { const result = await human(['project', 'get', '--project-id', 'missing', '--server-url', mockURL]); - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(4); // not found expect(result.stderr).toContain("Error: Couldn't get project | HTTP 404 Not Found"); expect(result.stderr.split('Project not found').length - 1, result.stderr).toBe(1); expect(result.stderr).toContain("'vf project list' lists the IDs you can use"); @@ -237,14 +256,14 @@ describe('human-mode errors print once', () => { it('fails on a word a command group does not know, instead of printing its help', async () => { const result = await human(['workspace', 'lsit']); - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(2); // a usage error expect(result.stderr).toContain('vf workspace has no command "lsit"'); expect(result.stderr).toContain("Did you mean 'vf workspace list'?"); }); it('refuses an unusable --jq before sending a write', async () => { const result = await human(['project', 'create', '--body', '{"name":"x","workspaceID":"w","type":"webchat"}', '--server-url', mockURL, '--jq', '.[']); - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(2); // a usage error expect(result.stderr).toContain('invalid --jq expression'); expect(result.stderr).toContain("The request wasn't sent."); }); diff --git a/test/exit-codes.test.ts b/test/exit-codes.test.ts new file mode 100644 index 00000000..7bc7190a --- /dev/null +++ b/test/exit-codes.test.ts @@ -0,0 +1,124 @@ +// Tests for vf's exit codes (internal/output/exitcode.go): each kind of +// failure exits with its own code, in every mode, and in agent mode the JSON +// error says the same code as exit_code. Every failure used to exit 1, so a +// script couldn't tell a mistyped flag from a 404, a timeout or a failed test. +// +// 0 success 4 not found (404) +// 1 any other failure 5 timed out (--timeout, a wait's --max-wait) +// 2 usage error, nothing sent 6 a test run didn't pass +// 3 not signed in, 401 +// +// Uses a local mock API. Requires: go build -o vf ./cmd/vf + +import { execa } from 'execa'; +import * as http from 'node:http'; +import type { AddressInfo } from 'node:net'; +import * as path from 'node:path'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +const VF = path.resolve(__dirname, '..', 'vf'); + +// Mirrors the list in internal/output/agentmode.go. +const AGENT_ENV_VARS = [ + 'CLAUDECODE', 'CLAUDE_CODE', 'CURSOR_AGENT', 'CODEX', 'AIDER', 'CLINE', + 'WINDSURF_AGENT', 'GITHUB_COPILOT', 'AMAZON_Q', 'GEMINI_CODE_ASSIST', + 'SRC_CODY', 'FORCE_AGENT_MODE', +]; + +const waitBody = (statuses: string[]) => ({ + done: !statuses.includes('running'), + stoppedBy: 'finished', + waitedSeconds: 3, + runs: statuses.map((status, i) => ({ runID: `run${i}`, testID: 't', status, totalChecks: 1 })), +}); + +let server: http.Server; +let serverURL: string; + +beforeAll(async () => { + server = http.createServer((req, res) => { + req.resume(); + const reply = (status: number, body: object, delayMs = 0) => + setTimeout(() => { + res.writeHead(status, { 'content-type': 'application/json' }); + res.end(JSON.stringify(body)); + }, delayMs); + // The project ID is in the path or, for a test run wait, the query. + const project = /\bp-[a-z0-9]+/.exec(req.url ?? '')?.[0] ?? ''; + switch (project) { + case 'p-401': return reply(401, { statusCode: 401, message: 'Unauthorized' }); + case 'p-404': return reply(404, { statusCode: 404, message: 'Project not found' }); + case 'p-400': return reply(400, { statusCode: 400, message: 'Name is taken' }); + case 'p-500': return reply(500, { statusCode: 500, message: 'Internal server error' }); + case 'p-slow': return reply(200, {}, 3000); + case 'p-failed': return reply(200, waitBody(['passed', 'failed'])); + case 'p-going': return reply(200, waitBody(['passed', 'running'])); + case 'p-passed': return reply(200, waitBody(['passed', 'passed'])); + } + return reply(404, { statusCode: 404, message: 'Not found' }); + }); + await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve)); + serverURL = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; +}); + +afterAll(async () => { + await new Promise<void>((resolve) => server.close(() => resolve())); +}); + +function vf(args: string[], opts: { agentMode: boolean; token?: string; bare?: boolean }) { + const env: Record<string, string | undefined> = Object.fromEntries(AGENT_ENV_VARS.map((name) => [name, undefined])); + if (opts.agentMode) env.CLAUDECODE = '1'; + env.VF_TOKEN = opts.token ?? 'vfp_x'; + const extra = opts.bare ? [] : ['--server-url', serverURL, '--no-interactive']; + return execa({ reject: false, timeout: 20_000, stdin: 'ignore', env, extendEnv: true })(VF, [...args, ...extra]); +} + +const wait = (project: string) => ['test', 'run', 'wait', '--project-id', project, '--environment-alias', 'main', '--run-ids', 'run0']; + +const cases: Array<[name: string, args: string[], exitCode: number, token?: string]> = [ + ['success', wait('p-passed'), 0], + ['an unknown flag', ['project', 'list', '--nosuch'], 2], + ['an unknown command', ['project', 'lsit'], 2], + ['a missing required flag', ['project', 'get'], 2], + ['a --body that is not JSON', ['project', 'update', '--project-id', 'p-1', '--body', '{bad'], 2], + ['an invalid flag value', ['project', 'list', '--output-format', 'xml'], 2], + ['no credential', ['project', 'get', '--project-id', 'p-1'], 3, ''], + ['a 401', ['project', 'get', '--project-id', 'p-401'], 3], + ['a 404', ['project', 'get', '--project-id', 'p-404'], 4], + ['--timeout running out', ['project', 'get', '--project-id', 'p-slow', '--timeout', '300ms'], 5], + ['a wait that ran out with runs still going', wait('p-going'), 5], + ['a test run that failed', wait('p-failed'), 6], + ['a 400', ['project', 'get', '--project-id', 'p-400'], 1], + ['a 500', ['project', 'get', '--project-id', 'p-500'], 1], +]; + +describe('exit codes', () => { + for (const [name, args, exitCode, token] of cases) { + it(`${name} exits ${exitCode}, and agent mode's error JSON says so`, async () => { + const human = await vf([...args, '--agent-mode=false'], { agentMode: false, token }); + expect(human.exitCode, human.stderr).toBe(exitCode); + + const agent = await vf(args, { agentMode: true, token }); + expect(agent.exitCode, agent.stderr).toBe(exitCode); + if (exitCode !== 0) { + // The error is the last JSON object on stderr; a wait prints its + // result to stdout first. + const envelope = JSON.parse(agent.stderr.slice(agent.stderr.lastIndexOf('\n{') + 1)); + expect(envelope.exit_code, agent.stderr).toBe(exitCode); + } + }); + } + + it('-o json errors carry the same code outside agent mode', async () => { + const result = await vf(['project', 'get', '--project-id', 'p-404', '--agent-mode=false', '-o', 'json'], { agentMode: false }); + expect(result.exitCode).toBe(4); + expect(JSON.parse(result.stderr).exit_code).toBe(4); + }); + + it('are listed at the end of vf --help', async () => { + const result = await vf(['--help'], { agentMode: false, bare: true }); + expect(result.exitCode).toBe(0); + const table = result.stdout.slice(result.stdout.indexOf('Exit Codes:')); + for (const code of ['0', '1', '2', '3', '4', '5', '6']) expect(table).toMatch(new RegExp(`^ ${code} \\S`, 'm')); + }); +}); diff --git a/test/flag-errors.test.ts b/test/flag-errors.test.ts index 7c745d68..338d52d7 100644 --- a/test/flag-errors.test.ts +++ b/test/flag-errors.test.ts @@ -105,8 +105,11 @@ describe('structured flags still reject raw text', () => { assertMode(r.stderr, 'human'); expect(r.stderr).toContain('expected a JSON value'); expect(r.stderr).toContain('you passed: gpt-4'); - expect(r.stderr).toContain(`--llm '{"key":"value"}'`); - expect(r.stderr).toContain('--llm null'); + // The keys and the example come from the field's type. Null isn't + // offered: on --llm it leaves the field out rather than clearing it. + expect(r.stderr).toContain('--llm takes { priorityProcessing?: boolean, defaults?: {'); + expect(r.stderr).toContain(`for example: --llm '{"defaults":{"model":"<model>"}}'`); + expect(r.stderr).not.toContain('--llm null'); }); it('emits a structured envelope in agent mode', async () => { @@ -122,6 +125,26 @@ describe('structured flags still reject raw text', () => { /** Collapses whitespace runs, since help indents a description's later lines. */ const squash = (text: string) => text.replace(/\s+/g, ' '); +/** An API name in a description: an MCP tool or operation, or a field. */ +const API_NAME = /`?\b(?:[a-z]+(?:_[a-z]+)+(?:\.[a-z]+(?:_[a-z]+)*)?|[a-z][a-z0-9]*(?:[A-Z][A-Za-z0-9]*)+)\b`?/g; + +/** + * Matches a spec description as help shows it: backticks become quotes, and + * an API name may have become the vf command or flag for it, as + * voiceflow_workflow.list becomes 'vf workflow list' and `environmentAlias` + * --environment-alias (internal/flagutil/apinames.go). + */ +function helpPattern(description: string): RegExp { + const literal = (text: string) => squash(text.replaceAll('`', "'")).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + let pattern = ''; + let last = 0; + for (const name of description.matchAll(API_NAME)) { + pattern += `${literal(description.slice(last, name.index))}(?:${literal(name[0])}|'vf [a-z -]+'|--[\\w.-]+)`; + last = name.index + name[0].length; + } + return new RegExp(pattern + literal(description.slice(last))); +} + /** The escapes a KDL string can hold, beyond \u{...}. */ const KDL_ESCAPES: Record<string, string> = { n: '\n', r: '\r', t: '\t', b: '\b', f: '\f', s: ' ', '"': '"', '\\': '\\', '/': '/' }; @@ -235,7 +258,7 @@ describe('help shows the flag type, not a word from its description', () => { if (label !== undefined && !TYPE_LABELS.has(label)) { problems.push(`${where}: labelled "${label}"`); } - if (!squash(entry).includes(squash(description.replaceAll('`', "'")))) { + if (!helpPattern(description).test(squash(entry))) { problems.push(`${where}: description changed: ${squash(entry).trim()}`); } } @@ -258,7 +281,7 @@ describe('rejection messages are actionable, not circular', () => { it(`--${flag}: the suggested example is one the CLI accepts`, async () => { const rejected = await run([...BASE, ...extra, `--${flag}`, 'not json at all']); const suggestion = (rejected.stderr + rejected.stdout).match( - new RegExp(`expected shape: --${flag} '(.+)'`), + new RegExp(`for example: --${flag} '(.+)'`), )?.[1]; expect(suggestion, `no shape hint offered for --${flag}`).toBeDefined(); @@ -278,9 +301,10 @@ describe('rejection messages are actionable, not circular', () => { expect(r.stderr).not.toContain('the value is not valid JSON'); }); - it('surfaces what the decoder objected to, without the misleading response-body prefix', async () => { + it('says what the decoder objected to in plain words, without the misleading response-body prefix', async () => { const r = await run([...BASE, '--llm', '[1,2]']); - expect(r.stderr).toContain('cannot unmarshal array'); + expect(r.stderr).toContain('it should be an object, not a list'); + expect(r.stderr).not.toContain('Go value'); // it said "cannot unmarshal array into Go value of type map[string]jsontext.Value" // A flag value is a request that was never sent; there is no response body. expect(r.stderr).not.toContain('response body'); }); diff --git a/test/run-suite-wait.test.ts b/test/run-suite-wait.test.ts index f6ee997c..1c0940d8 100644 --- a/test/run-suite-wait.test.ts +++ b/test/run-suite-wait.test.ts @@ -171,12 +171,12 @@ describe('create-suite --wait', () => { expect(waits()[0]!.body).toEqual({ bulkID: BULK_ID, timeoutSeconds: 45 }); }); - it('exits 1 when a run failed, after printing the failed checks', async () => { + it('exits 6 when a run failed, after printing the failed checks', async () => { waitReplies = [waitReply({ total: 2, passed: 1, failed: 1, canceled: 0, unfinished: 0 }, [run('r1', 'failed')])]; const result = await vf([...SUITE_FLAGS, '--all', '--wait']); - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(6); expect(JSON.parse(result.stdout).runs[0].failedChecks[0].reason).toBe('Did not greet the user'); expect(result.stderr).toContain(`1 of 2 runs in suite ${BULK_ID} did not pass (1 failed, 0 canceled)`); expect(result.stderr).toContain(`vf test run get ${target()} --run-id <id>`); @@ -190,20 +190,21 @@ describe('create-suite --wait', () => { const result = await vf([...SUITE_FLAGS, '--all', '--wait'], { agentMode: true }); - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(6); const events = jsonStream(result.stderr); expect(events.map((event) => event.status ?? event.error_type)).toEqual(['started', 'waiting', 'test_suite_failed']); + expect(events[2]!.exit_code).toBe(6); expect(events[0]).toMatchObject({ bulkID: BULK_ID, runs: 2 }); expect(events[1]).toMatchObject({ counts: { passed: 1, unfinished: 1 } }); expect(events[2]!.message).toContain('did not pass (0 failed, 1 canceled)'); }); - it('exits 1 with the command to keep waiting when --max-wait runs out first', async () => { + it('exits 5 with the command to keep waiting when --max-wait runs out first', async () => { waitReplies = [waitReply({ total: 2, passed: 0, failed: 0, canceled: 0, unfinished: 2 }, [run('r1', 'running')])]; const result = await vf([...SUITE_FLAGS, '--all', '--wait', '--max-wait', '3s']); - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(5); expect(JSON.parse(result.stdout)).toMatchObject({ done: false, counts: { unfinished: 2 } }); expect(result.stderr).toContain(`2 of 2 runs in suite ${BULK_ID} were still going after 3s`); expect(result.stderr).toContain(`vf test run wait-suite ${target()} --bulk-id ${BULK_ID}`); @@ -239,7 +240,7 @@ describe('create-suite --wait', () => { it('refuses a --timeout no wait fits in, before starting the suite', async () => { const result = await vf([...SUITE_FLAGS, '--all', '--wait', '--timeout', '3s']); - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(2); // a usage error expect(result.stderr).toContain('--wait needs a --timeout of at least 10s'); expect(requests).toHaveLength(0); }); @@ -247,7 +248,7 @@ describe('create-suite --wait', () => { it('refuses --max-wait without --wait', async () => { const result = await vf([...SUITE_FLAGS, '--all', '--max-wait', '5m']); - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(2); expect(result.stderr).toContain('--max-wait only applies with --wait'); expect(requests).toHaveLength(0); }); @@ -269,16 +270,16 @@ describe('create-suite --wait', () => { }); it('keeps an API error structured, and says how to keep waiting rather than rerun, when a wait fails', async () => { - for (const [status, errorType] of [ - [401, 'authentication_error'], - [404, 'not_found'], + for (const [status, errorType, exitCode] of [ + [401, 'authentication_error', 3], + [404, 'not_found', 4], ] as const) { requests = []; waitReplies = [{ status, body: { statusCode: status, message: 'Nope' } }]; const result = await vf([...SUITE_FLAGS, '--all', '--wait'], { agentMode: true }); - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(exitCode); expect(waits()).toHaveLength(1); const events = jsonStream(result.stderr); expect(events.map((event) => event.status ?? event.error_type)).toEqual(['started', errorType]); @@ -293,7 +294,7 @@ describe('create-suite --wait', () => { const result = await vf([...SUITE_FLAGS, '--all', '--wait']); - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(4); expect(result.stderr).toContain('404'); expect(result.stderr).toContain(`keep waiting with: vf test run wait-suite ${target()} --bulk-id ${BULK_ID}`); }); @@ -321,7 +322,7 @@ describe('create-suite --wait', () => { const result = await vf([...SUITE_FLAGS, '--all', '--wait', '--max-wait', '4s']); - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(5); expect(waits()).toHaveLength(2); expect(result.stderr).not.toContain('Retrying'); expect(JSON.parse(result.stdout)).toMatchObject({ done: false, counts: { unfinished: 2 } }); @@ -344,7 +345,7 @@ describe('create-suite --wait', () => { for (const jq of ['.counts |||', '.counts | no_such_function']) { const result = await vf([...SUITE_FLAGS, '--all', '--wait', '--jq', jq]); - expect(result.exitCode, jq).toBe(1); + expect(result.exitCode, jq).toBe(2); expect(result.stderr).toContain('invalid --jq expression'); } expect(requests).toHaveLength(0); @@ -353,7 +354,7 @@ describe('create-suite --wait', () => { it('checks the --wait flags under --dry-run too', async () => { const result = await vf([...SUITE_FLAGS, '--all', '--wait', '--max-wait', '0s', '--dry-run']); - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(2); expect(result.stderr).toContain('--max-wait must be more than zero'); expect(requests).toHaveLength(0); }); @@ -361,7 +362,7 @@ describe('create-suite --wait', () => { it('keeps stderr JSON in agent mode when --wait --dry-run fails before sending', async () => { const result = await vf([...SUITE_FLAGS, '--wait', '--dry-run', '--body', '{bad'], { agentMode: true }); - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(2); // a usage error, like the same --body without --wait expect(jsonStream(result.stderr)).toHaveLength(1); expect(requests).toHaveLength(0); }); @@ -389,10 +390,11 @@ describe('create-suite --wait', () => { ]) { const result = await vf([...SUITE_FLAGS, '--all', ...flags], { agentMode: true }); - expect(result.exitCode, flags.join(' ')).toBe(1); + expect(result.exitCode, flags.join(' ')).toBe(2); const events = jsonStream(result.stderr); expect(events, flags.join(' ')).toHaveLength(1); expect(events[0]!.error_type).toBe('invalid_flag_value'); + expect(events[0]!.exit_code).toBe(2); } expect(requests).toHaveLength(0); }); diff --git a/test/union-variant-flags.test.ts b/test/union-variant-flags.test.ts index 2ff15679..19a7f4f0 100644 --- a/test/union-variant-flags.test.ts +++ b/test/union-variant-flags.test.ts @@ -118,7 +118,7 @@ describe('a string flag whose field is not text', () => { it('says it wants JSON when given text for an object', async () => { const result = await dryRun([...TURN, '--body-param.agent.payload', 'sequential']); - expect(result.exitCode).toBe(1); + expect(result.exitCode).toBe(2); // a usage error expect(result.stderr).toContain('invalid value for --body-param.agent.payload: expected a JSON value'); }); });