apierr

package
v1.4.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 12, 2026 License: AGPL-3.0 Imports: 16 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package apierr is the one place the Agent GM REST error taxonomy lives.

The REST layer, the CLI and (from Slice 3) MCP all render errors through this package, so a code's HTTP status, its retryable flag, the exit code it produces and the words of an irreversible effect cannot drift between surfaces. It is a vocabulary, not a router: it holds no handler logic and imports net/http only for the status constants.

The layer below is internal/gm, which classifies library errors into the same code vocabulary (spec section 3.5). This package agrees with it rather than duplicating it; gm_agreement_test.go asserts that agreement.

Spec sections 4.1, 4.7, 7.1, 7.2, 7.3, 7.7, 7.8, 11.2.

Index

Constants

View Source
const (
	// EffectMessageDelete is DELETE /v1/messages/{message_id} (spec 7.7).
	EffectMessageDelete = "deletes this message from your Google Messages account only; the recipient keeps it"

	// EffectConversationDelete is DELETE /v1/conversations/{conversation_id}
	// (spec 7.7).
	EffectConversationDelete = "deletes this conversation from your Google Messages account only; the other people in it keep it"

	// EffectAccountRemove is DELETE /v1/accounts/{id} (spec 4.7). Account
	// removal is the ONLY thing in Agent GM that deletes stored rows.
	EffectAccountRemove = "" /* 172-byte string literal not displayed */
)

The effect sentences of spec sections 7.7 and 4.7, byte for byte.

Each one is the `effect` field of the route's response, the closing sentence of the MCP tool description, and the text of the `agm` confirmation prompt. They are constants in this package so that those three surfaces are literally the same string: a model or a human must not be able to read a broader claim off one surface than another, and three hand-copied sentences drift the first time one is reworded.

The sentences say what is NOT affected as well as what is, because "delete" on a messaging surface is ambiguous and the ambiguity is the dangerous part: an agent that believes it can unsend a message will act on that belief.

View Source
const (
	// EffectAuthorizationRevoke is DELETE /v1/admin/authorizations/{id}.
	EffectAuthorizationRevoke = "revokes every token of this authorization. The client's next call is a 401, and it cannot refresh its way back"

	// EffectEnrollmentCodeRevoke is DELETE /v1/admin/enrollment-codes/{id}.
	EffectEnrollmentCodeRevoke = "stops this enrollment code being redeemable. Repeating it is not an error"

	// EffectClientRevoke is DELETE /v1/admin/clients/{id}.
	EffectClientRevoke = "removes this registration and revokes every authorization it holds. The client must register again"
)

The revocation sentences of spec section 9.5's admin routes.

They are a SEPARATE group from Effects() above, and deliberately so. Effects() holds the three sentences spec sections 7.7 and 4.7 write out verbatim, and a test asserts each of them appears in the spec word for word; these three are the same KIND of thing -- one sentence shared by the route's `effect` field and the `agm` confirmation prompt, so a human cannot confirm different words from the ones the server acted on -- but the spec describes the routes rather than quoting a sentence, so there is nothing to match against and adding them to Effects() would make that test assert something it cannot check.

Like the other three, none of them carries its own full stop: a surface that adds one would otherwise get two.

View Source
const (
	// ExitOK: success.
	ExitOK = 0
	// ExitUsage: CLI usage or validation error. idempotency_conflict lands
	// here because reusing a key with a different body is a caller mistake.
	ExitUsage = 2
	// ExitAuthRequired: authentication required or expired credentials.
	ExitAuthRequired = 3
	// ExitForbidden: authorization or insufficient scope.
	ExitForbidden = 4
	// ExitNotFound: requested resource absent.
	ExitNotFound = 5
	// ExitUnsupported: unsupported capability for this account, conversation
	// or message. not_signed_in is an account-level condition and lands here,
	// which is why the spec's gloss names the account.
	ExitUnsupported = 6
	// ExitRetryable: retryable network, Google, phone, or rate-limit failure.
	// phone_not_responding is here and NOT ExitOperationFailed: the operation
	// is pending, and a script that treats it as failed resends the message.
	ExitRetryable = 7
	// ExitOperationFailed: an operation reached a terminal failure. It is
	// produced by waiting on an operation, not by an error code, so no row of
	// section 7.2 maps to it.
	ExitOperationFailed = 8
	// ExitLocalConfig: local configuration or credential-store failure. It is
	// decided before a request is ever sent, so no row of section 7.2 maps
	// to it either.
	ExitLocalConfig = 9
	// ExitServerFailure: server contract or internal failure.
	ExitServerFailure = 10
)

