api

package
v1.3.3 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2026 License: AGPL-3.0 Imports: 32 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 api serves the REST surface of spec section 7: handlers, DTOs, the error envelope, strict parameter rejection and pagination. It contains no business logic -- that is internal/core -- and it is the only package that knows a route from a tool.

Index

Constants

View Source
const (
	DefaultLimit = 50
	MaxLimit     = 100
	// DefaultContext and MaxContext bound GET /v1/messages/{id}/context.
	DefaultContext = 5
	MaxContext     = 100
)

DefaultLimit and MaxLimit are spec section 7.4's bounds, on every listing.

View Source
const MaxIdempotencyKeyBytes = 200

MaxIdempotencyKeyBytes is spec section 6.3's bound.

View Source
const MaxUploadsPerMessage = 1

MaxUploadsPerMessage is spec section 10.2's "one attachment per message".

View Source
const SignOutEffect = "shreds this account's Google session file and stops its connection; " +
	"every conversation, message and attachment Agent GM has indexed is kept and stays readable"

SignOutEffect is what signing out does, in one sentence, so no surface can claim more than another (spec section 4.7).

View Source
const UnknownCommit = "unknown"

UnknownCommit is what a build with neither a link-time stamp nor a VCS stamp reports. It is declared here, next to the one place that has to recognise it, so the string cannot drift from the binary that produces it.

Variables

View Source
var ErrUnknownRoute = errors.New("no such route in the inventory")

ErrUnknownRoute is returned by Handle for a name absent from the inventory.

