From 0e90461d79d0f0cbdb6d6ff4cac9953462b754f8 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:37:35 -0500 Subject: [PATCH 01/30] fix(conversation): send shows what the agent said first MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A turn printed every trace the runtime made: blocks, debug messages carrying each tool's whole JSON schema, token accounting. One "hi" printed 320 to 580 lines, with the agent's one-line reply two-thirds of the way down. Four of the round-3 sweep's testers hit it, people and agents alike, and dug the reply out with a --jq filter or by scrolling. Pretty output now shows the turn as a chat reads: the agent's messages, its buttons and cards as "[buttons: Yes | No]" and "[card: …]" (the form run-script's digest uses), and whether the conversation ended. The other traces are counted on one line. TOON, agent mode's default, leads with the same replies under `agent`, then `ended`, `needsRecompile` and the count. --show-debug adds the full traces after the reply. -o json, --jq, YAML and table still print the response as the API sent it, since scripts read those. run-script needed nothing: its answer is already a digest of turns. --- internal/cli/conversation/reply.go | 298 +++++++++++++++++++++++++ internal/cli/conversation/send.go | 3 +- internal/cli/conversationreply_test.go | 181 +++++++++++++++ 3 files changed, 481 insertions(+), 1 deletion(-) create mode 100644 internal/cli/conversation/reply.go create mode 100644 internal/cli/conversationreply_test.go diff --git a/internal/cli/conversation/reply.go b/internal/cli/conversation/reply.go new file mode 100644 index 0000000..8d8778c --- /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 8b79044..8c5c8ac 100644 --- a/internal/cli/conversation/send.go +++ b/internal/cli/conversation/send.go @@ -36,6 +36,7 @@ func initSendCmd(parent *cobra.Command) error { } flagutil.RegisterFlags(cmd, sendCmdMeta) addNoCompileFlag(cmd) // autocompile.go: --no-compile + addShowDebugFlag(cmd) // reply.go: --show-debug if err := flagutil.ValidateMeta[operations.StableConversationControllerSendRequest](sendCmdMeta); err != nil { return fmt.Errorf("invalid metadata for send: %w", err) } @@ -86,7 +87,7 @@ func runSendCmd(cmd *cobra.Command, args []string) error { } 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/conversationreply_test.go b/internal/cli/conversationreply_test.go new file mode 100644 index 0000000..8d69c74 --- /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) + } +} From 61166a455f0d989fccc80f1b6a423581d0e31f60 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:40:50 -0500 Subject: [PATCH 02/30] fix(conversation): send --text says something in plain words MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit There was no plain way to talk to the agent. --action takes only JSON, in one of fifteen request shapes, and its help shows a type union. The form asked for the user ID and the version but never for the message, then failed with "needs --action". The help's only example ended a conversation. The round-3 sweep's newcomer couldn't send a message without guessing {"type":"text","payload":"…"}. --text "" now sends exactly that, and can't be combined with --action, which stays for every other action. At a terminal, when nothing says what to send (no --text, --action or --body), the form asks for the message with the other fields. Without one, the error offers --text first. The help's first example sends typed words, the second a launch. --- internal/cli/conversation/send.go | 13 ++- internal/cli/conversation/text.go | 108 ++++++++++++++++++++++ internal/cli/conversation/text_test.go | 48 ++++++++++ internal/cli/conversationtext_test.go | 119 +++++++++++++++++++++++++ 4 files changed, 284 insertions(+), 4 deletions(-) create mode 100644 internal/cli/conversation/text.go create mode 100644 internal/cli/conversation/text_test.go create mode 100644 internal/cli/conversationtext_test.go diff --git a/internal/cli/conversation/send.go b/internal/cli/conversation/send.go index 8c5c8ac..ccb6eb7 100644 --- a/internal/cli/conversation/send.go +++ b/internal/cli/conversation/send.go @@ -31,12 +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) } @@ -50,14 +51,18 @@ 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 } s, err := client.NewClient(cmd) if err != nil { diff --git a/internal/cli/conversation/text.go b/internal/cli/conversation/text.go new file mode 100644 index 0000000..a344a50 --- /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. Each line runs as +// written. +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"}'` + +// 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). + if f := cmd.Flags().Lookup(actionFlag); f != nil { + delete(f.Annotations, flagutil.UnionNeedsAForm) + } + 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 0000000..526340b --- /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/conversationtext_test.go b/internal/cli/conversationtext_test.go new file mode 100644 index 0000000..977d9ad --- /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) + } +} From 0801b2301f56f3462bc06ecdeefc38e6d295d2eb Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:44:08 -0500 Subject: [PATCH 03/30] fix(conversation): an end action works as written, and action errors name their form MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The help's example, --action '{"type":"end"}', failed every time with a 230 to 310-line error. Two things were wrong. The API wants {"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 runs only on a transcript that has ended. Three of the round-3 sweep's testers hit it. An end action without a reason now gets "Ended with vf conversation send" (the API takes any reason) and goes out as an end action, from --action, --body or stdin alike. The help's end example gives a reason. The API's 422 for an action lists all fifteen forms' complaints, and only the one whose type matched says what's wrong: a person saw "action: Invalid input", an agent 300 lines of JSON. vf now keeps that form's complaints, with full paths: "action.payload.reason: Invalid input for type "end": expected string, …". An action whose type matches no form gets one line naming the types there are. --- internal/cli/conversation/endaction.go | 177 +++++++++++++++++++++++ internal/cli/conversation/send.go | 3 +- internal/cli/conversation/text.go | 8 +- internal/cli/conversationend_test.go | 192 +++++++++++++++++++++++++ 4 files changed, 376 insertions(+), 4 deletions(-) create mode 100644 internal/cli/conversation/endaction.go create mode 100644 internal/cli/conversationend_test.go diff --git a/internal/cli/conversation/endaction.go b/internal/cli/conversation/endaction.go new file mode 100644 index 0000000..98c621a --- /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/send.go b/internal/cli/conversation/send.go index ccb6eb7..ec45dd6 100644 --- a/internal/cli/conversation/send.go +++ b/internal/cli/conversation/send.go @@ -64,6 +64,7 @@ func runSendCmd(cmd *cobra.Command, args []string) error { if err != nil { 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 @@ -88,7 +89,7 @@ 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 diff --git a/internal/cli/conversation/text.go b/internal/cli/conversation/text.go index a344a50..8bbe489 100644 --- a/internal/cli/conversation/text.go +++ b/internal/cli/conversation/text.go @@ -31,10 +31,12 @@ const ( actionFlag = "action" ) -// sendExample leads with typed words, the usual turn. Each line runs as -// written. +// 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":"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) { diff --git a/internal/cli/conversationend_test.go b/internal/cli/conversationend_test.go new file mode 100644 index 0000000..c611c84 --- /dev/null +++ b/internal/cli/conversationend_test.go @@ -0,0 +1,192 @@ +// 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 { + Path []string `json:"path"` + 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 || strings.Join(e.Details[0].Path, ".") != "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) + } + if n := strings.Count(errOut, "\n"); n > 30 { + 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) + } + }) +} From 4ca167fc80e3e93eaba2a4eb9901c8cd36b9da76 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:44:52 -0500 Subject: [PATCH 04/30] feat(cli): a delete asks before it sends, at a terminal Deletes never confirmed. `project delete`, `secret delete`, `environment delete` and the 31 other delete commands sent their request at once, so one Enter on the wrong picker row deleted an environment that was serving traffic. The round-3 sweep's power user and release manager both hit it. Every command named delete or delete-* now asks first, after the pickers have filled its flags and before its request leaves: Delete environment "Production" (main)? This can't be undone. Yes No No is chosen, so Enter keeps it. It names the thing by the name a picker showed or the home prompt knows, and by its ID otherwise. No, or Ctrl-C, sends nothing and says "Canceled". It asks only when a person can answer: stdin and stderr are a terminal, agent mode is off and --no-interactive isn't set. Scripts, CI, agents and pipes run as before, and --dry-run never asks. Each delete takes -y/--yes to skip the question; -y is free on all 34 today, and a command that uses it already gets --yes alone. The deletes are found by name at startup (confirm.go), and the question is asked from the HTTP client just before the first request that isn't a read (client/confirm.go), so no generated command changes. --usage lists --yes as well, which needed a fix in usage.AddFlags: it dropped a flag line any sibling already had, so only the first delete at each depth got it. --- internal/cli/confirm.go | 245 ++++++++++++++++++++++ internal/cli/confirm_test.go | 299 +++++++++++++++++++++++++++ internal/cli/root.go | 1 + internal/client/client.go | 1 + internal/client/confirm.go | 57 +++++ internal/client/confirm_test.go | 88 ++++++++ internal/interactive/confirm.go | 56 +++++ internal/interactive/confirm_test.go | 35 ++++ internal/interactive/pickers.go | 2 + internal/usage/extra_flags.go | 9 +- internal/usage/extra_flags_test.go | 26 +++ 11 files changed, 817 insertions(+), 2 deletions(-) create mode 100644 internal/cli/confirm.go create mode 100644 internal/cli/confirm_test.go create mode 100644 internal/client/confirm.go create mode 100644 internal/client/confirm_test.go create mode 100644 internal/interactive/confirm.go create mode 100644 internal/interactive/confirm_test.go create mode 100644 internal/usage/extra_flags_test.go diff --git a/internal/cli/confirm.go b/internal/cli/confirm.go new file mode 100644 index 0000000..6fb6a36 --- /dev/null +++ b/internal/cli/confirm.go @@ -0,0 +1,245 @@ +// 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. + +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 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) { + if isDelete(c) { + if y, ok := addYes(c, yesHelp); 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 + } + yes, err := askYesNo(req.Context(), "Delete "+deleteTarget(cmd)+"?", "This can't be undone.") + 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 0000000..7765601 --- /dev/null +++ b/internal/cli/confirm_test.go @@ -0,0 +1,299 @@ +// 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) + } +} + +// 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/root.go b/internal/cli/root.go index 788bc29..7413952 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -241,6 +241,7 @@ func NewRootCommand() (*cobra.Command, error) { describeBodyFlags(rootCmd) // bodyhelp.go: --body says how stdin is read fixExamples(rootCmd) // examplehelp.go: every example runs as written + askFirst(rootCmd) // confirm.go: a delete asks before it sends, at a terminal rootCmd.SetUsageTemplate(groupedUsageTemplate()) return rootCmd, nil diff --git a/internal/client/client.go b/internal/client/client.go index 04407fe..ead725a 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 0000000..f23fc6a --- /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 0000000..0ed4df6 --- /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/interactive/confirm.go b/internal/interactive/confirm.go new file mode 100644 index 0000000..dd42367 --- /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 0000000..e6d8b1b --- /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/pickers.go b/internal/interactive/pickers.go index 71d82ea..94ecc24 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/usage/extra_flags.go b/internal/usage/extra_flags.go index 9b78a88..3d3ddd7 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 0000000..0537f65 --- /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) + } +} From ddf8cc11a4460a8400c9bff7c275da7aa5b6fcbf Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:49:53 -0500 Subject: [PATCH 05/30] feat(environment): merge says it goes live at once, and asks first `vf environment merge` made the source's live version live on Main, for all of Main's traffic, with no question asked. Its help said only "Merge one environment into another.", which to a git user changes a branch. The round-3 sweep's release manager merged Staging and found Main already answering with Staging's behaviour. The help now says what the API spec says: the target, normally main, switches to the source's live version at once, with no publish step; it takes what the source last published, not its draft; anything published to the target since the source was cloned is replaced; and the previous version stays in the target's history. At a terminal it asks first, as deletes now do, naming both ends: Merge staging into main? staging's live version goes live on main now, for all of main's traffic. Its draft isn't included. Then staging is deleted. The aliases come from the request being sent, so --body counts, and the last sentence shows only with --remove-source-environment. -y/--yes skips the question; scripts, CI, agents, pipes and --dry-run never see it. --- internal/cli/confirm.go | 27 ++++++++--- internal/cli/confirm_test.go | 3 ++ internal/cli/merge.go | 73 +++++++++++++++++++++++++++++ internal/cli/merge_test.go | 91 ++++++++++++++++++++++++++++++++++++ internal/cli/root.go | 2 +- 5 files changed, 188 insertions(+), 8 deletions(-) create mode 100644 internal/cli/merge.go create mode 100644 internal/cli/merge_test.go diff --git a/internal/cli/confirm.go b/internal/cli/confirm.go index 6fb6a36..59b0afe 100644 --- a/internal/cli/confirm.go +++ b/internal/cli/confirm.go @@ -19,7 +19,8 @@ // // 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. +// files. `environment merge` asks as well: it puts a version live on Main +// (merge.go). package cli @@ -50,15 +51,23 @@ const yesHelp = "Delete without asking first. vf asks only at a terminal: script func init() { client.BeforeChange = confirmChange } -// askFirst makes every delete under root 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. +// 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) { - if isDelete(c) { - if y, ok := addYes(c, yesHelp); ok { + 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) } } @@ -165,7 +174,11 @@ func confirmChange(cmd *cobra.Command, req *http.Request) error { if !asks(cmd) { return nil } - yes, err := askYesNo(req.Context(), "Delete "+deleteTarget(cmd)+"?", "This can't be undone.") + 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) diff --git a/internal/cli/confirm_test.go b/internal/cli/confirm_test.go index 7765601..9d0ad88 100644 --- a/internal/cli/confirm_test.go +++ b/internal/cli/confirm_test.go @@ -223,6 +223,9 @@ func TestUsageListsYes(t *testing.T) { 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 diff --git a/internal/cli/merge.go b/internal/cli/merge.go new file mode 100644 index 0000000..bc00a7d --- /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 0000000..9ea03b6 --- /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/root.go b/internal/cli/root.go index 7413952..dbfe39c 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -241,7 +241,7 @@ func NewRootCommand() (*cobra.Command, error) { describeBodyFlags(rootCmd) // bodyhelp.go: --body says how stdin is read fixExamples(rootCmd) // examplehelp.go: every example runs as written - askFirst(rootCmd) // confirm.go: a delete asks before it sends, at a terminal + askFirst(rootCmd) // confirm.go: deletes and merges ask before they send, at a terminal rootCmd.SetUsageTemplate(groupedUsageTemplate()) return rootCmd, nil From 788806744714de183f781e5913af8742314c5eef Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:37:26 -0500 Subject: [PATCH 06/30] fix(output): --jq prints a string raw, as jq -r and gh --jq do MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every --jq result printed as JSON, so a string kept its quotes. `ID=$(vf test create … --jq .test.id)` captured the quotes too, and the next call failed with `No test exists with ID "\"6b0d…\""`. Multi-line text came out on one line with \n escapes. Four of the round-3 sweep's testers hit it; each script needed `| jq -r .`, the extra tool --jq is meant to replace. --jq also ignored -o without saying so. A string result now prints raw, one per line. An object, an array, a number, a boolean or null still prints as JSON, and `| tojson` keeps a string quoted. It is the same in agent mode, under every -o, and for `vf docs search`. --jq's help, in --help and in --usage, now says how it prints and that it overrides -o; so does the README. --- README.md | 4 +- internal/cli/docs.go | 9 +-- internal/cli/docs_test.go | 4 +- internal/cli/jqraw_test.go | 114 +++++++++++++++++++++++++++++++++++++ internal/cli/root.go | 2 +- internal/output/jqraw.go | 44 ++++++++++++++ internal/output/output.go | 11 +--- internal/usage/schema.go | 2 +- 8 files changed, 167 insertions(+), 23 deletions(-) create mode 100644 internal/cli/jqraw_test.go create mode 100644 internal/output/jqraw.go diff --git a/README.md b/README.md index 92a3ecb..c448e84 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 diff --git a/internal/cli/docs.go b/internal/cli/docs.go index 0cd1063..c91a38b 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 51d663b..e1f6ae3 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/jqraw_test.go b/internal/cli/jqraw_test.go new file mode 100644 index 0000000..19fd332 --- /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/root.go b/internal/cli/root.go index dbfe39c..e9ea945 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -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") diff --git a/internal/output/jqraw.go b/internal/output/jqraw.go new file mode 100644 index 0000000..fa9c9b8 --- /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 ee185f7..a718e9d 100644 --- a/internal/output/output.go +++ b/internal/output/output.go @@ -795,16 +795,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/usage/schema.go b/internal/usage/schema.go index bf8010b..6b5d5e5 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 \" help=\"Specify the output format. Options: pretty, json, yaml, table, toon.\" global=#true config=\"output_format\" default=\"pretty\"\nflag \"--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 \" help=\"Filter and transform output using a jq expression (e.g., '.name', '.items[] | .id')\" global=#true\nflag \"--server-url \" help=\"Override the default server URL\" global=#true\nflag \"--server \" help=\"Select a server by index (for indexed servers) or name (for named servers)\" global=#true\nflag \"-H --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 \" 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 \" 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 \" help=\"[required]\"\n flag \"--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 \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--prompt \" help=\"string value\"\n flag \"--end-tool \" help=\"JSON object\"\n flag \"--card-tool \" help=\"JSON object\"\n flag \"--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 \" 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 \" help=\"JSON object\"\n flag \"--carousel-tool \" help=\"JSON object\"\n flag \"--instructions \" help=\"string value\"\n flag \"--skip-turn-tool \" help=\"JSON object\"\n flag \"--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 \" help=\"JSON object\"\n flag \"--call-forward-tool \" help=\"JSON object\"\n flag \"--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 \" help=\"JSON object\"\n flag \"--voice \" help=\"JSON object\"\n flag \"--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 \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" help=\"When the agent should run this workflow. The agent reads it to choose between its playbooks and workflows. [required]\"\n flag \"--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 \" help=\"The workflow to add. Copy its ID from voiceflow_workflow.list. [required]\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" help=\"When the agent should run this workflow. The agent reads it to choose between its playbooks and workflows.\"\n flag \"--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 \" 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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n }\n cmd \"read-instructions\" help=\"Read agent instructions\" {\n alias \"ri\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--offset \" help=\"integer value\" default=1\n flag \"--limit \" help=\"integer value\" default=400\n }\n cmd \"patch-instructions\" help=\"Patch agent instructions\" {\n alias \"pi\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" 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 \" 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 \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" help=\"How many lines either side of each match to return.\" default=0\n flag \"--limit \" help=\"The maximum number of matching LINES to return. The reported totals cover the whole document.\" default=50\n flag \"--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 \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--offset \" help=\"integer value\" default=1\n flag \"--limit \" help=\"integer value\" default=400\n }\n cmd \"patch-prompt\" help=\"Patch the global prompt\" {\n alias \"pp\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" 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 \" 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 \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" help=\"How many lines either side of each match to return.\" default=0\n flag \"--limit \" help=\"The maximum number of matching LINES to return. The reported totals cover the whole document.\" default=50\n flag \"--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 \" 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 \" 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 \" 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 \" 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 \" 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 \" help=\"{ type: string, examples: string[] } | { type: string, messageID: string }\"\n flag \"--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 \" 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 \" 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 \" 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 \" 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 \" 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 \" help=\"{ type: string, examples: string[] } | { type: string, messageID: string }\"\n flag \"--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 \" 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 \" 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 \" 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 \" 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 \" 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 \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" help=\"Written words whose entries to delete.\" var=#true\n flag \"--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 \" help=\"[required]\"\n flag \"--search \" help=\"string value\"\n flag \"--language \" help=\"string value\"\n flag \"--provider \" help=\"A TTS provider whose voices are in the voice catalog. (options: elevenlabs, cartesia)\"\n flag \"--gender \" help=\"How the vendor describes the voice. (options: male, female, neutral)\"\n flag \"--limit \" help=\"integer value\" default=10\n flag \"--offset \" help=\"integer value\" default=0\n }\n cmd \"patch-voices\" help=\"Patch voices\" {\n alias \"pv\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--primary \" help=\"The default voice: the one a conversation speaks with unless a language voice matches its locale.\"\n flag \"--set-overrides \" help=\"Language voices to add, or to change when the agent already has one for that locale.\"\n flag \"--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 \" 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 \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n }\n cmd \"set-initialization-workflow\" help=\"Set initialization workflow\" {\n alias \"siw\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--workflow-id \" help=\"The workflow to run before the user's first turn, or null to run none. [required]\"\n flag \"--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 \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--folder-id \" help=\"string value\"\n flag \"--cursor \" help=\"string value\"\n flag \"--limit \" help=\"integer value\"\n }\n cmd \"create\" help=\"Create workflow\" {\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--name \" help=\"[required]\"\n flag \"--description \" help=\"string value\"\n flag \"--folder-id \" help=\"string value\"\n flag \"--entry \" help=\"string value\"\n flag \"--blocks \" help=\"list of values\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--cursor \" help=\"string value\"\n }\n cmd \"update\" help=\"Update workflow\" {\n flag \"--workflow-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--name \" help=\"string value\"\n flag \"--description \" help=\"string value\"\n flag \"--folder-id \" help=\"A workflow folder in this environment, or null for the top level.\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n }\n cmd \"get-step\" help=\"Get workflow step\" {\n alias \"gs\"\n flag \"--workflow-id \" help=\"[required]\"\n flag \"--step-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n }\n cmd \"update-step\" help=\"Update workflow step\" {\n alias \"us\"\n flag \"--workflow-id \" help=\"[required]\"\n flag \"--step-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--body-param \" help=\"{ kind: string, content: object }\"\n flag \"--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 \" help=\"[required]\"\n flag \"--step-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--expected-steps \" help=\"[required]\" var=#true\n }\n cmd \"get-raw\" help=\"Get raw workflow\" {\n alias \"gr\"\n flag \"--workflow-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--block-ids \" help=\"list of values\" var=#true\n }\n cmd \"duplicate\" help=\"Duplicate workflow\" {\n flag \"--workflow-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--name \" help=\"The name of the copy. [required]\"\n flag \"--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 \" help=\"[required]\"\n flag \"--step-id \" help=\"[required]\"\n flag \"--port-key \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" 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 \" help=\"[required]\"\n flag \"--step-id \" help=\"[required]\"\n flag \"--port-key \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n }\n cmd \"link-many\" help=\"Link many ports\" {\n alias \"lm\"\n flag \"--workflow-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--links \" help=\"1 to 50 ports to link, each once. [required]\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--name \" help=\"[required]\"\n flag \"--color-param \" help=\"string value\"\n flag \"--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 \" help=\"Also link this port to the new block in the same call, with the same checks as voiceflow_workflow.link.\"\n flag \"--steps \" help=\"[required]\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" help=\"Existing ports to link to new blocks in the same call, with the same checks as voiceflow_workflow.link.\"\n flag \"--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 \" 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 \" help=\"[required]\"\n flag \"--block-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--name \" help=\"string value\"\n flag \"--color-param \" help=\"string value\"\n flag \"--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 \" help=\"[required]\"\n flag \"--block-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--expected-steps \" help=\"[required]\" var=#true\n }\n cmd \"arrange-blocks\" help=\"Arrange workflow blocks\" {\n alias \"abl\"\n flag \"--workflow-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" 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 \" help=\"[required]\"\n flag \"--block-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" help=\"The new block name. Default: the block name with \\\" (continued)\\\".\"\n flag \"--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 \" 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 \" help=\"[required]\"\n flag \"--block-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" help=\"{ kind: string, key: string, content: value, links: object } | { kind: string, key: string, content: object, links: object }\"\n flag \"--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 \" 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 \" help=\"[required]\"\n flag \"--step-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" 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 \" help=\"[required]\"\n flag \"--step-id \" help=\"[required]\"\n flag \"--branch-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" 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 \" help=\"[required]\"\n flag \"--step-id \" help=\"[required]\"\n flag \"--branch-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n }\n cmd \"add-actions\" help=\"Add port actions\" {\n alias \"aa\"\n flag \"--workflow-id \" help=\"[required]\"\n flag \"--step-id \" help=\"[required]\"\n flag \"--port-key \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--actions \" help=\"1 to 10 actions to add, in run order. [required]\"\n flag \"--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 \" 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 \" 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 \" 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 \" help=\"[required]\"\n flag \"--step-id \" help=\"[required]\"\n flag \"--port-key \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--order \" help=\"Every action ID of this exit, in the new order. [required]\" var=#true\n flag \"--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 \" help=\"[required]\"\n flag \"--action-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--action \" help=\"{ kind: string, content: object }\"\n flag \"--expected-actions \" help=\"The IDs in this exit's actions from your last read, in order. [required]\" var=#true\n flag \"--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 \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--include-instructions\" help=\"boolean flag\" default=#false\n }\n cmd \"create\" help=\"Create playbook\" {\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--name \" help=\"[required]\"\n flag \"--description \" help=\"A human-readable description of what the playbook does.\"\n flag \"--instructions \" help=\"string value\"\n flag \"--end-tool \" help=\"JSON object\"\n flag \"--card-tool \" help=\"JSON object\"\n flag \"--button-tool \" help=\"JSON object\"\n flag \"--carousel-tool \" help=\"JSON object\"\n flag \"--skip-turn-tool \" help=\"JSON object\"\n flag \"--web-search-tool \" help=\"JSON object\"\n flag \"--call-forward-tool \" help=\"JSON object\"\n flag \"--knowledge-base-tool \" help=\"JSON object\"\n flag \"--settings \" help=\"JSON object\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--include-instructions\" help=\"boolean flag\" default=#false\n }\n cmd \"update\" help=\"Update playbook\" {\n flag \"--playbook-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--name \" help=\"string value\"\n flag \"--settings \" help=\"JSON object\"\n flag \"--description \" help=\"A human-readable description of what the playbook does.\"\n flag \"--instructions \" help=\"string value\"\n flag \"--end-tool \" help=\"JSON object\"\n flag \"--card-tool \" help=\"JSON object\"\n flag \"--button-tool \" help=\"JSON object\"\n flag \"--carousel-tool \" help=\"JSON object\"\n flag \"--skip-turn-tool \" help=\"JSON object\"\n flag \"--web-search-tool \" help=\"JSON object\"\n flag \"--call-forward-tool \" help=\"JSON object\"\n flag \"--knowledge-base-tool \" help=\"JSON object\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n }\n cmd \"read-instructions\" help=\"Read playbook instructions\" {\n alias \"ri\"\n flag \"--playbook-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--offset \" help=\"integer value\" default=1\n flag \"--limit \" help=\"integer value\" default=400\n }\n cmd \"patch-instructions\" help=\"Patch playbook instructions\" {\n alias \"pi\"\n flag \"--playbook-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" 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 \" 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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" help=\"How many lines either side of each match to return.\" default=0\n flag \"--limit \" help=\"The maximum number of matching LINES to return. The reported totals cover the whole document.\" default=50\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--name \" help=\"The name of the copy. Leave it out to use the original's name with \\\" copy\\\" added.\"\n flag \"--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 \" help=\"[required]\"\n flag \"--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 \" 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 \" 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 \" 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 \" 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 \" help=\"{ type: string, examples: string[] } | { type: string, messageID: string }\"\n flag \"--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 \" help=\"[required]\"\n flag \"--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 \" 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 \" 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 \" 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 \" 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 \" help=\"{ type: string, examples: string[] } | { type: string, messageID: string }\"\n flag \"--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 \" help=\"[required]\"\n flag \"--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 \" 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 \" 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 \" 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 \" 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 \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--playbook-id \" help=\"[required]\"\n }\n cmd \"create\" help=\"Create exit path\" {\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--playbook-id \" help=\"The ID of the playbook to add the exit path to. [required]\"\n flag \"--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 \" help=\"The exit condition: the model reads it to decide when to leave the playbook through this path.\"\n flag \"--required-variables \" help=\"The variables or entities the model must fill before it can leave through this path, in order.\"\n flag \"--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 \" 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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--playbook-id \" help=\"[required]\"\n flag \"--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 \" help=\"The exit condition: the model reads it to decide when to leave the playbook through this path.\"\n flag \"--required-variables \" help=\"Replaces the stored list, in order. Leave it out to keep it; send [] to remove every one.\"\n flag \"--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 \" 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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" help=\"string value\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--body-param \" help=\"{ description: string, target: object, messages: object, captureInputVariables: object, ... }\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--body-param \" help=\"{ description: string, messages: object, toolSound: object, captureInputVariables: object, ... }\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" help=\"[required]\"\n flag \"--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 \" help=\"[required]\"\n flag \"--organization-id \" help=\"The ID of the organization the workspace belongs to. [required]\"\n flag \"--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 \" help=\"[required]\"\n }\n cmd \"update\" help=\"Update workspace\" {\n flag \"--workspace-id \" help=\"[required]\"\n flag \"--name \" help=\"string value\"\n flag \"--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 \" help=\"[required]\"\n }\n}\ncmd \"project\" help=\"Create, list and manage projects\" {\n cmd \"list\" help=\"List projects\" {\n flag \"--workspace-id \" help=\"[required]\"\n }\n cmd \"create\" help=\"Create project\" {\n flag \"--name \" help=\"[required]\"\n flag \"--workspace-id \" help=\"The ID of the workspace the project belongs to. [required]\"\n flag \"--type \" help=\"The channel type of the project to create. (options: webchat, phone-call) [required]\"\n flag \"--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 \" help=\"[required]\"\n }\n cmd \"update\" help=\"Update project\" {\n flag \"--project-id \" help=\"[required]\"\n flag \"--name \" help=\"string value\"\n flag \"--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 \" help=\"[required]\"\n }\n}\ncmd \"environment\" help=\"Publish, clone, merge and compare environments\" {\n cmd \"list\" help=\"List environments\" {\n flag \"--project-id \" help=\"[required]\"\n }\n cmd \"merge\" help=\"Merge environments\" {\n flag \"--project-id \" help=\"[required]\"\n flag \"--source-environment-alias \" help=\"The alias of the environment whose changes are merged. [required]\"\n flag \"--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 \" 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 \" help=\"[required]\"\n flag \"--traffic \" help=\"Map of environmentAlias → traffic percentage (0-100). Values must sum to 100. [required]\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n }\n cmd \"update\" help=\"Update environment\" {\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--name \" help=\"string value\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n }\n cmd \"diff\" help=\"Diff environment\" {\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n }\n cmd \"audit-wiring\" help=\"Audit environment wiring\" {\n alias \"aw\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n }\n cmd \"search-text\" help=\"Search project text\" {\n alias \"st\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--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 \" help=\"Search only these kinds of resource. Default: all of them.\" var=#true\n flag \"--limit \" help=\"Hits per page. Default 50.\"\n flag \"--offset \" help=\"Hits to skip: nextOffset from the previous page.\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n }\n cmd \"clone\" help=\"Clone environment\" {\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--name \" help=\"The display name of the new environment. [required]\"\n flag \"--alias \" help=\"Short URL-safe identifier; cannot be 'main' (reserved). [required]\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--name \" help=\"The name of the release created by publishing. [required]\"\n flag \"--description \" help=\"An optional description of what changed in this release.\"\n flag \"--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 \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--ids \" help=\"Message IDs to read. Duplicates are ignored; at most 50 distinct IDs. [required]\" var=#true\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n }\n cmd \"delete\" help=\"Delete message\" {\n flag \"--message-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n }\n cmd \"update\" help=\"Reorder message variants\" {\n flag \"--message-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--variant-order \" help=\"Every variant ID of the message, each exactly once, in the new order. [required]\" var=#true\n flag \"--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 \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" 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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--text \" help=\"Message text shown to the end user. Limited markdown: **bold**, _italic_, underline, ~~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 \" help=\"Milliseconds to wait before this variant is sent.\"\n flag \"--condition \" help=\"{ type: string, matchAll: boolean, assertions: object[] } | { type: string, code: string }\"\n flag \"--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 \" help=\"[required]\"\n flag \"--variant-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--text \" help=\"string value\"\n flag \"--delay \" help=\"Milliseconds to wait before this variant is sent. null removes the delay.\"\n flag \"--condition \" help=\"{ type: string, matchAll: boolean, assertions: object[] } | { type: string, code: string }\"\n flag \"--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 \" help=\"[required]\"\n flag \"--variant-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--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 \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--ids \" help=\"Prompt IDs to read. Duplicates are ignored; at most 50 distinct IDs. [required]\" var=#true\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n }\n cmd \"update\" help=\"Update prompt\" {\n flag \"--prompt-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--name \" help=\"string value\"\n flag \"--system \" help=\"string value\"\n flag \"--settings \" help=\"JSON object\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n }\n cmd \"create\" help=\"Create prompt\" {\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--name \" help=\"Defaults to \\\"Untitled prompt\\\", as the editor names one.\"\n flag \"--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 \" help=\"JSON object\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" help=\"number value\"\n flag \"--temperature \" help=\"number value\"\n flag \"--response-format \" help=\"string value\"\n flag \"--reasoning-effort \" help=\"options: off, adaptive, minimal, low, medium, high\"\n flag \"--service-tier \" help=\"options: default, flex, priority\"\n flag \"--use-structured-output\" help=\"boolean flag\"\n flag \"--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 \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n }\n cmd \"create\" help=\"Create variable\" {\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" 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 \" help=\"A short description of what the variable stores.\"\n flag \"--default-value \" help=\"The initial value of the variable at the start of a conversation.\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n }\n cmd \"update\" help=\"Update variable\" {\n flag \"--variable-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" 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 \" help=\"A short description of what the variable stores.\"\n flag \"--default-value \" help=\"The initial value of the variable at the start of a conversation.\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--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 \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n }\n cmd \"create\" help=\"Create API tool\" {\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--url \" help=\"string value\"\n flag \"--name \" help=\"[required]\"\n flag \"--body-param \" help=\"{ type: string, contentType: string, content: string } | { type: string, formData: object[] } | { type: string, params: object[] }\"\n flag \"--settings \" help=\"JSON object\"\n flag \"--http-method \" help=\"options: get, put, post, patch, delete [required]\"\n flag \"--description \" help=\"A description of what the API tool does, used by the agent to decide when to call it.\"\n flag \"--headers \" help=\"list of values\"\n flag \"--query-parameters \" help=\"list of values\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n }\n cmd \"update\" help=\"Update API tool\" {\n flag \"--tool-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--url \" help=\"string value\"\n flag \"--name \" help=\"string value\"\n flag \"--body-param \" help=\"{ type: string, contentType: string, content: string } | { type: string, formData: object[] } | { type: string, params: object[] }\"\n flag \"--headers \" help=\"list of values\"\n flag \"--settings \" help=\"JSON object\"\n flag \"--http-method \" help=\"options: get, put, post, patch, delete\"\n flag \"--description \" help=\"A description of what the API tool does, used by the agent to decide when to call it.\"\n flag \"--query-parameters \" help=\"list of values\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n }\n cmd \"get-schema\" help=\"Get API tool schema\" {\n alias \"gs\"\n flag \"--tool-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n }\n cmd \"execute\" help=\"Execute API tool\" {\n flag \"--tool-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" 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 \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--api-tool-id \" help=\"[required]\"\n }\n cmd \"create\" help=\"Create variable\" {\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" help=\"The ID of the API tool this variable belongs to. [required]\"\n flag \"--description \" help=\"A description of the variable, used by the agent to determine what value to provide.\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n }\n cmd \"update\" help=\"Update variable\" {\n flag \"--variable-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" help=\"A description of the variable, used by the agent to determine what value to provide.\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--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 \" help=\"[required]\"\n flag \"--take \" help=\"Page size, 1 to 50. There is no `limit`. Page with `skip` while `hasMore` is true.\" default=20\n flag \"--skip \" help=\"The number of results to skip, used for pagination.\" default=0\n flag \"--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 \" 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 \" 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 \" help=\"list of values\"\n flag \"--session-id \" help=\"When provided, only transcripts from this conversation session are returned.\"\n flag \"--environment-alias \" help=\"When provided, only transcripts from the environment with this alias are returned.\"\n flag \"--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 \" 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 \" help=\"[required]\"\n flag \"--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 \" help=\"Transcripts to scan. Leave it out to scan the newest transcripts in the date range.\" var=#true\n flag \"--start-date \" help=\"Lower bound when no transcriptIDs are given: a day or a timestamp.\"\n flag \"--end-date \" help=\"Upper bound when no transcriptIDs are given: a day or a timestamp.\"\n flag \"--environment-alias \" help=\"Only transcripts from this environment, when no transcriptIDs are given.\"\n flag \"--limit \" help=\"How many transcripts to scan at most, 1 to 60.\" default=25\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--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 \" help=\"string | array of string\"\n }\n cmd \"files\" help=\"List transcript files\" {\n flag \"--transcript-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n }\n cmd \"query-logs\" help=\"Query transcript logs\" {\n alias \"ql\"\n flag \"--transcript-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--kinds \" help=\"Keep only entries of these kinds. Omit to keep every kind.\" var=#true\n flag \"--levels \" help=\"Keep only entries at these levels, for example [\\\"fatal\\\", \\\"error\\\", \\\"warn\\\"] for what went wrong.\" var=#true\n flag \"--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 \" help=\"Keep only entries of these turns. Turn 0 holds anything logged before the first input.\"\n flag \"--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 \" help=\"options: summary, full\" default=\"summary\"\n flag \"--limit \" help=\"The most entries to return in one page.\" default=50\n flag \"--offset \" help=\"How many matching entries to skip, for paging.\" default=0\n flag \"--order \" help=\"options: asc, desc\" default=\"asc\"\n flag \"--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 \" help=\"[required]\"\n }\n cmd \"create\" help=\"Create property\" {\n flag \"--project-id \" help=\"[required]\"\n flag \"--name \" help=\"[required]\"\n flag \"--type \" help=\"The type of value the property holds. (options: boolean, number, string) [required]\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n }\n cmd \"update\" help=\"Update property\" {\n flag \"--property-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--name \" help=\"string value\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n }\n cmd \"set-value\" help=\"Set property value\" {\n alias \"sv\"\n flag \"--property-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--value \" help=\"The value to set for the property on the transcript. [required]\"\n flag \"--transcript-id \" help=\"The ID of the transcript to set the property value on. [required]\"\n flag \"--metadata \" help=\"Additional structured data to record alongside the value. Omit or pass `null` to record none.\"\n flag \"--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 \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n }\n cmd \"create\" help=\"Create function\" {\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--name \" help=\"[required]\"\n flag \"--code \" help=\"The JavaScript source code executed when the function runs. [required]\"\n flag \"--settings \" help=\"JSON object\"\n flag \"--description \" help=\"A human-readable description of what the function does.\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n }\n cmd \"update\" help=\"Update function\" {\n flag \"--function-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--name \" help=\"string value\"\n flag \"--code \" help=\"The JavaScript source code executed when the function runs.\"\n flag \"--settings \" help=\"JSON object\"\n flag \"--path-order \" help=\"An ordered list of path IDs controlling the display order of the function's exit paths.\" var=#true\n flag \"--description \" help=\"A human-readable description of what the function does.\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n }\n cmd \"patch-code\" help=\"Patch function code\" {\n alias \"pc\"\n flag \"--function-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" 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 \" 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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n }\n cmd \"execute\" help=\"Execute function\" {\n flag \"--function-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--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 \" 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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--cases \" help=\"[required]\"\n flag \"--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 \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--function-id \" help=\"[required]\"\n }\n cmd \"create\" help=\"Create variable\" {\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--name \" help=\"The name used to reference the variable in the function code. [required]\"\n flag \"--type \" help=\"options: input, output [required]\"\n flag \"--function-id \" help=\"The ID of the function this variable belongs to. [required]\"\n flag \"--description \" help=\"A human-readable description of what the variable holds.\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n }\n cmd \"update\" help=\"Update variable\" {\n flag \"--variable-id \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--name \" help=\"The name used to reference the variable in the function code.\"\n flag \"--description \" help=\"A human-readable description of what the variable holds.\"\n flag \"--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 \" help=\"[required]\"\n flag \"--project-id \" help=\"[required]\"\n flag \"--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 \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--function-id \" help=\"[required]\"\n }\n cmd \"create\" help=\"Create path\" {\n flag \"--project-id \" help=\"[required]\"\n flag \"--environment-alias \" help=\"[required]\"\n flag \"--name \" help=\"The name of the exit path, referenced by the function code when returning which path to take. [required]\"\n flag \"--function-id \" help=\"The ID of the function this path belongs to. [required]\"\n flag \"--label