The CLI exit codes of spec section 11.2. They are exported from here rather than kept in internal/cli so that the CLI, a script and a test all read one table; a second copy is how `agm` and the API come to disagree about what exit 7 means.

1 is deliberately unassigned: the Go runtime and the shell both use it for "something went wrong", so reserving it keeps "the process died" clearly distinct from "Agent GM decided something".

View Source
const (
	WarnReasonNormalized   = "reason_normalized"
	WarnReasonTruncated    = "reason_truncated"
	WarnFilenameNormalized = "filename_normalized"
	WarnFilenameTruncated  = "filename_truncated"
)

The warning strings of spec section 7.1. Text normalisation is never silent: a reason or a filename that had to be cleaned or shortened is accepted and the change is reported in the envelope's warnings array, so a caller never has to diff what it sent against what came back to discover that something changed.

View Source
const (
	// MaxReasonRunes bounds a human-supplied reason, which is stored and
	// shown but never parsed.
	MaxReasonRunes = 500
	// MaxFilenameRunes is the conventional filesystem name bound; the name
	// reaches a filename on disk and a Content-Disposition header.
	MaxFilenameRunes = 255
)

The length bounds. Spec section 7.1 requires a bound and a warning without naming a number, so the numbers are fixed here, once, and every surface reads them from here rather than choosing its own.

View Source
const AuthRealm = "agent-gm"

AuthRealm is the realm every 401 and 403 advertises (spec section 7.2).

View Source
const MaxBodyBytes int64 = 1 << 20

MaxBodyBytes is the 1 MiB body limit of spec section 7.2. A body over it is 413 payload_too_large; a body that fails to read for any other reason is 400, because "too large" would be a guess.

View Source
const RequestIDPrefix = "req_"

RequestIDPrefix is the typed prefix of the per-request ID (spec section 4.1). Unlike every other prefixed ID it is never stored.

View Source
const ResourceMetadataPath = "/.well-known/oauth-protected-resource/mcp"

ResourceMetadataPath is the path the resource_metadata parameter points at. It is the protected-resource metadata for the MCP surface, which is what an MCP client fetches to discover where to authorize (RFC 9728, spec 9.2).

Variables

View Source
var (
	// ReasonNotSignedIn: the account this touches is signed_out, error,
	// parked or account_changed. Its history stays readable; only writes are
	// refused. Distinct from the service-level not_paired, which means there
	// are no accounts at all.
	ReasonNotSignedIn = Reason{"not_signed_in"}
	// ReasonConversationReadOnly: Conversation.ReadOnly is set.
	ReasonConversationReadOnly = Reason{"conversation_read_only"}
	// ReasonConversationDeleted: delete-for-me has been applied locally.
	ReasonConversationDeleted = Reason{"conversation_deleted"}
	// ReasonNotMyMessage: deleting a message the owner did not send.
	ReasonNotMyMessage = Reason{"not_my_message"}
	// ReasonNotMyReaction: removing somebody else's reaction.
	ReasonNotMyReaction = Reason{"not_my_reaction"}
	// ReasonReplyNotSupported: reply_to_message_id on an SMS/MMS
	// conversation; replies are RCS-only.
	ReasonReplyNotSupported = Reason{"reply_not_supported"}
	// ReasonRCSNotAvailable: force_rcs where capabilities.force_rcs is false.
	ReasonRCSNotAvailable = Reason{"rcs_not_available"}
	// ReasonMediaPending: the attachment's bytes are not downloaded yet.
	ReasonMediaPending = Reason{"media_pending"}
)

Spec section 7.8's closed vocabulary, complete.

Functions

func Effects

func Effects() []string

Effects returns the three sentences, for a test or a documentation generator that has to enumerate them.

func ExitCodeFor