View Source
var Routes = []Route{

	{
		Method: http.MethodGet, Path: "/healthz", Name: "healthz", Scope: ScopeNone,
		Notes: "liveness. Never touches SQLite, so it answers while a migration runs.",
	},
	{
		Method: http.MethodGet, Path: "/v1/health", Name: "health", Scope: ScopeRead,
		Notes: "status describes the server, not the accounts: an account in signed_out or error does not make Agent GM unhealthy.",
	},

	{
		Method: http.MethodPost, Path: "/v1/auth/admin-session", Name: "auth_admin_session",
		Scope: ScopeNone, Body: []string{"secret", "scopes"},
		Notes: "presents AGENT_GM_ADMIN_SECRET in the body. Mints admin plus the three messaging scopes; `scopes` may only narrow (9.7).",
	},
	{
		Method: http.MethodPost, Path: "/v1/auth/refresh", Name: "auth_refresh",
		Scope: ScopeNone, Body: []string{"refresh_token", "scopes"},
		Notes: "rotates. `scopes` may only narrow relative to what the session was MINTED with; widening is invalid_scope and does not spend the token (9.6).",
	},
	{
		Method: http.MethodGet, Path: "/v1/auth/whoami", Name: "auth_whoami", Scope: ScopeRead,
	},
	{
		Method: http.MethodPost, Path: "/v1/auth/logout", Name: "auth_logout", Scope: ScopeRead,
		Notes: "ends a TOKEN's session. Nothing to do with signing a Google account out (4.7), which is why it is not called sign-out.",
	},

	{
		Method: http.MethodGet, Path: "/v1/accounts", Name: "accounts_list", Scope: ScopeRead,
		Notes: "every account, whatever its state. google_account is served because the owner needs to tell their accounts apart; it is never an ID and never in a URL.",
	},
	{
		Method: http.MethodGet, Path: "/v1/accounts/{account_id}", Name: "accounts_get", Scope: ScopeRead,
		Notes: "one account plus its google, backfill, sweep and counters blocks. The list route omits those four deliberately (7.5).",
	},
	{
		Method: http.MethodPatch, Path: "/v1/accounts/{account_id}", Name: "accounts_label",
		Scope: ScopeAdmin, Body: []string{"label"},
		Notes: "a human name for a listing. Nothing else is mutable.",
	},
	{
		Method: http.MethodGet, Path: "/v1/accounts/{account_id}/events", Name: "accounts_events",
		Scope: ScopeRead,
		Notes: "SSE. The only streaming route; it carries no message data, so it needs no replay ring and no cursor.",
	},
	{
		Method: http.MethodGet, Path: "/v1/accounts/events", Name: "accounts_events_all", Scope: ScopeRead,
		Notes: "every account's state changes, each tagged.",
	},
	{
		Method: http.MethodPost, Path: "/v1/accounts/{account_id}/reconnect", Name: "accounts_reconnect",
		Scope: ScopeAdmin,
	},
	{
		Method: http.MethodPost, Path: "/v1/accounts/{account_id}/sign-out", Name: "accounts_sign_out",
		Scope: ScopeAdmin, Body: []string{"confirm"},
		Notes: "shreds the session file, keeps every row (4.7). Requires confirm:true.",
	},
	{
		Method: http.MethodDelete, Path: "/v1/accounts/{account_id}", Name: "accounts_remove",
		Scope: ScopeAdmin, Body: []string{"confirm"},
		Notes: "THE ONLY ROUTE THAT DELETES AN ACCOUNT'S DATA (D30). Requires confirm:true; returns the deleted row counts and the effect sentence.",
	},
	{
		Method: http.MethodPost, Path: "/v1/accounts/{account_id}/refresh-cookies",
		Name: "accounts_refresh_cookies", Scope: ScopeAdmin, Body: []string{"cookies"},
		Notes: "a different Google address is pairing_wrong_account and changes nothing (3.2).",
	},

	{
		Method: http.MethodPost, Path: "/v1/pairing/start", Name: "pairing_start", Scope: ScopeAdmin,
		Body:  []string{"cookies", "device_index", "account_id"},
		Notes: "adds an account, or resumes an existing one. There is one pairing flow, so there is no `method` field; a body carrying one is invalid_request naming it (D19).",
	},
	{
		Method: http.MethodGet, Path: "/v1/pairing/{pairing_id}", Name: "pairing_get", Scope: ScopeAdmin,
	},
	{
		Method: http.MethodDelete, Path: "/v1/pairing/{pairing_id}", Name: "pairing_abandon", Scope: ScopeAdmin,
		Notes: "abandon an in-flight pairing. Leaves nothing behind (16 Slice 2 test 38).",
	},

	{
		Method: http.MethodGet, Path: "/v1/conversations", Name: "conversations_list", Scope: ScopeRead,
		Query: withPaging("account_id", "query", "participant", "folder", "type",
			"unread_only", "group_only", "pinned_only", "after", "before", "include_deleted"),
		Paginated: true,
	},
	{
		Method: http.MethodGet, Path: "/v1/conversations/{conversation_id}", Name: "conversations_get",
		Scope: ScopeRead,
		Notes: "the only route that populates peer_typing_until, which is in-memory live state and is always null in a list (7.6).",
	},
	{
		Method: http.MethodGet, Path: "/v1/conversations/{conversation_id}/messages",
		Name: "conversation_messages_list", Scope: ScopeRead,
		Query: withPaging(messageFilters...), Paginated: true,
	},
	{
		Method: http.MethodGet, Path: "/v1/messages", Name: "messages_list", Scope: ScopeRead,
		Query:     withPaging(append([]string{"account_id", "conversation_id"}, messageFilters...)...),
		Paginated: true,
	},
	{
		Method: http.MethodGet, Path: "/v1/messages/{message_id}", Name: "messages_get", Scope: ScopeRead,
	},
	{
		Method: http.MethodGet, Path: "/v1/messages/{message_id}/context", Name: "messages_context",
		Scope: ScopeRead, Query: []string{"before", "after"},
		Notes: "before and after each default to 5 and cap at 100 (7.4).",
	},
	{
		Method: http.MethodGet, Path: "/v1/messages/{message_id}/attachments",
		Name: "message_attachments_list", Scope: ScopeRead,
		Notes: "metadata only. Folded into get_message on MCP (8.2), so it has no tool.",
	},
	{
		Method: http.MethodGet, Path: "/v1/search/messages", Name: "search_messages", Scope: ScopeRead,
		Query: withPaging("q", "account_id", "mode", "conversation_id", "sender",
			"after", "before", "has_attachment"),
		Paginated: true,
		Notes:     "q is required. mode is words|exact -- a search vocabulary, not a switch between destructive behaviours (13.5).",
	},
	{
		Method: http.MethodGet, Path: "/v1/contacts", Name: "contacts_list", Scope: ScopeRead,
		Query: withPaging("account_id", "query", "top"), Paginated: true,
	},
	{
		Method: http.MethodGet, Path: "/v1/attachments/{attachment_id}", Name: "attachments_get",
		Scope: ScopeRead,
		Notes: "metadata plus a download ticket (10.1).",
	},
	{
		Method: http.MethodGet, Path: "/v1/attachments/{attachment_id}/content",
		Name: "attachments_content", Scope: ScopeRead, AltCredential: true,
		Notes: "bytes. An access token OR a download ticket; the ticket is accepted only in the Authorization header, never as ?t= (10.3).",
	},
	{
		Method: http.MethodGet, Path: "/v1/operations", Name: "operations_list", Scope: ScopeWrite,
		Query:     withPaging("account_id", "kind", "status", "terminal", "after", "before"),
		Paginated: true,
		Notes:     "the caller's own operations. messages:write because that is the scope that creates them.",
	},
	{
		Method: http.MethodGet, Path: "/v1/operations/{operation_id}", Name: "operations_get",
		Scope: ScopeWrite,
		Notes: "another authorization's ID answers not_found with a body byte-identical to a genuinely absent one (6.5).",
	},
	{
		Method: http.MethodGet, Path: "/v1/uploads/{upload_id}", Name: "uploads_get", Scope: ScopeWrite,
		Notes: "the caller's own reservation. No CLI command and no MCP tool, for the same reason (11.3, 8.2).",
	},

	{
		Method: http.MethodPost, Path: "/v1/conversations", Name: "conversations_start", Scope: ScopeWrite,
		Body:           []string{"account_id", "recipients", "name"},
		IdempotencyKey: true,
		Notes:          "the ONE write whose target is a phone number rather than an ID, so nothing else can imply the account: account_id is required when more than one account exists (7.3).",
	},
	{
		Method: http.MethodPost, Path: "/v1/conversations/{conversation_id}/messages",
		Name: "messages_send", Scope: ScopeWrite,
		Body:           []string{"text", "upload_ids", "reply_to_message_id", "force_rcs"},
		IdempotencyKey: true,
		Notes:          "upload_ids is an array but currently accepts exactly one element; two is invalid_request naming the limit (10.2).",
	},
	{
		Method: http.MethodPost, Path: "/v1/conversations/{conversation_id}/typing",
		Name: "conversations_typing", Scope: ScopeWrite,
		Notes: "204. Fire-and-forget: no operation and no idempotency key, because it has no lasting effect (D15).",
	},
	{
		Method: http.MethodPost, Path: "/v1/conversations/{conversation_id}/read",
		Name: "conversations_mark_read", Scope: ScopeWrite,
		Body:           []string{"message_id"},
		IdempotencyKey: true,
	},
	{
		Method: http.MethodPatch, Path: "/v1/conversations/{conversation_id}",
		Name: "conversations_update", Scope: ScopeWrite,
		Body:           []string{"folder", "pinned", "unread"},
		IdempotencyKey: true,
		Notes:          "returns operation:null and changed:false when already in the requested state, and calls the backend zero times (16 Slice 2 test 16).",
	},
	{
		Method: http.MethodPost, Path: "/v1/messages/{message_id}/reactions", Name: "reactions_add",
		Scope: ScopeWrite, Body: []string{"emoji"}, IdempotencyKey: true,
		Notes: "ADD, or SWITCH when the owner already has a different reaction (D23). emoji is canonicalised first (3.7).",
	},
	{
		Method: http.MethodDelete, Path: "/v1/messages/{message_id}/reactions/{emoji}",
		Name: "reactions_remove", Scope: ScopeWrite,
		IdempotencyKey: true,
		Notes:          "the path segment is canonicalised before matching, so ❤ and ❤️ address the same reaction.",
	},
	{
		Method: http.MethodDelete, Path: "/v1/reactions/{reaction_id}", Name: "reactions_remove_by_id",
		Scope: ScopeWrite, IdempotencyKey: true,
		Notes: "somebody else's reaction is unsupported_capability with reason not_my_reaction.",
	},
	{
		Method: http.MethodPost, Path: "/v1/uploads", Name: "uploads_create", Scope: ScopeWrite,
		Body:           []string{"filename", "mime_type", "size_bytes", "sha256"},
		IdempotencyKey: true,
	},
	{
		Method: http.MethodDelete, Path: "/v1/uploads/{upload_id}", Name: "uploads_delete", Scope: ScopeWrite,
		Notes: "204. Drops the reservation and its staged bytes. No CLI command and no MCP tool (11.3, 8.2).",
	},
	{
		Method: http.MethodPut, Path: "/v1/uploads/{upload_id}/content", Name: "uploads_content",
		Scope: ScopeNone, RawBody: true,
		Notes: "raw bytes, authenticated by the UPLOAD TOKEN rather than the access token. Its redemption re-checks the issuing authorization's messages:write scope and revocation state (10.3).",
	},

	{
		Method: http.MethodDelete, Path: "/v1/messages/{message_id}", Name: "messages_delete",
		Scope: ScopeDelete, IdempotencyKey: true,
		Notes: "carries the effect sentence. There is no other delete and no delete option: a request carrying an action or scope switch is invalid_request naming it (D14).",
	},
	{
		Method: http.MethodDelete, Path: "/v1/conversations/{conversation_id}",
		Name: "conversations_delete", Scope: ScopeDelete,
		IdempotencyKey: true,
		Notes:          "carries the effect sentence.",
	},

	{
		Method: http.MethodGet, Path: "/v1/admin/settings", Name: "admin_settings_list", Scope: ScopeAdmin,
		Notes: "effective value, source (default|environment|database), mutability, restart requirement.",
	},
	{
		Method: http.MethodGet, Path: "/v1/admin/settings/{key}", Name: "admin_settings_get", Scope: ScopeAdmin,
	},
	{
		Method: http.MethodPatch, Path: "/v1/admin/settings", Name: "admin_settings_set", Scope: ScopeAdmin,
		OpenBody: true,
		Notes:    "validates the WHOLE body: any invalid key rejects the request and changes nothing. Its body fields are the settings keys themselves, so they are validated against the settings registry -- which checks bounds, type, mutability and the retired-key table, not merely the name -- rather than against a second copy of the key list here.",
	},
	{
		Method: http.MethodPost, Path: "/v1/admin/backfill", Name: "admin_backfill", Scope: ScopeAdmin,
		Body:  []string{"account_id", "conversation_id", "confirm"},
		Notes: "with no body it is a full re-backfill of every account -- the most expensive operation Agent GM offers -- so it requires confirm:true (5.4).",
	},
	{
		Method: http.MethodPost, Path: "/v1/admin/backup", Name: "admin_backup", Scope: ScopeAdmin,
		Notes: "the caller does not choose the path (15.2).",
	},
	{
		Method: http.MethodGet, Path: "/v1/admin/audit", Name: "admin_audit", Scope: ScopeAdmin,
		Query:     withPaging("kind", "kind_prefix", "account_id", "authorization_id", "after", "before"),
		Paginated: true,
	},

	{
		Method: http.MethodPost, Path: "/v1/admin/enrollment-codes", Name: "admin_enrollment_codes_create",
		Scope: ScopeAdmin,
		Body:  []string{"label", "expires_in", "scopes", "allow_scopes"},
		Notes: "answers 200, not 201. `data.code` is the ONLY time the value is returned and only its SHA-256 is stored (9.5). `scopes` replaces the default ceiling, `allow_scopes` extends it, and they are mutually exclusive. admin can never be enrolled.",
	},
	{
		Method: http.MethodGet, Path: "/v1/admin/enrollment-codes", Name: "admin_enrollment_codes_list",
		Scope: ScopeAdmin,
		Notes: "no code value appears here, or anywhere else after creation.",
	},
	{
		Method: http.MethodGet, Path: "/v1/admin/enrollment-codes/{enrollment_code_id}",
		Name: "admin_enrollment_codes_get", Scope: ScopeAdmin,
	},
	{
		Method: http.MethodDelete, Path: "/v1/admin/enrollment-codes/{enrollment_code_id}",
		Name: "admin_enrollment_codes_revoke", Scope: ScopeAdmin,
		Query: []string{"reason"},
		Notes: "repeating it answers 200 with `revoked: false` (9.5): a second revocation is not a failure.",
	},
	{
		Method: http.MethodGet, Path: "/v1/admin/authorization-requests",
		Name: "admin_authorization_requests_list", Scope: ScopeAdmin,
		Query: []string{"status"},
	},
	{
		Method: http.MethodGet, Path: "/v1/admin/authorization-requests/{authorization_request_id}",
		Name: "admin_authorization_requests_get", Scope: ScopeAdmin,
	},
	{
		Method: http.MethodPost, Path: "/v1/admin/authorization-requests/{authorization_request_id}/approve",
		Name: "admin_authorization_requests_approve", Scope: ScopeAdmin,
		Body:  []string{"scopes"},
		Notes: "`scopes` may only NARROW the browser-selected set; widening or an empty list is invalid_request, a no-longer-pending request is idempotency_conflict, an expired one is invalid_request (9.5).",
	},
	{
		Method: http.MethodPost, Path: "/v1/admin/authorization-requests/{authorization_request_id}/deny",
		Name: "admin_authorization_requests_deny", Scope: ScopeAdmin,
		Body:  []string{"reason"},
		Notes: "a denial is a decision the client is entitled to hear: the waiting page's completion redirects with error=access_denied (9.5).",
	},
	{
		Method: http.MethodGet, Path: "/v1/admin/authorizations", Name: "admin_authorizations_list",
		Scope: ScopeAdmin,
		Query: []string{"include_revoked"},
	},
	{
		Method: http.MethodGet, Path: "/v1/admin/authorizations/{authorization_id}",
		Name: "admin_authorizations_get", Scope: ScopeAdmin,
	},
	{
		Method: http.MethodDelete, Path: "/v1/admin/authorizations/{authorization_id}",
		Name: "admin_authorizations_revoke", Scope: ScopeAdmin,
		Query: []string{"reason"},
		Notes: "revoking any authorization revokes every token of it. This is the route section 16 Slice 3 test 29 uses to cut a connector off.",
	},
	{
		Method: http.MethodGet, Path: "/v1/admin/clients", Name: "admin_clients_list", Scope: ScopeAdmin,
	},
	{
		Method: http.MethodGet, Path: "/v1/admin/clients/{client_id}", Name: "admin_clients_get",
		Scope: ScopeAdmin,
	},
	{
		Method: http.MethodDelete, Path: "/v1/admin/clients/{client_id}", Name: "admin_clients_revoke",
		Scope: ScopeAdmin,
		Query: []string{"reason"},
		Notes: "removes a dynamic registration and revokes every authorization it holds.",
	},
	{
		Method: http.MethodGet, Path: "/v1/admin/diagnostics", Name: "admin_diagnostics", Scope: ScopeAdmin,
		Query: []string{"account_id"},
		Notes: "the ONLY place raw Google values appear: delivery_state_raw, operations.google_status_raw, CurrentSessionID, the chosen gaia device, compiled and live ConfigVersion (4.1, 7.7).",
	},
}

