diff --git a/internal/app/app.go b/internal/app/app.go index 36f0777d0547474c6b4fa8053436f3cf7b274406..099b092089c4a4e4e0ddcc9ccf79c36ca66acdce 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -149,10 +149,13 @@ func (a *App) RunNonInteractive(ctx context.Context, prompt string, outputFormat content = result.Message.Content().String() } - fmt.Println(format.FormatOutput(content, outputFormat)) + out, err := format.FormatOutput(content, outputFormat) + if err != nil { + return err + } + fmt.Println(out) slog.Info("Non-interactive run completed", "session_id", sess.ID) - return nil } diff --git a/internal/format/format.go b/internal/format/format.go index f21da240868c541bc1fb0a29626cdc2305d103d1..9f5a98910cafa41b924ff516da54ab751eb7f058 100644 --- a/internal/format/format.go +++ b/internal/format/format.go @@ -57,11 +57,10 @@ func GetHelpText() string { } // FormatOutput formats the AI response according to the specified format -func FormatOutput(content string, formatStr string) string { +func FormatOutput(content string, formatStr string) (string, error) { format, err := Parse(formatStr) if err != nil { - // Default to text format on error - return content + format = Text } switch format { @@ -70,12 +69,12 @@ func FormatOutput(content string, formatStr string) string { case Text: fallthrough default: - return content + return content, nil } } // formatAsJSON wraps the content in a simple JSON object -func formatAsJSON(content string) string { +func formatAsJSON(content string) (string, error) { // Use the JSON package to properly escape the content response := struct { Response string `json:"response"` @@ -85,15 +84,8 @@ func formatAsJSON(content string) string { jsonBytes, err := json.MarshalIndent(response, "", " ") if err != nil { - // In case of an error, return a manually formatted JSON - jsonEscaped := strings.ReplaceAll(content, "\\", "\\\\") - jsonEscaped = strings.ReplaceAll(jsonEscaped, "\"", "\\\"") - jsonEscaped = strings.ReplaceAll(jsonEscaped, "\n", "\\n") - jsonEscaped = strings.ReplaceAll(jsonEscaped, "\r", "\\r") - jsonEscaped = strings.ReplaceAll(jsonEscaped, "\t", "\\t") - - return fmt.Sprintf("{\n \"response\": \"%s\"\n}", jsonEscaped) + return "", fmt.Errorf("failed to marshal output into JSON: %w", err) } - return string(jsonBytes) + return string(jsonBytes), nil }