func ExitCodeFor(c Code) int

ExitCodeFor is the exit code spec section 11.2 assigns to c. A code outside the vocabulary exits 10: an answer Agent GM does not recognise is a server contract failure, which is exactly what 10 means.

func ExitCodes

func ExitCodes() map[Code]int

ExitCodes returns a copy of the whole mapping, for the CLI's documentation and for tests that enumerate it.

func HTTPStatus

func HTTPStatus(c Code) int

HTTPStatus is the status spec section 7.2 assigns to c. An unknown code is 500: a code that is not in the vocabulary is a bug in Agent GM, not a caller error, and answering 200 for it would be worse than answering 500.

func Known

func Known(c Code) bool

Known reports whether c is one of spec section 7.2's codes.

func NewRequestID

func NewRequestID() string

NewRequestID mints the `req_` UUIDv7 that goes in every envelope. UUIDv7 so that request IDs sort by time in a log; not stored, so there is nothing to derive it from (spec section 4.1).

func NormalizeFilename

func NormalizeFilename(filename string) (string, []string)

NormalizeFilename cleans a caller-supplied filename and returns it with the warnings that describe what changed. Besides control characters it strips any directory part: a filename is a name, and "../../etc/passwd" reaching the media cache would be a path traversal. An empty result becomes "file", because a nameless attachment cannot be served.

func NormalizeReason

func NormalizeReason(reason string) (string, []string)

NormalizeReason cleans a caller-supplied reason and returns it with the warnings that describe what changed. Control characters are removed -- a newline in a reason that is later logged is a log-injection vector -- and surrounding whitespace is trimmed.

func ResourceMetadataURL

func ResourceMetadataURL(publicURL string) string

ResourceMetadataURL is the absolute metadata URL for a deployment's public URL. It is built from the configured public URL and never from the request Host, so a hostile Host or X-Forwarded-Host cannot point a client at an attacker's authorization server.

func RevocationEffects

func RevocationEffects() []string

RevocationEffects returns the three sentences of spec section 9.5's admin revocations, for a test that has to enumerate them.

func WWWAuthenticate

func WWWAuthenticate(publicURL string, code Code, requiredScope string) string

WWWAuthenticate builds the header value that accompanies a 401 or a 403 (spec section 7.2): realm="agent-gm", an error parameter, resource_metadata pointing at the protected-resource document, and, for a scope refusal, the scope the route requires.

requiredScope is used only for insufficient_scope and is ignored otherwise; a 401 does not know what scope the caller would have needed, because it has not established who the caller is.

func WWWAuthenticateFor

func WWWAuthenticateFor(publicURL string, e *Error) string

WWWAuthenticateFor is WWWAuthenticate for an error value. It returns "" for any code that is not 401 or 403, so a handler can call it unconditionally and an unrelated error never advertises an authorization challenge.

Types

type AccountCandidate

type AccountCandidate struct {
	ID            string `json:"id"`
	GoogleAccount string `json:"google_account"`
	State         string `json:"state"`
}

AccountCandidate is one row of details.accounts on an ambiguous-account error: enough for the caller to retry without a second round trip.

type AllowedQuery

type AllowedQuery map[string]struct{}

AllowedQuery is the set of query parameters one route defines. Nothing else is accepted -- there is no allowlist for cache-busting parameters such as `_`, because a route that quietly ignores `?directon=incoming` answers a full unfiltered list that looks exactly like a correct answer (spec section 7.1).

func NewAllowedQuery

func NewAllowedQuery(names ...string) AllowedQuery

NewAllowedQuery builds the allowed set for a route.

type Code

type Code string

Code is an Agent GM error code from spec section 7.2.