Routes is the whole `/v1` surface of spec section 7, plus the two unversioned routes. Order is the spec's: health and auth, accounts and pairing, reads, writes, admin.

Functions

func AllowHeader

func AllowHeader(methods []string) string

AllowHeader renders the Allow header for a 405.

func IdempotencyKeyFrom

func IdempotencyKeyFrom(header string) (string, *apierr.Error)

IdempotencyKeyFrom returns the key for a mutation from the one transport spec section 6.3 gives it: the `Idempotency-Key` header. It is OPTIONAL (D38), so an absent header returns an empty key and no error, and the operation gets a server-minted ID.

A key over 200 bytes or carrying a control character is `invalid_request` naming `Idempotency-Key` in `details.field`, and writes nothing. A present but unusable key is a caller mistake worth reporting; an absent one is not a mistake at all.

func RegisterAll

func RegisterAll(s *Server, d *HandlerDeps) error

RegisterAll hangs a handler off every route in the inventory.

A route is never added by writing a handler: it is added to `Routes` in routes.go, and the handler is hung off it here, by name. Two things follow from that, and both are the point:

  • `Server.Handle` refuses a name the inventory does not have, so a handler for a route nobody declared is a startup failure rather than an endpoint nobody documented;
  • this function is checked against the inventory in both directions by TestEveryRouteHasAHandler, so **a route declared and left unserved is a test failure, not a 500 in production**. That is the direction that actually goes wrong: adding a route to a table is easy, and the 500 it produces surfaces on the day an agent first calls it.

