Files
alan 16643b9f1b Stop a run when the model provider refuses for balance or quota
Ten runs each burned five visits in seconds on "OpenCode agent reported an
execution error": the provider answered HTTP 402 provider.quota and the
classifier read neither field. That refusal is now its own error with fixed
text, is not retried inside the stage, and ends the run instead of
following the error edge.
2026-11-11 10:10:40 +00:00

138 lines
5.5 KiB
Go

package opencode
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
)
// FormatProbe is retained, deny-all and no-inference. Some native releases
// accept a format on POST but reject their own stored user message on GET.
type FormatProbe struct {
SessionID string `json:"session_id"`
Supported bool `json:"supported"`
Diagnostic string `json:"diagnostic,omitempty"`
Response string `json:"response,omitempty"`
}
func (c *Connection) supportsFormat(ctx context.Context, format json.RawMessage) (bool, error) {
if c.formatChecked {
return c.formatSupported, nil
}
created, err := c.Native(ctx, "post", "/session", map[string]any{"title": "Pipelines structured-format compatibility probe (no inference)", "permission": []map[string]string{{"permission": "*", "pattern": "*", "action": "deny"}}})
if err != nil {
return false, err
}
var session struct {
ID string `json:"id"`
}
if json.Unmarshal(created, &session) != nil || !sessionID.MatchString(session.ID) {
return false, fmt.Errorf("invalid structured-format probe session")
}
c.FormatProbe = &FormatProbe{SessionID: session.ID}
posted, err := c.Native(ctx, "post", "/session/"+session.ID+"/message", map[string]any{"noReply": true, "format": format, "parts": []map[string]string{{"type": "text", "text": "Compatibility probe only. No reply, inference or tool execution requested."}}})
if err != nil {
c.FormatProbe.Response = string(posted)
return false, err
}
data, err := c.Native(ctx, "get", "/session/"+session.ID+"/message", nil)
if err != nil {
// Downgrade only this specific readback incompatibility, never an auth,
// network or unrelated HTTP failure. Do not alter the stored probe.
c.FormatProbe.Response = string(data)
if !strings.Contains(err.Error(), "HTTP 400") || !strings.Contains(string(data), "Expected OutputFormat") {
return false, err
}
c.FormatProbe.Diagnostic = "native format readback incompatibility; explicit format omitted, strict local JSON validation remains enabled"
c.FormatProbe.Response = string(data)
c.formatChecked = true
return false, nil
}
var messages []json.RawMessage
if json.Unmarshal(data, &messages) != nil || len(messages) == 0 {
return false, fmt.Errorf("invalid structured-format probe readback")
}
c.formatChecked = true
c.formatSupported = true
c.FormatProbe.Supported = true
return true, nil
}
// ErrProviderQuota is a provider refusal for the account's balance or quota.
// Its text is fixed: no provider message, link or credential is copied.
var ErrProviderQuota = errors.New("the model provider refused the request: the account's balance or quota is used up; top up the provider account or choose another model for the stage")
// ExecutionError exposes a safe classification, not arbitrary provider messages,
// prompts or credentials. Full redacted responses belong in failure evidence.
func ExecutionError(data json.RawMessage) error {
var failure struct {
Name string `json:"name"`
Tag string `json:"_tag"`
Type string `json:"type"`
Status int `json:"status"`
Data struct {
StatusCode int `json:"statusCode"`
} `json:"data"`
}
if json.Unmarshal(data, &failure) != nil {
return fmt.Errorf("OpenCode agent reported an execution error")
}
if failure.Data.StatusCode == 0 {
failure.Data.StatusCode = failure.Status
}
// The provider refused for the account, not for this request: another
// attempt cannot succeed, so the caller must not retry or loop.
if failure.Type == "provider.quota" || failure.Data.StatusCode == 402 {
return fmt.Errorf("%w (HTTP %d)", ErrProviderQuota, failure.Data.StatusCode)
}
name := failure.Name
if name == "" {
name = failure.Type
}
if name == "" {
name = failure.Tag
}
if name == "StructuredOutputError" {
return fmt.Errorf("StructuredOutputError: Model did not produce structured output; inspect retained response for tool-call markup or result-envelope mismatch")
}
safeNames := map[string]bool{"APIError": true, "ProviderAuthError": true, "ContextOverflowError": true, "MessageAbortedError": true, "OutputLengthError": true, "UnknownError": true, "ServiceUnavailableError": true}
if !safeNames[name] {
// An unrecognized provider error name is still reported, but only as a
// bounded, safe identifier plus any HTTP status. No provider body,
// message, prompt or credential is copied.
if safe := sanitizedExecutionName(name); safe != "" {
if failure.Data.StatusCode >= 400 && failure.Data.StatusCode <= 599 {
return fmt.Errorf("OpenCode agent reported an execution error: %s (HTTP %d)", safe, failure.Data.StatusCode)
}
return fmt.Errorf("OpenCode agent reported an execution error: %s", safe)
}
return fmt.Errorf("OpenCode agent reported an execution error")
}
if failure.Data.StatusCode >= 400 && failure.Data.StatusCode <= 599 {
return fmt.Errorf("OpenCode agent execution error: %s (HTTP %d)", name, failure.Data.StatusCode)
}
return fmt.Errorf("OpenCode agent execution error: %s", name)
}
// sanitizedExecutionName reduces an unknown provider error name/tag to a
// bounded, safe identifier so the diagnostic can name the failure shape without
// copying an arbitrary message, prompt or credential. A name containing any
// other byte returns empty and is reported as a generic execution error.
func sanitizedExecutionName(name string) string {
if len(name) > 64 {
name = name[:64]
}
var b strings.Builder
for _, r := range name {
switch {
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '_', r == '.', r == '-':
b.WriteRune(r)
default:
return ""
}
}
return b.String()
}