const (
	CodeInvalidRequest           Code = "invalid_request"
	CodeInvalidToken             Code = "invalid_token"
	CodeInsufficientScope        Code = "insufficient_scope"
	CodeNotFound                 Code = "not_found"
	CodeIdempotencyConflict      Code = "idempotency_conflict"
	CodeNotPaired                Code = "not_paired"
	CodePairingNoCookies         Code = "pairing_no_cookies"
	CodePairingNoDevices         Code = "pairing_no_devices"
	CodePairingWrongEmoji        Code = "pairing_wrong_emoji"
	CodePairingCancelled         Code = "pairing_cancelled"
	CodePairingTimeout           Code = "pairing_timeout"
	CodePairingInitTimeout       Code = "pairing_init_timeout"
	CodePairingWrongAccount      Code = "pairing_wrong_account"
	CodePairingNoAccount         Code = "pairing_no_account"
	CodeUnsupportedCapability    Code = "unsupported_capability"
	CodePayloadTooLarge          Code = "payload_too_large"
	CodeMediaUnsupportedType     Code = "media_unsupported_type"
	CodeRateLimited              Code = "rate_limited"
	CodeInternalError            Code = "internal_error"
	CodeNotDefaultSMSApp         Code = "not_default_sms_app"
	CodeGoogleUndocumentedStatus Code = "google_undocumented_status"
	CodeGoogleError              Code = "google_error"
	CodeGoogleHTTPError          Code = "google_http_error"
	CodeGooglePermissionDenied   Code = "google_permission_denied"
	CodeDisconnected             Code = "disconnected"
	CodePhoneNotResponding       Code = "phone_not_responding"
)

The closed vocabulary of spec section 7.2's table. Every code the REST surface can produce is here; a code outside this list does not exist.

func Codes

func Codes() []Code

Codes returns every code of spec section 7.2, sorted, so a caller that has to enumerate the vocabulary -- a test, the CLI's exit-code table, an MCP tool description -- reads it from here rather than writing its own list.

type Error

type Error struct {
	// Code is the spec section 7.2 code.
	Code Code
	// Message is the human sentence. It never contains a secret, a cookie or
	// a raw Google identifier (spec section 12.2).
	Message string
	// Details is details{} in the envelope.
	Details map[string]any
	// RetryAfter is set only for rate_limited and drives the Retry-After
	// header. Zero means the header is not sent.
	RetryAfter time.Duration
	// Err is an underlying error, for errors.Is/As and for logs. It is never
	// rendered to a caller.
	Err error
	// HTTPStatusOverride is the status to send instead of the one section
	// 7.2 assigns to Code. It is set in exactly one place, by
	// MethodNotAllowed -- 405 has no row of its own in the table and the
	// code there is still invalid_request -- so the table stays the single
	// authority for every other answer.
	HTTPStatusOverride int
	// contains filtered or unexported fields
}

Error is one REST error. Its HTTP status and its retryable flag are read from spec section 7.2's table rather than stored on the value, so an instance cannot carry a status the table disagrees with.

func AmbiguousAccount

func AmbiguousAccount(candidates []AccountCandidate) *Error

AmbiguousAccount is a write that omitted account_id while more than one account exists. It lists the candidates so the answer can be acted on rather than merely understood (spec section 7.3).

func BadIdempotencyKey

func BadIdempotencyKey(why string) *Error

BadIdempotencyKey is a key that is present but unusable. `why` completes the sentence "the idempotency key is refused because ...".

There is deliberately no "missing key" error: an absent header means a new operation with a server-minted ID, which is the ordinary case.

func CheckIDPrefix

func CheckIDPrefix(value, parameter, expectedPrefix string) *Error

CheckIDPrefix is the one implementation of the section 4.1 prefix rule. Every route calls this rather than writing its own strings.HasPrefix, so no route can answer not_found for a wrong-prefix ID. It returns nil when value is well formed.

func DecodeBody

func DecodeBody(r io.Reader, dst any) *Error

DecodeBody reads at most MaxBodyBytes of JSON from r into dst, rejecting unknown fields (spec section 7.1). An empty body is accepted and leaves dst untouched, because the two DELETE routes of spec section 7.7 carry an optional body.

The size rule of spec section 7.2 is exact: over the limit is 413 payload_too_large, and any other read failure is 400, because calling a truncated upload "too large" would be a guess.

func DecodeBodyBytes

func DecodeBodyBytes(body []byte, dst any) *Error

DecodeBodyBytes is DecodeBody for a body already in memory, for the callers that must hash or log the bytes before decoding them.

func DecodeQuery

func DecodeQuery(values url.Values, allowed AllowedQuery) *Error