The map below is written out one line per route rather than derived from anything, so the compiler names an unregistered route's handler and the test names an unhandled route's name.

func SearchCoverageType

func SearchCoverageType() reflect.Type

SearchCoverageType is the type of search's `coverage` sibling, which is the one key any listing puts beside `items`.

Types

type DataShape

type DataShape struct {
	// Type is the struct `data` renders from, or, when Items is true, the
	// struct one row of `data.items` renders from.
	Type reflect.Type
	// Items reports that this route is a listing, whose rows live in
	// `data.items` and never in `data` as a bare array (spec section 7.1).
	Items bool
	// Coverage reports that `data` carries search's `coverage` sibling.
	Coverage bool
}

DataShape describes the Go type a route's envelope `data` renders from.

It exists so that section 8.2's "every tool declares an `outputSchema` describing the envelope it really returns, with `data` typed by that tool's own DTO" can be true by construction: the MCP layer reflects over the same struct the handler serialises, so a field added to a DTO appears in the tool's output schema without anybody remembering to add it.

The DTOs are unexported, which is deliberate -- nothing outside this package constructs one -- so the shape is handed out as a reflect.Type rather than as a value.

func DataShapeFor

func DataShapeFor(routeName string) (DataShape, bool)

DataShapeFor returns the DTO shape a route's `data` renders from.

