| 1 | package control |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "regexp" |
| 8 | "strings" |
| 9 | "time" |
| 10 | |
| 11 | "reasonix/internal/i18n" |
| 12 | "reasonix/internal/provider" |
| 13 | "reasonix/internal/secrets" |
| 14 | "reasonix/internal/turnevent" |
| 15 | ) |
| 16 | |
| 17 | // explainStreamFailure explains a failure of the response body itself, or |
| 18 | // returns nil when err is not one. |
| 19 | func explainStreamFailure(err error) error { |
| 20 | switch { |
| 21 | case errors.Is(err, provider.ErrNonStreamingResponse): |
| 22 | return &explainedError{msg: fmt.Sprintf(i18n.M.ProviderErrNonStreamingFmt, err.Error()), cause: err} |
| 23 | case provider.IsStreamInterrupted(err): |
| 24 | return &explainedError{msg: fmt.Sprintf(i18n.M.ProviderErrStreamInterruptedFmt, err.Error()), cause: err} |
| 25 | case provider.IsConnReset(err): |
| 26 | return &explainedError{msg: fmt.Sprintf(i18n.M.ProviderErrDisconnectedFmt, err.Error()), cause: err} |
| 27 | } |
| 28 | return nil |
| 29 | } |
| 30 | |
| 31 | // explainError maps a provider HTTP failure to an actionable, localized message |
| 32 | // so the turn-done error the UI shows is never a bare status code or silent |
| 33 | // failure. Unknown errors (and nil) pass through unchanged. |
| 34 | func explainError(err error) error { |
| 35 | if err == nil { |
| 36 | return nil |
| 37 | } |
| 38 | // Filesystem errors can satisfy net.Error on some platforms. Preserve the |
| 39 | // storage sentinel before provider retry classification so a poisoned WAL |
| 40 | // is never reported as a model-stream disconnect. |
| 41 | if errors.Is(err, turnevent.ErrTurnLedgerUnavailable) { |
| 42 | return err |
| 43 | } |
| 44 | if errors.Is(err, provider.ErrNoDeliverableOutput) { |
| 45 | return &explainedError{msg: i18n.M.NoDeliverableOutput, cause: err} |
| 46 | } |
| 47 | // The exhausted wait wraps its transport cause; explain the wait itself |
| 48 | // before the connect/status branches below explain that cause instead. |
| 49 | if wait := provider.AsRecoveryWaitExhausted(err); wait != nil { |
| 50 | return &explainedError{msg: explainRecoveryWait(wait), cause: err} |
| 51 | } |
| 52 | if explained := explainStreamFailure(err); explained != nil { |
| 53 | return explained |
| 54 | } |
| 55 | // An overflow without token numbers has nothing to quote; the generic 400 |
| 56 | // branch below keeps the provider's own reason instead of zeros. |
| 57 | if limit := provider.AsContextLimitError(err); limit != nil && limit.WindowTokens > 0 { |
| 58 | msg := fmt.Sprintf(i18n.M.ProviderErrContextOverflowFmt, limit.PromptTokens, limit.CompletionTokens, limit.RequestedTokens, limit.WindowTokens) |
| 59 | if reason := apiErrorReason(limit.APIError); reason != "" { |
| 60 | msg = fmt.Sprintf("%s\n%s", msg, reason) |
| 61 | } |
| 62 | label := "" |
| 63 | if limit.APIError != nil { |
| 64 | label = provider.ProviderDisplayLabel(limit.APIError.Provider, limit.APIError.ProviderDisplayName, limit.APIError.Protocol) |
| 65 | } |
| 66 | return &explainedError{msg: providerFailureMessage(label, limit.APIError, msg), cause: err} |
| 67 | } |
| 68 | if quota := provider.AsQuotaError(err); quota != nil { |
| 69 | label := provider.ProviderDisplayLabel(quota.Provider, quota.ProviderDisplayName, quota.Protocol) |
| 70 | return &explainedError{msg: fmt.Sprintf(i18n.M.ProviderErrQuotaExhaustedFmt, label, quota.Status), cause: err} |
| 71 | } |
| 72 | var apiErr *provider.APIError |
| 73 | if errors.As(err, &apiErr) { |
| 74 | label := provider.ProviderDisplayLabel(apiErr.Provider, apiErr.ProviderDisplayName, apiErr.Protocol) |
| 75 | if provider.IsOpaqueBadRequest(err) { |
| 76 | if trace := provider.DiagnoseFailure(err).TraceID; trace != "" { |
| 77 | return &explainedError{msg: providerFailureMessage(label, apiErr, fmt.Sprintf("%s\nTrace ID: %s", i18n.M.ProviderErrReasonMissing, trace)), cause: err} |
| 78 | } |
| 79 | return &explainedError{msg: providerFailureMessage(label, apiErr, i18n.M.ProviderErrReasonMissing), cause: err} |
| 80 | } |
| 81 | if msg := providerContentSafetyMessage(apiErr); msg != "" { |
| 82 | if reason := apiErrorReason(apiErr); reason != "" { |
| 83 | msg = fmt.Sprintf("%s\n%s", msg, reason) |
| 84 | } |
| 85 | return &explainedError{msg: providerFailureMessage(label, apiErr, msg), cause: err} |
| 86 | } |
| 87 | msg := i18n.M.ProviderStatusMessage(apiErr.Status) |
| 88 | if msg == "" { |
| 89 | return err |
| 90 | } |
| 91 | if reason := apiErrorReason(apiErr); reason != "" { |
| 92 | msg = fmt.Sprintf("%s\n%s", msg, reason) |
| 93 | } |
| 94 | return &explainedError{msg: providerFailureMessage(label, apiErr, msg), cause: err} |
| 95 | } |
| 96 | var authErr *provider.AuthError |
| 97 | if errors.As(err, &authErr) { |
| 98 | label := provider.ProviderDisplayLabel(authErr.Provider, authErr.ProviderDisplayName, authErr.Protocol) |
| 99 | reason := redactAuthReason(providerBodyReason(authErr.Body)) |
| 100 | if modelFormatMismatchReason(reason) { |
| 101 | details := []string{i18n.M.ProviderErrModelFormatMismatch} |
| 102 | lower := strings.ToLower(reason) |
| 103 | isOpenCodeGo := strings.Contains(strings.ToLower(authErr.Provider), "opencode-go") || strings.EqualFold(authErr.KeyEnv, "OPENCODE_GO_API_KEY") |
| 104 | if isOpenCodeGo && strings.Contains(lower, "grok-4.5") && strings.Contains(lower, "format anthropic") { |
| 105 | details = append(details, i18n.M.ProviderErrOpenCodeGoGrokRoute) |
| 106 | } |
| 107 | if reason != "" { |
| 108 | details = append(details, reason) |
| 109 | } |
| 110 | return &explainedError{msg: providerFailureMessage(label, authErr, strings.Join(details, "\n")), cause: err} |
| 111 | } |
| 112 | msg := i18n.M.ProviderErrAuth |
| 113 | if authErr.HasKey { |
| 114 | msg = i18n.M.ProviderErrAuthRejected |
| 115 | } |
| 116 | switch { |
| 117 | case authErr.KeyEnv != "" && authErr.KeySource != "": |
| 118 | msg = fmt.Sprintf("%s (%s from %s)", msg, authErr.KeyEnv, authErr.KeySource) |
| 119 | case authErr.KeyEnv != "": |
| 120 | msg = fmt.Sprintf("%s (%s)", msg, authErr.KeyEnv) |
| 121 | } |
| 122 | // Relays explain *why* auth failed in the body ("token expired", key |
| 123 | // not entitled to the model) — as diagnostic here as on APIError, but |
| 124 | // auth bodies also echo credentials, so scrub key material first. |
| 125 | if reason != "" { |
| 126 | msg = fmt.Sprintf("%s\n%s", msg, reason) |
| 127 | } |
| 128 | return &explainedError{msg: providerFailureMessage(label, authErr, msg), cause: err} |
| 129 | } |
| 130 | return err |
| 131 | } |
| 132 | |
| 133 | func providerFailureMessage(label string, source any, message string) string { |
| 134 | hasDisplayIdentity := false |
| 135 | switch value := source.(type) { |
| 136 | case *provider.APIError: |
| 137 | hasDisplayIdentity = value != nil && (strings.TrimSpace(value.ProviderDisplayName) != "" || strings.TrimSpace(value.Protocol) != "") |
| 138 | case *provider.AuthError: |
| 139 | hasDisplayIdentity = value != nil && (strings.TrimSpace(value.ProviderDisplayName) != "" || strings.TrimSpace(value.Protocol) != "") |
| 140 | } |
| 141 | if !hasDisplayIdentity || strings.TrimSpace(label) == "" { |
| 142 | return message |
| 143 | } |
| 144 | return label + ": " + message |
| 145 | } |
| 146 | |
| 147 | // explainedError shows the localized message while keeping the typed cause |
| 148 | // reachable, so DiagnoseFailure on the TurnDone error still classifies it. |
| 149 | type explainedError struct { |
| 150 | msg string |
| 151 | cause error |
| 152 | } |
| 153 | |
| 154 | func (e *explainedError) Error() string { return e.msg } |
| 155 | func (e *explainedError) Unwrap() error { return e.cause } |
| 156 | |
| 157 | func explainRecoveryWait(wait *provider.RecoveryWaitExhaustedError) string { |
| 158 | lines := []string{fmt.Sprintf(i18n.M.ProviderErrWaitExhaustedFmt, wait.Waited.Round(time.Second))} |
| 159 | var apiErr *provider.APIError |
| 160 | switch { |
| 161 | case errors.As(wait.Cause, &apiErr): |
| 162 | lines = append(lines, fmt.Sprintf("HTTP %d", apiErr.Status)) |
| 163 | if reason := apiErrorReason(apiErr); reason != "" { |
| 164 | lines = append(lines, reason) |
| 165 | } |
| 166 | case wait.Cause != nil: |
| 167 | lines = append(lines, wait.Cause.Error()) |
| 168 | } |
| 169 | return strings.Join(lines, "\n") |
| 170 | } |
| 171 | |
| 172 | func modelFormatMismatchReason(reason string) bool { |
| 173 | lower := strings.ToLower(strings.TrimSpace(reason)) |
| 174 | return strings.Contains(lower, "model") && strings.Contains(lower, "not supported for format") |
| 175 | } |
| 176 | |
| 177 | // apiErrorReason returns the provider's verbatim reason for a failed request — |
| 178 | // the localized line names the category, the body names the actual cause |
| 179 | // (context-length exceeded, unpaired tool_calls, a relay's "no available |
| 180 | // channel"). Every mapped status surfaces its body, not just the |
| 181 | // request-shaped 4xx: relay gateways wrap the real failure — dead upstream |
| 182 | // channel, unsupported tools, exhausted quota — in a 402/429/5xx body, and |
| 183 | // without it those errors are undiagnosable from the category line alone. |
| 184 | func apiErrorReason(e *provider.APIError) string { |
| 185 | details := make([]string, 0, 3) |
| 186 | if reason := providerBodyReason(e.Body); reason != "" { |
| 187 | details = append(details, reason) |
| 188 | } |
| 189 | if traceID := strings.TrimSpace(e.TraceID); traceID != "" { |
| 190 | details = append(details, "Trace ID: "+clampRunes(traceID, 200)) |
| 191 | } |
| 192 | if e.ToolContext != "" { |
| 193 | details = append(details, e.ToolContext) |
| 194 | } |
| 195 | return strings.Join(details, "\n") |
| 196 | } |
| 197 | |
| 198 | var ( |
| 199 | miniMax1026CodeRe = regexp.MustCompile(`(^|[^0-9])1026([^0-9]|$)`) |
| 200 | miniMax1027CodeRe = regexp.MustCompile(`(^|[^0-9])1027([^0-9]|$)`) |
| 201 | ) |
| 202 | |
| 203 | // providerContentSafetyMessage recognizes MiniMax's provider-specific content |
| 204 | // review failures before the generic HTTP 422 mapping calls them invalid |
| 205 | // parameters. A custom-named MiniMax provider is still recognized by the |
| 206 | // documented status text; numeric-only errors require a MiniMax provider name |
| 207 | // so another OpenAI-compatible API cannot accidentally inherit this meaning. |
| 208 | func providerContentSafetyMessage(e *provider.APIError) string { |
| 209 | if e == nil || e.Status != 422 { |
| 210 | return "" |
| 211 | } |
| 212 | body := strings.ToLower(e.Body) |
| 213 | providerName := strings.ToLower(e.Provider) |
| 214 | isMiniMax := strings.Contains(providerName, "minimax") |
| 215 | switch { |
| 216 | case strings.Contains(body, "input new_sensitive") || isMiniMax && miniMax1026CodeRe.MatchString(body): |
| 217 | return i18n.M.ProviderErrInputSensitive |
| 218 | case strings.Contains(body, "output new_sensitive") || isMiniMax && miniMax1027CodeRe.MatchString(body): |
| 219 | return i18n.M.ProviderErrOutputSensitive |
| 220 | default: |
| 221 | return "" |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | // redactAuthReason scrubs key material from an auth-failure reason before |
| 226 | // display. Deliberately applied only to 401/403 bodies: other statuses don't |
| 227 | // carry credentials, and 400 schema errors legitimately contain long |
| 228 | // identifiers that this stronger scrub would mangle. |
| 229 | func redactAuthReason(s string) string { |
| 230 | return secrets.RedactCredentials(s) |
| 231 | } |
| 232 | |
| 233 | // providerBodyReason pulls the human reason from an OpenAI/Anthropic-shaped |
| 234 | // error body ({"error":{"message":…}}) or MiniMax's base_resp envelope, |
| 235 | // falling back to the trimmed raw body. |
| 236 | func providerBodyReason(body string) string { |
| 237 | if body == "" { |
| 238 | return "" |
| 239 | } |
| 240 | var parsed struct { |
| 241 | Error struct { |
| 242 | Message string `json:"message"` |
| 243 | } `json:"error"` |
| 244 | BaseResp struct { |
| 245 | StatusMsg string `json:"status_msg"` |
| 246 | } `json:"base_resp"` |
| 247 | } |
| 248 | if json.Unmarshal([]byte(body), &parsed) == nil { |
| 249 | switch { |
| 250 | case parsed.Error.Message != "": |
| 251 | return clampRunes(parsed.Error.Message, 800) |
| 252 | case parsed.BaseResp.StatusMsg != "": |
| 253 | return clampRunes(parsed.BaseResp.StatusMsg, 800) |
| 254 | } |
| 255 | } |
| 256 | return clampRunes(body, 800) |
| 257 | } |
| 258 | |
| 259 | func clampRunes(s string, max int) string { |
| 260 | r := []rune(s) |
| 261 | if len(r) <= max { |
| 262 | return s |
| 263 | } |
| 264 | return string(r[:max]) + "…" |
| 265 | } |
| 266 |