diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 68aa6b8d..78c38c14 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -10,7 +10,7 @@ permissions: contents: read env: - SPEAKEASY_VERSION: v2.959.1 + SPEAKEASY_VERSION: v2.965.1 jobs: non-live-validation: diff --git a/internal/output/agentmode.go b/internal/output/agentmode.go index f86c4502..77cfc709 100644 --- a/internal/output/agentmode.go +++ b/internal/output/agentmode.go @@ -145,7 +145,7 @@ func CLIError(cmd *cobra.Command, err error) error { if !changed || jqExpr == "" { jqExpr = preparsedRendering.jq } - format := resolveOutputFormat(cmd) + format := resolveErrorOutputFormat(cmd) classification := Classify(cmd, withErrorOrigin(err, ErrorOriginCLI)) if shouldClassifyError(format, jqExpr) { return renderClassifiedError(cmd, err, classification, shouldRenderStructuredError(format, jqExpr)) diff --git a/internal/output/artifact.go b/internal/output/artifact.go index 2c7ca2e1..3f1dc4fb 100644 --- a/internal/output/artifact.go +++ b/internal/output/artifact.go @@ -181,7 +181,7 @@ func artifactResult(cmd *cobra.Command, res interface{}, cfg *artifactConfig) er return err } if extensionMismatch && !IsMachineMode(cmd) { - fmt.Fprintf(cmd.ErrOrStderr(), "Note: %s contains %s content; its extension does not match\n", filepath.Base(finalPath), mimeType) + fmt.Fprintf(cmd.ErrOrStderr(), "Note: %s contains %q content; its extension does not match\n", filepath.Base(finalPath), mimeType) } absPath, err := filepath.Abs(finalPath) if err != nil { @@ -195,14 +195,6 @@ func artifactResult(cmd *cobra.Command, res interface{}, cfg *artifactConfig) er return fmt.Errorf("the written %s artifact is empty: %s", cfg.Kind, absPath) } - if !IsMachineMode(cmd) { - mimeNote := "" - if mimeType != "" { - mimeNote = ", " + mimeType - } - fmt.Fprintf(cmd.ErrOrStderr(), "Wrote %s to %s (%d bytes%s)\n", cfg.Kind, absPath, written.Size(), mimeNote) - } - envelope := map[string]interface{}{ "path": absPath, "kind": cfg.Kind, @@ -222,6 +214,17 @@ func artifactResult(cmd *cobra.Command, res interface{}, cfg *artifactConfig) er envelope["status"] = status } } + if !IsMachineMode(cmd) { + mimeNote := "" + if mimeType != "" { + mimeNote = fmt.Sprintf(", %q", mimeType) + } + idNote := "" + if id, ok := envelope["response_id"].(string); ok { + idNote = fmt.Sprintf(", response ID %q", id) + } + fmt.Fprintf(cmd.ErrOrStderr(), "Wrote %s to %s (%d bytes%s%s)\n", cfg.Kind, absPath, written.Size(), mimeNote, idNote) + } return renderArtifactEnvelope(cmd, absPath, envelope) } diff --git a/internal/output/artifact_test.go b/internal/output/artifact_test.go index aecbf086..667f4471 100644 --- a/internal/output/artifact_test.go +++ b/internal/output/artifact_test.go @@ -17,9 +17,12 @@ package output import ( + "bytes" "encoding/json" + "fmt" "net/http" "net/http/httptest" + "path/filepath" "strings" "sync/atomic" "testing" @@ -27,6 +30,76 @@ import ( "github.com/spf13/cobra" ) +func TestArtifactResultResponseIDNote(t *testing.T) { + for _, tc := range []struct { + id, mimeType, filename string + }{ + {id: "job-123", mimeType: "image/png", filename: "asset.png"}, + {id: "", mimeType: "image/png", filename: "asset.png"}, + {id: "job\n\x1b[31m", mimeType: "image/png", filename: "asset.png"}, + {id: "job-123", mimeType: "image/png;\n\x1b[31m", filename: "asset.png"}, + {id: "job-123", mimeType: "image/png;\n\x1b[31m", filename: "asset.jpg"}, + } { + t.Run(fmt.Sprintf("%q/%q/%s", tc.id, tc.mimeType, tc.filename), func(t *testing.T) { + ResetAgentMode() + ResetPreparsedRendering() + var stdout, stderr bytes.Buffer + cmd := &cobra.Command{} + cmd.SetOut(&stdout) + cmd.SetErr(&stderr) + cmd.Flags().String("out", filepath.Join(t.TempDir(), tc.filename), "") + cmd.Flags().String("output-format", "pretty", "") + if err := cmd.Flags().Set("output-format", "pretty"); err != nil { + t.Fatal(err) + } + cfg := &artifactConfig{ + Pointer: []artifactSegment{ + {Field: "items"}, + {Wild: true}, + }, + Kind: "image", + DefaultPath: "asset.png", + TypeField: "type", + DataField: "data", + MimeTypeField: "mime_type", + IDField: "job_id", + } + body := map[string]interface{}{ + "job_id": tc.id, + "items": []interface{}{ + map[string]interface{}{"type": "image", "data": "eA==", "mime_type": tc.mimeType}, + }, + } + if err := artifactResult(cmd, body, cfg); err != nil { + t.Fatal(err) + } + if tc.id == "" { + if strings.Contains(stderr.String(), "response ID") { + t.Fatalf("missing ID must not add a note: %q", stderr.String()) + } + } else if want := fmt.Sprintf("response ID %q", tc.id); !strings.Contains(stderr.String(), want) { + t.Fatalf("expected %q in %q", want, stderr.String()) + } + if want := fmt.Sprintf(", %q", tc.mimeType); !strings.Contains(stderr.String(), want) { + t.Fatalf("expected quoted MIME %q in %q", want, stderr.String()) + } + lines := 1 + if strings.HasSuffix(tc.filename, ".jpg") { + lines++ + if want := fmt.Sprintf("contains %q content", tc.mimeType); !strings.Contains(stderr.String(), want) { + t.Fatalf("expected quoted mismatch MIME %q in %q", want, stderr.String()) + } + } + if strings.Count(stderr.String(), "\n") != lines || strings.Contains(stderr.String(), "\x1b") { + t.Fatalf("artifact notes must not contain unescaped control characters: %q", stderr.String()) + } + if !filepath.IsAbs(strings.TrimSpace(stdout.String())) || strings.Count(stdout.String(), "\n") != 1 { + t.Fatalf("stdout must contain only the absolute path: %q", stdout.String()) + } + }) + } +} + // apiResponseFrom stands in for the API response that delivered the URI. func apiResponseFrom(apiURL string) *http.Response { return &http.Response{Request: httptest.NewRequest(http.MethodPost, apiURL, nil)} diff --git a/internal/output/async.go b/internal/output/async.go index 117397e7..e8efe495 100644 --- a/internal/output/async.go +++ b/internal/output/async.go @@ -539,7 +539,7 @@ func protocolAsyncError(cfg *asyncConfig, id, resumePrefix, message string, payl func renderAsyncError(cmd *cobra.Command, runtimeErr *asyncRuntimeError) error { jqExpr, _ := flagutil.GetStringFlag(cmd, "jq") - if !shouldRenderStructuredError(resolveOutputFormat(cmd), jqExpr) { + if !shouldRenderStructuredError(resolveErrorOutputFormat(cmd), jqExpr) { writeScrubbed(cmd.ErrOrStderr(), fmt.Sprintf("Error: %s (handle %s; resume: %s)%s", runtimeErr.message, runtimeErr.id, runtimeErr.resume, string(rune(10)))) classification := Classify(cmd, withErrorOrigin(runtimeErr, ErrorOriginCLI)) return markRendered(runtimeErr, classification) diff --git a/internal/output/classify.go b/internal/output/classify.go index 0938f138..bad0f7c7 100644 --- a/internal/output/classify.go +++ b/internal/output/classify.go @@ -29,6 +29,7 @@ import ( "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/sdkinternal/utils" "github.com/spf13/cobra" ) @@ -181,6 +182,10 @@ func Classify(cmd *cobra.Command, err error) Classification { if classification, ok := ClassificationFrom(err); ok { return classification } + var invalidPath *utils.InvalidPathParameterError + if errors.As(err, &invalidPath) { + err = flagutil.WithCLIValidation(err) + } c := Classification{ StatusCode: extractErrorStatusCode(err), diff --git a/internal/output/exitcodes.go b/internal/output/exitcodes.go index 763f4079..63f4c492 100644 --- a/internal/output/exitcodes.go +++ b/internal/output/exitcodes.go @@ -220,7 +220,7 @@ func renderingMode(cmd *cobra.Command) (format, jqExpr string) { if !changed || jqExpr == "" { jqExpr = preparsedRendering.jq } - return resolveOutputFormat(cmd), jqExpr + return resolveErrorOutputFormat(cmd), jqExpr } func structuredErrorsRequested(cmd *cobra.Command) bool { diff --git a/internal/output/number.go b/internal/output/number.go new file mode 100644 index 00000000..56225e9f --- /dev/null +++ b/internal/output/number.go @@ -0,0 +1,78 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package output + +import ( + "math/big" + "strconv" + "strings" +) + +const ( + maxDecimalLength = 128 + maxDecimalExponent = 1000 +) + +// parseBoundedRat parses a JSON decimal lexeme exactly. big.Rat.SetString +// allocates memory proportional to the exponent, so lexemes that are too long, +// not JSON decimals, or carry a large exponent are rejected first. +func parseBoundedRat(text string) (*big.Rat, bool) { + if text == "" || len(text) > maxDecimalLength || !isJSONDecimal(text) { + return nil, false + } + if i := strings.IndexAny(text, "eE"); i >= 0 { + exponent, err := strconv.ParseInt(text[i+1:], 10, 32) + if err != nil || exponent > maxDecimalExponent || exponent < -maxDecimalExponent { + return nil, false + } + } + return new(big.Rat).SetString(text) +} + +func isJSONDecimal(text string) bool { + i := 0 + digits := func() bool { + start := i + for i < len(text) && text[i] >= '0' && text[i] <= '9' { + i++ + } + return i > start + } + if i < len(text) && text[i] == '-' { + i++ + } + integer := i + if !digits() || (text[integer] == '0' && i-integer > 1) { + return false + } + if i < len(text) && text[i] == '.' { + i++ + if !digits() { + return false + } + } + if i < len(text) && (text[i] == 'e' || text[i] == 'E') { + i++ + if i < len(text) && (text[i] == '+' || text[i] == '-') { + i++ + } + if !digits() { + return false + } + } + return i == len(text) +} diff --git a/internal/output/outcome.go b/internal/output/outcome.go index 4db7e6bc..6735ce1b 100644 --- a/internal/output/outcome.go +++ b/internal/output/outcome.go @@ -29,12 +29,13 @@ import ( const outcomeAnnotation = "speakeasy_outcome" type outcomeConfig struct { - StatePointer string `json:"statePointer"` - StreamStatePointer string `json:"streamStatePointer"` - States map[string]string `json:"states"` - ErrorPointer string `json:"errorPointer"` - StreamErrorPointer string `json:"streamErrorPointer"` - ErrorMessageField string `json:"errorMessageField"` + StatePointer string `json:"statePointer"` + StreamStatePointer string `json:"streamStatePointer"` + StreamStatePointers []string `json:"streamStatePointers"` + States map[string]string `json:"states"` + ErrorPointer string `json:"errorPointer"` + StreamErrorPointer string `json:"streamErrorPointer"` + ErrorMessageField string `json:"errorMessageField"` } func activeOutcome(cmd *cobra.Command) *outcomeConfig { @@ -182,7 +183,7 @@ func outcomePointer(root interface{}, pointer string) (interface{}, bool) { } func outcomeStreamFailure(cmd *cobra.Command, cfg *outcomeConfig, item interface{}, frame map[string]interface{}) *outcomeError { - if cfg == nil || cfg.StreamStatePointer == "" { + if cfg == nil { return nil } var payload interface{} = frame @@ -197,5 +198,22 @@ func outcomeStreamFailure(cmd *cobra.Command, cfg *outcomeConfig, item interface } payload = decoded } - return outcomeFailure(cmd, cfg, payload, cfg.StreamStatePointer, cfg.StreamErrorPointer) + for _, pointer := range cfg.streamStatePointers() { + if value, ok := outcomePointer(payload, pointer); ok { + if state, ok := value.(string); ok && state != "" { + return outcomeFailure(cmd, cfg, payload, pointer, cfg.StreamErrorPointer) + } + } + } + return nil +} + +func (cfg *outcomeConfig) streamStatePointers() []string { + if len(cfg.StreamStatePointers) > 0 { + return cfg.StreamStatePointers + } + if cfg.StreamStatePointer != "" { + return []string{cfg.StreamStatePointer} + } + return nil } diff --git a/internal/output/output.go b/internal/output/output.go index ac635273..999cbc5b 100644 --- a/internal/output/output.go +++ b/internal/output/output.go @@ -121,12 +121,16 @@ func formatErrorBody(body string) string { // 2. Agent mode default (TOON) // 3. Default "pretty" func resolveOutputFormat(cmd *cobra.Command) string { + if preparsedRendering.outputFormat == "" && WantsRawResponse(cmd) { + return flagutil.ResolveOutputFormat(cmd, "json", IsAgentMode()) + } + return resolveErrorOutputFormat(cmd) +} + +func resolveErrorOutputFormat(cmd *cobra.Command) string { if format := preparsedRendering.outputFormat; format != "" { return flagutil.ResolveOutputFormat(cmd, format, IsAgentMode()) } - if WantsRawResponse(cmd) { - return flagutil.ResolveOutputFormat(cmd, "json", IsAgentMode()) - } return flagutil.ResolveOutputFormat(cmd, config.GetString("output-format"), IsAgentMode()) } @@ -589,7 +593,7 @@ func Error(cmd *cobra.Command, err error) error { if err == nil { return nil } - format := resolveOutputFormat(cmd) + format := resolveErrorOutputFormat(cmd) jqExpr, _ := flagutil.GetStringFlag(cmd, "jq") classification := Classify(cmd, withErrorOrigin(err, ErrorOriginAPI)) structured := shouldRenderStructuredError(format, jqExpr) diff --git a/internal/output/output_test.go b/internal/output/output_test.go index 1e9626d2..3b5c7207 100644 --- a/internal/output/output_test.go +++ b/internal/output/output_test.go @@ -21,6 +21,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "io" "net/http" "reflect" @@ -28,10 +29,54 @@ import ( "testing" "time" + "github.com/google-gemini/gemini-api-cli/internal/clierrors" "github.com/google-gemini/gemini-api-cli/internal/config" + "github.com/google-gemini/gemini-api-cli/internal/sdk/sdkinternal/utils" "github.com/spf13/cobra" ) +func TestPathParameterErrorsAreUsageErrors(t *testing.T) { + for _, format := range []string{"pretty", "json"} { + for _, wrapped := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/wrapped=%t", format, wrapped), func(t *testing.T) { + ResetAgentMode() + ResetPreparsedRendering() + var stderr bytes.Buffer + cmd := &cobra.Command{} + cmd.SetErr(&stderr) + cmd.Flags().String("output-format", "", "") + if err := cmd.Flags().Set("output-format", format); err != nil { + t.Fatal(err) + } + var err error = &utils.InvalidPathParameterError{Name: "resource"} + if wrapped { + err = fmt.Errorf("construct request: %w", err) + } + classification := Classify(cmd, err) + if classification.Type != ErrorTypeValidation || classification.Reason != ReasonCLIValidation || classification.Origin != ErrorOriginCLI || classification.StatusCode != 0 { + t.Fatalf("unexpected classification: %+v", classification) + } + rendered := Error(cmd, err) + if clierrors.ExitCode(rendered) != clierrors.ExitUsage { + t.Fatalf("expected exit 2, got %v", rendered) + } + var invalidPath *utils.InvalidPathParameterError + if !errors.As(rendered, &invalidPath) || invalidPath.Name != "resource" { + t.Fatalf("typed path error lost during rendering: %v", rendered) + } + if got := json.Valid(stderr.Bytes()); got != (format == "json") { + t.Fatalf("wrong error format: %s", stderr.String()) + } + stderr.Reset() + untyped := Classify(cmd, errors.New(err.Error())) + if untyped.Reason == ReasonCLIValidation { + t.Fatal("an untyped error must not be classified by matching its text") + } + }) + } + } +} + type tableTestRow struct { ID int64 `json:"id"` Name string `json:"name"` @@ -1025,6 +1070,95 @@ func TestUnknownSubcommandKeepsHelpAndCompletionWorking(t *testing.T) { } } +func TestOutcomeStreamStatePointerOrder(t *testing.T) { + cmd := &cobra.Command{Use: "compose"} + cfg := &outcomeConfig{ + StreamStatePointers: []string{"/data/status", "/data/widget/status"}, + States: map[string]string{"done": "success", "failed": "failure"}, + } + for _, tc := range []struct { + name string + status interface{} + wantFailure bool + }{ + {"first wins", "done", false}, + {"empty falls through", "", true}, + {"non-string falls through", false, true}, + } { + t.Run(tc.name, func(t *testing.T) { + frame := map[string]interface{}{"data": map[string]interface{}{ + "status": tc.status, + "widget": map[string]interface{}{"status": "failed"}, + }} + if got := outcomeStreamFailure(cmd, cfg, nil, frame); (got != nil) != tc.wantFailure { + t.Fatalf("failure = %v, want failure %v", got, tc.wantFailure) + } + }) + } +} + +func unboundedJSONNumbers() []json.Number { + return []json.Number{ + "1e100000000", + "1e-100000000", + "1E+99999999999999999999", + json.Number(strings.Repeat("9", maxDecimalLength+1)), + "1/2", + "0x1p100000000", + "1_000", + "+1", + ".5", + "1.", + "1e", + "", + "00", + "01", + "-01", + "01e2", + "01.5", + } +} + +func TestParseBoundedRat(t *testing.T) { + for _, number := range unboundedJSONNumbers() { + if _, ok := parseBoundedRat(number.String()); ok { + t.Errorf("parseBoundedRat(%.20q) parsed", number) + } + } + for text, want := range map[string]string{ + "0": "0", + "-0": "0", + "0.5": "1/2", + "-0e1": "0", + "10": "10", + "12": "12", + "-1.5": "-3/2", + "2.5E+1": "25", + "25e-1": "5/2", + "1e1000": "1" + strings.Repeat("0", 1000), + "1e-1000": "1/1" + strings.Repeat("0", 1000), + } { + got, ok := parseBoundedRat(text) + if !ok || got.RatString() != want { + t.Errorf("parseBoundedRat(%q) = %v, %t, want %s", text, got, ok, want) + } + } + if _, ok := parseBoundedRat("1e1001"); ok { + t.Error("parseBoundedRat(1e1001) parsed") + } +} + +func TestCanonicalNumberKeepsUnboundedLexemes(t *testing.T) { + for _, number := range unboundedJSONNumbers() { + if got := canonicalNumber(number); got != number { + t.Errorf("canonicalNumber(%.20q) = %v", number, got) + } + } + if got := canonicalNumber("1.50"); got != json.Number("1.5") { + t.Errorf("canonicalNumber(1.50) = %v", got) + } +} + func TestUnknownSubcommandHonoursDisableSuggestions(t *testing.T) { root, _ := unknownCommandTestTree() group, _, _ := root.Find([]string{"errors"}) diff --git a/internal/output/streaming.go b/internal/output/streaming.go index a4d88fde..b887b719 100644 --- a/internal/output/streaming.go +++ b/internal/output/streaming.go @@ -52,6 +52,7 @@ func StreamResult(cmd *cobra.Command, res interface{}, streamFieldName string, s // so every hop's events reach one projector and one output sequence. type streamHops interface { observe(frame map[string]interface{}) + abort() wrap(err error) error next() (interface{}, bool, error) discrete(res interface{}) error @@ -75,7 +76,7 @@ func streamResult(cmd *cobra.Command, res interface{}, streamFieldName string, h projector := newStreamProjector(cmd) outcomeCfg := activeOutcome(cmd) - if outcomeCfg != nil && outcomeCfg.StreamStatePointer == "" { + if outcomeCfg != nil && len(outcomeCfg.streamStatePointers()) == 0 { outcomeCfg = nil } var streamFailure *outcomeError @@ -191,6 +192,9 @@ func streamResult(cmd *cobra.Command, res interface{}, streamFieldName string, h if len(valueResults) == 1 { if body, isErr := streamErrorEvent(item, raw); isErr { + if hops != nil { + hops.abort() + } return false, renderAfterFinish(wrap(&StreamEventError{Body: string(body)})) } } @@ -395,7 +399,7 @@ func typedLeaves(wire, typed interface{}) interface{} { // Bigint and long-decimal lexemes are kept: float64 would change their value. func canonicalNumber(n json.Number) interface{} { - exact, ok := new(big.Rat).SetString(n.String()) + exact, ok := parseBoundedRat(n.String()) if !ok { return n } diff --git a/internal/sdk/models/sdkerrors/cancelinteractionbyid.go b/internal/sdk/models/sdkerrors/cancelinteractionbyid.go index 6cf554c2..f1423bdd 100644 --- a/internal/sdk/models/sdkerrors/cancelinteractionbyid.go +++ b/internal/sdk/models/sdkerrors/cancelinteractionbyid.go @@ -18,6 +18,7 @@ package sdkerrors import ( "encoding/json" + "fmt" "github.com/google-gemini/gemini-api-cli/internal/sdk/models/components" "github.com/google-gemini/gemini-api-cli/internal/sdk/models/interactions" @@ -33,6 +34,15 @@ type CancelInteractionByIDServerError struct { var _ error = &CancelInteractionByIDServerError{} func (e *CancelInteractionByIDServerError) Error() string { + if e != nil { + if e.ErrorInfo.Message != nil && *e.ErrorInfo.Message != "" { + if e.ErrorInfo.Code != nil && *e.ErrorInfo.Code != "" { + return fmt.Sprintf("%v: %s", *e.ErrorInfo.Code, *e.ErrorInfo.Message) + } + return *e.ErrorInfo.Message + } + } + data, _ := json.Marshal(e) return string(data) } @@ -47,6 +57,15 @@ type CancelInteractionByIDClientError struct { var _ error = &CancelInteractionByIDClientError{} func (e *CancelInteractionByIDClientError) Error() string { + if e != nil { + if e.ErrorInfo.Message != nil && *e.ErrorInfo.Message != "" { + if e.ErrorInfo.Code != nil && *e.ErrorInfo.Code != "" { + return fmt.Sprintf("%v: %s", *e.ErrorInfo.Code, *e.ErrorInfo.Message) + } + return *e.ErrorInfo.Message + } + } + data, _ := json.Marshal(e) return string(data) } diff --git a/internal/sdk/models/sdkerrors/createinteraction.go b/internal/sdk/models/sdkerrors/createinteraction.go index b96f0350..de04f7cd 100644 --- a/internal/sdk/models/sdkerrors/createinteraction.go +++ b/internal/sdk/models/sdkerrors/createinteraction.go @@ -18,6 +18,7 @@ package sdkerrors import ( "encoding/json" + "fmt" "github.com/google-gemini/gemini-api-cli/internal/sdk/models/components" "github.com/google-gemini/gemini-api-cli/internal/sdk/models/interactions" @@ -33,6 +34,15 @@ type CreateInteractionServerError struct { var _ error = &CreateInteractionServerError{} func (e *CreateInteractionServerError) Error() string { + if e != nil { + if e.ErrorInfo.Message != nil && *e.ErrorInfo.Message != "" { + if e.ErrorInfo.Code != nil && *e.ErrorInfo.Code != "" { + return fmt.Sprintf("%v: %s", *e.ErrorInfo.Code, *e.ErrorInfo.Message) + } + return *e.ErrorInfo.Message + } + } + data, _ := json.Marshal(e) return string(data) } @@ -47,6 +57,15 @@ type CreateInteractionClientError struct { var _ error = &CreateInteractionClientError{} func (e *CreateInteractionClientError) Error() string { + if e != nil { + if e.ErrorInfo.Message != nil && *e.ErrorInfo.Message != "" { + if e.ErrorInfo.Code != nil && *e.ErrorInfo.Code != "" { + return fmt.Sprintf("%v: %s", *e.ErrorInfo.Code, *e.ErrorInfo.Message) + } + return *e.ErrorInfo.Message + } + } + data, _ := json.Marshal(e) return string(data) } diff --git a/internal/sdk/models/sdkerrors/deleteinteraction.go b/internal/sdk/models/sdkerrors/deleteinteraction.go index e1437495..3a3a63a8 100644 --- a/internal/sdk/models/sdkerrors/deleteinteraction.go +++ b/internal/sdk/models/sdkerrors/deleteinteraction.go @@ -18,6 +18,7 @@ package sdkerrors import ( "encoding/json" + "fmt" "github.com/google-gemini/gemini-api-cli/internal/sdk/models/components" "github.com/google-gemini/gemini-api-cli/internal/sdk/models/interactions" @@ -33,6 +34,15 @@ type DeleteInteractionServerError struct { var _ error = &DeleteInteractionServerError{} func (e *DeleteInteractionServerError) Error() string { + if e != nil { + if e.ErrorInfo.Message != nil && *e.ErrorInfo.Message != "" { + if e.ErrorInfo.Code != nil && *e.ErrorInfo.Code != "" { + return fmt.Sprintf("%v: %s", *e.ErrorInfo.Code, *e.ErrorInfo.Message) + } + return *e.ErrorInfo.Message + } + } + data, _ := json.Marshal(e) return string(data) } @@ -47,6 +57,15 @@ type DeleteInteractionClientError struct { var _ error = &DeleteInteractionClientError{} func (e *DeleteInteractionClientError) Error() string { + if e != nil { + if e.ErrorInfo.Message != nil && *e.ErrorInfo.Message != "" { + if e.ErrorInfo.Code != nil && *e.ErrorInfo.Code != "" { + return fmt.Sprintf("%v: %s", *e.ErrorInfo.Code, *e.ErrorInfo.Message) + } + return *e.ErrorInfo.Message + } + } + data, _ := json.Marshal(e) return string(data) } diff --git a/internal/sdk/models/sdkerrors/getinteractionbyid.go b/internal/sdk/models/sdkerrors/getinteractionbyid.go index 42be5725..258ad9a3 100644 --- a/internal/sdk/models/sdkerrors/getinteractionbyid.go +++ b/internal/sdk/models/sdkerrors/getinteractionbyid.go @@ -18,6 +18,7 @@ package sdkerrors import ( "encoding/json" + "fmt" "github.com/google-gemini/gemini-api-cli/internal/sdk/models/components" "github.com/google-gemini/gemini-api-cli/internal/sdk/models/interactions" @@ -33,6 +34,15 @@ type GetInteractionByIDServerError struct { var _ error = &GetInteractionByIDServerError{} func (e *GetInteractionByIDServerError) Error() string { + if e != nil { + if e.ErrorInfo.Message != nil && *e.ErrorInfo.Message != "" { + if e.ErrorInfo.Code != nil && *e.ErrorInfo.Code != "" { + return fmt.Sprintf("%v: %s", *e.ErrorInfo.Code, *e.ErrorInfo.Message) + } + return *e.ErrorInfo.Message + } + } + data, _ := json.Marshal(e) return string(data) } @@ -47,6 +57,15 @@ type GetInteractionByIDClientError struct { var _ error = &GetInteractionByIDClientError{} func (e *GetInteractionByIDClientError) Error() string { + if e != nil { + if e.ErrorInfo.Message != nil && *e.ErrorInfo.Message != "" { + if e.ErrorInfo.Code != nil && *e.ErrorInfo.Code != "" { + return fmt.Sprintf("%v: %s", *e.ErrorInfo.Code, *e.ErrorInfo.Message) + } + return *e.ErrorInfo.Message + } + } + data, _ := json.Marshal(e) return string(data) } diff --git a/internal/sdk/sdkinternal/utils/pathparams.go b/internal/sdk/sdkinternal/utils/pathparams.go index 315d87d8..9b3bab2c 100644 --- a/internal/sdk/sdkinternal/utils/pathparams.go +++ b/internal/sdk/sdkinternal/utils/pathparams.go @@ -28,6 +28,14 @@ import ( "github.com/google-gemini/gemini-api-cli/internal/sdk/types" ) +type InvalidPathParameterError struct { + Name string +} + +func (e *InvalidPathParameterError) Error() string { + return fmt.Sprintf("path parameter %q contains a dot segment", e.Name) +} + func GenerateURL(_ context.Context, serverURL, path string, pathParams interface{}, globals interface{}) (string, error) { uri := strings.TrimSuffix(serverURL, "/") + path @@ -47,7 +55,7 @@ func GenerateURL(_ context.Context, serverURL, path string, pathParams interface for name, value := range parsedParameters { for _, segment := range strings.Split(value, "/") { if segment == "." || segment == ".." { - return "", fmt.Errorf("path parameter %q contains a dot segment", name) + return "", &InvalidPathParameterError{Name: name} } } } diff --git a/scripts/install.sh b/scripts/install.sh index 3ae0094c..f85c34dc 100644 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -140,8 +140,8 @@ install_cli() { log_info "Downloading from: $download_url" # Create temporary directory - local tmp_dir=$(mktemp -d) - trap "rm -rf $tmp_dir" EXIT + tmp_dir=$(mktemp -d) || exit 1 + trap 'rm -rf -- "$tmp_dir"' EXIT # Download archive if command -v curl >/dev/null 2>&1; then diff --git a/tests/contract/cli_contract_test.go b/tests/contract/cli_contract_test.go index f6f75a92..c4b07252 100644 --- a/tests/contract/cli_contract_test.go +++ b/tests/contract/cli_contract_test.go @@ -176,7 +176,7 @@ func TestImageArtifactOutput(t *testing.T) { if strings.TrimSpace(result.stdout) != target { t.Errorf("--out path = %q, want %q (explicit path kept as given)", strings.TrimSpace(result.stdout), target) } - if !strings.Contains(result.stderr, "Note: hero.jpg contains image/png content; its extension does not match") { + if !strings.Contains(result.stderr, `Note: hero.jpg contains "image/png" content; its extension does not match`) { t.Errorf("mismatch note missing from stderr:\n%s", result.stderr) } <-requests @@ -1326,7 +1326,7 @@ func TestBodySchemaFlag(t *testing.T) { } var modelDef struct { - Required []string `json:"required"` + Required []string `json:"required"` Properties map[string]map[string]any `json:"properties"` } if err := json.Unmarshal(modelRaw, &modelDef); err != nil { diff --git a/tests/contract/streaming_defaults_test.go b/tests/contract/streaming_defaults_test.go index e5d132f9..e7cab7cc 100644 --- a/tests/contract/streaming_defaults_test.go +++ b/tests/contract/streaming_defaults_test.go @@ -447,7 +447,7 @@ func TestImageInteractivePromptsForOutputFile(t *testing.T) { if data, err := os.ReadFile(target); err != nil || len(data) != 69 { t.Errorf("written file %q: err=%v len=%d, want the 69-byte PNG", target, err, len(data)) } - if !strings.Contains(stderr, "Note: hero.jpg contains image/png content; its extension does not match") { + if !strings.Contains(stderr, `Note: hero.jpg contains "image/png" content; its extension does not match`) { t.Errorf("stderr lacks the extension-mismatch note:\n%s", stderr) }