type Deps

type Deps struct {
	Authz *authz.Service
	// PublicURL is AGENT_GM_PUBLIC_URL. Every URL this server hands out is
	// built from it and NEVER from the request's Host or X-Forwarded-Host,
	// so an agent in a sandbox on another machine reaches the same origin
	// the tunnel exposes (spec sections 10.3, 12.3).
	PublicURL string
	// Log receives one line per refused request. It never writes to stdout.
	Log func(msg string, kv ...any)
	// LogError receives an internal_error, at error level, ALWAYS. It is
	// separate from Log because the two have different audiences and
	// different levels: a refusal is ordinary traffic an operator reads when
	// they go looking, and a 500 is a bug they must be told about without
	// having to.
	LogError func(msg string, kv ...any)
}

Deps are the collaborators a server needs. They are an explicit struct rather than a package-level singleton so a test can build a whole server over two fakes and its own clock.

type Handler

type Handler func(*Request) (*Response, error)

Handler serves one route.

type HandlerDeps

type HandlerDeps struct {
	Freshness  *core.Freshener
	Store      *store.Store
	Sessions   *store.SessionStore
	Supervisor *accounts.Supervisor
	Authz      *authz.Service
	Settings   *settings.Settings
	// OAuth is the authorization server of spec section 9. The admin routes
	// of section 9.5 delegate to it; it is nil in a narrow unit test, and
	// those routes then answer internal_error rather than pretending.
	OAuth   *oauth.Server
	Audit   *audit.Writer
	Signer  *media.Signer
	Cache   *media.Cache
	Clock   clock.Clock
	DataKey store.DataKey
	Log     core.Logger

	// DataDir is where backups, the media cache and staged upload bytes
	// live. The caller of POST /v1/admin/backup does not choose a path
	// (spec section 15.2), so the server has to know one.
	DataDir string
	// StagingDir holds the bytes of a filled upload reservation until the
	// send that consumes them. It defaults to <DataDir>/uploads.
	StagingDir string

	// PublicURL is AGENT_GM_PUBLIC_URL. **Every URL a handler hands out is
	// built from it and never from the request's Host or X-Forwarded-Host**
	// (spec sections 10.3, 12.3), so an agent in a sandbox on another
	// machine reaches the origin the tunnel exposes rather than the one it
	// happened to dial.
	PublicURL string

	// The build facts GET /v1/health reports.
	Version               string
	Commit                string
	SourceURLBase         string
	ConfigVersionCompiled string
	UpstreamCommit        string

	// Core is the ingest and operation configuration a per-request engine
	// is built with.
	Core core.Config

	// NewBackend mints a backend for a pairing that has no account yet. It
	// is nil in a deployment that cannot pair, and POST /v1/pairing/start
	// then answers internal_error rather than pretending.
	NewBackend func() (gm.Backend, error)

	// AfterErase is a fault seam for spec section 16 Slice 2 test 20: it
	// runs between the erasure transaction's commit and the unlink of the
	// cached files, which is the one window where a crash is supposed to
	// leave an orphan file and no orphan row. It is nil in production, and
	// it is placed exactly where the window is rather than anywhere
	// convenient.
	AfterErase func(accountID string, paths []string) error

	// PeerTyping reports the instant a conversation's peer stops being
	// considered to be typing, or nil. It is in-memory live state, never
	// persisted (spec section 7.6).
	PeerTyping func(conversationID string) *time.Time

	// Heartbeat is the SSE keep-alive interval. Zero means the 30 seconds
	// spec section 7.5 fixes; a test sets it shorter rather than waiting.
	Heartbeat time.Duration
	// contains filtered or unexported fields
}

HandlerDeps is everything the handlers collaborate with.

It is a separate struct from Deps, which the transport needs, because the two have different lifetimes and different audiences: Deps is what ServeHTTP reaches for on every request, and this is what a handler reaches for once the transport has finished. Keeping them apart also keeps the middleware chain from acquiring a dependency on the store by accident.

Every field is an explicit collaborator rather than a package-level singleton, so section 13.1's "one fake is one account" test can build a whole server over two fakes, its own clock and its own temporary directory.

func (*HandlerDeps) SourceURL

func (d *HandlerDeps) SourceURL() string

SourceURL points at the tree this build came from, so an owner reading /v1/health can go and look at the code that answered them.

It is EXPORTED because MCP's `serverInfo` has to report the same string (spec sections 1.4, 8.1, section 16 Slice 3 test 28), and the two surfaces serving different strings is not a cosmetic disagreement -- it is an AGPL section 13 obligation half kept. A reviewer's run against the real binary caught exactly that: `/v1/health` computed the tree URL and `serverInfo` served the bare repository link.