DecodeQuery rejects any query parameter the route does not define, returning invalid_request naming it in details.parameter. It returns nil when every parameter is known.

When several are unknown it names the first in sorted order, so the same request always produces the same answer regardless of map iteration.

func Disconnected

func Disconnected() *Error

Disconnected is ErrConnectionClosed: the long poll is down.

func From

func From(err error) *Error

From turns any error into an *Error.

It is the single funnel every handler's return value passes through, so that an error nobody classified becomes `internal_error` -- a bug, reported as one -- rather than leaking a Go error string to a caller. Section 7.2's vocabulary is closed, and this is what keeps it closed at the edge.

An *Error passes through unchanged. Anything else is internal_error with a fixed message: the underlying text may name a file path, a SQL statement or a Google identifier, none of which belong on a public surface.

func GoogleError

func GoogleError(googleType int64, googleMessage string, retryable bool) *Error

GoogleError is a tachyon error. details.google_type and details.google_message are diagnostic values with no Agent GM meaning; they exist because an owner reading this needs something to search for.

retryable is a parameter because spec section 7.2 writes this row's retryable column as "maybe": only the Google status behind it knows.

func GoogleHTTPError

func GoogleHTTPError(status int64) *Error

GoogleHTTPError is a transport-level failure. details.status is the HTTP status Google answered with.

func GooglePermissionDenied

func GooglePermissionDenied() *Error

GooglePermissionDenied is ErrCallerNoPermission.

func GoogleUndocumentedStatus

func GoogleUndocumentedStatus(status int64) *Error

GoogleUndocumentedStatus is a Google enum value the pinned proto has no name for. details.status is the BARE integer and no meaning is claimed: an invented name would be a guess an agent could act on (spec section 3.7).

func IDFromAnotherAccount

func IDFromAnotherAccount(parameter, id, accountID string) *Error

IDFromAnotherAccount is a conv_ or msg_ ID that exists but belongs to a different account than the account_id the caller named. It is invalid_request naming BOTH -- never not_found, which would suggest the thread is gone (spec section 7.3).

func IdempotencyConflict

func IdempotencyConflict(key string) *Error

IdempotencyConflict is the same idempotency key presented with a different body (spec section 6.3). It is the caller's mistake, which is why spec section 11.2 gives it exit 2 rather than a server-failure code.

func IdempotencyKeyUsedWithAnotherAccount

func IdempotencyKeyUsedWithAnotherAccount(key, firstAccountID string) *Error

IdempotencyKeyUsedWithAnotherAccount is the mirror hazard of spec section 6.3, and it is refused rather than obeyed.

Because the account is part of the idempotency tuple, reusing a key against a DIFFERENT account_id is not a replay -- it is a new operation, and it sends a second real message to a real person. That is the safe direction for the store, which never silently adopts a row across accounts, and the dangerous direction for a caller that "retries" a failed send by switching accounts. So both agent-facing surfaces refuse it, naming the account the key was first used with.

It survives D38 unchanged: the hazard belongs to a key that IS present, and a caller that bothered to send one is exactly the caller who would retry with it.

func InsufficientScope

func InsufficientScope(required string) *Error

InsufficientScope is a valid token with the wrong scope. The scope the route requires is named so the caller can ask for it.

func Internal

func Internal(err error) *Error

Internal is a bug in Agent GM. Its message never carries the underlying error; that goes to the log with the request ID.

func InvalidToken

func InvalidToken(detail string) *Error

InvalidToken is an absent, expired, unknown or wrong-audience bearer.

func MalformedBody

func MalformedBody(reason string) *Error

MalformedBody is a body that is not the JSON this route expects, for a reason other than an unknown field.

func MediaUnsupportedType

func MediaUnsupportedType(mime string) *Error

MediaUnsupportedType is a mime type absent from libgm.MimeToMediaType.

func MethodNotAllowed

func MethodNotAllowed(method, allow string) *Error

MethodNotAllowed is a path that exists for another method.

It is deliberately NOT `not_found`. A caller who typed GET where the route takes POST has a fixable mistake, and answering "no such thing" sends them looking for a missing object instead. The allowed methods travel in the Allow header and in details, so the answer says what to do.

