From 9c541253794945cc98f6818bccf5b389c3b6f9e4 Mon Sep 17 00:00:00 2001 From: Google Team Member Date: Thu, 3 Dec 2026 07:23:34 -0800 Subject: [PATCH] feat: sync Speakeasy OpenAPI generator to v2.969.8 and regenerate SDKs Updates the Speakeasy OpenAPI generator from v2.965.1 to v2.969.8, regenerates the Java, Go, .NET (v1), and CLI outputs (adding Java request timeout options, C# cancellation handling, allowReserved path-parameter escaping and retry content-header preservation, Go and CLI enum Values() helpers, and CLI error-body redaction), and updates SPEAKEASY_VERSION in the Python and TypeScript CI workflows. PiperOrigin-RevId: 1035403236 --- .github/workflows/ci.yaml | 2 +- internal/cli/auth.go | 13 +- internal/cli/configure.go | 2 +- internal/cli/root.go | 43 ++- internal/cli/version.go | 3 +- internal/cli/whoami.go | 2 +- internal/config/config.go | 81 ++++- internal/explorer/tui.go | 98 +++--- internal/flagutil/metadata.go | 57 +++- internal/forms/forms.go | 2 +- internal/output/agentmode.go | 10 +- internal/output/async.go | 24 +- internal/output/classify.go | 281 +++++++++++++++++- internal/output/color.go | 7 + internal/output/jq.go | 46 ++- internal/output/output.go | 89 ++++-- internal/output/output_test.go | 144 +++++++++ internal/output/outputitems.go | 8 +- internal/output/paginated.go | 20 +- internal/output/streaming.go | 81 ++++- internal/output/streaming_test.go | 52 ++++ internal/sdk/models/credentials/credential.go | 17 ++ .../credentials/injectionlocationenum.go | 9 + .../environments/createenvironmentrequest.go | 7 + .../sdk/models/environments/environment.go | 15 + .../models/environments/environmentfile.go | 8 + internal/sdk/models/genai/file.go | 20 ++ internal/sdk/models/genai/generatedfile.go | 10 + .../sdk/models/interactions/agentoption.go | 10 + .../sdk/models/interactions/audiocontent.go | 26 ++ .../sdk/models/interactions/audiodelta.go | 19 ++ .../interactions/audioresponseformat.go | 20 ++ .../codeexecutioncallarguments.go | 8 + .../sdk/models/interactions/computeruse.go | 22 ++ .../interactions/deepresearchagentconfig.go | 8 + .../models/interactions/documentcontent.go | 25 ++ .../sdk/models/interactions/documentdelta.go | 18 ++ .../sdk/models/interactions/environment.go | 7 + .../models/interactions/environmentmode.go | 8 + .../environmentnetworkegressallowlist.go | 7 + .../sdk/models/interactions/findrequest.go | 8 + .../sdk/models/interactions/googlesearch.go | 9 + .../interactions/googlesearchcallstep.go | 9 + .../models/interactions/groundingtoolcount.go | 9 + .../sdk/models/interactions/harmcategory.go | 16 + .../sdk/models/interactions/imageconfig.go | 30 ++ .../sdk/models/interactions/imagecontent.go | 14 + .../sdk/models/interactions/imagedelta.go | 14 + .../interactions/imageresponseformat.go | 45 +++ .../sdk/models/interactions/interaction.go | 15 + .../interactionsseeventinteraction.go | 15 + .../interactions/interactionstatusupdate.go | 15 + .../models/interactions/mediaresolution.go | 10 + internal/sdk/models/interactions/model.go | 45 +++ .../interactions/pageprocessingoptions.go | 8 + .../models/interactions/responsemodality.go | 11 + internal/sdk/models/interactions/retrieval.go | 10 + .../models/interactions/retrievalcalldelta.go | 10 + .../models/interactions/retrievalcallstep.go | 10 + .../sdk/models/interactions/safetysetting.go | 19 ++ .../sdk/models/interactions/servicetier.go | 10 + internal/sdk/models/interactions/source.go | 10 + .../sdk/models/interactions/speakerconfig.go | 9 + .../spreadsheetprocessingoptions.go | 9 + .../interactions/staticmediaprocessing.go | 9 + .../models/interactions/textresponseformat.go | 8 + .../sdk/models/interactions/thinkinglevel.go | 11 + .../models/interactions/thinkingsummaries.go | 8 + .../sdk/models/interactions/toolchoicetype.go | 10 + .../sdk/models/interactions/toolsearch.go | 8 + .../interactions/transcriptionconfig.go | 8 + .../models/interactions/urlcontextresult.go | 10 + .../sdk/models/interactions/videoconfig.go | 12 + .../sdk/models/interactions/videocontent.go | 23 ++ .../sdk/models/interactions/videodelta.go | 16 + .../interactions/videoresponseformat.go | 26 ++ internal/sdk/models/triggers/trigger.go | 9 + .../sdk/models/triggers/triggerexecution.go | 11 + internal/sdk/models/triggers/triggerupdate.go | 9 + internal/sdk/models/voices/pitch.go | 9 + internal/sdk/models/voices/voicetype.go | 9 + .../webhooks/rotatesigningsecretrequest.go | 8 + internal/sdk/models/webhooks/webhook.go | 22 ++ internal/sdk/models/webhooks/webhookupdate.go | 22 ++ internal/sdk/redact/redact.go | 20 +- internal/sdk/sdkinternal/utils/json.go | 83 +++++- internal/usage/schema.go | 6 +- scripts/install.ps1 | 35 ++- scripts/install.sh | 94 ++++-- 89 files changed, 1985 insertions(+), 190 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 78c38c14..f7eab195 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -10,7 +10,7 @@ permissions: contents: read env: - SPEAKEASY_VERSION: v2.965.1 + SPEAKEASY_VERSION: v2.969.8 jobs: non-live-validation: diff --git a/internal/cli/auth.go b/internal/cli/auth.go index 1e9dad52..1f0b9e71 100644 --- a/internal/cli/auth.go +++ b/internal/cli/auth.go @@ -92,7 +92,7 @@ Sources are shown as: [unset] - Not configured Credential values are masked for security.`, - Annotations: map[string]string{"speakeasy_settings_command": "true"}, + Annotations: map[string]string{"speakeasy_settings_command": "true", "speakeasy_config_optional": "true"}, Args: cobra.NoArgs, RunE: runWhoamiCmd, }) @@ -103,7 +103,7 @@ Credential values are masked for security.`, Long: `Clear all stored authentication credentials from both the OS keychain and config file. This removes all credentials previously set via auth login or configure.`, - Annotations: map[string]string{"speakeasy_settings_command": "true"}, + Annotations: map[string]string{"speakeasy_settings_command": "true", "speakeasy_config_optional": "true"}, Args: cobra.NoArgs, RunE: runAuthLogoutCmd, }) @@ -158,7 +158,7 @@ func runAuthLoginCmd(cmd *cobra.Command, args []string) error { Title("Authentication Method"). Description("Choose which credentials to configure") - if err := forms.New(forms.NewPage("", schemeSelect)).Accessible(accessible).IO(promptInput, cmd.OutOrStdout()).Run(); err != nil { + if err := forms.New(forms.NewPage("", schemeSelect)).Accessible(accessible).IO(promptInput, cmd.ErrOrStderr()).Run(); err != nil { return fmt.Errorf("auth login: %w", err) } @@ -174,7 +174,7 @@ func runAuthLoginCmd(cmd *cobra.Command, args []string) error { Placeholder(maskSecret(config.GetStoredSecret("api-key", cfg.Security.ApiKey))), } - form := forms.New(forms.NewPage("", fields...)).Accessible(accessible).IO(promptInput, cmd.OutOrStdout()) + form := forms.New(forms.NewPage("", fields...)).Accessible(accessible).IO(promptInput, cmd.ErrOrStderr()) if err := form.Run(); err != nil { return fmt.Errorf("auth login: %w", err) @@ -197,7 +197,7 @@ func runAuthLoginCmd(cmd *cobra.Command, args []string) error { Placeholder(maskSecret(config.GetStoredSecret("access-token", cfg.Security.AccessToken))), } - form := forms.New(forms.NewPage("", fields...)).Accessible(accessible).IO(promptInput, cmd.OutOrStdout()) + form := forms.New(forms.NewPage("", fields...)).Accessible(accessible).IO(promptInput, cmd.ErrOrStderr()) if err := form.Run(); err != nil { return fmt.Errorf("auth login: %w", err) @@ -236,6 +236,9 @@ func runAuthLogoutCmd(cmd *cobra.Command, args []string) error { if dryRunLocalNoop(cmd, "auth logout removes local credentials only (no API request); nothing was changed.") { return nil } + if err := config.LoadError(); err != nil { + return fmt.Errorf("%w; fix or remove the file before logging out", err) + } cfg := config.GetConfig() if cfg == nil { cfg = &config.Config{} diff --git a/internal/cli/configure.go b/internal/cli/configure.go index 810526bf..13cd4e46 100644 --- a/internal/cli/configure.go +++ b/internal/cli/configure.go @@ -217,7 +217,7 @@ func runConfigureCmd(cmd *cobra.Command, args []string) error { pages = append(pages, forms.NewPage("Preferences", preferenceFields...)) } - form := forms.New(pages...).Accessible(accessible).IO(cmd.InOrStdin(), cmd.OutOrStdout()) + form := forms.New(pages...).Accessible(accessible).IO(cmd.InOrStdin(), cmd.ErrOrStderr()) if err := form.Run(); err != nil { return fmt.Errorf("configure: %w", err) diff --git a/internal/cli/root.go b/internal/cli/root.go index d99ca16a..ca245dfd 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -60,6 +60,7 @@ func NewRootCommand() (*cobra.Command, error) { Long: "Gemini API: Use the Gemini Interactions API and managed-agent platform from the command line.\n\nGet started:\n Set GEMINI_API_KEY, or run: gemini-api configure\n Then run a model or managed agent: gemini-api agent --help\n Add --dry-run to preview any API call without sending it.", SilenceUsage: true, SilenceErrors: true, + Annotations: map[string]string{config.OptionalAnnotation: "true"}, RunE: func(cmd *cobra.Command, args []string) error { if usage.UsageRequested(cmd) { return usage.EmitSchema(cmd, cmd.OutOrStdout()) @@ -89,7 +90,18 @@ func NewRootCommand() (*cobra.Command, error) { return err } if err := config.Init("gemini-api", "GEMINI"); err != nil { - return err + if !config.RunsWithoutConfig(cmd) { + return err + } + fmt.Fprintf(cmd.ErrOrStderr(), "Warning: %v\n", err) + } + if cmd.Annotations["speakeasy_settings_command"] != "true" { + if err := output.ValidateConfiguredOutputFormat(cmd); err != nil { + if !config.RunsWithoutConfig(cmd) { + return err + } + fmt.Fprintf(cmd.ErrOrStderr(), "Warning: %v\n", err) + } } config.SetKeyringWarningOutput(cmd.ErrOrStderr()) if noKeyring, changed := flagutil.GetBoolFlag(cmd, "no-keyring"); changed { @@ -238,7 +250,9 @@ func NewRootCommand() (*cobra.Command, error) { custom.Register(rootCmd) // Cobra creates its default help and completion commands lazily inside Execute. - usage.InitDefaultCommands(rootCmd) + for _, cmd := range usage.InitDefaultCommands(rootCmd) { + cmd.Annotations[config.OptionalAnnotation] = "true" + } applyDeclaredCommandOrder(rootCmd) interactive.Intercept(rootCmd) usage.Intercept(rootCmd) @@ -275,6 +289,7 @@ func InterruptContext(parent context.Context) (context.Context, context.CancelFu func ExecuteRoot(ctx context.Context, root *cobra.Command, args []string) error { // Cobra aborts on an unknown command or flag before PersistentPreRunE runs. + _ = config.Init("gemini-api", "GEMINI") output.InitAgentMode(root) target, _, _ := root.Find(args) if target == nil { @@ -319,15 +334,23 @@ func ExplorerHandoffArgs(root *cobra.Command, selectedArgs []string) []string { if debug, _ := root.PersistentFlags().GetBool("debug"); debug { handoffArgs = append(handoffArgs, "--debug") } - // Rendering flags given to the explore invocation apply to the selected - // command: the fresh command tree re-parses argv (and resets the - // preparsed rendering state), so they must travel with it. The - // --name=value form keeps boolean flags from swallowing the next token. - for _, name := range []string{"output-format", "jq", "raw-output", "color"} { - if flag := root.PersistentFlags().Lookup(name); flag != nil && flag.Changed { - handoffArgs = append(handoffArgs, "--"+name+"="+flag.Value.String()) + // Global flags given to the explore invocation (server, credentials, + // headers, rendering) apply to the selected command: the fresh command + // tree re-parses argv, so they must travel with it. The --name=value form + // keeps boolean flags from swallowing the next token. + handled := map[string]bool{"interactive": true, "no-interactive": true, "dry-run": true, "debug": true, "help": true} + root.PersistentFlags().VisitAll(func(flag *pflag.Flag) { + if !flag.Changed || handled[flag.Name] { + return } - } + if values, ok := flag.Value.(pflag.SliceValue); ok { + for _, value := range values.GetSlice() { + handoffArgs = append(handoffArgs, "--"+flag.Name+"="+value) + } + return + } + handoffArgs = append(handoffArgs, "--"+flag.Name+"="+flag.Value.String()) + }) return append(handoffArgs, selectedArgs...) } diff --git a/internal/cli/version.go b/internal/cli/version.go index a599ab73..063f9f74 100644 --- a/internal/cli/version.go +++ b/internal/cli/version.go @@ -45,7 +45,8 @@ The version defaults to the SDK version set during generation, but can be overridden at build time using Go linker flags: go build -ldflags "-X main.version=x.y.z -X main.buildTime=$(date -u +%Y-%m-%dT%H:%M:%SZ)" ./cmd/gemini-api`, - Args: cobra.NoArgs, + Annotations: map[string]string{"speakeasy_config_optional": "true"}, + Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { if usage.UsageRequested(cmd) { return usage.EmitSchema(cmd, cmd.OutOrStdout()) diff --git a/internal/cli/whoami.go b/internal/cli/whoami.go index 99a70f86..ccdbe0b9 100644 --- a/internal/cli/whoami.go +++ b/internal/cli/whoami.go @@ -41,7 +41,7 @@ Sources are shown as: [unset] - Not configured Credential values are masked for security.`, - Annotations: map[string]string{"speakeasy_settings_command": "true"}, + Annotations: map[string]string{"speakeasy_settings_command": "true", "speakeasy_config_optional": "true"}, Args: cobra.NoArgs, RunE: runWhoamiCmd, } diff --git a/internal/config/config.go b/internal/config/config.go index 250712d7..fd81e950 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -128,6 +128,36 @@ func Init(name, prefix string) error { return initErr } +// OptionalAnnotation marks a command that still runs, with a warning, when the +// config file cannot be read or parsed. +const OptionalAnnotation = "speakeasy_config_optional" + +// RunsWithoutConfig reports whether cmd can run when the config file cannot +// be read or parsed. Subcommands inherit OptionalAnnotation from every +// ancestor except the root. +func RunsWithoutConfig(cmd *cobra.Command) bool { + switch cmd.Name() { + case cobra.ShellCompRequestCmd, cobra.ShellCompNoDescRequestCmd: + return true + } + if cmd.Annotations[OptionalAnnotation] == "true" { + return true + } + for p := cmd.Parent(); p != nil && p.HasParent(); p = p.Parent() { + if p.Annotations[OptionalAnnotation] == "true" { + return true + } + } + return false +} + +// LoadError returns the error from reading or parsing the config file, if any. +func LoadError() error { + initMu.Lock() + defer initMu.Unlock() + return initErr +} + // Reset clears all configuration state, allowing Init to be called again. // This is intended for use in tests to support re-initialization between test cases. func Reset() { @@ -160,8 +190,12 @@ func GetString(key string) string { // GetEnvValue returns the environment variable value for a flag name, or "". func GetEnvValue(key string) string { - envKey := envPrefix + "_" + strings.ToUpper(strings.ReplaceAll(key, "-", "_")) - return os.Getenv(envKey) + return os.Getenv(EnvVarName(key)) +} + +// EnvVarName returns the environment variable that sets a flag name. +func EnvVarName(key string) string { + return envPrefix + "_" + strings.ToUpper(strings.ReplaceAll(key, "-", "_")) } // GetConfigValue returns the config file value for a flag name, or "". @@ -483,6 +517,9 @@ func GetConfig() *Config { // SaveConfig saves the configuration to the config file. // Creates the config directory if it doesn't exist. func SaveConfig(c *Config) error { + if err := LoadError(); err != nil { + return fmt.Errorf("%w; fix or remove the file before saving settings", err) + } homeDir, err := os.UserHomeDir() if err != nil { return fmt.Errorf("failed to get home directory: %w", err) @@ -500,7 +537,7 @@ func SaveConfig(c *Config) error { return fmt.Errorf("failed to marshal config: %w", err) } - if err := os.WriteFile(configPath, data, 0600); err != nil { + if err := writeConfigFile(configDir, configPath, data); err != nil { return fmt.Errorf("failed to write config file: %w", err) } @@ -511,3 +548,41 @@ func SaveConfig(c *Config) error { return nil } + +// writeConfigFile replaces the config file through a rename so a failed write +// keeps the previous contents. The file can hold credentials, so permissions +// left over from an earlier write are tightened rather than inherited. +func writeConfigFile(configDir, configPath string, data []byte) error { + if err := os.Chmod(configDir, 0700); err != nil { + return err + } + if info, err := os.Lstat(configPath); err == nil && info.Mode()&os.ModeSymlink != 0 { + target, err := filepath.EvalSymlinks(configPath) + if err != nil { + return fmt.Errorf("resolve config symlink: %w", err) + } + configPath = target + } + tmp, err := os.CreateTemp(filepath.Dir(configPath), ".config-*.yaml.tmp") + if err != nil { + return err + } + tmpName := tmp.Name() + defer os.Remove(tmpName) + if err := tmp.Chmod(0600); err != nil { + tmp.Close() + return err + } + if _, err := tmp.Write(data); err != nil { + tmp.Close() + return err + } + if err := tmp.Sync(); err != nil { + tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + return os.Rename(tmpName, configPath) +} diff --git a/internal/explorer/tui.go b/internal/explorer/tui.go index b4e8e9b2..e743604c 100644 --- a/internal/explorer/tui.go +++ b/internal/explorer/tui.go @@ -19,6 +19,7 @@ package explorer import ( "fmt" "strings" + "unicode/utf8" "charm.land/bubbles/v2/key" tea "charm.land/bubbletea/v2" @@ -118,16 +119,7 @@ func (m model) handleClick(x, y int) (tea.Model, tea.Cmd) { if m.searching && m.searchResults != nil { total := len(m.searchResults) - // Compute the displayed range, mirroring renderList logic - listRows := m.listRowsAvailable(false) - dispEnd := m.scrollOffset + listRows - if dispEnd > total { - dispEnd = total - } - hasOverflow := m.scrollOffset > 0 || dispEnd < total - if hasOverflow && dispEnd-m.scrollOffset > 1 { - dispEnd-- - } + _, dispEnd, hasOverflow := m.listWindow(total) displayedCount := dispEnd - m.scrollOffset // Ignore clicks on the scroll indicator row @@ -162,17 +154,7 @@ func (m model) handleClick(x, y int) (tea.Model, tea.Cmd) { items := m.visibleItems() - listRows := m.listRowsAvailable(m.hasBack()) - - // Compute displayed range, mirroring renderList logic - dispEnd := m.scrollOffset + listRows - if dispEnd > len(items) { - dispEnd = len(items) - } - hasOverflow := m.scrollOffset > 0 || dispEnd < len(items) - if hasOverflow && dispEnd-m.scrollOffset > 1 { - dispEnd-- - } + _, dispEnd, hasOverflow := m.listWindow(len(items)) displayedCount := dispEnd - m.scrollOffset // Determine what's at this row: items, scroll indicator, or Back button @@ -353,7 +335,8 @@ func (m model) updateSearch(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) { case tea.KeyBackspace, tea.KeyDelete: if len(m.filter) > 0 { - m.filter = m.filter[:len(m.filter)-1] + _, size := utf8.DecodeLastRuneInString(m.filter) + m.filter = m.filter[:len(m.filter)-size] m.applyFilter() } return m, nil @@ -400,6 +383,7 @@ func (m *model) applyFilter() { m.filtered = nil m.searchResults = nil m.cursor = 0 + m.scrollOffset = 0 return } // Deep search from root across the entire tree @@ -441,21 +425,15 @@ func (m model) listRowsAvailable(includeBack bool) int { } func (m *model) ensureVisible(items []int) { - rows := m.listRowsAvailable(m.hasBack() && !(m.searching && m.searchResults != nil)) - if rows <= 0 { - return - } - - // Account for scroll indicator: when items overflow the viewport, - // renderList reserves one row for the indicator, reducing visible items by 1. total := len(items) - if m.searching && m.searchResults != nil { + if m.inDeepSearch() { total = len(m.searchResults) } - visible := rows - if total > rows && rows > 1 { - visible = rows - 1 + rows := m.listRowsAvailable(m.hasBack() && !m.inDeepSearch()) + if rows <= 0 { + return } + visible := visibleListItems(total, rows) if m.cursor < m.scrollOffset { m.scrollOffset = m.cursor @@ -465,6 +443,32 @@ func (m *model) ensureVisible(items []int) { } } +func (m model) inDeepSearch() bool { + return m.searching && m.searchResults != nil +} + +// visibleListItems returns how many of total items fit in rows, keeping one +// row for the scroll indicator when they overflow. +func visibleListItems(total, rows int) int { + if total > rows && rows > 1 { + return rows - 1 + } + return rows +} + +// listWindow returns the range of items rendered from the current scroll +// offset and whether the scroll indicator row is shown. renderList and mouse +// hit-testing must agree with ensureVisible on this range. +func (m model) listWindow(total int) (start, end int, indicator bool) { + rows := m.listRowsAvailable(m.hasBack() && !m.inDeepSearch()) + start = m.scrollOffset + end = start + max(visibleListItems(total, rows), 0) + if end > total { + end = total + } + return start, end, start > 0 || end < total +} + func (m model) listHeight() int { // Reserve 3 header lines (title + desc + separator) + 2 status bar lines (border + text) h := m.height - 5 @@ -600,8 +604,6 @@ func padToHeight(content string, height int) string { } func (m model) renderList(width int) string { - listRows := m.listRowsAvailable(m.hasBack()) - var b strings.Builder maxNameLen := width - 6 // account for " " prefix + padding @@ -612,21 +614,10 @@ func (m model) renderList(width int) string { // Deep search mode: render flat search results if m.searching && m.searchResults != nil { total := len(m.searchResults) - start := m.scrollOffset - end := start + listRows - if end > total { - end = total - } - + start, end, _ := m.listWindow(total) hasAbove := start > 0 hasBelow := end < total - // Reserve a row for the scroll indicator when items overflow - if (hasAbove || hasBelow) && end-start > 1 { - end-- - hasBelow = end < total - } - for vi := start; vi < end; vi++ { result := m.searchResults[vi] name := result.Node.Name @@ -670,21 +661,10 @@ func (m model) renderList(width int) string { // Normal navigation mode: render current level's children items := m.visibleItems() - start := m.scrollOffset - end := start + listRows - if end > len(items) { - end = len(items) - } - + start, end, _ := m.listWindow(len(items)) hasAbove := start > 0 hasBelow := end < len(items) - // Reserve a row for the scroll indicator when items overflow - if (hasAbove || hasBelow) && end-start > 1 { - end-- - hasBelow = end < len(items) - } - for vi := start; vi < end; vi++ { idx := items[vi] child := m.current.Children[idx] diff --git a/internal/flagutil/metadata.go b/internal/flagutil/metadata.go index dc64bdf8..3318df96 100644 --- a/internal/flagutil/metadata.go +++ b/internal/flagutil/metadata.go @@ -2540,33 +2540,49 @@ func buildUnionField(cmd *cobra.Command, root reflect.Value, m FlagMeta) error { // Variant fields are always *VariantType pointers variantType := variantStructField.Type.Elem() - // Priority 2: Variant-level JSON flag + // Priority 2: Variant-level JSON flag, with that variant's expanded + // field flags applied on top if FlagChanged(cmd, v.FlagName) { jsonStr, _ := GetStringFlag(cmd, v.FlagName) variantPtr := reflect.New(variantType) if err := utils.UnmarshalJsonFromString(jsonStr, variantPtr.Interface(), ""); err != nil { return newDecodeError("invalid value for --"+v.FlagName, err) } + if err := enforceStrictOrWarn(cmd, verifyBodyKeys("--"+v.FlagName, []byte(jsonStr), variantPtr, nil)); err != nil { + return err + } injectDiscriminator(variantPtr.Elem(), u.DiscriminatorKey, v.DiscriminatorValue) + if v.CanExpand { + for _, fm := range relaxVariantFields(v.Fields) { + if err := buildFieldOnValue(cmd, variantPtr.Elem(), fm); err != nil { + return err + } + } + } unionVal := assembleUnionValue(unionType, v.FieldName, variantPtr) setUnionFieldValue(unionField, unionVal, isPtr) return nil } - // Priority 3: Expanded variant fields + // Priority 3: Expanded variant fields, layered over the same variant + // when --body or stdin already supplied it if v.CanExpand { - variantVal := reflect.New(variantType).Elem() + variantPtr := reflect.New(variantType) + fields := v.Fields + if existing := existingUnionVariant(unionField, v.FieldName); existing.IsValid() { + variantPtr.Elem().Set(existing.Elem()) + fields = relaxVariantFields(fields) + } + variantVal := variantPtr.Elem() injectDiscriminator(variantVal, u.DiscriminatorKey, v.DiscriminatorValue) // Build variant fields using the same per-kind builders - for _, fm := range v.Fields { + for _, fm := range fields { if err := buildFieldOnValue(cmd, variantVal, fm); err != nil { return err } } - variantPtr := reflect.New(variantType) - variantPtr.Elem().Set(variantVal) unionVal := assembleUnionValue(unionType, v.FieldName, variantPtr) setUnionFieldValue(unionField, unionVal, isPtr) return nil @@ -2576,6 +2592,35 @@ func buildUnionField(cmd *cobra.Command, root reflect.Value, m FlagMeta) error { return nil } +// existingUnionVariant returns the variant pointer already stored on a union +// field, or an invalid Value when the field is unset or holds another variant. +func existingUnionVariant(unionField reflect.Value, variantFieldName string) reflect.Value { + union := unionField + if union.Kind() == reflect.Ptr { + if union.IsNil() { + return reflect.Value{} + } + union = union.Elem() + } + variant := union.FieldByName(variantFieldName) + if !variant.IsValid() || variant.Kind() != reflect.Ptr || variant.IsNil() { + return reflect.Value{} + } + return variant +} + +// relaxVariantFields keeps unset variant field flags from requiring or +// defaulting values that an earlier source already supplied. +func relaxVariantFields(fields []FlagMeta) []FlagMeta { + relaxed := make([]FlagMeta, len(fields)) + copy(relaxed, fields) + for i := range relaxed { + relaxed[i].Required = false + relaxed[i].HasDefault = false + } + return relaxed +} + // setUnionFieldValue sets a union field on the request struct. // Handles both value (Shape) and pointer (*Shape) field types. func setUnionFieldValue(field reflect.Value, val reflect.Value, isPtr bool) { diff --git a/internal/forms/forms.go b/internal/forms/forms.go index eb976342..4cb047f9 100644 --- a/internal/forms/forms.go +++ b/internal/forms/forms.go @@ -277,7 +277,7 @@ type Form struct { // New returns a form over pages. func New(pages ...*Page) *Form { - f := &Form{pages: pages, in: os.Stdin, out: os.Stdout} + f := &Form{pages: pages, in: os.Stdin, out: os.Stderr} f.resize(terminalWidth(), 0) return f } diff --git a/internal/output/agentmode.go b/internal/output/agentmode.go index 77cfc709..61956c3e 100644 --- a/internal/output/agentmode.go +++ b/internal/output/agentmode.go @@ -141,6 +141,11 @@ func CLIError(cmd *cobra.Command, err error) error { if err == nil || IsRendered(err) { return err } + if halt := jqHalt(err); halt != nil { + if err = jqHaltOutcome(cmd.ErrOrStderr(), halt); err == nil { + return nil + } + } jqExpr, changed := flagutil.GetStringFlag(cmd, "jq") if !changed || jqExpr == "" { jqExpr = preparsedRendering.jq @@ -155,7 +160,7 @@ func CLIError(cmd *cobra.Command, err error) error { } envelope := map[string]interface{}{ - "error": err.Error(), + "error": redactedErrorText(err, classification), "exit_code": ExitCodeFor(classification), } mergeMachineErrorFields(envelope, err) @@ -166,7 +171,6 @@ func CLIError(cmd *cobra.Command, err error) error { if marshalErr != nil { return retainClassification(err, classification) } - colorFlag, _ := flagutil.GetStringFlag(cmd, "color") - printScrubbedJSON(cmd.ErrOrStderr(), jsonData, ShouldColorize(colorFlag)) + printScrubbedJSON(cmd.ErrOrStderr(), jsonData, stderrColorize(cmd)) return markRendered(err, classification) } diff --git a/internal/output/async.go b/internal/output/async.go index e8efe495..75b5ecf1 100644 --- a/internal/output/async.go +++ b/internal/output/async.go @@ -108,13 +108,15 @@ func (e *asyncRuntimeError) MachineErrorFields() map[string]interface{} { if errorMember == "" { errorMember = "error" } - errorPayload := e.payload - if object, ok := e.payload.(map[string]interface{}); ok { - if member, exists := object[errorMember]; exists { - errorPayload = member - } + object, isObject := e.payload.(map[string]interface{}) + member, exists := object[errorMember] + switch { + case isObject && exists: + fields["error"] = member + case !isObject || e.reason != ReasonCLIAsyncFailed: + // Without a failure detail, the poll response is the only diagnostic. + fields["error"] = e.payload } - fields["error"] = errorPayload } return fields } @@ -572,16 +574,12 @@ func asyncElapsed(elapsed time.Duration) string { } // asyncFailureDetail extracts the human failure message through the -// declared bindings (default "error"/"message"). +// declared bindings (default "error"/"message"). The error member may be an +// object, a string, or an array of either; the first message found is used. func asyncFailureDetail(cfg *asyncConfig, payload interface{}) string { object, ok := payload.(map[string]interface{}) if !ok { return "" } - errorMember, ok := object[cfg.ErrorField].(map[string]interface{}) - if !ok { - return "" - } - message, _ := errorMember[cfg.ErrorMessageField].(string) - return message + return outcomeDetailMessage(object[cfg.ErrorField], cfg.ErrorMessageField) } diff --git a/internal/output/classify.go b/internal/output/classify.go index bad0f7c7..1c6aafdf 100644 --- a/internal/output/classify.go +++ b/internal/output/classify.go @@ -25,10 +25,13 @@ import ( "io" "net" "net/url" + "reflect" + "sort" "strings" "github.com/google-gemini/gemini-api-cli/internal/clierrors" "github.com/google-gemini/gemini-api-cli/internal/flagutil" + "github.com/google-gemini/gemini-api-cli/internal/sdk/redact" "github.com/google-gemini/gemini-api-cli/internal/sdk/sdkinternal/utils" "github.com/spf13/cobra" ) @@ -87,6 +90,7 @@ type Classification struct { // because the request carried no credential; hints declared for the // permission reason do not apply to that caller. credentialsMissing bool + redaction messageRedaction } type errorRule struct { @@ -187,9 +191,10 @@ func Classify(cmd *cobra.Command, err error) Classification { err = flagutil.WithCLIValidation(err) } + rawBody := extractErrorBody(err) c := Classification{ StatusCode: extractErrorStatusCode(err), - RawBody: extractErrorBody(err), + RawBody: redactErrorBody(cmd, err, rawBody), Origin: ErrorOriginAPI, } var origin interface{ ErrorOrigin() ErrorOrigin } @@ -275,11 +280,283 @@ func Classify(cmd *cobra.Command, err error) Classification { } } - c.Message = classificationMessage(bodyMap, errorObject, err, c.RawBody) + c.redaction = newMessageRedaction(rawBody, c.RawBody) + if rawBody == "" { + if model := errorModelJSON(err); model != "" { + c.redaction = newMessageRedaction(model, redactErrorBody(cmd, err, model)) + } + } + c.Message = c.redaction.apply(classificationMessage(bodyMap, errorObject, err, c.RawBody)) c.Hints = assembleHints(cmd, err, c, bodyMap, errorObject, ruleHints, useReasonRule) return c } +// redactErrorBody masks the values the operation's schema marks sensitive in +// an error response body, as --debug does when logging it. The operation comes +// from the response's request, or from the command when the error carries no +// response. +func redactErrorBody(cmd *cobra.Command, err error, body string) string { + if body == "" { + return body + } + ctx := context.Background() + contentType := "" + for current := err; current != nil; current = errors.Unwrap(current) { + if res := extractHTTPResponse(current); res != nil { + contentType = res.Header.Get("Content-Type") + if res.Request != nil { + ctx = res.Request.Context() + } + break + } + } + if redact.Operation(ctx) == "" && cmd != nil { + operation := cmd.Annotations["speakeasy_sdk_operation"] + if operation == "" { + operation = cmd.Annotations["speakeasy_operation"] + } + ctx = redact.WithOperation(ctx, operation) + } + if parsed, ok := decodeStrictSingleJSON(body); ok && !jsonHasDuplicateKeys(body) { + if unwrapped := unwrapArrayWrappedError(parsed); unwrapped != nil { + if inner, marshalErr := json.Marshal(unwrapped); marshalErr == nil { + redactedInner := redact.ResponseBody(ctx, contentType, inner) + if bytes.Equal(redactedInner, inner) { + return body + } + if string(redactedInner) == redact.Mask { + return redact.Mask + } + return "[" + string(redactedInner) + "]" + } + } + } + return string(redact.ResponseBody(ctx, contentType, []byte(body))) +} + +// decodeStrictSingleJSON decodes a single JSON value keeping number spellings +// and rejects any trailing tokens after it, matching redact.ResponseBody. +func decodeStrictSingleJSON(body string) (any, bool) { + decoder := json.NewDecoder(strings.NewReader(body)) + decoder.UseNumber() + var value any + if err := decoder.Decode(&value); err != nil { + return nil, false + } + if _, err := decoder.Token(); err != io.EOF { + return nil, false + } + return value, true +} + +// jsonHasDuplicateKeys reports whether any JSON object in body repeats a key, +// mirroring redact.hasDuplicateKeys so unwrapping an array-wrapped error cannot +// drop an earlier sensitive duplicate key before redaction. +func jsonHasDuplicateKeys(body string) bool { + type object struct { + keys map[string]bool + expectKey bool + } + dec := json.NewDecoder(strings.NewReader(body)) + dec.UseNumber() + var stack []*object + for { + token, err := dec.Token() + if err != nil { + return err != io.EOF + } + switch t := token.(type) { + case json.Delim: + switch t { + case '{': + stack = append(stack, &object{keys: map[string]bool{}, expectKey: true}) + continue + case '[': + stack = append(stack, nil) + continue + } + stack = stack[:len(stack)-1] + case string: + if n := len(stack); n > 0 && stack[n-1] != nil && stack[n-1].expectKey { + if stack[n-1].keys[t] { + return true + } + stack[n-1].keys[t] = true + stack[n-1].expectKey = false + continue + } + } + if n := len(stack); n > 0 && stack[n-1] != nil { + stack[n-1].expectKey = true + } + } +} + +// messageRedaction keeps a message taken from the error's own text from +// re-exposing what body redaction masked: typed error models render their +// fields as JSON or as a single field, and fallback errors embed the raw body. +type messageRedaction struct { + raw, redacted string + scrubber *strings.Replacer +} + +func newMessageRedaction(rawBody, redactedBody string) messageRedaction { + r := messageRedaction{raw: rawBody, redacted: redactedBody} + if rawBody == "" || rawBody == redactedBody { + return r + } + seen := map[string]bool{} + var pairs []string + for _, value := range maskedBodyValues(rawBody, redactedBody) { + if !seen[value.raw] { + seen[value.raw] = true + pairs = append(pairs, value.raw, value.redacted) + } + } + if len(pairs) > 0 { + r.scrubber = strings.NewReplacer(pairs...) + } + return r +} + +// apply must run once per message: a masked value can occur inside the mask +// text that replaces it. +func (r messageRedaction) apply(message string) string { + if r.raw == "" || r.raw == r.redacted { + return message + } + if !isValidJSON(r.redacted) { + return r.redacted + } + if strings.Contains(message, r.raw) { + parts := strings.Split(message, r.raw) + for i, part := range parts { + parts[i] = r.scrub(part) + } + return strings.Join(parts, r.redacted) + } + if isValidJSON(message) { + return r.redacted + } + return r.scrub(message) +} + +func (r messageRedaction) scrub(text string) string { + if r.scrubber == nil { + return text + } + return r.scrubber.Replace(text) +} + +// errorModelJSON encodes a generated error model that carries no response +// body, so its fields can still be checked against the operation's sensitive +// fields. +func errorModelJSON(err error) string { + for current := err; current != nil; current = errors.Unwrap(current) { + v := reflect.ValueOf(current) + if v.Kind() != reflect.Ptr || v.IsNil() || v.Elem().Kind() != reflect.Struct { + continue + } + if !strings.HasPrefix(v.Elem().Type().PkgPath(), "google3/third_party/gemini_api_cli/internal/sdk/models/models") { + continue + } + if data, marshalErr := json.Marshal(current); marshalErr == nil { + return string(data) + } + } + return "" +} + +type maskedBodyValue struct{ raw, redacted string } + +// maskedBodyValues lists the scalar values of rawBody that redaction replaced, +// longest first so a value never shadows a longer one containing it. +func maskedBodyValues(rawBody, redactedBody string) []maskedBodyValue { + raw, rawOK := decodeJSONKeepingNumbers(rawBody) + redacted, redactedOK := decodeJSONKeepingNumbers(redactedBody) + if !rawOK || !redactedOK { + return nil + } + var out []maskedBodyValue + var walk func(raw, redacted any) + walk = func(raw, redacted any) { + if mask, ok := redacted.(string); ok { + if _, rawIsString := raw.(string); !rawIsString || raw != mask { + for _, leaf := range jsonScalarTexts(raw) { + if leaf != "" && leaf != mask { + out = append(out, maskedBodyValue{raw: leaf, redacted: mask}) + } + } + } + return + } + switch rawValue := raw.(type) { + case map[string]any: + redactedMap, _ := redacted.(map[string]any) + for key, value := range rawValue { + walk(value, redactedMap[key]) + } + case []any: + redactedList, _ := redacted.([]any) + for i, value := range rawValue { + if i < len(redactedList) { + walk(value, redactedList[i]) + } + } + } + } + walk(raw, redacted) + sort.SliceStable(out, func(i, j int) bool { return len(out[i].raw) > len(out[j].raw) }) + return out +} + +// decodeJSONKeepingNumbers keeps each number's original spelling, which is how +// it appears in an error's text. +func decodeJSONKeepingNumbers(body string) (any, bool) { + decoder := json.NewDecoder(strings.NewReader(body)) + decoder.UseNumber() + var value any + if err := decoder.Decode(&value); err != nil { + return nil, false + } + return value, true +} + +func jsonScalarTexts(value any) []string { + switch typed := value.(type) { + case nil: + return nil + case string: + return []string{typed} + case json.Number: + return []string{typed.String()} + case map[string]any: + var out []string + for _, member := range typed { + out = append(out, jsonScalarTexts(member)...) + } + return out + case []any: + var out []string + for _, item := range typed { + out = append(out, jsonScalarTexts(item)...) + } + return out + default: + return []string{fmt.Sprint(typed)} + } +} + +// redactedErrorText is err's own text with any response body it embeds +// replaced by the classification's redacted copy. +func redactedErrorText(err error, classification Classification) string { + redaction := classification.redaction + if redaction.raw == "" { + redaction = newMessageRedaction(extractErrorBody(err), classification.RawBody) + } + return redaction.apply(err.Error()) +} + func parseClassificationBody(raw string, c *Classification) (map[string]any, map[string]any) { if raw == "" { return nil, map[string]any{} diff --git a/internal/output/color.go b/internal/output/color.go index bc674b23..c24f302a 100644 --- a/internal/output/color.go +++ b/internal/output/color.go @@ -44,6 +44,13 @@ func ShouldColorize(colorFlag string) bool { return shouldColorizeWriter(colorFlag, os.Stdout) } +// stderrColorize reports whether output written to the command's error stream +// should be colorized, judged on that stream rather than stdout. +func stderrColorize(cmd *cobra.Command) bool { + colorFlag, _ := flagutil.GetStringFlag(cmd, "color") + return shouldColorizeWriter(colorFlag, cmd.ErrOrStderr()) +} + func shouldColorizeWriter(colorFlag string, out io.Writer) bool { // Agent mode: never colorize — output must be machine-parseable. if IsAgentMode() { diff --git a/internal/output/jq.go b/internal/output/jq.go index c560932c..e50c1ef0 100644 --- a/internal/output/jq.go +++ b/internal/output/jq.go @@ -18,7 +18,10 @@ package output import ( "encoding/json" + "errors" "fmt" + "io" + "strings" "sync" "github.com/google-gemini/gemini-api-cli/internal/flagutil" @@ -61,7 +64,8 @@ func compileJqExpression(expression string) (*gojq.Code, error) { // ApplyJqFilter applies a jq expression to the given content and returns the results. // The content is first marshaled to JSON and back to ensure a clean interface{} structure, -// then the jq expression is evaluated against it. +// then the jq expression is evaluated against it. A jq halt or halt_error ends +// evaluation: the results produced before it are returned with its *gojq.HaltError. func ApplyJqFilter(content interface{}, expression string) ([]interface{}, error) { // Marshal to JSON and back to get a clean JSON-compatible structure. // SDK types have custom marshal methods so we need to go through JSON @@ -89,6 +93,9 @@ func ApplyJqFilter(content interface{}, expression string) ([]interface{}, error break } if err, isErr := v.(error); isErr { + if halt := jqHalt(err); halt != nil { + return results, halt + } return nil, fmt.Errorf("jq error: %w", err) } results = append(results, v) @@ -96,3 +103,40 @@ func ApplyJqFilter(content interface{}, expression string) ([]interface{}, error return results, nil } + +func jqHalt(err error) *gojq.HaltError { + var halt *gojq.HaltError + if errors.As(err, &halt) { + return halt + } + return nil +} + +// jqHaltOutcome follows jq: halt succeeds, halt_error writes its value to +// stderr, and a non-zero halt_error fails the command with that value as the +// message. +func jqHaltOutcome(stderr io.Writer, halt *gojq.HaltError) error { + value := halt.Value() + if value == nil { + if halt.ExitCode() == 0 { + return nil + } + return errors.New("jq halt_error") + } + message, isString := value.(string) + if !isString { + data, err := json.Marshal(value) + if err != nil { + return fmt.Errorf("jq error: %w", halt) + } + message = string(data) + "\n" + } + if halt.ExitCode() == 0 { + _, err := io.WriteString(stderr, message) + return err + } + if message = strings.TrimRight(message, "\n"); message == "" { + message = "jq halt_error" + } + return errors.New(message) +} diff --git a/internal/output/output.go b/internal/output/output.go index 999cbc5b..87e692e6 100644 --- a/internal/output/output.go +++ b/internal/output/output.go @@ -25,6 +25,7 @@ import ( "io" "net/http" "reflect" + "slices" "sort" "strconv" "strings" @@ -131,7 +132,32 @@ func resolveErrorOutputFormat(cmd *cobra.Command) string { if format := preparsedRendering.outputFormat; format != "" { return flagutil.ResolveOutputFormat(cmd, format, IsAgentMode()) } - return flagutil.ResolveOutputFormat(cmd, config.GetString("output-format"), IsAgentMode()) + return flagutil.ResolveOutputFormat(cmd, configuredOutputFormat(), IsAgentMode()) +} + +// configuredOutputFormat returns the env or config output format, or "" when +// it is not one of Formats. +func configuredOutputFormat() string { + if format := config.GetString("output-format"); slices.Contains(Formats, format) { + return format + } + return "" +} + +// ValidateConfiguredOutputFormat rejects an env or config output format that +// is not one of Formats when --output-format does not override it. +func ValidateConfiguredOutputFormat(cmd *cobra.Command) error { + if flagutil.FlagChanged(cmd, "output-format") { + return nil + } + format, source := config.GetEnvValue("output-format"), config.EnvVarName("output-format") + if format == "" { + format, source = config.GetConfigValue("output-format"), "output_format in "+config.GetConfigPath() + } + if format == "" || slices.Contains(Formats, format) { + return nil + } + return flagutil.WithCLIValidation(fmt.Errorf("invalid output format %q from %s; valid options: %s", format, source, strings.Join(Formats, ", "))) } // configuredTimeout returns the timeout setting: --timeout, then env/config. @@ -440,7 +466,7 @@ func result(cmd *cobra.Command, res interface{}, allowArtifact bool) error { if failure != nil && allowArtifact && activeArtifact(cmd) != nil { return Error(cmd, failure) } - if err := renderResult(cmd, res, allowArtifact); err != nil { + if err := renderResult(cmd, res, allowArtifact); err != nil && (failure == nil || jqHalt(err) == nil) { return err } if failure != nil { @@ -665,8 +691,7 @@ func renderUnclassifiedPrettyAPIError(cmd *cobra.Command, out io.Writer, err err if wantsHeaders(cmd) { headers := extractErrorResponseHeaders(err) if len(headers) > 0 { - colorFlag, _ := flagutil.GetStringFlag(cmd, "color") - printResponseHeadersPretty(out, headers, ShouldColorize(colorFlag)) + printResponseHeadersPretty(out, headers, stderrColorize(cmd)) } } if classification.RawBody != "" && classification.StatusCode != 0 { @@ -702,7 +727,7 @@ func renderUnclassifiedStructuredAPIError(cmd *cobra.Command, out io.Writer, err } envelope = object } else { - wrapped := map[string]interface{}{"error": err.Error(), "body": parsed} + wrapped := map[string]interface{}{"error": redactedErrorText(err, classification), "body": parsed} if statusCode != 0 { wrapped["status_code"] = statusCode } @@ -714,7 +739,7 @@ func renderUnclassifiedStructuredAPIError(cmd *cobra.Command, out io.Writer, err } } if envelope == nil { - wrapped := map[string]interface{}{"error": err.Error()} + wrapped := map[string]interface{}{"error": redactedErrorText(err, classification)} if statusCode != 0 { wrapped["status_code"] = statusCode } @@ -745,18 +770,16 @@ func renderUnclassifiedStructuredAPIError(cmd *cobra.Command, out io.Writer, err } jsonData, marshalErr := json.MarshalIndent(envelope, "", " ") if marshalErr != nil { - jsonData, _ = json.MarshalIndent(map[string]interface{}{"error": err.Error(), "exit_code": ExitCodeFor(classification)}, "", " ") + jsonData, _ = json.MarshalIndent(map[string]interface{}{"error": redactedErrorText(err, classification), "exit_code": ExitCodeFor(classification)}, "", " ") } - colorFlag, _ := flagutil.GetStringFlag(cmd, "color") - printScrubbedJSON(out, jsonData, ShouldColorize(colorFlag)) + printScrubbedJSON(out, jsonData, stderrColorize(cmd)) } func renderPrettyError(cmd *cobra.Command, out io.Writer, err error, classification Classification) { if wantsHeaders(cmd) { headers := extractErrorResponseHeaders(err) if len(headers) > 0 { - colorFlag, _ := flagutil.GetStringFlag(cmd, "color") - printResponseHeadersPretty(out, headers, ShouldColorize(colorFlag)) + printResponseHeadersPretty(out, headers, stderrColorize(cmd)) } } fmt.Fprintf(out, "Error (%s): %s\n", classification.Type, classification.Message) @@ -790,15 +813,14 @@ func renderStructuredError(cmd *cobra.Command, out io.Writer, err error, classif jsonData, marshalErr := json.MarshalIndent(envelope, "", " ") if marshalErr != nil { jsonData, _ = json.MarshalIndent(map[string]interface{}{ - "error": err.Error(), + "error": redactedErrorText(err, classification), "error_type": string(classification.Type), "exit_code": ExitCodeFor(classification), "message": classification.Message, "hints": classification.Hints, }, "", " ") } - colorFlag, _ := flagutil.GetStringFlag(cmd, "color") - printScrubbedJSON(out, jsonData, ShouldColorize(colorFlag)) + printScrubbedJSON(out, jsonData, stderrColorize(cmd)) } func classifiedErrorEnvelope(err error, classification Classification) map[string]interface{} { @@ -809,7 +831,7 @@ func classifiedErrorEnvelope(err error, classification Classification) map[strin envelope[key] = value } } else { - envelope = map[string]interface{}{"error": err.Error()} + envelope = map[string]interface{}{"error": redactedErrorText(err, classification)} if classification.Body != nil { envelope["body"] = classification.Body } else if classification.RawBody != "" { @@ -1219,19 +1241,12 @@ func extractResponseHeaders(res interface{}) http.Header { return httpRes.Header } -// extractErrorResponseHeaders extracts HTTP response headers from an SDK error. -// Error types store *http.Response in a RawResponse field. +// extractErrorResponseHeaders extracts HTTP response headers from an SDK error +// or any error it wraps. func extractErrorResponseHeaders(err error) http.Header { for current := err; current != nil; current = errors.Unwrap(current) { - v, ok := derefToStruct(reflect.ValueOf(current)) - if !ok { - continue - } - rawResp := v.FieldByName("RawResponse") - if rawResp.IsValid() && rawResp.CanInterface() { - if r, ok := rawResp.Interface().(*http.Response); ok && r != nil { - return r.Header - } + if r := extractHTTPResponse(current); r != nil { + return r.Header } } return nil @@ -1395,19 +1410,25 @@ func applyJqToRawJSON(out io.Writer, rawBody []byte, jqExpr string, colorize, ra return fmt.Errorf("failed to parse response JSON for jq: %w", err) } results, err := ApplyJqFilter(data, jqExpr) - if err != nil { + if err != nil && jqHalt(err) == nil { return err } - return outputJqResults(out, results, colorize, raw) + if outErr := outputJqResults(out, results, colorize, raw); outErr != nil { + return outErr + } + return err } // applyJqToTyped applies a jq expression to typed content (non-raw path). func applyJqToTyped(out io.Writer, content interface{}, jqExpr string, colorize, raw bool) error { results, err := ApplyJqFilter(content, jqExpr) - if err != nil { + if err != nil && jqHalt(err) == nil { return err } - return outputJqResults(out, results, colorize, raw) + if outErr := outputJqResults(out, results, colorize, raw); outErr != nil { + return outErr + } + return err } // printTable renders content as an aligned table. @@ -1418,10 +1439,14 @@ func printTable(out io.Writer, content any) error { v := reflect.ValueOf(content) for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface { if v.IsNil() { - return fmt.Errorf("nil value, nothing to display as table") + break } v = v.Elem() } + if !v.IsValid() || ((v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface) && v.IsNil()) { + _, err := fmt.Fprintln(out, "(empty)") + return err + } switch v.Kind() { case reflect.Slice, reflect.Array: @@ -1563,7 +1588,7 @@ func printTableSingle(out io.Writer, v reflect.Value) error { } } if blocks == 0 { - return fmt.Errorf("no displayable fields found") + buf.WriteString("(empty)\n") } _, err := out.Write(buf.Bytes()) return err diff --git a/internal/output/output_test.go b/internal/output/output_test.go index da3e04cd..364d840e 100644 --- a/internal/output/output_test.go +++ b/internal/output/output_test.go @@ -750,6 +750,73 @@ func TestUnclassifiedRenderersKeepPollHandle(t *testing.T) { } } +func TestAsyncFailureDetailReadsDeclaredErrorMember(t *testing.T) { + for name, tc := range map[string]struct { + cfg asyncConfig + payload string + want string + }{ + "object": {cfg: asyncConfig{ErrorField: "error", ErrorMessageField: "message"}, payload: `{"error":{"message":"quota exceeded"}}`, want: "quota exceeded"}, + "array of objects": {cfg: asyncConfig{ErrorField: "errors", ErrorMessageField: "message"}, payload: `{"errors":[{"code":"x"},{"message":"unsafe prompt"},{"message":"second"}]}`, want: "unsafe prompt"}, + "array of strings": {cfg: asyncConfig{ErrorField: "errors", ErrorMessageField: "message"}, payload: `{"errors":[" unsafe prompt "]}`, want: "unsafe prompt"}, + "custom message": {cfg: asyncConfig{ErrorField: "errors", ErrorMessageField: "detail"}, payload: `{"errors":[{"detail":"rejected"}]}`, want: "rejected"}, + "missing member": {cfg: asyncConfig{ErrorField: "error", ErrorMessageField: "message"}, payload: `{"errors":[{"message":"elsewhere"}]}`, want: ""}, + "empty array": {cfg: asyncConfig{ErrorField: "errors", ErrorMessageField: "message"}, payload: `{"errors":[]}`, want: ""}, + } { + t.Run(name, func(t *testing.T) { + var payload interface{} + if err := json.Unmarshal([]byte(tc.payload), &payload); err != nil { + t.Fatal(err) + } + if got := asyncFailureDetail(&tc.cfg, payload); got != tc.want { + t.Fatalf("got %q; want %q", got, tc.want) + } + }) + } +} + +func TestAsyncMachineErrorOnlyIncludesDeclaredErrorMember(t *testing.T) { + for name, tc := range map[string]struct { + reason string + errorField string + payload string + want string + }{ + "default member": {payload: `{"state":"failed","error":{"message":"quota exceeded"}}`, want: `{"message":"quota exceeded"}`}, + "declared member": {errorField: "errors", payload: `{"state":"failed","errors":[{"message":"unsafe"}]}`, want: `[{"message":"unsafe"}]`}, + "missing member": {payload: `{"state":"failed","output":"large result body"}`}, + "non-object": {payload: `"failed"`, want: `"failed"`}, + "unknown state keeps payload": {reason: ReasonCLIAsyncUnknownState, payload: `{"state":"odd"}`, want: `{"state":"odd"}`}, + "protocol error keeps payload": {reason: ReasonCLIProtocol, payload: `{"output":"x"}`, want: `{"output":"x"}`}, + } { + t.Run(name, func(t *testing.T) { + var payload interface{} + if err := json.Unmarshal([]byte(tc.payload), &payload); err != nil { + t.Fatal(err) + } + reason := tc.reason + if reason == "" { + reason = ReasonCLIAsyncFailed + } + runtimeErr := &asyncRuntimeError{reason: reason, message: "failed", id: "handle", resume: "wait handle", payload: payload, errorField: tc.errorField} + got, present := runtimeErr.MachineErrorFields()["error"] + if tc.want == "" { + if present { + t.Fatalf("expected no error field, got %v", got) + } + return + } + encoded, err := json.Marshal(got) + if err != nil { + t.Fatal(err) + } + if string(encoded) != tc.want { + t.Fatalf("got %s; want %s", encoded, tc.want) + } + }) + } +} + func TestAsyncFailureScrubsResolvedCredentials(t *testing.T) { t.Cleanup(config.Reset) config.RegisterSecret("example-secret") @@ -766,6 +833,60 @@ func TestAsyncFailureScrubsResolvedCredentials(t *testing.T) { } } +func TestRedactedMessageDropsMaskedValues(t *testing.T) { + raw := `{"name":"n","value":"secret-value"}` + redacted := `{"name":"n","value":"(sensitive)"}` + for name, tc := range map[string]struct { + message, redacted, want string + }{ + "embedded raw body": {message: "API error occurred: Status 400\n" + raw, redacted: redacted, want: "API error occurred: Status 400\n" + redacted}, + "typed model JSON": {message: `{"value":"secret-value","name":"n"}`, redacted: redacted, want: redacted}, + "message from body field": {message: "request rejected", redacted: redacted, want: "request rejected"}, + "nothing masked": {message: raw, redacted: raw, want: raw}, + } { + t.Run(name, func(t *testing.T) { + if got := newMessageRedaction(raw, tc.redacted).apply(tc.message); got != tc.want { + t.Fatalf("got %q; want %q", got, tc.want) + } + }) + } + if got := newMessageRedaction("", redacted).apply("request failed"); got != "request failed" { + t.Fatalf("a message with no source body must be kept, got %q", got) + } + if got := newMessageRedaction(raw, redacted).apply("secret-value"); got != "(sensitive)" { + t.Fatalf("a message that is a masked field must be masked, got %q", got) + } + if got := newMessageRedaction(raw, "(sensitive)").apply("secret-value"); got != "(sensitive)" { + t.Fatalf("a message from a wholly masked body must be the mask, got %q", got) + } + nested := `{"outer":{"token":"abc-secret","codes":[123456]}}` + nestedRedacted := `{"outer":"(sensitive)"}` + if got := newMessageRedaction(nested, nestedRedacted).apply("rejected abc-secret with 123456"); got != "rejected (sensitive) with (sensitive)" { + t.Fatalf("values under a masked subtree must be masked, got %q", got) + } + numbers := `{"id":9007199254740993,"rate":1.50,"name":"n"}` + numbersRedacted := `{"id":"(sensitive)","rate":"(sensitive)","name":"n"}` + + if got := newMessageRedaction(numbers, numbersRedacted).apply("id 9007199254740993 at 1.50"); got != "id (sensitive) at (sensitive)" { + t.Fatalf("masked numbers must keep their original spelling, got %q", got) + } + repeated := `{"message":"rejected s","secrets":["s","s","s","s","s","s","s","s","s","s","s","s","s","s","s","s"]}` + repeatedRedacted := `{"message":"rejected s","secrets":["(sensitive)","(sensitive)","(sensitive)","(sensitive)","(sensitive)","(sensitive)","(sensitive)","(sensitive)","(sensitive)","(sensitive)","(sensitive)","(sensitive)","(sensitive)","(sensitive)","(sensitive)","(sensitive)"]}` + if got := newMessageRedaction(repeated, repeatedRedacted).apply("rejected s"); got != "rejected (sensitive)" { + t.Fatalf("each masked value must be replaced in a single pass, got %q", got) + } +} + +func TestStructuredErrorEnvelopeRedactsNonObjectBodyErrorText(t *testing.T) { + raw := `["secret-value"]` + classification := Classification{RawBody: `["(sensitive)"]`, Body: []interface{}{"(sensitive)"}} + envelope := classifiedErrorEnvelope(errors.New(raw), classification) + text, _ := envelope["error"].(string) + if strings.Contains(text, "secret-value") || text != classification.RawBody { + t.Fatalf("error text = %q; want the redacted body", text) + } +} + func TestScrubJSONDocumentMasksDecodedValues(t *testing.T) { t.Cleanup(config.Reset) config.RegisterSecret(`example"secret`) @@ -1817,3 +1938,26 @@ func TestUnknownSubcommandHonoursDisableSuggestions(t *testing.T) { } } } + +type failingTableWriter struct{} + +func (failingTableWriter) Write([]byte) (int, error) { return 0, errors.New("write failed") } + +func TestPrintTableRendersEmptyValues(t *testing.T) { + var nilPointer *struct{ Name string } + for name, content := range map[string]any{ + "untyped nil": nil, + "nil pointer": nilPointer, + "empty struct": struct{}{}, + } { + t.Run(name, func(t *testing.T) { + var buf bytes.Buffer + if err := printTable(&buf, content); err != nil || buf.String() != "(empty)\n" { + t.Fatalf("got %q, error %v; want (empty)", buf.String(), err) + } + if err := printTable(failingTableWriter{}, content); err == nil { + t.Fatal("expected the write error to be returned") + } + }) + } +} diff --git a/internal/output/outputitems.go b/internal/output/outputitems.go index 51376ed1..e763c262 100644 --- a/internal/output/outputitems.go +++ b/internal/output/outputitems.go @@ -28,9 +28,9 @@ import ( // outputOneItem outputs a single item in the appropriate streaming format. func outputOneItem(out io.Writer, item interface{}, format, jqExpr string, colorize, jqRaw, first bool) error { if jqExpr != "" { - results, err := ApplyJqFilter(item, jqExpr) - if err != nil { - return err + results, jqErr := ApplyJqFilter(item, jqExpr) + if jqErr != nil && jqHalt(jqErr) == nil { + return jqErr } for _, r := range results { if s, ok := r.(string); ok && jqRaw { @@ -45,7 +45,7 @@ func outputOneItem(out io.Writer, item interface{}, format, jqExpr string, color } printJSON(out, data, colorize) } - return nil + return jqErr } switch format { diff --git a/internal/output/paginated.go b/internal/output/paginated.go index e4001d72..8801fc98 100644 --- a/internal/output/paginated.go +++ b/internal/output/paginated.go @@ -124,7 +124,7 @@ func PaginatedResult(cmd *cobra.Command, res interface{}, contentFieldName, resu lastHeaders = extractResponseHeaders(page) } else if pageHeaders { if err := outputPageWithHeaders(out, page, format, jqExpr, colorize, jqRaw, rawJSON, first); err != nil { - return err + return pageOutcomeOverHalt(cmd, page, err) } first = false handledRaw = true @@ -133,7 +133,7 @@ func PaginatedResult(cmd *cobra.Command, res interface{}, contentFieldName, resu var err error handledRaw, err = outputRawPage(out, page, resultsFieldName != "", probe.Results, jqExpr, colorize, jqRaw) if err != nil { - return err + return pageOutcomeOverHalt(cmd, page, err) } if handledRaw { first = false @@ -158,7 +158,7 @@ func PaginatedResult(cmd *cobra.Command, res interface{}, contentFieldName, resu } else { for i := 0; i < itemsVal.Len(); i++ { if err := outputOneItem(out, itemsVal.Index(i).Interface(), format, jqExpr, colorize, jqRaw, first); err != nil { - return err + return pageOutcomeOverHalt(cmd, page, err) } first = false } @@ -168,7 +168,7 @@ func PaginatedResult(cmd *cobra.Command, res interface{}, contentFieldName, resu } else { // No results field path — output the entire content per page if err := outputOneItem(out, content, format, jqExpr, colorize, jqRaw, first); err != nil { - return err + return pageOutcomeOverHalt(cmd, page, err) } first = false } @@ -208,6 +208,18 @@ func PaginatedResult(cmd *cobra.Command, res interface{}, contentFieldName, resu return finish() } +// pageOutcomeOverHalt reports the page's outcome failure in place of a jq +// halt, so a halt cannot turn a failed outcome into success. +func pageOutcomeOverHalt(cmd *cobra.Command, page interface{}, err error) error { + if jqHalt(err) == nil { + return err + } + if failure := outcomeResultFailure(cmd, page); failure != nil { + return Error(cmd, failure) + } + return err +} + // outputPageWithHeaders prints one whole page with its response headers: // machine formats and jq get the page object with _response_headers, human // formats get the typed page followed by a headers section. diff --git a/internal/output/streaming.go b/internal/output/streaming.go index b887b719..4cd00005 100644 --- a/internal/output/streaming.go +++ b/internal/output/streaming.go @@ -19,6 +19,7 @@ package output import ( + "bytes" "encoding/json" "errors" "math/big" @@ -217,6 +218,9 @@ func streamResult(cmd *cobra.Command, res interface{}, streamFieldName string, h return false, finishJoin(err) } } else if err := outputOneItem(out, item, format, jqExpr, colorize, jqRaw, first); err != nil { + if streamFailure != nil && jqHalt(err) != nil { + return false, renderAfterFinish(wrap(streamFailure)) + } return false, err } first = false @@ -417,23 +421,84 @@ func canonicalNumber(n json.Number) interface{} { return json.Number(shortest) } +// The frame's wire data object is preferred over the decoded model, whose +// re-encoding drops undeclared members that error classification reads. A +// union of whole envelopes keeps the envelope level, with only its data +// replaced. func streamErrorEvent(item interface{}, raw []byte) (json.RawMessage, bool) { u, ok := errorUnionValue(reflect.ValueOf(item)) if !ok { return nil, false } - if data, err := marshalJSON(u.Interface()); err == nil { - return data, true + var frame map[string]json.RawMessage + frameErr := json.Unmarshal(raw, &frame) + var wireData json.RawMessage + if frameErr == nil && strings.HasPrefix(strings.TrimSpace(string(frame["data"])), "{") { + wireData = frame["data"] + } + envelopeUnion := isUnionStruct(derefValue(reflect.ValueOf(item)).Type()) + if wireData != nil && !envelopeUnion { + return wireData, true } - if isUnionStruct(derefValue(reflect.ValueOf(item)).Type()) { + var body json.RawMessage + if data, err := marshalJSON(u.Interface()); err == nil { + body = data + } else if envelopeUnion { data, err := json.Marshal(wireStreamItem(item, raw, nil, false)) - return data, err == nil + if err != nil { + return nil, false + } + body = data + } else { + if frameErr != nil || len(frame["data"]) == 0 { + return nil, false + } + return frame["data"], true } - var frame map[string]json.RawMessage - if err := json.Unmarshal(raw, &frame); err != nil || len(frame["data"]) == 0 { - return nil, false + if wireData != nil { + return replaceEnvelopeData(body, wireData), true + } + return body, true +} + +// replaceEnvelopeData swaps the top-level data member of an encoded envelope, +// keeping the other members in order. Without such a member the envelope is +// returned unchanged. +func replaceEnvelopeData(envelope, data json.RawMessage) json.RawMessage { + decoder := json.NewDecoder(bytes.NewReader(envelope)) + if token, err := decoder.Token(); err != nil || token != json.Delim('{') { + return envelope + } + var out bytes.Buffer + out.WriteByte('{') + replaced := false + for decoder.More() { + token, err := decoder.Token() + if err != nil { + return envelope + } + key, _ := token.(string) + var value json.RawMessage + if err := decoder.Decode(&value); err != nil { + return envelope + } + if key == "data" { + value = data + replaced = true + } + if out.Len() > 1 { + out.WriteByte(',') + } + encodedKey, _ := json.Marshal(key) + out.Write(encodedKey) + out.WriteByte(':') + out.Write(value) + } + if !replaced { + return envelope } - return frame["data"], true + out.WriteByte('}') + return out.Bytes() } func errorUnionValue(v reflect.Value) (reflect.Value, bool) { diff --git a/internal/output/streaming_test.go b/internal/output/streaming_test.go index 580eb2cd..6b4ddc55 100644 --- a/internal/output/streaming_test.go +++ b/internal/output/streaming_test.go @@ -20,6 +20,7 @@ import ( "bytes" "encoding/json" "errors" + "reflect" "testing" ) @@ -123,6 +124,57 @@ func TestStreamErrorEventUnencodableBodyMatchesEncodableShape(t *testing.T) { } } +type objectErrorEnvelope struct { + Data *errorData `json:"data"` + Event string `json:"event"` + ID string `json:"id"` + Retry int `json:"retry"` +} + +type objectEnvelopeUnion struct { + Envelope *objectErrorEnvelope `union:"member"` + Type string +} + +func (u objectEnvelopeUnion) MarshalJSON() ([]byte, error) { + return json.Marshal(u.Envelope) +} + +type unencodableObjectEnvelopeUnion struct { + Envelope *objectErrorEnvelope `union:"member"` + Type string +} + +func (unencodableObjectEnvelopeUnion) MarshalJSON() ([]byte, error) { + return nil, errors.New("required union has no member") +} + +func TestStreamErrorEventEnvelopeUnionKeepsEnvelopeLevel(t *testing.T) { + raw := `{"id":"7","event":"error","retry":3000,"data":{"message":"quota exceeded","extra":{"href":"https://example.com"}}}` + envelope := &objectErrorEnvelope{Data: &errorData{Message: "quota exceeded"}, Event: "error", ID: "7", Retry: 3000} + want := map[string]interface{}{ + "id": "7", + "event": "error", + "retry": float64(3000), + "data": map[string]interface{}{"message": "quota exceeded", "extra": map[string]interface{}{"href": "https://example.com"}}, + } + for name, item := range map[string]interface{}{ + "encodable": objectEnvelopeUnion{Envelope: envelope, Type: "error"}, + "unencodable": unencodableObjectEnvelopeUnion{Envelope: envelope, Type: "error"}, + } { + t.Run(name, func(t *testing.T) { + body, isErr := streamErrorEvent(item, []byte(raw)) + if !isErr { + t.Fatal("not classified as an error event") + } + var got map[string]interface{} + if err := json.Unmarshal(body, &got); err != nil || !reflect.DeepEqual(got, want) { + t.Fatalf("got %s, error %v; want %v", body, err, want) + } + }) + } +} + type tableEnvelopeRow struct { Name string `json:"name"` Age int `json:"age"` diff --git a/internal/sdk/models/credentials/credential.go b/internal/sdk/models/credentials/credential.go index c888a611..7e3631cf 100644 --- a/internal/sdk/models/credentials/credential.go +++ b/internal/sdk/models/credentials/credential.go @@ -34,6 +34,14 @@ func (e Status) ToPointer() *Status { return &e } +// StatusValues returns every known Status value in schema order. +func StatusValues() []Status { + return []Status{ + StatusActive, + StatusRevoked, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *Status) IsExact() bool { if e != nil { @@ -58,6 +66,15 @@ func (e Type) ToPointer() *Type { return &e } +// TypeValues returns every known Type value in schema order. +func TypeValues() []Type { + return []Type{ + TypeBearerToken, + TypeOauth2, + TypeEnvironmentVariable, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *Type) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/credentials/injectionlocationenum.go b/internal/sdk/models/credentials/injectionlocationenum.go index c9611381..da11c53a 100644 --- a/internal/sdk/models/credentials/injectionlocationenum.go +++ b/internal/sdk/models/credentials/injectionlocationenum.go @@ -32,6 +32,15 @@ const ( func (e InjectionLocationEnum) ToPointer() *InjectionLocationEnum { return &e } + +// InjectionLocationEnumValues returns every known InjectionLocationEnum value in schema order. +func InjectionLocationEnumValues() []InjectionLocationEnum { + return []InjectionLocationEnum{ + InjectionLocationEnumHeader, + InjectionLocationEnumQuery, + InjectionLocationEnumBody, + } +} func (e *InjectionLocationEnum) UnmarshalJSON(data []byte) error { var v string if err := json.Unmarshal(data, &v); err != nil { diff --git a/internal/sdk/models/environments/createenvironmentrequest.go b/internal/sdk/models/environments/createenvironmentrequest.go index 48a17a72..a2421c6e 100644 --- a/internal/sdk/models/environments/createenvironmentrequest.go +++ b/internal/sdk/models/environments/createenvironmentrequest.go @@ -130,6 +130,13 @@ const ( func (e CreateEnvironmentRequestNetworkEnum) ToPointer() *CreateEnvironmentRequestNetworkEnum { return &e } + +// CreateEnvironmentRequestNetworkEnumValues returns every known CreateEnvironmentRequestNetworkEnum value in schema order. +func CreateEnvironmentRequestNetworkEnumValues() []CreateEnvironmentRequestNetworkEnum { + return []CreateEnvironmentRequestNetworkEnum{ + CreateEnvironmentRequestNetworkEnumDisabled, + } +} func (e *CreateEnvironmentRequestNetworkEnum) UnmarshalJSON(data []byte) error { var v string if err := json.Unmarshal(data, &v); err != nil { diff --git a/internal/sdk/models/environments/environment.go b/internal/sdk/models/environments/environment.go index 49bc2f18..7c5276bb 100644 --- a/internal/sdk/models/environments/environment.go +++ b/internal/sdk/models/environments/environment.go @@ -35,6 +35,13 @@ func (e EnvironmentNetworkEnum) ToPointer() *EnvironmentNetworkEnum { return &e } +// EnvironmentNetworkEnumValues returns every known EnvironmentNetworkEnum value in schema order. +func EnvironmentNetworkEnumValues() []EnvironmentNetworkEnum { + return []EnvironmentNetworkEnum{ + EnvironmentNetworkEnumDisabled, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *EnvironmentNetworkEnum) IsExact() bool { if e != nil { @@ -181,6 +188,14 @@ func (e Status) ToPointer() *Status { return &e } +// StatusValues returns every known Status value in schema order. +func StatusValues() []Status { + return []Status{ + StatusActive, + StatusExpired, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *Status) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/environments/environmentfile.go b/internal/sdk/models/environments/environmentfile.go index 399b8ee2..74059c46 100644 --- a/internal/sdk/models/environments/environmentfile.go +++ b/internal/sdk/models/environments/environmentfile.go @@ -34,6 +34,14 @@ func (e Type) ToPointer() *Type { return &e } +// TypeValues returns every known Type value in schema order. +func TypeValues() []Type { + return []Type{ + TypeFile, + TypeDirectory, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *Type) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/genai/file.go b/internal/sdk/models/genai/file.go index 0c64af58..b4c0e2d4 100644 --- a/internal/sdk/models/genai/file.go +++ b/internal/sdk/models/genai/file.go @@ -40,6 +40,16 @@ func (e Source) ToPointer() *Source { return &e } +// SourceValues returns every known Source value in schema order. +func SourceValues() []Source { + return []Source{ + SourceSourceUnspecified, + SourceUploaded, + SourceGenerated, + SourceRegistered, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *Source) IsExact() bool { if e != nil { @@ -69,6 +79,16 @@ func (e FileState) ToPointer() *FileState { return &e } +// FileStateValues returns every known FileState value in schema order. +func FileStateValues() []FileState { + return []FileState{ + FileStateStateUnspecified, + FileStateProcessing, + FileStateActive, + FileStateFailed, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *FileState) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/genai/generatedfile.go b/internal/sdk/models/genai/generatedfile.go index 30e3693e..dd891bde 100644 --- a/internal/sdk/models/genai/generatedfile.go +++ b/internal/sdk/models/genai/generatedfile.go @@ -38,6 +38,16 @@ func (e GeneratedFileState) ToPointer() *GeneratedFileState { return &e } +// GeneratedFileStateValues returns every known GeneratedFileState value in schema order. +func GeneratedFileStateValues() []GeneratedFileState { + return []GeneratedFileState{ + GeneratedFileStateStateUnspecified, + GeneratedFileStateGenerating, + GeneratedFileStateGenerated, + GeneratedFileStateFailed, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *GeneratedFileState) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/agentoption.go b/internal/sdk/models/interactions/agentoption.go index aad3b34e..beedaa3b 100644 --- a/internal/sdk/models/interactions/agentoption.go +++ b/internal/sdk/models/interactions/agentoption.go @@ -34,6 +34,16 @@ func (e AgentOption) ToPointer() *AgentOption { return &e } +// AgentOptionValues returns every known AgentOption value in schema order. +func AgentOptionValues() []AgentOption { + return []AgentOption{ + AgentOptionDeepResearchPreview042026, + AgentOptionDeepResearchMaxPreview042026, + AgentOptionAntigravityPreview052026, + AgentOptionAntigravityPreview092026, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *AgentOption) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/audiocontent.go b/internal/sdk/models/interactions/audiocontent.go index f1aac51f..4ac34855 100644 --- a/internal/sdk/models/interactions/audiocontent.go +++ b/internal/sdk/models/interactions/audiocontent.go @@ -47,6 +47,25 @@ func (e AudioContentMimeType) ToPointer() *AudioContentMimeType { return &e } +// AudioContentMimeTypeValues returns every known AudioContentMimeType value in schema order. +func AudioContentMimeTypeValues() []AudioContentMimeType { + return []AudioContentMimeType{ + AudioContentMimeTypeAudioWav, + AudioContentMimeTypeAudioMp3, + AudioContentMimeTypeAudioAiff, + AudioContentMimeTypeAudioAac, + AudioContentMimeTypeAudioOgg, + AudioContentMimeTypeAudioFlac, + AudioContentMimeTypeAudioMpeg, + AudioContentMimeTypeAudioM4a, + AudioContentMimeTypeAudioL16, + AudioContentMimeTypeAudioOpus, + AudioContentMimeTypeAudioAlaw, + AudioContentMimeTypeAudioMulaw, + AudioContentMimeTypeAudioWebm, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *AudioContentMimeType) IsExact() bool { if e != nil { @@ -68,6 +87,13 @@ func (e AudioProcessingEnum) ToPointer() *AudioProcessingEnum { return &e } +// AudioProcessingEnumValues returns every known AudioProcessingEnum value in schema order. +func AudioProcessingEnumValues() []AudioProcessingEnum { + return []AudioProcessingEnum{ + AudioProcessingEnumStatic, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *AudioProcessingEnum) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/audiodelta.go b/internal/sdk/models/interactions/audiodelta.go index e486b7c9..3b65ea5e 100644 --- a/internal/sdk/models/interactions/audiodelta.go +++ b/internal/sdk/models/interactions/audiodelta.go @@ -42,6 +42,25 @@ func (e AudioDeltaMimeType) ToPointer() *AudioDeltaMimeType { return &e } +// AudioDeltaMimeTypeValues returns every known AudioDeltaMimeType value in schema order. +func AudioDeltaMimeTypeValues() []AudioDeltaMimeType { + return []AudioDeltaMimeType{ + AudioDeltaMimeTypeAudioWav, + AudioDeltaMimeTypeAudioMp3, + AudioDeltaMimeTypeAudioAiff, + AudioDeltaMimeTypeAudioAac, + AudioDeltaMimeTypeAudioOgg, + AudioDeltaMimeTypeAudioFlac, + AudioDeltaMimeTypeAudioMpeg, + AudioDeltaMimeTypeAudioM4a, + AudioDeltaMimeTypeAudioL16, + AudioDeltaMimeTypeAudioOpus, + AudioDeltaMimeTypeAudioAlaw, + AudioDeltaMimeTypeAudioMulaw, + AudioDeltaMimeTypeAudioWebm, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *AudioDeltaMimeType) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/audioresponseformat.go b/internal/sdk/models/interactions/audioresponseformat.go index a6ef4a29..a4e7d817 100644 --- a/internal/sdk/models/interactions/audioresponseformat.go +++ b/internal/sdk/models/interactions/audioresponseformat.go @@ -32,6 +32,14 @@ func (e AudioResponseFormatDelivery) ToPointer() *AudioResponseFormatDelivery { return &e } +// AudioResponseFormatDeliveryValues returns every known AudioResponseFormatDelivery value in schema order. +func AudioResponseFormatDeliveryValues() []AudioResponseFormatDelivery { + return []AudioResponseFormatDelivery{ + AudioResponseFormatDeliveryInline, + AudioResponseFormatDeliveryURI, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *AudioResponseFormatDelivery) IsExact() bool { if e != nil { @@ -59,6 +67,18 @@ func (e AudioResponseFormatMimeType) ToPointer() *AudioResponseFormatMimeType { return &e } +// AudioResponseFormatMimeTypeValues returns every known AudioResponseFormatMimeType value in schema order. +func AudioResponseFormatMimeTypeValues() []AudioResponseFormatMimeType { + return []AudioResponseFormatMimeType{ + AudioResponseFormatMimeTypeAudioMp3, + AudioResponseFormatMimeTypeAudioOggOpus, + AudioResponseFormatMimeTypeAudioL16, + AudioResponseFormatMimeTypeAudioWav, + AudioResponseFormatMimeTypeAudioAlaw, + AudioResponseFormatMimeTypeAudioMulaw, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *AudioResponseFormatMimeType) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/codeexecutioncallarguments.go b/internal/sdk/models/interactions/codeexecutioncallarguments.go index d72a8271..22ce4dd6 100644 --- a/internal/sdk/models/interactions/codeexecutioncallarguments.go +++ b/internal/sdk/models/interactions/codeexecutioncallarguments.go @@ -32,6 +32,14 @@ func (e Language) ToPointer() *Language { return &e } +// LanguageValues returns every known Language value in schema order. +func LanguageValues() []Language { + return []Language{ + LanguagePython, + LanguageBash, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *Language) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/computeruse.go b/internal/sdk/models/interactions/computeruse.go index 693834fc..9c19d37a 100644 --- a/internal/sdk/models/interactions/computeruse.go +++ b/internal/sdk/models/interactions/computeruse.go @@ -36,6 +36,19 @@ func (e DisabledSafetyPolicy) ToPointer() *DisabledSafetyPolicy { return &e } +// DisabledSafetyPolicyValues returns every known DisabledSafetyPolicy value in schema order. +func DisabledSafetyPolicyValues() []DisabledSafetyPolicy { + return []DisabledSafetyPolicy{ + DisabledSafetyPolicyFinancialTransactions, + DisabledSafetyPolicySensitiveDataModification, + DisabledSafetyPolicyCommunicationTool, + DisabledSafetyPolicyAccountCreation, + DisabledSafetyPolicyDataModification, + DisabledSafetyPolicyUserConsentManagement, + DisabledSafetyPolicyLegalTermsAndAgreements, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *DisabledSafetyPolicy) IsExact() bool { if e != nil { @@ -60,6 +73,15 @@ func (e EnvironmentEnum) ToPointer() *EnvironmentEnum { return &e } +// EnvironmentEnumValues returns every known EnvironmentEnum value in schema order. +func EnvironmentEnumValues() []EnvironmentEnum { + return []EnvironmentEnum{ + EnvironmentEnumBrowser, + EnvironmentEnumMobile, + EnvironmentEnumDesktop, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *EnvironmentEnum) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/deepresearchagentconfig.go b/internal/sdk/models/interactions/deepresearchagentconfig.go index 7ded1a79..f5d54af2 100644 --- a/internal/sdk/models/interactions/deepresearchagentconfig.go +++ b/internal/sdk/models/interactions/deepresearchagentconfig.go @@ -32,6 +32,14 @@ func (e Visualization) ToPointer() *Visualization { return &e } +// VisualizationValues returns every known Visualization value in schema order. +func VisualizationValues() []Visualization { + return []Visualization{ + VisualizationOff, + VisualizationAuto, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *Visualization) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/documentcontent.go b/internal/sdk/models/interactions/documentcontent.go index 7c7c6855..4207c383 100644 --- a/internal/sdk/models/interactions/documentcontent.go +++ b/internal/sdk/models/interactions/documentcontent.go @@ -46,6 +46,24 @@ func (e DocumentContentMimeType) ToPointer() *DocumentContentMimeType { return &e } +// DocumentContentMimeTypeValues returns every known DocumentContentMimeType value in schema order. +func DocumentContentMimeTypeValues() []DocumentContentMimeType { + return []DocumentContentMimeType{ + DocumentContentMimeTypeApplicationPdf, + DocumentContentMimeTypeTextCsv, + DocumentContentMimeTypeApplicationVndOpenxmlformatsOfficedocumentPresentationmlPresentation, + DocumentContentMimeTypeApplicationVndMsPowerpoint, + DocumentContentMimeTypeApplicationVndOasisOpendocumentPresentation, + DocumentContentMimeTypeApplicationVndOpenxmlformatsOfficedocumentWordprocessingmlDocument, + DocumentContentMimeTypeApplicationMsword, + DocumentContentMimeTypeApplicationVndOpenxmlformatsOfficedocumentWordprocessingmlTemplate, + DocumentContentMimeTypeApplicationVndOasisOpendocumentText, + DocumentContentMimeTypeApplicationVndOpenxmlformatsOfficedocumentSpreadsheetmlSheet, + DocumentContentMimeTypeApplicationVndMsExcel, + DocumentContentMimeTypeApplicationVndOasisOpendocumentSpreadsheet, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *DocumentContentMimeType) IsExact() bool { if e != nil { @@ -67,6 +85,13 @@ func (e DocumentProcessingEnum) ToPointer() *DocumentProcessingEnum { return &e } +// DocumentProcessingEnumValues returns every known DocumentProcessingEnum value in schema order. +func DocumentProcessingEnumValues() []DocumentProcessingEnum { + return []DocumentProcessingEnum{ + DocumentProcessingEnumStatic, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *DocumentProcessingEnum) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/documentdelta.go b/internal/sdk/models/interactions/documentdelta.go index 08d372cb..ad5dc29d 100644 --- a/internal/sdk/models/interactions/documentdelta.go +++ b/internal/sdk/models/interactions/documentdelta.go @@ -41,6 +41,24 @@ func (e DocumentDeltaMimeType) ToPointer() *DocumentDeltaMimeType { return &e } +// DocumentDeltaMimeTypeValues returns every known DocumentDeltaMimeType value in schema order. +func DocumentDeltaMimeTypeValues() []DocumentDeltaMimeType { + return []DocumentDeltaMimeType{ + DocumentDeltaMimeTypeApplicationPdf, + DocumentDeltaMimeTypeTextCsv, + DocumentDeltaMimeTypeApplicationVndOpenxmlformatsOfficedocumentPresentationmlPresentation, + DocumentDeltaMimeTypeApplicationVndMsPowerpoint, + DocumentDeltaMimeTypeApplicationVndOasisOpendocumentPresentation, + DocumentDeltaMimeTypeApplicationVndOpenxmlformatsOfficedocumentWordprocessingmlDocument, + DocumentDeltaMimeTypeApplicationMsword, + DocumentDeltaMimeTypeApplicationVndOpenxmlformatsOfficedocumentWordprocessingmlTemplate, + DocumentDeltaMimeTypeApplicationVndOasisOpendocumentText, + DocumentDeltaMimeTypeApplicationVndOpenxmlformatsOfficedocumentSpreadsheetmlSheet, + DocumentDeltaMimeTypeApplicationVndMsExcel, + DocumentDeltaMimeTypeApplicationVndOasisOpendocumentSpreadsheet, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *DocumentDeltaMimeType) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/environment.go b/internal/sdk/models/interactions/environment.go index e304e01b..ae4f416b 100644 --- a/internal/sdk/models/interactions/environment.go +++ b/internal/sdk/models/interactions/environment.go @@ -156,6 +156,13 @@ func (e NetworkEnum) ToPointer() *NetworkEnum { return &e } +// NetworkEnumValues returns every known NetworkEnum value in schema order. +func NetworkEnumValues() []NetworkEnum { + return []NetworkEnum{ + NetworkEnumDisabled, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *NetworkEnum) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/environmentmode.go b/internal/sdk/models/interactions/environmentmode.go index 2a1f6c0f..c9762901 100644 --- a/internal/sdk/models/interactions/environmentmode.go +++ b/internal/sdk/models/interactions/environmentmode.go @@ -28,6 +28,14 @@ func (e EnvironmentMode) ToPointer() *EnvironmentMode { return &e } +// EnvironmentModeValues returns every known EnvironmentMode value in schema order. +func EnvironmentModeValues() []EnvironmentMode { + return []EnvironmentMode{ + EnvironmentModeOnDemand, + EnvironmentModeSelfHosted, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *EnvironmentMode) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/environmentnetworkegressallowlist.go b/internal/sdk/models/interactions/environmentnetworkegressallowlist.go index 5952ae45..04fd9b94 100644 --- a/internal/sdk/models/interactions/environmentnetworkegressallowlist.go +++ b/internal/sdk/models/interactions/environmentnetworkegressallowlist.go @@ -34,6 +34,13 @@ func (e Disabled) ToPointer() *Disabled { return &e } +// DisabledValues returns every known Disabled value in schema order. +func DisabledValues() []Disabled { + return []Disabled{ + DisabledDisabled, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *Disabled) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/findrequest.go b/internal/sdk/models/interactions/findrequest.go index b1e4a9ba..4dfb32f6 100644 --- a/internal/sdk/models/interactions/findrequest.go +++ b/internal/sdk/models/interactions/findrequest.go @@ -32,6 +32,14 @@ func (e Mode) ToPointer() *Mode { return &e } +// ModeValues returns every known Mode value in schema order. +func ModeValues() []Mode { + return []Mode{ + ModeScan, + ModeVerify, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *Mode) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/googlesearch.go b/internal/sdk/models/interactions/googlesearch.go index 012fb103..08ad47f8 100644 --- a/internal/sdk/models/interactions/googlesearch.go +++ b/internal/sdk/models/interactions/googlesearch.go @@ -32,6 +32,15 @@ func (e GoogleSearchSearchType) ToPointer() *GoogleSearchSearchType { return &e } +// GoogleSearchSearchTypeValues returns every known GoogleSearchSearchType value in schema order. +func GoogleSearchSearchTypeValues() []GoogleSearchSearchType { + return []GoogleSearchSearchType{ + GoogleSearchSearchTypeWebSearch, + GoogleSearchSearchTypeImageSearch, + GoogleSearchSearchTypeEnterpriseWebSearch, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *GoogleSearchSearchType) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/googlesearchcallstep.go b/internal/sdk/models/interactions/googlesearchcallstep.go index e8aa4c5a..b1f8de30 100644 --- a/internal/sdk/models/interactions/googlesearchcallstep.go +++ b/internal/sdk/models/interactions/googlesearchcallstep.go @@ -33,6 +33,15 @@ func (e GoogleSearchCallStepSearchType) ToPointer() *GoogleSearchCallStepSearchT return &e } +// GoogleSearchCallStepSearchTypeValues returns every known GoogleSearchCallStepSearchType value in schema order. +func GoogleSearchCallStepSearchTypeValues() []GoogleSearchCallStepSearchType { + return []GoogleSearchCallStepSearchType{ + GoogleSearchCallStepSearchTypeWebSearch, + GoogleSearchCallStepSearchTypeImageSearch, + GoogleSearchCallStepSearchTypeEnterpriseWebSearch, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *GoogleSearchCallStepSearchType) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/groundingtoolcount.go b/internal/sdk/models/interactions/groundingtoolcount.go index b3e68338..44e9be15 100644 --- a/internal/sdk/models/interactions/groundingtoolcount.go +++ b/internal/sdk/models/interactions/groundingtoolcount.go @@ -33,6 +33,15 @@ func (e GroundingToolCountType) ToPointer() *GroundingToolCountType { return &e } +// GroundingToolCountTypeValues returns every known GroundingToolCountType value in schema order. +func GroundingToolCountTypeValues() []GroundingToolCountType { + return []GroundingToolCountType{ + GroundingToolCountTypeGoogleSearch, + GroundingToolCountTypeGoogleMaps, + GroundingToolCountTypeRetrieval, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *GroundingToolCountType) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/harmcategory.go b/internal/sdk/models/interactions/harmcategory.go index 20245ff7..25b3007c 100644 --- a/internal/sdk/models/interactions/harmcategory.go +++ b/internal/sdk/models/interactions/harmcategory.go @@ -35,6 +35,22 @@ func (e HarmCategory) ToPointer() *HarmCategory { return &e } +// HarmCategoryValues returns every known HarmCategory value in schema order. +func HarmCategoryValues() []HarmCategory { + return []HarmCategory{ + HarmCategoryHateSpeech, + HarmCategoryDangerousContent, + HarmCategoryHarassment, + HarmCategorySexuallyExplicit, + HarmCategoryCivicIntegrity, + HarmCategoryImageHate, + HarmCategoryImageDangerousContent, + HarmCategoryImageHarassment, + HarmCategoryImageSexuallyExplicit, + HarmCategoryJailbreak, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *HarmCategory) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/imageconfig.go b/internal/sdk/models/interactions/imageconfig.go index 9d3df331..03c8df32 100644 --- a/internal/sdk/models/interactions/imageconfig.go +++ b/internal/sdk/models/interactions/imageconfig.go @@ -48,6 +48,26 @@ func (e ImageConfigAspectRatio) ToPointer() *ImageConfigAspectRatio { return &e } +// ImageConfigAspectRatioValues returns every known ImageConfigAspectRatio value in schema order. +func ImageConfigAspectRatioValues() []ImageConfigAspectRatio { + return []ImageConfigAspectRatio{ + ImageConfigAspectRatioEleven, + ImageConfigAspectRatioTwentyThree, + ImageConfigAspectRatioThirtyTwo, + ImageConfigAspectRatioThirtyFour, + ImageConfigAspectRatioFortyThree, + ImageConfigAspectRatioFortyFive, + ImageConfigAspectRatioFiftyFour, + ImageConfigAspectRatioNineHundredAndSixteen, + ImageConfigAspectRatioOneHundredAndSixtyNine, + ImageConfigAspectRatioTwoHundredAndNineteen, + ImageConfigAspectRatioEighteen, + ImageConfigAspectRatioEightyOne, + ImageConfigAspectRatioFourteen, + ImageConfigAspectRatioFortyOne, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *ImageConfigAspectRatio) IsExact() bool { if e != nil { @@ -74,6 +94,16 @@ func (e ImageConfigImageSize) ToPointer() *ImageConfigImageSize { return &e } +// ImageConfigImageSizeValues returns every known ImageConfigImageSize value in schema order. +func ImageConfigImageSizeValues() []ImageConfigImageSize { + return []ImageConfigImageSize{ + ImageConfigImageSizeOneK, + ImageConfigImageSizeTwoK, + ImageConfigImageSizeFourK, + ImageConfigImageSizeFiveHundredAndTwelve, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *ImageConfigImageSize) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/imagecontent.go b/internal/sdk/models/interactions/imagecontent.go index b10b4696..ac939f06 100644 --- a/internal/sdk/models/interactions/imagecontent.go +++ b/internal/sdk/models/interactions/imagecontent.go @@ -38,6 +38,20 @@ func (e ImageContentMimeType) ToPointer() *ImageContentMimeType { return &e } +// ImageContentMimeTypeValues returns every known ImageContentMimeType value in schema order. +func ImageContentMimeTypeValues() []ImageContentMimeType { + return []ImageContentMimeType{ + ImageContentMimeTypeImagePng, + ImageContentMimeTypeImageJpeg, + ImageContentMimeTypeImageWebp, + ImageContentMimeTypeImageHeic, + ImageContentMimeTypeImageHeif, + ImageContentMimeTypeImageGif, + ImageContentMimeTypeImageBmp, + ImageContentMimeTypeImageTiff, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *ImageContentMimeType) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/imagedelta.go b/internal/sdk/models/interactions/imagedelta.go index 4542e96a..6e340252 100644 --- a/internal/sdk/models/interactions/imagedelta.go +++ b/internal/sdk/models/interactions/imagedelta.go @@ -37,6 +37,20 @@ func (e ImageDeltaMimeType) ToPointer() *ImageDeltaMimeType { return &e } +// ImageDeltaMimeTypeValues returns every known ImageDeltaMimeType value in schema order. +func ImageDeltaMimeTypeValues() []ImageDeltaMimeType { + return []ImageDeltaMimeType{ + ImageDeltaMimeTypeImagePng, + ImageDeltaMimeTypeImageJpeg, + ImageDeltaMimeTypeImageWebp, + ImageDeltaMimeTypeImageHeic, + ImageDeltaMimeTypeImageHeif, + ImageDeltaMimeTypeImageGif, + ImageDeltaMimeTypeImageBmp, + ImageDeltaMimeTypeImageTiff, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *ImageDeltaMimeType) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/imageresponseformat.go b/internal/sdk/models/interactions/imageresponseformat.go index d503d68b..7b0550e2 100644 --- a/internal/sdk/models/interactions/imageresponseformat.go +++ b/internal/sdk/models/interactions/imageresponseformat.go @@ -44,6 +44,26 @@ func (e ImageResponseFormatAspectRatio) ToPointer() *ImageResponseFormatAspectRa return &e } +// ImageResponseFormatAspectRatioValues returns every known ImageResponseFormatAspectRatio value in schema order. +func ImageResponseFormatAspectRatioValues() []ImageResponseFormatAspectRatio { + return []ImageResponseFormatAspectRatio{ + ImageResponseFormatAspectRatioEleven, + ImageResponseFormatAspectRatioTwentyThree, + ImageResponseFormatAspectRatioThirtyTwo, + ImageResponseFormatAspectRatioThirtyFour, + ImageResponseFormatAspectRatioFortyThree, + ImageResponseFormatAspectRatioFortyFive, + ImageResponseFormatAspectRatioFiftyFour, + ImageResponseFormatAspectRatioNineHundredAndSixteen, + ImageResponseFormatAspectRatioOneHundredAndSixtyNine, + ImageResponseFormatAspectRatioTwoHundredAndNineteen, + ImageResponseFormatAspectRatioEighteen, + ImageResponseFormatAspectRatioEightyOne, + ImageResponseFormatAspectRatioFourteen, + ImageResponseFormatAspectRatioFortyOne, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *ImageResponseFormatAspectRatio) IsExact() bool { if e != nil { @@ -67,6 +87,14 @@ func (e ImageResponseFormatDelivery) ToPointer() *ImageResponseFormatDelivery { return &e } +// ImageResponseFormatDeliveryValues returns every known ImageResponseFormatDelivery value in schema order. +func ImageResponseFormatDeliveryValues() []ImageResponseFormatDelivery { + return []ImageResponseFormatDelivery{ + ImageResponseFormatDeliveryInline, + ImageResponseFormatDeliveryURI, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *ImageResponseFormatDelivery) IsExact() bool { if e != nil { @@ -92,6 +120,16 @@ func (e ImageResponseFormatImageSize) ToPointer() *ImageResponseFormatImageSize return &e } +// ImageResponseFormatImageSizeValues returns every known ImageResponseFormatImageSize value in schema order. +func ImageResponseFormatImageSizeValues() []ImageResponseFormatImageSize { + return []ImageResponseFormatImageSize{ + ImageResponseFormatImageSizeFiveHundredAndTwelve, + ImageResponseFormatImageSizeOneK, + ImageResponseFormatImageSizeTwoK, + ImageResponseFormatImageSizeFourK, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *ImageResponseFormatImageSize) IsExact() bool { if e != nil { @@ -114,6 +152,13 @@ func (e ImageResponseFormatMimeType) ToPointer() *ImageResponseFormatMimeType { return &e } +// ImageResponseFormatMimeTypeValues returns every known ImageResponseFormatMimeType value in schema order. +func ImageResponseFormatMimeTypeValues() []ImageResponseFormatMimeType { + return []ImageResponseFormatMimeType{ + ImageResponseFormatMimeTypeImageJpeg, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *ImageResponseFormatMimeType) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/interaction.go b/internal/sdk/models/interactions/interaction.go index ff8e543b..d6e477f2 100644 --- a/internal/sdk/models/interactions/interaction.go +++ b/internal/sdk/models/interactions/interaction.go @@ -461,6 +461,21 @@ func (e InteractionStatus) ToPointer() *InteractionStatus { return &e } +// InteractionStatusValues returns every known InteractionStatus value in schema order. +func InteractionStatusValues() []InteractionStatus { + return []InteractionStatus{ + InteractionStatusInProgress, + InteractionStatusRequiresAction, + InteractionStatusCompleted, + InteractionStatusFailed, + InteractionStatusCancelled, + InteractionStatusIncomplete, + InteractionStatusBudgetExceeded, + InteractionStatusQueued, + InteractionStatusRequiresContinuation, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *InteractionStatus) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/interactionsseeventinteraction.go b/internal/sdk/models/interactions/interactionsseeventinteraction.go index 38bd7a72..fecc3c3e 100644 --- a/internal/sdk/models/interactions/interactionsseeventinteraction.go +++ b/internal/sdk/models/interactions/interactionsseeventinteraction.go @@ -39,6 +39,21 @@ func (e InteractionSseEventInteractionStatus) ToPointer() *InteractionSseEventIn return &e } +// InteractionSseEventInteractionStatusValues returns every known InteractionSseEventInteractionStatus value in schema order. +func InteractionSseEventInteractionStatusValues() []InteractionSseEventInteractionStatus { + return []InteractionSseEventInteractionStatus{ + InteractionSseEventInteractionStatusInProgress, + InteractionSseEventInteractionStatusRequiresAction, + InteractionSseEventInteractionStatusCompleted, + InteractionSseEventInteractionStatusFailed, + InteractionSseEventInteractionStatusCancelled, + InteractionSseEventInteractionStatusIncomplete, + InteractionSseEventInteractionStatusBudgetExceeded, + InteractionSseEventInteractionStatusQueued, + InteractionSseEventInteractionStatusRequiresContinuation, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *InteractionSseEventInteractionStatus) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/interactionstatusupdate.go b/internal/sdk/models/interactions/interactionstatusupdate.go index 9e95551f..580f184b 100644 --- a/internal/sdk/models/interactions/interactionstatusupdate.go +++ b/internal/sdk/models/interactions/interactionstatusupdate.go @@ -38,6 +38,21 @@ func (e InteractionStatusUpdateStatus) ToPointer() *InteractionStatusUpdateStatu return &e } +// InteractionStatusUpdateStatusValues returns every known InteractionStatusUpdateStatus value in schema order. +func InteractionStatusUpdateStatusValues() []InteractionStatusUpdateStatus { + return []InteractionStatusUpdateStatus{ + InteractionStatusUpdateStatusInProgress, + InteractionStatusUpdateStatusRequiresAction, + InteractionStatusUpdateStatusCompleted, + InteractionStatusUpdateStatusFailed, + InteractionStatusUpdateStatusCancelled, + InteractionStatusUpdateStatusIncomplete, + InteractionStatusUpdateStatusBudgetExceeded, + InteractionStatusUpdateStatusQueued, + InteractionStatusUpdateStatusRequiresContinuation, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *InteractionStatusUpdateStatus) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/mediaresolution.go b/internal/sdk/models/interactions/mediaresolution.go index cea9dd04..beb9b4d8 100644 --- a/internal/sdk/models/interactions/mediaresolution.go +++ b/internal/sdk/models/interactions/mediaresolution.go @@ -29,6 +29,16 @@ func (e MediaResolution) ToPointer() *MediaResolution { return &e } +// MediaResolutionValues returns every known MediaResolution value in schema order. +func MediaResolutionValues() []MediaResolution { + return []MediaResolution{ + MediaResolutionLow, + MediaResolutionMedium, + MediaResolutionHigh, + MediaResolutionUltraHigh, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *MediaResolution) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/model.go b/internal/sdk/models/interactions/model.go index 15039be3..a4a9f582 100644 --- a/internal/sdk/models/interactions/model.go +++ b/internal/sdk/models/interactions/model.go @@ -104,6 +104,51 @@ func (e Model) ToPointer() *Model { return &e } +// ModelValues returns every known Model value in schema order. +func ModelValues() []Model { + return []Model{ + ModelGemma426bA4bIt, + ModelGemma431bIt, + ModelGeminiFlashLatest, + ModelGeminiFlashLiteLatest, + ModelGeminiProLatest, + ModelGemini25Flash, + ModelGemini25Pro, + ModelGemini25FlashLite, + ModelGemini35FlashLite, + ModelGemini25FlashImage, + ModelGemini3FlashPreview, + ModelGemini31ProPreview, + ModelGemini31ProPreviewCustomtools, + ModelGemini31FlashLite, + ModelGemini31FlashLiteImage, + ModelGemini3ProImage, + ModelNanoBananaProPreview, + ModelGemini31FlashImage, + ModelGeminiNanoBanana21, + ModelGemini31FlashTtsPreview, + ModelGemini35Flash, + ModelGemini36Flash, + ModelGemini37Flash, + ModelGemini38Flash, + ModelGemini4Argon, + ModelGemini4Carbon, + ModelGemini4Hydrogen, + ModelGemini4Neon, + ModelGemini38FlashTts, + ModelGemini38FlashLiteTts, + ModelGemini35Transcribe, + ModelLyria3ClipPreview, + ModelLyria3ProPreview, + ModelGeminiRoboticsEr16Preview, + ModelGeminiRoboticsEr2Preview, + ModelLyria35, + ModelGeminiOmni12Flash, + ModelGeminiOmni11Flash, + ModelGeminiOmniFlashPreview, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *Model) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/pageprocessingoptions.go b/internal/sdk/models/interactions/pageprocessingoptions.go index 204d7346..3e3e11d1 100644 --- a/internal/sdk/models/interactions/pageprocessingoptions.go +++ b/internal/sdk/models/interactions/pageprocessingoptions.go @@ -31,6 +31,14 @@ func (e PageProcessingOptionsContentLayer) ToPointer() *PageProcessingOptionsCon return &e } +// PageProcessingOptionsContentLayerValues returns every known PageProcessingOptionsContentLayer value in schema order. +func PageProcessingOptionsContentLayerValues() []PageProcessingOptionsContentLayer { + return []PageProcessingOptionsContentLayer{ + PageProcessingOptionsContentLayerPageImage, + PageProcessingOptionsContentLayerPageText, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *PageProcessingOptionsContentLayer) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/responsemodality.go b/internal/sdk/models/interactions/responsemodality.go index f3559ae1..733b2d11 100644 --- a/internal/sdk/models/interactions/responsemodality.go +++ b/internal/sdk/models/interactions/responsemodality.go @@ -30,6 +30,17 @@ func (e ResponseModality) ToPointer() *ResponseModality { return &e } +// ResponseModalityValues returns every known ResponseModality value in schema order. +func ResponseModalityValues() []ResponseModality { + return []ResponseModality{ + ResponseModalityText, + ResponseModalityImage, + ResponseModalityAudio, + ResponseModalityVideo, + ResponseModalityDocument, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *ResponseModality) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/retrieval.go b/internal/sdk/models/interactions/retrieval.go index fee204d3..9c24b47e 100644 --- a/internal/sdk/models/interactions/retrieval.go +++ b/internal/sdk/models/interactions/retrieval.go @@ -33,6 +33,16 @@ func (e RetrievalRetrievalType) ToPointer() *RetrievalRetrievalType { return &e } +// RetrievalRetrievalTypeValues returns every known RetrievalRetrievalType value in schema order. +func RetrievalRetrievalTypeValues() []RetrievalRetrievalType { + return []RetrievalRetrievalType{ + RetrievalRetrievalTypeVertexAiSearch, + RetrievalRetrievalTypeRagStore, + RetrievalRetrievalTypeExaAiSearch, + RetrievalRetrievalTypeParallelAiSearch, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *RetrievalRetrievalType) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/retrievalcalldelta.go b/internal/sdk/models/interactions/retrievalcalldelta.go index 3d2b5ac7..20295315 100644 --- a/internal/sdk/models/interactions/retrievalcalldelta.go +++ b/internal/sdk/models/interactions/retrievalcalldelta.go @@ -34,6 +34,16 @@ func (e RetrievalCallDeltaRetrievalType) ToPointer() *RetrievalCallDeltaRetrieva return &e } +// RetrievalCallDeltaRetrievalTypeValues returns every known RetrievalCallDeltaRetrievalType value in schema order. +func RetrievalCallDeltaRetrievalTypeValues() []RetrievalCallDeltaRetrievalType { + return []RetrievalCallDeltaRetrievalType{ + RetrievalCallDeltaRetrievalTypeVertexAiSearch, + RetrievalCallDeltaRetrievalTypeRagStore, + RetrievalCallDeltaRetrievalTypeExaAiSearch, + RetrievalCallDeltaRetrievalTypeParallelAiSearch, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *RetrievalCallDeltaRetrievalType) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/retrievalcallstep.go b/internal/sdk/models/interactions/retrievalcallstep.go index 43a40209..0c6bd193 100644 --- a/internal/sdk/models/interactions/retrievalcallstep.go +++ b/internal/sdk/models/interactions/retrievalcallstep.go @@ -34,6 +34,16 @@ func (e RetrievalCallStepRetrievalType) ToPointer() *RetrievalCallStepRetrievalT return &e } +// RetrievalCallStepRetrievalTypeValues returns every known RetrievalCallStepRetrievalType value in schema order. +func RetrievalCallStepRetrievalTypeValues() []RetrievalCallStepRetrievalType { + return []RetrievalCallStepRetrievalType{ + RetrievalCallStepRetrievalTypeVertexAiSearch, + RetrievalCallStepRetrievalTypeRagStore, + RetrievalCallStepRetrievalTypeExaAiSearch, + RetrievalCallStepRetrievalTypeParallelAiSearch, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *RetrievalCallStepRetrievalType) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/safetysetting.go b/internal/sdk/models/interactions/safetysetting.go index a19d3655..ea28b908 100644 --- a/internal/sdk/models/interactions/safetysetting.go +++ b/internal/sdk/models/interactions/safetysetting.go @@ -33,6 +33,14 @@ func (e Method) ToPointer() *Method { return &e } +// MethodValues returns every known Method value in schema order. +func MethodValues() []Method { + return []Method{ + MethodSeverity, + MethodProbability, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *Method) IsExact() bool { if e != nil { @@ -60,6 +68,17 @@ func (e Threshold) ToPointer() *Threshold { return &e } +// ThresholdValues returns every known Threshold value in schema order. +func ThresholdValues() []Threshold { + return []Threshold{ + ThresholdBlockLowAndAbove, + ThresholdBlockMediumAndAbove, + ThresholdBlockOnlyHigh, + ThresholdBlockNone, + ThresholdOff, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *Threshold) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/servicetier.go b/internal/sdk/models/interactions/servicetier.go index 30204e80..5d05e828 100644 --- a/internal/sdk/models/interactions/servicetier.go +++ b/internal/sdk/models/interactions/servicetier.go @@ -29,6 +29,16 @@ func (e ServiceTier) ToPointer() *ServiceTier { return &e } +// ServiceTierValues returns every known ServiceTier value in schema order. +func ServiceTierValues() []ServiceTier { + return []ServiceTier{ + ServiceTierFlex, + ServiceTierStandard, + ServiceTierPriority, + ServiceTierDeferred, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *ServiceTier) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/source.go b/internal/sdk/models/interactions/source.go index 66dce80b..38b19d64 100644 --- a/internal/sdk/models/interactions/source.go +++ b/internal/sdk/models/interactions/source.go @@ -33,6 +33,16 @@ func (e SourceType) ToPointer() *SourceType { return &e } +// SourceTypeValues returns every known SourceType value in schema order. +func SourceTypeValues() []SourceType { + return []SourceType{ + SourceTypeGcs, + SourceTypeInline, + SourceTypeRepository, + SourceTypeSkillRegistry, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *SourceType) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/speakerconfig.go b/internal/sdk/models/interactions/speakerconfig.go index b58162d1..d17c339b 100644 --- a/internal/sdk/models/interactions/speakerconfig.go +++ b/internal/sdk/models/interactions/speakerconfig.go @@ -33,6 +33,15 @@ func (e TextNormalization) ToPointer() *TextNormalization { return &e } +// TextNormalizationValues returns every known TextNormalization value in schema order. +func TextNormalizationValues() []TextNormalization { + return []TextNormalization{ + TextNormalizationAuto, + TextNormalizationEnabled, + TextNormalizationDisabled, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *TextNormalization) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/spreadsheetprocessingoptions.go b/internal/sdk/models/interactions/spreadsheetprocessingoptions.go index 51956c17..28409504 100644 --- a/internal/sdk/models/interactions/spreadsheetprocessingoptions.go +++ b/internal/sdk/models/interactions/spreadsheetprocessingoptions.go @@ -32,6 +32,15 @@ func (e SpreadsheetProcessingOptionsContentLayer) ToPointer() *SpreadsheetProces return &e } +// SpreadsheetProcessingOptionsContentLayerValues returns every known SpreadsheetProcessingOptionsContentLayer value in schema order. +func SpreadsheetProcessingOptionsContentLayerValues() []SpreadsheetProcessingOptionsContentLayer { + return []SpreadsheetProcessingOptionsContentLayer{ + SpreadsheetProcessingOptionsContentLayerVisual, + SpreadsheetProcessingOptionsContentLayerData, + SpreadsheetProcessingOptionsContentLayerFormulas, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *SpreadsheetProcessingOptionsContentLayer) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/staticmediaprocessing.go b/internal/sdk/models/interactions/staticmediaprocessing.go index 5da9c7b5..c6c6732f 100644 --- a/internal/sdk/models/interactions/staticmediaprocessing.go +++ b/internal/sdk/models/interactions/staticmediaprocessing.go @@ -32,6 +32,15 @@ func (e StaticMediaProcessingContentLayer) ToPointer() *StaticMediaProcessingCon return &e } +// StaticMediaProcessingContentLayerValues returns every known StaticMediaProcessingContentLayer value in schema order. +func StaticMediaProcessingContentLayerValues() []StaticMediaProcessingContentLayer { + return []StaticMediaProcessingContentLayer{ + StaticMediaProcessingContentLayerFrames, + StaticMediaProcessingContentLayerAudio, + StaticMediaProcessingContentLayerTranscript, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *StaticMediaProcessingContentLayer) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/textresponseformat.go b/internal/sdk/models/interactions/textresponseformat.go index 7df24a0b..58d41bef 100644 --- a/internal/sdk/models/interactions/textresponseformat.go +++ b/internal/sdk/models/interactions/textresponseformat.go @@ -32,6 +32,14 @@ func (e TextResponseFormatMimeType) ToPointer() *TextResponseFormatMimeType { return &e } +// TextResponseFormatMimeTypeValues returns every known TextResponseFormatMimeType value in schema order. +func TextResponseFormatMimeTypeValues() []TextResponseFormatMimeType { + return []TextResponseFormatMimeType{ + TextResponseFormatMimeTypeApplicationJSON, + TextResponseFormatMimeTypeTextPlain, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *TextResponseFormatMimeType) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/thinkinglevel.go b/internal/sdk/models/interactions/thinkinglevel.go index 45bb0fb7..d3bed423 100644 --- a/internal/sdk/models/interactions/thinkinglevel.go +++ b/internal/sdk/models/interactions/thinkinglevel.go @@ -30,6 +30,17 @@ func (e ThinkingLevel) ToPointer() *ThinkingLevel { return &e } +// ThinkingLevelValues returns every known ThinkingLevel value in schema order. +func ThinkingLevelValues() []ThinkingLevel { + return []ThinkingLevel{ + ThinkingLevelMinimal, + ThinkingLevelLow, + ThinkingLevelMedium, + ThinkingLevelHigh, + ThinkingLevelXhigh, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *ThinkingLevel) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/thinkingsummaries.go b/internal/sdk/models/interactions/thinkingsummaries.go index 038abd54..21dc2578 100644 --- a/internal/sdk/models/interactions/thinkingsummaries.go +++ b/internal/sdk/models/interactions/thinkingsummaries.go @@ -27,6 +27,14 @@ func (e ThinkingSummaries) ToPointer() *ThinkingSummaries { return &e } +// ThinkingSummariesValues returns every known ThinkingSummaries value in schema order. +func ThinkingSummariesValues() []ThinkingSummaries { + return []ThinkingSummaries{ + ThinkingSummariesAuto, + ThinkingSummariesNone, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *ThinkingSummaries) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/toolchoicetype.go b/internal/sdk/models/interactions/toolchoicetype.go index e96f1586..18ca0b96 100644 --- a/internal/sdk/models/interactions/toolchoicetype.go +++ b/internal/sdk/models/interactions/toolchoicetype.go @@ -29,6 +29,16 @@ func (e ToolChoiceType) ToPointer() *ToolChoiceType { return &e } +// ToolChoiceTypeValues returns every known ToolChoiceType value in schema order. +func ToolChoiceTypeValues() []ToolChoiceType { + return []ToolChoiceType{ + ToolChoiceTypeAuto, + ToolChoiceTypeAny, + ToolChoiceTypeNone, + ToolChoiceTypeValidated, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *ToolChoiceType) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/toolsearch.go b/internal/sdk/models/interactions/toolsearch.go index 71caa9ae..5c1c0bf0 100644 --- a/internal/sdk/models/interactions/toolsearch.go +++ b/internal/sdk/models/interactions/toolsearch.go @@ -32,6 +32,14 @@ func (e Execution) ToPointer() *Execution { return &e } +// ExecutionValues returns every known Execution value in schema order. +func ExecutionValues() []Execution { + return []Execution{ + ExecutionServer, + ExecutionClient, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *Execution) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/transcriptionconfig.go b/internal/sdk/models/interactions/transcriptionconfig.go index 5a4f15ba..c296c7b1 100644 --- a/internal/sdk/models/interactions/transcriptionconfig.go +++ b/internal/sdk/models/interactions/transcriptionconfig.go @@ -35,6 +35,14 @@ func (e TranscriptionConfigModeEnum) ToPointer() *TranscriptionConfigModeEnum { return &e } +// TranscriptionConfigModeEnumValues returns every known TranscriptionConfigModeEnum value in schema order. +func TranscriptionConfigModeEnumValues() []TranscriptionConfigModeEnum { + return []TranscriptionConfigModeEnum{ + TranscriptionConfigModeEnumVerbatim, + TranscriptionConfigModeEnumSmart, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *TranscriptionConfigModeEnum) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/urlcontextresult.go b/internal/sdk/models/interactions/urlcontextresult.go index 4c093880..458516cc 100644 --- a/internal/sdk/models/interactions/urlcontextresult.go +++ b/internal/sdk/models/interactions/urlcontextresult.go @@ -34,6 +34,16 @@ func (e URLContextResultStatus) ToPointer() *URLContextResultStatus { return &e } +// URLContextResultStatusValues returns every known URLContextResultStatus value in schema order. +func URLContextResultStatusValues() []URLContextResultStatus { + return []URLContextResultStatus{ + URLContextResultStatusSuccess, + URLContextResultStatusError, + URLContextResultStatusPaywall, + URLContextResultStatusUnsafe, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *URLContextResultStatus) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/videoconfig.go b/internal/sdk/models/interactions/videoconfig.go index d83d8308..4a7e8cd9 100644 --- a/internal/sdk/models/interactions/videoconfig.go +++ b/internal/sdk/models/interactions/videoconfig.go @@ -38,6 +38,18 @@ func (e Task) ToPointer() *Task { return &e } +// TaskValues returns every known Task value in schema order. +func TaskValues() []Task { + return []Task{ + TaskTextToVideo, + TaskImageToVideo, + TaskReferenceToVideo, + TaskEdit, + TaskExtend, + TaskUpscale, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *Task) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/videocontent.go b/internal/sdk/models/interactions/videocontent.go index e8430182..a6dd3660 100644 --- a/internal/sdk/models/interactions/videocontent.go +++ b/internal/sdk/models/interactions/videocontent.go @@ -43,6 +43,21 @@ func (e VideoContentMimeType) ToPointer() *VideoContentMimeType { return &e } +// VideoContentMimeTypeValues returns every known VideoContentMimeType value in schema order. +func VideoContentMimeTypeValues() []VideoContentMimeType { + return []VideoContentMimeType{ + VideoContentMimeTypeVideoMp4, + VideoContentMimeTypeVideoMpeg, + VideoContentMimeTypeVideoMpg, + VideoContentMimeTypeVideoMov, + VideoContentMimeTypeVideoAvi, + VideoContentMimeTypeVideoXFlv, + VideoContentMimeTypeVideoWebm, + VideoContentMimeTypeVideoWmv, + VideoContentMimeTypeVideo3gpp, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *VideoContentMimeType) IsExact() bool { if e != nil { @@ -65,6 +80,14 @@ func (e ProcessingEnum) ToPointer() *ProcessingEnum { return &e } +// ProcessingEnumValues returns every known ProcessingEnum value in schema order. +func ProcessingEnumValues() []ProcessingEnum { + return []ProcessingEnum{ + ProcessingEnumStatic, + ProcessingEnumAgentic, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *ProcessingEnum) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/videodelta.go b/internal/sdk/models/interactions/videodelta.go index 056d88dd..5457555d 100644 --- a/internal/sdk/models/interactions/videodelta.go +++ b/internal/sdk/models/interactions/videodelta.go @@ -39,6 +39,22 @@ func (e VideoDeltaMimeType) ToPointer() *VideoDeltaMimeType { return &e } +// VideoDeltaMimeTypeValues returns every known VideoDeltaMimeType value in schema order. +func VideoDeltaMimeTypeValues() []VideoDeltaMimeType { + return []VideoDeltaMimeType{ + VideoDeltaMimeTypeVideoMp4, + VideoDeltaMimeTypeVideoMpeg, + VideoDeltaMimeTypeVideoMpg, + VideoDeltaMimeTypeVideoMov, + VideoDeltaMimeTypeVideoAvi, + VideoDeltaMimeTypeVideoXFlv, + VideoDeltaMimeTypeVideoWebm, + VideoDeltaMimeTypeVideoWmv, + VideoDeltaMimeTypeVideo3gpp, + VideoDeltaMimeTypeVideoJpeg2000, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *VideoDeltaMimeType) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/interactions/videoresponseformat.go b/internal/sdk/models/interactions/videoresponseformat.go index 3f4fbd9e..a92177f2 100644 --- a/internal/sdk/models/interactions/videoresponseformat.go +++ b/internal/sdk/models/interactions/videoresponseformat.go @@ -32,6 +32,14 @@ func (e VideoResponseFormatAspectRatio) ToPointer() *VideoResponseFormatAspectRa return &e } +// VideoResponseFormatAspectRatioValues returns every known VideoResponseFormatAspectRatio value in schema order. +func VideoResponseFormatAspectRatioValues() []VideoResponseFormatAspectRatio { + return []VideoResponseFormatAspectRatio{ + VideoResponseFormatAspectRatioOneHundredAndSixtyNine, + VideoResponseFormatAspectRatioNineHundredAndSixteen, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *VideoResponseFormatAspectRatio) IsExact() bool { if e != nil { @@ -55,6 +63,14 @@ func (e VideoResponseFormatDelivery) ToPointer() *VideoResponseFormatDelivery { return &e } +// VideoResponseFormatDeliveryValues returns every known VideoResponseFormatDelivery value in schema order. +func VideoResponseFormatDeliveryValues() []VideoResponseFormatDelivery { + return []VideoResponseFormatDelivery{ + VideoResponseFormatDeliveryInline, + VideoResponseFormatDeliveryURI, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *VideoResponseFormatDelivery) IsExact() bool { if e != nil { @@ -80,6 +96,16 @@ func (e Resolution) ToPointer() *Resolution { return &e } +// ResolutionValues returns every known Resolution value in schema order. +func ResolutionValues() []Resolution { + return []Resolution{ + ResolutionThreeHundredAndSixtyp, + ResolutionSevenHundredAndTwentyp, + ResolutionOneThousandAndEightyp, + ResolutionFourk, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *Resolution) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/triggers/trigger.go b/internal/sdk/models/triggers/trigger.go index 95bb35df..13b44ed7 100644 --- a/internal/sdk/models/triggers/trigger.go +++ b/internal/sdk/models/triggers/trigger.go @@ -36,6 +36,15 @@ func (e TriggerStatus) ToPointer() *TriggerStatus { return &e } +// TriggerStatusValues returns every known TriggerStatus value in schema order. +func TriggerStatusValues() []TriggerStatus { + return []TriggerStatus{ + TriggerStatusActive, + TriggerStatusPaused, + TriggerStatusError, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *TriggerStatus) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/triggers/triggerexecution.go b/internal/sdk/models/triggers/triggerexecution.go index 40d8a318..0e900cfb 100644 --- a/internal/sdk/models/triggers/triggerexecution.go +++ b/internal/sdk/models/triggers/triggerexecution.go @@ -37,6 +37,17 @@ func (e TriggerExecutionStatus) ToPointer() *TriggerExecutionStatus { return &e } +// TriggerExecutionStatusValues returns every known TriggerExecutionStatus value in schema order. +func TriggerExecutionStatusValues() []TriggerExecutionStatus { + return []TriggerExecutionStatus{ + TriggerExecutionStatusInProgress, + TriggerExecutionStatusCompleted, + TriggerExecutionStatusFailed, + TriggerExecutionStatusSkipped, + TriggerExecutionStatusTimedOut, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *TriggerExecutionStatus) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/triggers/triggerupdate.go b/internal/sdk/models/triggers/triggerupdate.go index 6c77bc8e..e921cdcb 100644 --- a/internal/sdk/models/triggers/triggerupdate.go +++ b/internal/sdk/models/triggers/triggerupdate.go @@ -33,6 +33,15 @@ const ( func (e TriggerUpdateStatus) ToPointer() *TriggerUpdateStatus { return &e } + +// TriggerUpdateStatusValues returns every known TriggerUpdateStatus value in schema order. +func TriggerUpdateStatusValues() []TriggerUpdateStatus { + return []TriggerUpdateStatus{ + TriggerUpdateStatusActive, + TriggerUpdateStatusPaused, + TriggerUpdateStatusError, + } +} func (e *TriggerUpdateStatus) UnmarshalJSON(data []byte) error { var v string if err := json.Unmarshal(data, &v); err != nil { diff --git a/internal/sdk/models/voices/pitch.go b/internal/sdk/models/voices/pitch.go index 04a4eae2..fdf491fd 100644 --- a/internal/sdk/models/voices/pitch.go +++ b/internal/sdk/models/voices/pitch.go @@ -28,6 +28,15 @@ func (e Pitch) ToPointer() *Pitch { return &e } +// PitchValues returns every known Pitch value in schema order. +func PitchValues() []Pitch { + return []Pitch{ + PitchLow, + PitchMedium, + PitchHigh, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *Pitch) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/voices/voicetype.go b/internal/sdk/models/voices/voicetype.go index 31818178..d8931da0 100644 --- a/internal/sdk/models/voices/voicetype.go +++ b/internal/sdk/models/voices/voicetype.go @@ -28,6 +28,15 @@ func (e VoiceType) ToPointer() *VoiceType { return &e } +// VoiceTypeValues returns every known VoiceType value in schema order. +func VoiceTypeValues() []VoiceType { + return []VoiceType{ + VoiceTypeReplicated, + VoiceTypePrompted, + VoiceTypePrebuilt, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *VoiceType) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/webhooks/rotatesigningsecretrequest.go b/internal/sdk/models/webhooks/rotatesigningsecretrequest.go index d6d08e90..34679c5d 100644 --- a/internal/sdk/models/webhooks/rotatesigningsecretrequest.go +++ b/internal/sdk/models/webhooks/rotatesigningsecretrequest.go @@ -32,6 +32,14 @@ const ( func (e RevocationBehavior) ToPointer() *RevocationBehavior { return &e } + +// RevocationBehaviorValues returns every known RevocationBehavior value in schema order. +func RevocationBehaviorValues() []RevocationBehavior { + return []RevocationBehavior{ + RevocationBehaviorRevokePreviousSecretsAfterH24, + RevocationBehaviorRevokePreviousSecretsImmediately, + } +} func (e *RevocationBehavior) UnmarshalJSON(data []byte) error { var v string if err := json.Unmarshal(data, &v); err != nil { diff --git a/internal/sdk/models/webhooks/webhook.go b/internal/sdk/models/webhooks/webhook.go index 3f53656b..917546be 100644 --- a/internal/sdk/models/webhooks/webhook.go +++ b/internal/sdk/models/webhooks/webhook.go @@ -35,6 +35,15 @@ func (e WebhookState) ToPointer() *WebhookState { return &e } +// WebhookStateValues returns every known WebhookState value in schema order. +func WebhookStateValues() []WebhookState { + return []WebhookState{ + WebhookStateEnabled, + WebhookStateDisabled, + WebhookStateDisabledDueToFailedDeliveries, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *WebhookState) IsExact() bool { if e != nil { @@ -69,6 +78,19 @@ func (e WebhookSubscribedEvent) ToPointer() *WebhookSubscribedEvent { return &e } +// WebhookSubscribedEventValues returns every known WebhookSubscribedEvent value in schema order. +func WebhookSubscribedEventValues() []WebhookSubscribedEvent { + return []WebhookSubscribedEvent{ + WebhookSubscribedEventBatchSucceeded, + WebhookSubscribedEventBatchExpired, + WebhookSubscribedEventBatchFailed, + WebhookSubscribedEventInteractionRequiresAction, + WebhookSubscribedEventInteractionCompleted, + WebhookSubscribedEventInteractionFailed, + WebhookSubscribedEventVideoGenerated, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *WebhookSubscribedEvent) IsExact() bool { if e != nil { diff --git a/internal/sdk/models/webhooks/webhookupdate.go b/internal/sdk/models/webhooks/webhookupdate.go index f2cad141..00fc9918 100644 --- a/internal/sdk/models/webhooks/webhookupdate.go +++ b/internal/sdk/models/webhooks/webhookupdate.go @@ -35,6 +35,15 @@ const ( func (e WebhookUpdateState) ToPointer() *WebhookUpdateState { return &e } + +// WebhookUpdateStateValues returns every known WebhookUpdateState value in schema order. +func WebhookUpdateStateValues() []WebhookUpdateState { + return []WebhookUpdateState{ + WebhookUpdateStateEnabled, + WebhookUpdateStateDisabled, + WebhookUpdateStateDisabledDueToFailedDeliveries, + } +} func (e *WebhookUpdateState) UnmarshalJSON(data []byte) error { var v string if err := json.Unmarshal(data, &v); err != nil { @@ -76,6 +85,19 @@ func (e WebhookUpdateSubscribedEvent) ToPointer() *WebhookUpdateSubscribedEvent return &e } +// WebhookUpdateSubscribedEventValues returns every known WebhookUpdateSubscribedEvent value in schema order. +func WebhookUpdateSubscribedEventValues() []WebhookUpdateSubscribedEvent { + return []WebhookUpdateSubscribedEvent{ + WebhookUpdateSubscribedEventBatchSucceeded, + WebhookUpdateSubscribedEventBatchExpired, + WebhookUpdateSubscribedEventBatchFailed, + WebhookUpdateSubscribedEventInteractionRequiresAction, + WebhookUpdateSubscribedEventInteractionCompleted, + WebhookUpdateSubscribedEventInteractionFailed, + WebhookUpdateSubscribedEventVideoGenerated, + } +} + // IsExact returns true if the value matches a known enum value, false otherwise. func (e *WebhookUpdateSubscribedEvent) IsExact() bool { if e != nil { diff --git a/internal/sdk/redact/redact.go b/internal/sdk/redact/redact.go index 9f46c580..3c716bde 100644 --- a/internal/sdk/redact/redact.go +++ b/internal/sdk/redact/redact.go @@ -120,8 +120,18 @@ func (g *graph) redact(contentType string, body []byte) []byte { if g == nil || len(body) == 0 { return body } - if g.sensitive(g.roots) { - return []byte(Mask) + roots := g.roots + if g.sensitive(roots) { + var nonSensitive []int + for _, id := range roots { + if id > 0 && id < len(g.nodes) && !g.nodes[id].sensitive { + nonSensitive = append(nonSensitive, id) + } + } + if len(nonSensitive) == 0 { + return []byte(Mask) + } + roots = nonSensitive } mediaType, params, err := mime.ParseMediaType(contentType) if err != nil { @@ -131,11 +141,11 @@ func (g *graph) redact(contentType string, body []byte) []byte { ok := false switch { case mediaType == "application/x-www-form-urlencoded": - masked, _, ok = g.redactForm(body, g.roots) + masked, _, ok = g.redactForm(body, roots) case mediaType == "multipart/form-data": - masked, _, ok = g.redactMultipart(body, params["boundary"], g.roots) + masked, _, ok = g.redactMultipart(body, params["boundary"], roots) case mediaType == "" || mediaType == "application/json" || mediaType == "text/json" || strings.HasSuffix(mediaType, "+json"): - masked, _, ok = g.redactJSON(body, g.roots) + masked, _, ok = g.redactJSON(body, roots) } if !ok { return []byte(Mask) diff --git a/internal/sdk/sdkinternal/utils/json.go b/internal/sdk/sdkinternal/utils/json.go index afdbe678..0e61e5e4 100644 --- a/internal/sdk/sdkinternal/utils/json.go +++ b/internal/sdk/sdkinternal/utils/json.go @@ -253,6 +253,10 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool // If we receive a value for a const field ignore it but mark it as unmarshaled if field.Tag.Get("const") != "" { if r, ok := unmarshaled[fieldName]; ok { + if isContainerKind(field.Type) && bytes.Equal(bytes.TrimSpace(r), []byte("null")) { + delete(unmarshaled, fieldName) + continue + } val := string(r) if strings.HasPrefix(val, `"`) && strings.HasSuffix(val, `"`) { @@ -263,7 +267,11 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool } } constValue := field.Tag.Get("const") - if val != constValue { + matches := val == constValue + if isContainerKind(field.Type) { + matches = constJSONValuesEqual(r, constValue) + } + if !matches { return fmt.Errorf("const field `%s` does not match expected value `%s` got `%s`", fieldName, constValue, val) } @@ -482,6 +490,79 @@ func implementsJSONMarshaler(v interface{}) bool { return reflect.PtrTo(vType).Implements(marshalerType) } +func isContainerKind(typ reflect.Type) bool { + typ = dereferenceTypePointer(typ) + if optionalnullable.IsOptionalNullableType(typ) { + typ = dereferenceTypePointer(typ.Elem()) + } + switch typ.Kind() { + case reflect.Slice, reflect.Map: + return true + default: + return false + } +} + +func constJSONValuesEqual(received json.RawMessage, constValue string) bool { + got, err := decodeJSONWithNumbers(received) + if err != nil { + return false + } + want, err := decodeJSONWithNumbers([]byte(constValue)) + if err != nil { + return false + } + return jsonValuesEqual(got, want) +} + +func decodeJSONWithNumbers(data []byte) (interface{}, error) { + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + var value interface{} + if err := decoder.Decode(&value); err != nil { + return nil, err + } + return value, nil +} + +func jsonValuesEqual(a, b interface{}) bool { + switch av := a.(type) { + case json.Number: + bv, ok := b.(json.Number) + if !ok { + return false + } + ar, aok := new(big.Rat).SetString(av.String()) + br, bok := new(big.Rat).SetString(bv.String()) + return aok && bok && ar.Cmp(br) == 0 + case map[string]interface{}: + bv, ok := b.(map[string]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for key, value := range av { + other, ok := bv[key] + if !ok || !jsonValuesEqual(value, other) { + return false + } + } + return true + case []interface{}: + bv, ok := b.([]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for i := range av { + if !jsonValuesEqual(av[i], bv[i]) { + return false + } + } + return true + default: + return reflect.DeepEqual(a, b) + } +} + func handleDefaultConstValue(tagValue string, val interface{}, tag reflect.StructTag) json.RawMessage { if tagValue == "null" { return []byte("null") diff --git a/internal/usage/schema.go b/internal/usage/schema.go index a51ede75..fcadab58 100644 --- a/internal/usage/schema.go +++ b/internal/usage/schema.go @@ -374,18 +374,22 @@ func MarkGenerated(cmd *cobra.Command) { // InitDefaultCommands creates cobra's default help and completion commands and // marks only the ones cobra created, leaving a custom command of the same name live. -func InitDefaultCommands(root *cobra.Command) { +// It returns the commands cobra created. +func InitDefaultCommands(root *cobra.Command) []*cobra.Command { existing := map[*cobra.Command]bool{} for _, cmd := range root.Commands() { existing[cmd] = true } root.InitDefaultHelpCmd() root.InitDefaultCompletionCmd() + var created []*cobra.Command for _, cmd := range root.Commands() { if !existing[cmd] { MarkGenerated(cmd) + created = append(created, cmd) } } + return created } func usageFlagSetIdentity(cmd *cobra.Command) string { diff --git a/scripts/install.ps1 b/scripts/install.ps1 index 2997ca49..b83cadaf 100644 --- a/scripts/install.ps1 +++ b/scripts/install.ps1 @@ -43,7 +43,9 @@ function Get-LatestVersion { } function Get-Architecture { - $arch = $env:PROCESSOR_ARCHITECTURE + # A 32-bit PowerShell on 64-bit Windows reports x86 here and the native + # architecture in PROCESSOR_ARCHITEW6432. + $arch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE } switch ($arch) { "AMD64" { return "x86_64" } "ARM64" { return "arm64" } @@ -88,6 +90,31 @@ function Install-CLI { Write-ColorOutput "Download complete" -Color Green + $checksumsUrl = "https://github.com/$Repo/releases/download/$Version/checksums.txt" + $checksumsPath = Join-Path $tempDir "checksums.txt" + try { + Invoke-WebRequest -Uri $checksumsUrl -OutFile $checksumsPath -UseBasicParsing + } + catch { + throw "Failed to download checksums from ${checksumsUrl}: $_" + } + $expected = $null + foreach ($line in Get-Content -LiteralPath $checksumsPath) { + $fields = $line.Trim() -split '\s+', 2 + if ($fields.Count -eq 2 -and $fields[1].TrimStart('*') -eq $archiveName) { + $expected = $fields[0] + break + } + } + if (-not $expected) { + throw "checksums.txt has no entry for $archiveName" + } + $actual = (Get-FileHash -LiteralPath $archivePath -Algorithm SHA256).Hash + if ($actual -ne $expected) { + throw "Checksum mismatch for ${archiveName}: expected $expected, got $actual" + } + Write-ColorOutput "Checksum verified" -Color Green + # Extract archive Write-ColorOutput "Extracting archive..." -Color Cyan Expand-Archive -Path $archivePath -DestinationPath $tempDir -Force @@ -113,11 +140,13 @@ function Install-CLI { # Add to PATH if not already there $userPath = [Environment]::GetEnvironmentVariable("Path", "User") - if ($userPath -notlike "*$InstallDir*") { + $pathEntries = @($userPath -split ';' | Where-Object { $_ } | ForEach-Object { $_.Trim().TrimEnd('\') }) + if ($pathEntries -notcontains $InstallDir.TrimEnd('\')) { Write-ColorOutput "Adding $InstallDir to your PATH..." -Color Cyan + $newPath = if ($userPath) { "$userPath;$InstallDir" } else { $InstallDir } [Environment]::SetEnvironmentVariable( "Path", - "$userPath;$InstallDir", + $newPath, "User" ) $env:Path = "$env:Path;$InstallDir" diff --git a/scripts/install.sh b/scripts/install.sh index f85c34dc..f063d18c 100644 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -14,7 +14,7 @@ # GEMINI_VERSION - Specific version to install (default: latest) # -set -e +set -eo pipefail # Configuration REPO="google-gemini/gemini-api-cli" @@ -29,23 +29,57 @@ GREEN='\033[0;32m' YELLOW='\033[1;33m' NC='\033[0m' # No Color -# Helper functions +# Helper functions. Logs go to stderr so command substitutions capture only +# the value a function prints. log_info() { - echo -e "${GREEN}[INFO]${NC} $1" + echo -e "${GREEN}[INFO]${NC} $1" >&2 } log_warn() { - echo -e "${YELLOW}[WARN]${NC} $1" + echo -e "${YELLOW}[WARN]${NC} $1" >&2 } log_error() { - echo -e "${RED}[ERROR]${NC} $1" + echo -e "${RED}[ERROR]${NC} $1" >&2 +} + +download() { + if command -v curl >/dev/null 2>&1; then + curl -fsSL "$1" -o "$2" + elif command -v wget >/dev/null 2>&1; then + wget -q "$1" -O "$2" + else + log_error "curl or wget is required to download the CLI" + exit 1 + fi +} + +verify_checksum() { + local file="$1" name="$2" checksums="$3" expected actual + expected=$(awk -v name="$name" '$2 == name || $2 == "*" name { print $1; exit }' "$checksums") + if [ -z "$expected" ]; then + log_error "checksums.txt has no entry for $name" + exit 1 + fi + if command -v sha256sum >/dev/null 2>&1; then + actual=$(sha256sum "$file" | awk '{ print $1 }') + elif command -v shasum >/dev/null 2>&1; then + actual=$(shasum -a 256 "$file" | awk '{ print $1 }') + else + log_error "sha256sum or shasum is required to verify the download" + exit 1 + fi + if [ "$actual" != "$expected" ]; then + log_error "Checksum mismatch for $name: expected $expected, got $actual" + exit 1 + fi + log_info "Checksum verified" } # Detect operating system detect_os() { - local os - local uname_output="$(uname -s)" + local os uname_output + uname_output=$(uname -s) case "$uname_output" in Linux*) os="Linux" ;; Darwin*) os="Darwin" ;; @@ -78,14 +112,18 @@ get_latest_version() { local version if command -v curl >/dev/null 2>&1; then - version=$(curl -fsSL "$latest_url" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/') + version=$(curl -fsSL "$latest_url" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/') || version="" elif command -v wget >/dev/null 2>&1; then - version=$(wget -qO- "$latest_url" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/') + version=$(wget -qO- "$latest_url" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/') || version="" else log_error "curl or wget is required to download the CLI" exit 1 fi + if [ -z "$version" ]; then + log_error "Could not determine the latest release from $latest_url. Set GEMINI_VERSION to install a specific version." + exit 1 + fi echo "$version" } @@ -97,22 +135,28 @@ get_install_dir() { return fi - # Try to use /usr/local/bin if we have write access - if [ -w "$DEFAULT_INSTALL_DIR" ] || [ -w "$(dirname "$DEFAULT_INSTALL_DIR")" ]; then + # Use /usr/local/bin if it is writable, or can be created when missing + if [ -d "$DEFAULT_INSTALL_DIR" ]; then + if [ -w "$DEFAULT_INSTALL_DIR" ]; then + echo "$DEFAULT_INSTALL_DIR" + return + fi + elif [ -w "$(dirname "$DEFAULT_INSTALL_DIR")" ]; then echo "$DEFAULT_INSTALL_DIR" return fi # Fall back to user directory - log_info "No write access to $DEFAULT_INSTALL_DIR, using $USER_INSTALL_DIR instead" >&2 + log_info "No write access to $DEFAULT_INSTALL_DIR, using $USER_INSTALL_DIR instead" echo "$USER_INSTALL_DIR" } # Download and install install_cli() { - local INSTALL_DIR=$(get_install_dir) - local os=$(detect_os) - local arch=$(detect_arch) + local INSTALL_DIR os arch + INSTALL_DIR=$(get_install_dir) + os=$(detect_os) + arch=$(detect_arch) log_info "Detected OS: $os" log_info "Detected Architecture: $arch" @@ -144,20 +188,20 @@ install_cli() { trap 'rm -rf -- "$tmp_dir"' EXIT # Download archive - if command -v curl >/dev/null 2>&1; then - if ! curl -fsSL "$download_url" -o "$tmp_dir/$archive_name"; then - log_error "Failed to download from $download_url" - exit 1 - fi - elif command -v wget >/dev/null 2>&1; then - if ! wget -q "$download_url" -O "$tmp_dir/$archive_name"; then - log_error "Failed to download from $download_url" - exit 1 - fi + if ! download "$download_url" "$tmp_dir/$archive_name"; then + log_error "Failed to download from $download_url" + exit 1 fi log_info "Download complete" + local checksums_url="https://github.com/${REPO}/releases/download/${VERSION}/checksums.txt" + if ! download "$checksums_url" "$tmp_dir/checksums.txt"; then + log_error "Failed to download checksums from $checksums_url" + exit 1 + fi + verify_checksum "$tmp_dir/$archive_name" "$archive_name" "$tmp_dir/checksums.txt" + # Extract archive based on format log_info "Extracting archive..." if [ "$archive_format" = "zip" ]; then