An unstamped build falls back to the repository ROOT rather than pointing at `/tree/unknown`, which is a 404 -- and a 404 is worse than a link to the repository, because the AGPL section 13 obligation is to offer the source and a dead link offers nothing. It is only ever the repository root when there is genuinely no commit to name: `unknown` is what `buildCommit` returns for a build with neither an ldflag nor a VCS stamp, and a reviewer driving such a build found the dead link.

With no repository configured at all there is no honest answer, so the field is empty on both surfaces rather than invented.

type Invocation

type Invocation struct {
	Ctx context.Context
	// RouteName is the inventory name -- `messages_send`, not `POST
	// /v1/conversations/{id}/messages`. Routing by name rather than by a
	// synthesised path is what stops the MCP layer from having to build a
	// URL and the router from having to parse one back.
	RouteName string
	// Path binds the route's path parameters by name.
	Path map[string]string
	// Query is the query string as a caller would have written it.
	Query url.Values
	// Body is the raw JSON body, or nil.
	Body []byte
	// Auth is the authenticated caller. It is never nil on a route whose
	// Scope is not ScopeNone: Invoke refuses rather than running a handler
	// with no authorization.
	Auth *authz.Authorization
	// Bearer is the presented access token. It is needed by the one route
	// that authenticates for itself -- `GET /v1/attachments/{id}/content`,
	// which takes an access token or a download ticket (section 10.3).
	Bearer string
	// Source is the resolved client source (section 12.3).
	Source string
	// RequestID is the `req_` ID this call is correlated by.
	RequestID string
	// IdempotencyKeyHeader is the optional Idempotency-Key a caller
	// presented, if any. It is the ONLY transport for a key (D38); MCP has
	// no headers, so on that surface it is always empty and every write is a
	// new operation with a server-minted ID -- which is exactly what D38
	// decided an agent should get.
	IdempotencyKeyHeader string
}

Invocation is one in-process request. Every field is the same fact the transport would have resolved from the wire.

type Invoked

type Invoked struct {
	Route    Route
	Response *Response
	Warnings []string
}

Invoked is what a handler answered, plus the two things the envelope would otherwise have carried.

type Request

type Request struct {
	Ctx context.Context
	// Route is the inventory entry this request matched.
	Route Route
	// Path holds the bound path parameters, keyed by the names in the
	// pattern: `conversation_id`, `emoji`, and so on.
	Path map[string]string
	// Query is the query string, already checked against Route.Query.
	Query map[string]string
	// Body is the raw JSON body, already checked against Route.Body. It is
	// nil when the request carried none, and always nil on a RawBody route.
	Body []byte
	// RawBody is the unread request body, and is non-nil only on a route
	// declared RawBody -- the upload PUT. The handler is responsible for
	// bounding it: how many bytes are allowed is the reservation's business
	// and the transport has no way to know it.
	RawBody io.ReadCloser
	// Bearer is the presented bearer value, whatever it was. It is set on
	// every route that carried an Authorization header, including one whose
	// value is a media ticket rather than an access token -- which is the
	// whole point on an AltCredential route, where Auth is nil and the
	// handler has to check the ticket itself (spec section 10.3).
	//
	// It is a credential: it is never logged, never audited and never put in
	// an error message.
	Bearer string
	// Auth is the authenticated caller, or nil on a route whose Scope is
	// ScopeNone.
	Auth *authz.Authorization
	// Source is the resolved client source (spec section 12.3). It is never
	// the empty string.
	Source string
	// IdempotencyKeyHeader is the Idempotency-Key header as presented, and
	// the only transport a key has (D38). A handler passes it to
	// IdempotencyKeyFrom rather than reading it raw, so the 200-byte and
	// control-character rules of section 6.3 have one home.
	IdempotencyKeyHeader string
	// RequestID is the `req_` ID in this request's envelope.
	RequestID string
	// Warnings accumulate through the handler and are rendered in the
	// envelope (spec section 7.1). Text normalisation is never silent, so a
	// cleaned value adds one here rather than being quietly accepted.
	Warnings []string
}

Request is what a handler receives. It is deliberately not `*http.Request`: by the time a handler runs, the transport concerns are already settled -- the route is resolved, the caller is authenticated, the scope is checked, the rate limit is spent, the query is known to hold nothing unknown, and the body is read and known to hold nothing unknown. A handler that reached past this struct to the raw request could undo any of that.

func (*Request) DecodeBody

func (r *Request) DecodeBody(dst any) *apierr.Error

DecodeBody unmarshals the body into dst. The unknown-field check has already run against the inventory, so this cannot be the first thing that notices a misspelled field.

func (*Request) Warn

func (r *Request) Warn(w ...string)

Warn records a warning for the envelope.

type Response

type Response struct {
	// Status is the HTTP status. Zero means 200.
	Status int
	// Data is the envelope's `data`. A listing puts its rows in
	// `data.items` (spec section 7.1).
	Data any
	// NextCursor is the envelope's `next_cursor`.
	NextCursor string
	// Header carries any extra response headers, such as Location.
	Header http.Header
	// Raw, when set, is written instead of an envelope: attachment bytes and
	// the SSE stream are not JSON envelopes. A handler setting it is
	// responsible for its own content type.
	Raw func(w http.ResponseWriter)
}

Response is a handler's answer.

type Route

type Route struct {
	// Method and Path are the wire form. Path segments in braces are
	// parameters: `/v1/conversations/{conversation_id}`.
	Method string
	Path   string
	// Name is the stable identifier the CLI and the tests use. It is the
	// same word on every surface (spec section 11.3): mark-read is mark_read
	// is POST .../read.
	Name string
	// Scope is what a caller must hold. ScopeNone means the route
	// authenticates by something other than a bearer token -- the admin
	// secret, a refresh token, or a media ticket -- and says so in Notes.
	Scope Scope
	// Query is every query parameter this route accepts. Anything else is
	// invalid_request naming it. Path parameters are NOT listed here.
	Query []string
	// Body is every JSON body field this route accepts. Anything else is
	// invalid_request naming it.
	Body []string
	// IdempotencyKey marks a mutation, which ACCEPTS an optional key by way
	// of the `Idempotency-Key` header and by no other transport (spec
	// section 6.3, D38). There is no `client_request_id` body field and no
	// `?idempotency_key=` query parameter on any route: one presented as
	// either is invalid_request like any other unknown parameter (spec
	// section 7.1) -- which is true here by construction, because neither
	// Body nor Query ever contains it.
	IdempotencyKey bool
	// Paginated marks a listing: `cursor` and `limit`, newest first, limit
	// defaulting to 50 and capping at 100 (spec section 7.4).
	Paginated bool
	// RawBody marks a route whose body is BYTES rather than JSON: the
	// upload PUT of section 10.2, and nothing else today.
	//
	// It exists because the two transport rules that are right for every
	// other route are wrong for this one. The 1 MiB bound of section 7.2
	// applies to a JSON body; an upload is bounded by
	// `media.upload_max_bytes` (100 MiB by default) and by the length the
	// reservation declared, which only the handler knows. And the
	// unknown-field check would read a JPEG as a malformed JSON object.
	// Marking the route is better than special-casing its path in the
	// middleware, because the exception is then a property of the route a
	// reader can see rather than a condition buried in a chain.
	RawBody bool
	// OpenBody marks a route whose body fields are not a fixed list.
	//
	// `PATCH /v1/admin/settings` is the only one: its fields ARE the
	// settings keys of section 15.1, which live in the settings registry,
	// and which that registry validates far more strictly than a name check
	// could -- bounds, types, mutability, downward-only, and the retired-key
	// table. Enumerating them here would be a second copy that could drift
	// from the registry, and the strictness section 7.1 asks for is
	// delivered by the registry rather than lost.
	OpenBody bool
	// AltCredential marks a route that accepts something other than an
	// access token as well as one: `GET /v1/attachments/{id}/content` takes
	// a `messages:read` token **or** a download ticket (section 10.3).
	//
	// The transport still tries the bearer, because most callers present
	// one; it just does not refuse when that fails, and hands the request to
	// the handler with no authorization so the ticket path can run. Scope
	// still names what an access token would need, which is what the
	// `WWW-Authenticate` challenge on a refusal has to say.
	AltCredential bool
	// Notes records anything about the route a reader would otherwise have
	// to reconstruct from the spec.
	Notes string
}

Route is one `/v1` route, declared rather than discovered.

The inventory below is the single source of truth for three separate obligations that would otherwise drift apart:

  • **Strict parameter rejection** (spec section 7.1, section 16 Slice 2 test 12). Every route rejects an unknown query parameter and an unknown body field with `invalid_request` naming it, and nothing is allowlisted -- including a cache-busting `_=`. A handler that read its parameters ad hoc would have an allowed set that only its own code knew, and the route-by-route test could only sample. Here the allowed set is data, so the test is exhaustive by construction.
  • **The CLI two-way mapping** (section 16 Slice 2 test 27). Every `/v1` route parameter must be reachable from a CLI flag and every CLI command must map to a route. That test walks this table against the CLI's own command table, so a route added without a flag fails rather than being noticed later.
  • **The MCP three-way split** (section 8.2, Slice 3). Every route carrying a `messages:*` scope is served as a tool, as a resource, or as a named exclusion. Slice 3's test walks this same table.

A route is therefore never added by writing a handler. It is added here, and the handler is hung off it.

func Match

func Match(method, path string) (route Route, params map[string]string, allowed []string, ok bool)

Match resolves a method and path to a route.

The three outcomes are distinguished, because they are three different answers to a caller:

  • a route, with its path parameters;
  • no route at this path at all -> `not_found`;
  • a route at this path but not for this method -> `405` with `Allow`, which tells a caller that mistyped `GET` for `POST` what to fix rather than sending them looking for a missing object.

func RouteByName

func RouteByName(name string) (Route, bool)

RouteByName looks a route up by its stable name.

func (Route) AllowsBody

func (r Route) AllowsBody(f string) bool

AllowsBody reports whether f is a body field this route accepts.

func (Route) AllowsQuery

func (r Route) AllowsQuery(p string) bool

AllowsQuery reports whether p is a query parameter this route accepts. Nothing is allowlisted globally: a cache-busting `_` is an unknown parameter like any other (spec section 7.1).

func (Route) CheckBodyFields

func (r Route) CheckBodyFields(raw []byte) *apierr.Error

CheckBodyFields enforces the same rule for a JSON body.

It is a pre-pass over the raw object rather than a `DisallowUnknownFields` decode into the handler's struct, for two reasons. The inventory is the contract, and a struct's tags are a second place the allowed set could live and drift. And a body field that exists on the route but that this particular handler ignores would pass a struct decode silently, which is the same class of mistake as a misspelled query parameter.

An empty body is fine on every route: `{}` and no body at all are the same request, and a route that requires a field says so itself.

func (Route) CheckQuery

func (r Route) CheckQuery(values url.Values) *apierr.Error

CheckQuery enforces spec section 7.1's strict parameter rejection for this route's query string.

**Nothing is allowlisted**, including a cache-busting `_=`. A misspelled filter is refused rather than silently ignored, because `?directon=incoming` returning a full unfiltered list looks exactly like a correct answer, and an agent has no way to tell the difference. A refused request has no effect.

The allowed set comes from the inventory rather than from the handler, so section 16 Slice 2 test 12 is exhaustive route by route by construction rather than by a sample somebody remembered to keep up to date.

func (Route) Parameters

func (r Route) Parameters() []string

Parameters is every parameter a caller can supply on this route: path, query and body, sorted and deduplicated. It is what the CLI two-way mapping test (section 16 Slice 2 test 27) walks.

func (Route) PathParams

func (r Route) PathParams() []string

PathParams returns the brace-delimited parameters of a route's path, in order. They are never in Query: a path parameter is part of the address, and presenting one as a query parameter is an unknown parameter like any other.

func (Route) String

func (r Route) String() string

String renders a route the way an error message should name it.

type Scope

type Scope string

Scope is an OAuth scope name (spec section 9.7). It is declared here as a plain string so the inventory can name scopes without the API package depending on the credential layer.

const (
	ScopeNone   Scope = ""
	ScopeRead   Scope = "messages:read"
	ScopeWrite  Scope = "messages:write"
	ScopeDelete Scope = "messages:delete"
	ScopeAdmin  Scope = "admin"
)

The four scopes. `admin` is issued only by the admin bootstrap and is never enrollable.

type Server

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

Server routes and serves the `/v1` surface.

func NewServer

func NewServer(deps Deps) *Server

NewServer builds a server with no handlers registered. Handlers are added with Handle, which refuses a name the inventory does not have -- so a handler for a route nobody declared is a startup failure rather than an endpoint nobody documented.

func (*Server) Handle

func (s *Server) Handle(name string, h Handler) error

Handle registers the handler for one route name.

func (*Server) Invoke

func (s *Server) Invoke(in Invocation) (*Invoked, *apierr.Error)

Invoke dispatches one in-process request and returns the handler's response or the error envelope's error.

The returned *apierr.Error is the same value a REST caller would have been served, which is what lets the MCP layer put it in `structuredContent.error` unchanged (section 8.2's isError semantics).

func (*Server) Registered

func (s *Server) Registered() []string

Registered reports which route names have handlers, so a startup check can assert the inventory is fully served rather than discovering a 501 in production.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP is the middleware chain, in the order spec section 6.2 fixes for a mutation and section 7.1 fixes for every request.

The order is the contract, not a preference:

  1. a request ID, so every answer -- including a panic -- can be correlated;
  2. security headers, which must be on a refusal as well as on an answer;
  3. resolve the route: no route is not_found, wrong method is 405 with Allow, because a caller who typed GET for POST should be told what to fix rather than sent looking for a missing object;
  4. read the body under a 1 MiB bound -- over it is 413, and a read that fails for any other reason is 400, because "too large" would be a guess;
  5. authenticate, then check the scope. 401 before 403: a caller with no credential is told to get one, not that theirs is too narrow;
  6. spend the rate limit AFTER authenticating, because the buckets are per authorization;
  7. strict parameter rejection, on the query and then the body;
  8. the handler.

Authentication precedes strict parameter rejection deliberately: an unauthenticated caller must not be able to use the shape of a parameter refusal to learn which parameters a route takes.

func (*Server) SetLoggers

func (s *Server) SetLoggers(refused, internalError func(msg string, kv ...any))

SetLoggers replaces the server's two log hooks.

There are two, and the split is the point (see Deps): `refused` is ordinary traffic an operator reads when they go looking, and `internalError` is a bug they must be told about without having to. Wiring the second to the first, at debug level, is what made a 500 produce no log line at all for a whole slice while its own message told the caller to look in the logs.

type StoreAppender

type StoreAppender struct{ Store *store.Store }

StoreAppender writes audit rows to `audit_events`.

internal/audit deliberately knows nothing about internal/store: it declares a one-method Appender with **no Update and no Delete**, because "an audit row is never rewritten" (spec section 12.4) is a rule better stated as a missing method than as a paragraph somebody has to read every caller against. That leaves exactly one adapter to write, and this is it.

It matters for account removal in particular. `DELETE /v1/accounts/{id}` erases the account's rows and **leaves its audit trail standing**, carrying the `account_id` of an account that no longer exists -- which is how "what happened to this account" stays answerable afterwards. That only works because the rows are really in the table rather than in a process's memory, so a deployment that wired a memory appender would pass a removal test and lose the trail in production.

func NewStoreAppender

func NewStoreAppender(st *store.Store) *StoreAppender

NewStoreAppender builds the adapter.

func (*StoreAppender) AppendAudit

func (a *StoreAppender) AppendAudit(ctx context.Context, row audit.Row) error

AppendAudit implements audit.Appender. The nullable columns arrive as pointers so that "no account" is NULL rather than the empty string: `WHERE account_id = ”` finding rows would be a quiet lie about which events belong to an account.

Jump to

Keyboard shortcuts

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