It renders as `invalid_request`, because 405 has no row of its own in section 7.2's table and the caller's request was indeed malformed for this address; the HTTP status is what carries the distinction.

func MissingParameter

func MissingParameter(name string) *Error

MissingParameter is a required parameter that was not supplied.

func New

func New(code Code, message string) *Error

New builds an error with no details.

func Newf

func Newf(code Code, format string, args ...any) *Error

Newf is New with formatting.

func NotDefaultSMSApp

func NotDefaultSMSApp() *Error

NotDefaultSMSApp is SendMessageResponse_FAILURE_4 and is never retried.

func NotFound

func NotFound(what string) *Error

NotFound is a missing object. Its message is byte-identical whether the object never existed or the caller may not see it, so the answer leaks nothing about another account's data (spec section 7.2).

func NotPaired

func NotPaired() *Error

NotPaired means there is no Google Messages session at ALL. It is never used for a paired-but-unusable account, which is unsupported_capability with not_signed_in (spec sections 7.2, 7.8).

func PayloadTooLarge

func PayloadTooLarge(what string, limitBytes int64) *Error

PayloadTooLarge is a body over MaxBodyBytes or media over media.upload_max_bytes. The limit is in the message rather than in details because details on a public surface is reserved for values a caller acts on, and a raw integer there is spoken for by spec section 7.2.

func PhoneNotResponding

func PhoneNotResponding() *Error

PhoneNotResponding is ErrPhoneNotResponding. The operation is PENDING, not failed, and the message says so, because a caller that resends here sends the message twice (spec section 7.2, D5).

func RateLimited

func RateLimited(retryAfter time.Duration) *Error

RateLimited carries the Retry-After the caller must honour (spec sections 7.2, 12.3).

func UnknownBodyField

func UnknownBodyField(name string) *Error

UnknownBodyField refuses an unknown JSON body field, naming it in details.field.

func UnknownQueryParameter

func UnknownQueryParameter(name string) *Error

UnknownQueryParameter refuses an unknown query parameter, naming it in details.parameter. Nothing is allowlisted, including a cache-busting `_`: a misspelled filter must not return a full unfiltered list, which looks exactly like a correct answer.

func UnsupportedCapability

func UnsupportedCapability(reason Reason, objectID, action, capability string, current any) *Error

UnsupportedCapability refuses an action that cannot apply here. It carries the object ID, the action, the capability and the capability's current value alongside details.reason, so the caller learns why rather than only that (spec sections 7.7, 7.8).

It is emitted BEFORE any operation row exists, so a refused action never leaves a record that looks like an attempt.

The zero Reason is a programming error: it means a caller assembled a Reason{} instead of using one of this package's values, which the closed vocabulary exists to prevent.

current is the capability's value as a bool or a short string. It is never a raw Google integer: details.google_type and details.status are the only two of those on a public surface (spec section 7.2).

func WrongIDPrefix

func WrongIDPrefix(parameter, expectedPrefix string) *Error

WrongIDPrefix is an ID with the wrong typed prefix for the parameter it was given to. It is invalid_request naming the parameter and the expected prefix, and it is NEVER not_found: an ID of the wrong kind is a caller mistake, whereas not_found would say the object is gone and send the caller looking for a deleted thread (spec section 4.1). A raw Google ID lands here too, since it carries no Agent GM prefix.

The offending value is deliberately not echoed into details: it may be a raw Google identifier, which is admin-only on a public surface.

func WrongTypeForField

func WrongTypeForField(field, want string) *Error

WrongTypeForField is a body field with the right name and the wrong JSON type.

func WrongTypeForParameter

func WrongTypeForParameter(parameter, want string) *Error

WrongTypeForParameter is WrongTypeForField for a value that arrived as a QUERY parameter.

Section 7.1 names an unknown query parameter in `details.parameter` and an unknown body field in `details.field`, and a caller branching on those two keys is doing the reasonable thing. A cursor is a query parameter on every route that takes one, so reporting a tampered or mismatched cursor under `field` sent a client looking in the body for something that was never there.

func (*Error) Envelope

func (e *Error) Envelope(requestID string) Failure

Envelope renders e as the error envelope. retryable and the details map come from the error itself, so a handler cannot answer a retryable flag that disagrees with spec section 7.2's table.

func (*Error) Error

func (e *Error) Error() string

func (*Error) ExitCode

func (e *Error) ExitCode() int

ExitCode is the CLI exit code spec section 11.2 assigns to this error.

func (*Error) HTTPStatus

func (e *Error) HTTPStatus() int

HTTPStatus is the status spec section 7.2 assigns to this error's code.

func (*Error) Is

func (e *Error) Is(target error) bool

Is compares two API errors by code, so errors.Is(err, apierr.NotFound("")) asks "is this a not_found?" without matching on a message.

func (*Error) RetryAfterHeader

func (e *Error) RetryAfterHeader() string

RetryAfterHeader is the Retry-After header value in seconds, or "" when there is none. It rounds up and never returns "0", which a client would read as "retry immediately" and hammer the bucket that just refused it.

func (*Error) Retryable

func (e *Error) Retryable() bool

Retryable is the retryable flag of the envelope. For every code but google_error the table decides and the value on the error is ignored, so a constructor cannot contradict spec section 7.2.

func (*Error) Unwrap

func (e *Error) Unwrap() error

type ErrorBody

type ErrorBody struct {
	Code      Code           `json:"code"`
	Message   string         `json:"message"`
	Retryable bool           `json:"retryable"`
	Details   map[string]any `json:"details"`
}

ErrorBody is the inner object of the error envelope.

type Failure

type Failure struct {
	Error     ErrorBody `json:"error"`
	RequestID string    `json:"request_id"`
}

Failure is the error envelope of spec section 7.1:

{ "error": { "code", "message", "retryable", "details" },
  "request_id": "req_..." }

type Reason

type Reason struct {
	// contains filtered or unexported fields
}

Reason is a details.reason value from spec section 7.8's CLOSED vocabulary. It is a struct with an unexported field rather than a string type, so no package outside this one can invent a reason: the vocabulary is closed by the compiler, not by a review.

func ReasonByName

func ReasonByName(name string) (Reason, bool)

ReasonByName parses a wire value back into a Reason. It is how the CLI and MCP read a reason off a response without being able to mint a new one.

func Reasons

func Reasons() []Reason

Reasons returns spec section 7.8's vocabulary in the spec's order.

func (Reason) MarshalJSON

func (r Reason) MarshalJSON() ([]byte, error)

MarshalJSON writes the bare reason string.

func (Reason) String

func (r Reason) String() string

String is the wire value of the reason.

type Retryability

type Retryability int

Retryability is the "Retryable" column of spec section 7.2. Two of its three values are facts about the code; the third belongs to the single row the spec writes as "maybe".

const (
	// RetryNo: the envelope's retryable is false for this code, always.
	RetryNo Retryability = iota
	// RetryYes: the envelope's retryable is true for this code, always.
	RetryYes
	// RetryMaybe: google_error alone. The constructor decides, because only
	// the Google status behind it knows whether a retry can help.
	RetryMaybe
)

func RetryabilityOf

func RetryabilityOf(c Code) Retryability

RetryabilityOf is the "Retryable" column for c.

type Success

type Success struct {
	Data       any      `json:"data"`
	NextCursor *string  `json:"next_cursor"`
	Warnings   []string `json:"warnings"`
	RequestID  string   `json:"request_id"`
}

Success is the success envelope of spec section 7.1:

{ "data": {}, "next_cursor": null, "warnings": [], "request_id": "req_..." }

next_cursor is a pointer so an absent cursor is JSON null rather than an empty string, which a client could mistake for a valid cursor. warnings is always an array, never null, so a client can range over it unguarded.

func NewSuccess

func NewSuccess(requestID string, data any) Success

NewSuccess builds the success envelope with the field defaults spec section 7.1 shows: a null cursor and an empty warnings array.

func (Success) WithCursor

func (s Success) WithCursor(cursor string) Success

WithCursor sets next_cursor. An empty string leaves it null, because "" is not a cursor.

func (Success) WithWarnings

func (s Success) WithWarnings(warnings ...string) Success

WithWarnings appends warnings, keeping the array non-nil (spec section 7.1: normalisation is never silent, so warnings is the channel that says what was changed).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL