hex

package
v0.0.0-...-17a9677 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: Apache-2.0 Imports: 46 Imported by: 1 module, 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

Index

Constants

View Source
const (
	LevelViewers = "viewers"
	LevelEditors = "editors"
	LevelOwners  = "owners"
	LevelCreator = "creator"
)
View Source
const (
	RoleUser      = "user"
	RoleAssistant = "assistant"
)
View Source
const (
	ContentText       = "text"
	ContentImage      = "image"
	ContentThinking   = "thinking"
	ContentToolCall   = "tool_call"
	ContentToolResult = "tool_result"
)
View Source
const (
	EventText       = "text"
	EventThinking   = "thinking"
	EventToolCall   = "tool_call"
	EventToolResult = "tool_result"
	EventMessage    = "message"
	EventDone       = "done"
	EventError      = "error"

	StopEndTurn   = "end_turn"
	StopMaxTokens = "max_tokens"
	StopToolUse   = "tool_use"
	StopRefusal   = "refusal"
)
View Source
const (
	GroupBySite   = "site"
	GroupByCaller = "caller"
	GroupByModel  = "model"
	GroupByDay    = "day"
)

Grouping for AIUsageTotals.

View Source
const (
	BudgetPlatform      = "platform"
	BudgetSiteDefault   = "site-default"
	BudgetSite          = "site"
	BudgetPersonDefault = "person-default"
	BudgetPerson        = "person"
)
View Source
const (
	RunRunning   = "running"
	RunSucceeded = "succeeded"
	RunFailed    = "failed"

	OperationSucceeded = "succeeded"
	OperationFailed    = "failed"
	OperationDryRun    = "dry-run"

	TriggerSchedule = "schedule"
	TriggerManual   = "manual"
	TriggerTest     = "test"
)
View Source
const (
	ApprovalRequested = "requested"
	ApprovalApproved  = "approved"
)
View Source
const (
	OperationCreate = "create"
	OperationUpdate = "update"
	OperationDelete = "delete"
)
View Source
const (
	RoleOwner  = "owner"
	RoleEditor = "editor"
	RoleViewer = "viewer"

	GeneralRestricted = "restricted"
	GeneralView       = "view"
	GeneralEdit       = "edit"
)
View Source
const KindArtifact = "artifact"
View Source
const MaxActionInputBytes = 1 << 20

Variables

View Source
var ErrAuthorizationUnsupported = errors.New("database provider does not support guarded mutations or authorization filtering")
View Source
var ErrAutomationValidationBusy = errors.New("automation validation is busy; try again shortly")
View Source
var ErrCredentialChanged = errors.New("connected account changed")
View Source
var ErrDocumentReadLimit = errors.New("document exceeds read byte limit")

ErrDocumentReadLimit reports a document too large for a bounded read.

View Source
var ErrEventsUnavailable = errors.New("durable events are not enabled on this platform")

ErrEventsUnavailable reports that the platform runs without durable events (they need the site API and automations).

View Source
var ErrForbidden = errors.New("forbidden")

ErrForbidden reports that a conditional write was refused, such as replacing a document created by someone else under a creator-only rule.

View Source
var ErrNotConnected = errors.New("account not connected")

ErrNotConnected reports that a connector-backed endpoint was called by someone who has not connected their account.

View Source
var ErrNotFound = errors.New("not found")

Functions

func DoJSON

func DoJSON(client *http.Client, request *http.Request, service string, result any) error

DoJSON sends the request and decodes a successful JSON response into result, which may be nil. Failures the app can act on become an IntegrationError: 400, 404, 409, 422 and 429 keep their status, and 401 and 403 report that the service refused access. Other failures are returned as plain errors, which the API reports as 502.

func FormatDollars

func FormatDollars(micros int64) string

FormatDollars renders micro-dollars as US dollars for messages and pages.

func NewJSONRequest

func NewJSONRequest(ctx context.Context, method, url string, body any) (*http.Request, error)

NewJSONRequest builds a request with an optional JSON body.

func OpenAESGCM

func OpenAESGCM(aead cipher.AEAD, sealed, associated []byte) ([]byte, error)

OpenAESGCM opens a value sealed by SealAESGCM.

func ParseCredentialKey

func ParseCredentialKey(value string) ([]byte, error)

ParseCredentialKey decodes a base64 AES-256 key for a KeySealer.

func ProviderError

func ProviderError(provider string, status int, body []byte) error

ProviderError builds an AIError from a model provider's error status, so apps see rate limits and invalid requests while other failures stay internal.

func SameAutomationSchedule

func SameAutomationSchedule(a, b Automation) bool

Script and description changes preserve schedule position, but each store replacement still assigns a new revision to invalidate stale snapshots.

func SealAESGCM

func SealAESGCM(aead cipher.AEAD, plaintext, associated []byte) ([]byte, error)

SealAESGCM prefixes a random nonce to the ciphertext.

func UpstreamError

func UpstreamError(service string, status int, body []byte) error

UpstreamError translates a third-party error status for the app.

func ValidateAutomations

func ValidateAutomations(automations []Automation) error

func ValidateAutomationsContext

func ValidateAutomationsContext(ctx context.Context, automations []Automation) error

ValidateAutomationsContext cancels validation with its caller.

func ValidateDocumentData

func ValidateDocumentData(data json.RawMessage) error

ValidateDocumentData is used by guarded providers after a mutation callback.

func ValidateIntegrationGrants

func ValidateIntegrationGrants(grants []IntegrationGrant) error

ValidateIntegrationGrants checks principals and permission patterns.

func ValidatePublishedAccess

func ValidatePublishedAccess(access SiteAccess) error

ValidatePublishedAccess is also used by the CLI before making a publication.

Types

type AIBudget

type AIBudget struct {
	Scope       string    `json:"scope"`
	Subject     string    `json:"subject,omitempty"`
	LimitMicros *int64    `json:"limitMicros"`
	Disabled    bool      `json:"disabled,omitempty"`
	Models      []string  `json:"models,omitempty"`
	UpdatedBy   *Person   `json:"updatedBy,omitempty"`
	UpdatedAt   time.Time `json:"updatedAt"`
}

AIBudget is one stored budget. Scopes:

  • platform: every model call on the platform
  • site-default: each site without its own limit
  • site: one site (Subject); a nil Limit uses the default, Disabled turns AI off for the site and Models lists the restricted models enabled for it
  • person-default: each person without an override
  • person: people matching the principal in Subject (user:, group: or role:); the highest matching override applies

A nil Limit means no limit, except on site budgets as described.

type AIBudgetCheck

type AIBudgetCheck struct {
	Filter      AIUsageFilter
	LimitMicros int64
}

AIBudgetCheck supplies an effective monthly limit and its settled-usage filter. Outstanding holds match Site/Caller but deliberately ignore dates.

type AIBudgetExceededError

type AIBudgetExceededError struct{ Index int }

AIBudgetExceededError identifies the first denied check, in input order.

func (*AIBudgetExceededError) Error

func (e *AIBudgetExceededError) Error() string

type AICompletion

type AICompletion struct {
	Messages   []AIMessage `json:"messages"`
	Text       string      `json:"text"`
	StopReason string      `json:"stopReason"`
	Usage      AIUsage     `json:"usage"`
}

AICompletion is the non-streaming answer: every message the turn added (assistant output and server tool results), in order, plus the outcome.

type AIConfig

type AIConfig struct {
	Provider        AIProvider
	Permission      string
	MaxOutputTokens int
	MaxToolRounds   int
	Limits          AILimits
}

AIConfig enables the AI capability. Permission (default "ai") is needed to use it at all. MaxOutputTokens caps each model call (default 16000) and MaxToolRounds the server-side tool loop (default 8). Limits are the monthly budgets used where Config.AIUsage stores none; budgets need Config.AIUsage.

type AIContent

type AIContent struct {
	Type       string          `json:"type"`
	Text       string          `json:"text,omitempty"`
	Signature  string          `json:"signature,omitempty"`
	Redacted   string          `json:"redacted,omitempty"`
	ToolCallID string          `json:"toolCallId,omitempty"`
	Name       string          `json:"name,omitempty"`
	Input      json.RawMessage `json:"input,omitempty"`
	IsError    bool            `json:"isError,omitempty"`
	MediaType  string          `json:"mediaType,omitempty"`
	Data       string          `json:"data,omitempty"`
}

AIContent is one block of a message. Types:

  • text: Text
  • image: MediaType and base64 Data
  • thinking: Text plus the provider's opaque Signature, or Redacted data; send thinking blocks back unchanged so the model can continue its reasoning
  • tool_call: ToolCallID, Name and Input
  • tool_result: ToolCallID, Text (usually JSON) and IsError

type AIError

type AIError struct {
	Status  int
	Message string
}

AIError is a request problem the app should see, such as an unknown model.

func (*AIError) Error

func (e *AIError) Error() string

type AIEvent

type AIEvent struct {
	Type       string     `json:"type"`
	Text       string     `json:"text,omitempty"`
	Content    *AIContent `json:"content,omitempty"`
	Message    *AIMessage `json:"message,omitempty"`
	StopReason string     `json:"stopReason,omitempty"`
	Usage      *AIUsage   `json:"usage,omitempty"`
	Error      string     `json:"error,omitempty"`
}

AIEvent is one streamed event. Types:

  • text / thinking: a Text delta
  • tool_call: a complete tool call in Content
  • tool_result: the server ran an integration tool; Content is its result
  • message: a complete message (assistant output, or the user message of server tool results) to append to the conversation
  • done: StopReason (end_turn, max_tokens, tool_use, refusal) and Usage
  • error: Error describes a failure after the stream started

type AILimits

type AILimits struct {
	PlatformMonthly float64
	SiteMonthly     float64
	PersonMonthly   float64
}

AILimits are the monthly limits in US dollars used where no budget is stored; zero means no limit.

type AIMessage

type AIMessage struct {
	Role    string      `json:"role"`
	Content []AIContent `json:"content"`
}

AIMessage is one turn. Tool results are content of user messages.

type AIModel

type AIModel struct {
	ID              string   `json:"id"`
	Name            string   `json:"name"`
	Description     string   `json:"description,omitempty"`
	Thinking        bool     `json:"thinking"`
	Tools           bool     `json:"tools"`
	Images          bool     `json:"images"`
	ContextTokens   int      `json:"contextTokens,omitempty"`
	MaxOutputTokens int      `json:"maxOutputTokens,omitempty"`
	Restricted      bool     `json:"restricted,omitempty"`
	Price           *AIPrice `json:"price,omitempty"`
}

AIModel describes a model apps can choose. A Restricted model, such as an expensive one, works only on sites a platform admin has enabled it for; everyone on such a site, and its automations, may use it. Price is needed to count the model's spending against budgets.

type AINoSpendError

type AINoSpendError struct{ Err error }

AINoSpendError marks a definite pre-work failure or upstream rejection that incurred no usage. Do not use it for timeouts or ambiguous transport failures.

func (*AINoSpendError) Error

func (e *AINoSpendError) Error() string

func (*AINoSpendError) Unwrap

func (e *AINoSpendError) Unwrap() error

type AIPrice

type AIPrice struct {
	Input       float64 `json:"input"`
	CachedInput float64 `json:"cachedInput,omitempty"`
	CacheWrite  float64 `json:"cacheWrite,omitempty"`
	Output      float64 `json:"output"`
	// Overrides distinguish an explicitly free cache category from the
	// historical zero-value defaults without changing the float fields.
	CachedInputOverride *float64 `json:"cachedInputOverride,omitempty"`
	CacheWriteOverride  *float64 `json:"cacheWriteOverride,omitempty"`
}

AIPrice is what a model costs, in US dollars per million tokens. Cached input is what a cache read costs and CacheWrite what writing to the cache costs; they default to a tenth and 1.25 times the input price.

type AIProvider

type AIProvider interface {
	Models(ctx context.Context) ([]AIModel, error)
	Stream(ctx context.Context, request AIRequest) (AIStream, error)
}

AIProvider answers model requests. Stream returns events until io.EOF; the final events are a "message" event carrying the complete assistant message and a "done" event with the stop reason and usage. Stream errors are potentially billable unless explicitly marked AINoSpendError.

type AIRequest

type AIRequest struct {
	Model     string      `json:"model"`
	System    string      `json:"system,omitempty"`
	Messages  []AIMessage `json:"messages"`
	Tools     []AITool    `json:"tools,omitempty"`
	Thinking  *AIThinking `json:"thinking,omitempty"`
	MaxTokens int         `json:"maxTokens,omitempty"`
}

AIRequest is a provider-neutral conversation turn.

type AIStream

type AIStream interface {
	Next() (AIEvent, error)
	Close() error
}

AIStream yields events in order. Next returns io.EOF after the last one.

type AIThinking

type AIThinking struct {
	Effort string `json:"effort,omitempty"`
	Show   bool   `json:"show,omitempty"`
}

AIThinking asks for reasoning. Effort is low, medium, high, xhigh or max; providers map it to what the model supports. Show streams readable reasoning (a summary on models that only summarize) as thinking events.

type AITool

type AITool struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	InputSchema json.RawMessage `json:"inputSchema"`
}

AITool is a function the model may call.

type AIUsage

type AIUsage struct {
	InputTokens       int  `json:"inputTokens"`
	CachedInputTokens int  `json:"cachedInputTokens,omitempty"`
	CacheWriteTokens  int  `json:"cacheWriteTokens,omitempty"`
	OutputTokens      int  `json:"outputTokens"`
	Estimated         bool `json:"estimated,omitempty"`
}

AIUsage counts tokens for one model call or a whole tool loop. Input tokens exclude the cached ones: CachedInputTokens were read from the provider's prompt cache and CacheWriteTokens written to it, each priced separately. Estimated marks counts the server estimated because the provider did not report them, for example when a stream was cut off.

type AIUsageFilter

type AIUsageFilter struct {
	Since  time.Time
	Until  time.Time
	Site   string
	Caller string
}

AIUsageFilter selects records from Since (inclusive) to Until (exclusive); empty fields match everything.

type AIUsageRecord

type AIUsageRecord struct {
	ID         string    `json:"id"`
	At         time.Time `json:"at"`
	Site       string    `json:"site"`
	Caller     string    `json:"caller"`
	CallerName string    `json:"callerName,omitempty"`
	Model      string    `json:"model"`
	Usage      AIUsage   `json:"usage"`
	CostMicros int64     `json:"costMicros"`
	Priced     bool      `json:"priced"`
}

AIUsageRecord is one model call. Caller is the stable key of who it ran for ("user:<id>" or "automation:<site>/<name>").

type AIUsageReservation

type AIUsageReservation struct {
	ID              string    `json:"id"`
	At              time.Time `json:"at"`
	Site            string    `json:"site"`
	Caller          string    `json:"caller"`
	CostMicros      int64     `json:"costMicros"`
	CallerName      string    `json:"callerName,omitempty"`
	Model           string    `json:"model,omitempty"`
	Price           *AIPrice  `json:"price,omitempty"`
	ContextTokens   int       `json:"contextTokens,omitempty"`
	MaxOutputTokens int       `json:"maxOutputTokens,omitempty"`
	// This is the pre-call input estimate, not recovered upstream counts.
	EstimatedUsage AIUsage `json:"estimatedUsage"`
}

AIUsageReservation holds a conservative call ceiling under the future usage record's ID, timestamp and attribution. For budget-enforced calls CostMicros must cover all possible billed token categories for the model call.

func (AIUsageReservation) Clone

Clone keeps pricing snapshots independent of callers' mutable model catalogs.

type AIUsageSpend

type AIUsageSpend struct {
	SettledMicros  int64 `json:"settledMicros"`
	ReservedMicros int64 `json:"reservedMicros"`
	Reservations   int64 `json:"reservations"`
}

type AIUsageStore

type AIUsageStore interface {
	// ReserveAIUsage atomically checks settled monthly spend plus ALL
	// outstanding reservations against each check, then inserts the hold.
	// Admission is allowed only below every limit. The final admitted call
	// may cross a limit by at most its conservative CostMicros ceiling.
	// Reservations never expire, including across month boundaries.
	ReserveAIUsage(ctx context.Context, reservation AIUsageReservation, checks []AIBudgetCheck) error
	// SettleAIUsage atomically inserts the record and removes its reservation.
	// Retrying with the original record ID is idempotent. A failed transaction
	// retains the hold; an ambiguous commit leaves either the hold or the
	// durable record, never neither. Attribution must match the reservation.
	SettleAIUsage(ctx context.Context, record AIUsageRecord) error
	// ListAIReservations returns pending holds ordered by (At, ID). Date
	// filters apply to listing, but never age holds out of admission.
	ListAIReservations(ctx context.Context, filter AIUsageFilter) ([]AIUsageReservation, error)
	// AIBudgetSpend atomically reads settled spend in the filter's period plus
	// all outstanding holds for its Site/Caller, including older months.
	AIBudgetSpend(ctx context.Context, filter AIUsageFilter) (AIUsageSpend, error)
	// RecordAIUsage is an idempotent import of an already settled call by ID.
	RecordAIUsage(ctx context.Context, record AIUsageRecord) error
	SumAICost(ctx context.Context, filter AIUsageFilter) (int64, error)
	AIUsageTotals(ctx context.Context, filter AIUsageFilter, groupBy string) ([]AIUsageTotal, error)
	ListAIBudgets(ctx context.Context) ([]AIBudget, error)
	PutAIBudget(ctx context.Context, budget AIBudget) error
	DeleteAIBudget(ctx context.Context, scope, subject string) error
}

AIUsageStore keeps usage records and budgets. Totals are grouped by site, caller, model or UTC day (keyed YYYY-MM-DD); a caller group's Name is the latest name by (At, ID), with the lexically greatest ID breaking time ties.

type AIUsageTotal

type AIUsageTotal struct {
	Key               string `json:"key"`
	Name              string `json:"name,omitempty"`
	Calls             int64  `json:"calls"`
	InputTokens       int64  `json:"inputTokens"`
	CachedInputTokens int64  `json:"cachedInputTokens"`
	CacheWriteTokens  int64  `json:"cacheWriteTokens"`
	OutputTokens      int64  `json:"outputTokens"`
	CostMicros        int64  `json:"costMicros"`
	Estimated         int64  `json:"estimated"`
}

AIUsageTotal sums the records of one group.

type AccessStore

type AccessStore interface {
	GetSiteAccess(ctx context.Context, site string) (SiteAccess, error)
	PutSiteAccess(ctx context.Context, site string, access SiteAccess) error
	DeleteSiteAccess(ctx context.Context, site string) error
	// UpdateSiteAccess atomically reads, authorizes and changes a policy, even
	// when the site does not exist yet. All writes to a site must serialize
	// with this operation across store instances. The callback receives a
	// detached copy; nil deletes the policy, and an error leaves it unchanged.
	// Callbacks must not call back into the store.
	UpdateSiteAccess(ctx context.Context, site string, update AccessUpdate) error
}

type AccessUpdate

type AccessUpdate func(current SiteAccess, exists bool) (*SiteAccess, error)

type Action

type Action struct {
	Definition ActionDefinition
	Audience   Audience
	Handler    func(context.Context, ActionContext, json.RawMessage) (any, error)
}

Action registers an operation and its contract together. Audience uses the site's existing viewers/editors/owners or principals; it defaults to editors. The handler applies business rules and returns a JSON-marshalable result.

type ActionContext

type ActionContext struct {
	SourceSite   string
	InvocationID string
	Site         string
	Identity     *Identity
	Role         string
	// contains filtered or unexported fields
}

ActionContext carries the existing caller and site authorization, not a separate agent identity. Its helpers apply the site's data rules when a handler uses providers directly.

func (ActionContext) CanDeleteFile

func (c ActionContext) CanDeleteFile(key string) bool

func (ActionContext) CanReadDocument

func (c ActionContext) CanReadDocument(collection string, document Document) bool

func (ActionContext) CanReadFile

func (c ActionContext) CanReadFile(key string) bool

func (ActionContext) CanWriteFile

func (c ActionContext) CanWriteFile(key string) bool

func (ActionContext) CollectionWriteOptions

func (c ActionContext) CollectionWriteOptions(collection string) (WriteOptions, error)

func (ActionContext) MutateDocument

func (c ActionContext) MutateDocument(ctx context.Context, database Database, collection, id string, mutation DocumentMutation) (Document, error)

MutateDocument applies a trusted handler's proposed change under the provider lock and checks one complete collection grant against original/proposed data. Returning nil data deletes the record. The callback must not reenter storage.

type ActionDefinition

type ActionDefinition struct {
	Version      int             `json:"version,omitempty"`
	Exported     bool            `json:"exported,omitempty"`
	ReadOnly     bool            `json:"readOnly,omitempty"`
	Name         string          `json:"name"`
	Description  string          `json:"description"`
	InputSchema  json.RawMessage `json:"inputSchema"`
	OutputSchema json.RawMessage `json:"outputSchema"`
}

ActionDefinition is the discoverable contract for one app operation. Schemas default to JSON Schema draft 2020-12 and must be self-contained: local $refs and $defs are supported, but external resources are never fetched.

func (ActionDefinition) ValidateInput

func (d ActionDefinition) ValidateInput(input json.RawMessage) error

ValidateInput checks JSON against the same schema used by the server.

func (ActionDefinition) ValidateOutput

func (d ActionDefinition) ValidateOutput(output json.RawMessage) error

ValidateOutput checks the response against the action's output contract.

func (ActionDefinition) ValidateSchemas

func (d ActionDefinition) ValidateSchemas() error

ValidateSchemas checks both schemas before an operation is invoked.

type ActionError

type ActionError struct{ Message string }

ActionError reports a user-correctable business-rule failure as HTTP 400. Other handler errors remain internal, except ErrForbidden and ErrNotFound.

func (*ActionError) Error

func (e *ActionError) Error() string

type ActionRegistry

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

ActionRegistry stores per-site operations. Register validates and compiles contracts before exposing them; registered definitions cannot be replaced. Its zero value is ready to use and registration is safe alongside requests.

func (*ActionRegistry) Register

func (r *ActionRegistry) Register(site string, action Action) error

type AdminAccessGrant

type AdminAccessGrant struct {
	ID        string    `json:"id"`
	Site      string    `json:"site"`
	Subject   string    `json:"subject"`
	Actor     Person    `json:"actor"`
	Scope     string    `json:"scope"`
	Reason    string    `json:"reason"`
	StartedAt time.Time `json:"startedAt"`
	ExpiresAt time.Time `json:"expiresAt"`
	RevokedAt time.Time `json:"revokedAt,omitzero"`
	RevokedBy *Person   `json:"revokedBy,omitempty"`
}

func (AdminAccessGrant) Active

func (g AdminAccessGrant) Active(at time.Time) bool

type AdminAccessQuery

type AdminAccessQuery struct {
	ID       string
	Site     string
	Subject  string
	ActiveAt time.Time
	Before   string
	Limit    int
}

type AdminAccessStore

type AdminAccessStore interface {
	GrantAdminAccess(context.Context, AdminAccessGrant) error
	RevokeAdminAccess(context.Context, string, string, Person, time.Time) error
	// ListAdminAccess returns at most Limit grants, ordered by ID descending,
	// honoring every supplied filter. Before is an exclusive ID cursor.
	ListAdminAccess(context.Context, AdminAccessQuery) ([]AdminAccessGrant, error)
}

AdminAccessStore stores temporary privileges and their audit history together. Grant and revocation writes must be atomic and reads must not use a local cache.

type AdminAnalyticsQuery

type AdminAnalyticsQuery struct {
	AnalyticsQuery
	Section string
	Search  string
	Sort    string
	Page    int
	Limit   int
}

type AdminAnalyticsReader

type AdminAnalyticsReader interface {
	QueryAdminAnalytics(context.Context, AdminAnalyticsQuery) (AdminAnalyticsResult, error)
}

AdminAnalyticsReader returns only the rows used by an admin section. Storage implementations should aggregate, search, sort and page before returning rows.

type AdminAnalyticsResult

type AdminAnalyticsResult struct {
	AnalyticsReport
	Total int
	Page  int
}

func BoundAdminAnalytics

func BoundAdminAnalytics(report AnalyticsReport, query AdminAnalyticsQuery) AdminAnalyticsResult

BoundAdminAnalytics is the compatibility path for custom stores and the in-memory provider. PostgreSQL implements the bounded queries in storage.

type AnalyticsDay

type AnalyticsDay struct {
	Date         string `json:"date"`
	Created      int    `json:"created"`
	Publications int    `json:"publications"`
	Unpublished  int    `json:"unpublished"`
	NewUsers     int    `json:"newUsers"`
	TrafficTotals
}

type AnalyticsPerson

type AnalyticsPerson struct {
	Person
	FirstSeen time.Time `json:"firstSeen,omitzero"`
	LastSeen  time.Time `json:"lastSeen"`
}

type AnalyticsQuery

type AnalyticsQuery struct {
	From  time.Time `json:"from"`
	Until time.Time `json:"until"`
	Site  string    `json:"site,omitempty"`
	User  string    `json:"user,omitempty"`
}

AnalyticsQuery uses UTC calendar days and an exclusive Until bound. User filters concern the actor/visitor, not the site's current owners.

type AnalyticsReport

type AnalyticsReport struct {
	Query         AnalyticsQuery    `json:"query"`
	KnownUsers    int               `json:"knownUsers"`
	Active7Days   int               `json:"active7Days"`
	Active30Days  int               `json:"active30Days"`
	NewUsers      int               `json:"newUsers"`
	Created       int               `json:"created"`
	Publications  int               `json:"publications"`
	Unpublished   int               `json:"unpublished"`
	Traffic       TrafficTotals     `json:"traffic"`
	People        []AnalyticsPerson `json:"people"`
	Sites         []AnalyticsRow    `json:"sites"`
	Users         []AnalyticsRow    `json:"users"`
	Days          []AnalyticsDay    `json:"days"`
	Events        []SiteEvent       `json:"events"`
	LastCollected time.Time         `json:"lastCollected,omitzero"`
}

func SummarizeAnalytics

func SummarizeAnalytics(query AnalyticsQuery, people []AnalyticsPerson, events []SiteEvent, buckets []TrafficBucket, lastCollected time.Time) AnalyticsReport

SummarizeAnalytics is shared by storage implementations. Buckets and events are already filtered by the query. Distinct visitors are unioned across days and sites, rather than summing daily unique counts.

func SummarizeAnalyticsSummary

func SummarizeAnalyticsSummary(query AnalyticsQuery, people []AnalyticsPerson, events []SiteEvent, buckets []TrafficBucket, lastCollected time.Time) AnalyticsReport

type AnalyticsRow

type AnalyticsRow struct {
	Key    string  `json:"key"`
	Person *Person `json:"person,omitempty"`
	TrafficTotals
}

func SummarizeSiteTraffic

func SummarizeSiteTraffic(buckets []TrafficBucket) []AnalyticsRow

SummarizeSiteTraffic unions visitors across daily buckets for each site.

type AnalyticsStore

type AnalyticsStore interface {
	ObservePerson(context.Context, Person, time.Time) error
	RecordSiteEvents(context.Context, []SiteEvent) error
	RecordTraffic(context.Context, []TrafficEvent) error
	QueryAnalytics(context.Context, AnalyticsQuery) (AnalyticsReport, error)
}

AnalyticsStore owns platform statistics, independently of app documents. Writes must be concurrency-safe; event IDs make retries idempotent. Traffic is reduced to daily per-site/per-user buckets, not retained request bodies. Additional analytics sources can implement their own optional interfaces.

type AnalyticsSummaryReader

type AnalyticsSummaryReader interface {
	QueryAnalyticsSummary(context.Context, AnalyticsQuery) (AnalyticsReport, error)
}

AnalyticsSummaryReader omits inventories, visitor identities and event payloads. It retains headline counts and daily trends for comparisons and site reports.

type AnalyticsView

type AnalyticsView struct {
	Report             AnalyticsReport
	From               string
	Until              string
	Site               string
	Period             string
	Periods            []periodChoice
	CustomPeriod       bool
	CustomAttr         template.HTMLAttr
	Comparison         string
	Metrics            []metricCard
	Chart              trendChart
	Bytes              string
	Lifetime           *TrafficTotals
	LastVisit          string
	ShowVisitors       bool
	SiteVisitors       []siteVisitorRow
	AnonymousPageViews int64
	VisitorSearch      string
	VisitorSort        string
	VisitorSortChoices []choice
	VisitorPage        int
	VisitorPages       int
	VisitorTotal       int
	VisitorPrevious    string
	VisitorNext        string

	VisitorPreviousFragment string
	VisitorNextFragment     string
	VisitorSummary          string
	UpdateSummary           string
}

type AnalyticsVisitorReader

type AnalyticsVisitorReader interface {
	QueryAnalyticsVisitors(context.Context, AnalyticsVisitorsQuery) (AnalyticsVisitorsPage, error)
}

AnalyticsVisitorReader filters and paginates actual page visitors in storage.

type AnalyticsVisitorsPage

type AnalyticsVisitorsPage struct {
	Rows               []AnalyticsRow
	Total              int
	Page               int
	AnonymousPageViews int64
	PeakPageViews      int64
}

func PaginateAnalyticsVisitors

func PaginateAnalyticsVisitors(report AnalyticsReport, query AnalyticsVisitorsQuery) AnalyticsVisitorsPage

PaginateAnalyticsVisitors is shared by in-memory stores and custom providers.

type AnalyticsVisitorsQuery

type AnalyticsVisitorsQuery struct {
	AnalyticsQuery
	Search string
	Sort   string
	Page   int
	Limit  int
}

type ApplicationRole

type ApplicationRole struct {
	Name        string `json:"name,omitempty"`
	Description string `json:"description,omitempty"`
	SignedIn    bool   `json:"signedIn,omitempty"`
	Owners      bool   `json:"owners,omitempty"`
	Workspace   bool   `json:"workspace,omitempty"`
}

type Audience

type Audience struct {
	Level      string
	Principals []string
}

Audience is either a level (viewers, editors, owners or creator) or an explicit list of principals. In JSON it is a string or an array.

func (Audience) IsZero

func (a Audience) IsZero() bool

func (Audience) MarshalJSON

func (a Audience) MarshalJSON() ([]byte, error)

func (*Audience) UnmarshalJSON

func (a *Audience) UnmarshalJSON(data []byte) error

type AuthConfig

type AuthConfig struct {
	Type     string   `json:"type"`
	Issuer   string   `json:"issuer,omitempty"`
	ClientID string   `json:"clientId,omitempty"`
	Scopes   []string `json:"scopes,omitempty"`
}

AuthConfig describes public-client sign-in independently of the hosting gateway's identity resolver. It contains no secrets and travels with the platform connection document and installers.

func ParseAuthConfig

func ParseAuthConfig(value string) (*AuthConfig, error)

func (*AuthConfig) Validate

func (a *AuthConfig) Validate() error

type Automation

type Automation struct {
	Input       json.RawMessage   `json:"inputSchema,omitempty"`
	Name        string            `json:"name"`
	Description string            `json:"description,omitempty"`
	Schedule    string            `json:"schedule,omitempty"`
	Timezone    string            `json:"timezone,omitempty"`
	Disabled    bool              `json:"disabled,omitempty"`
	Script      *AutomationScript `json:"script"`
}

Automation configures when a site's JavaScript module runs. All workflow logic lives in Script; definitions contain scheduling and input contracts. Automations act as their site, never as the person deploying or triggering them. Integrations require site grants and approvals; connected accounts are unavailable. Within their site, automations act as owners.

type AutomationLog

type AutomationLog struct {
	Message string          `json:"message"`
	Data    json.RawMessage `json:"data,omitempty"`
}

type AutomationOperation

type AutomationOperation struct {
	Kind       string          `json:"kind"`
	Target     string          `json:"target,omitempty"`
	Status     string          `json:"status"`
	DurationMS int64           `json:"durationMs"`
	Output     json.RawMessage `json:"output,omitempty"`
	Truncated  bool            `json:"truncated,omitempty"`
	Error      string          `json:"error,omitempty"`
}

type AutomationRun

type AutomationRun struct {
	WorkflowID    string                `json:"workflowId,omitempty"`
	WorkflowLease string                `json:"-"`
	Input         json.RawMessage       `json:"input,omitempty"`
	WakeAt        time.Time             `json:"wakeAt,omitzero"`
	Event         *DurableEvent         `json:"event,omitempty"`
	ID            string                `json:"id"`
	Site          string                `json:"site"`
	Automation    string                `json:"automation"`
	Trigger       string                `json:"trigger"`
	DryRun        bool                  `json:"dryRun,omitempty"`
	Status        string                `json:"status"`
	StartedAt     time.Time             `json:"startedAt"`
	FinishedAt    time.Time             `json:"finishedAt,omitzero"`
	Error         string                `json:"error,omitempty"`
	StartedBy     *Person               `json:"startedBy,omitempty"`
	Revision      string                `json:"revision,omitempty"`
	SourceHash    string                `json:"sourceHash,omitempty"`
	Output        json.RawMessage       `json:"output,omitempty"`
	Truncated     bool                  `json:"truncated,omitempty"`
	Logs          []AutomationLog       `json:"logs,omitempty"`
	Operations    []AutomationOperation `json:"operations,omitempty"`
}

AutomationRun records one script's result and bounded operation history.

type AutomationScript

type AutomationScript struct {
	File   string `json:"file,omitempty"`
	Source string `json:"source,omitempty"`
}

AutomationScript is a JavaScript ES module with a default run(hex) export. Project metadata references File; the CLI includes Source for deployment. The server executes the stored Source and never reads File from disk.

type AutomationStatus

type AutomationStatus struct {
	ScheduledAutomation
	LastRun *AutomationRun `json:"lastRun,omitempty"`
}

AutomationStatus is a stored automation with its latest run.

type AutomationStore

type AutomationStore interface {
	ReplaceSiteAutomations(ctx context.Context, site string, automations []ScheduledAutomation) error
	ListSiteAutomations(ctx context.Context, site string) ([]ScheduledAutomation, error)
	DueAutomations(ctx context.Context, now time.Time, limit int) ([]ScheduledAutomation, error)
	ClaimAutomation(ctx context.Context, site, name, revision string, expected, next time.Time) (bool, error)
	RecordAutomationRun(ctx context.Context, run AutomationRun) error
	ListAutomationRuns(ctx context.Context, site, name string, limit int) ([]AutomationRun, error)
	GetAutomationRun(ctx context.Context, site, id string) (AutomationRun, error)
}

AutomationStore keeps definitions, scheduling state and history. Whole-site replacement must serialize with claims, including absent names, assign fresh non-reusable revisions, and preserve the authoritative stored NextRun for unchanged schedules (SameAutomationSchedule), including zero. Incoming NextRun values are proposals for new or changed schedules only. Claims compare both revision and NextRun before advancing the occurrence. Returned definitions must be detached snapshots. Stores retain at least the latest 50 runs per automation.

type Chrome

type Chrome struct {
	WorkspaceAPIs bool
	Platform      string
	Active        string
	Viewer        *viewerView
	Manage        bool
	Analytics     bool
	Connections   bool
	Integrations  bool
	LogoutURL     string
	AdminAI       bool
	AdminAudit    bool
	// AdminLink is where the Admin navigation leads platform admins: the
	// analytics overview, or the AI page when only AI is enabled.
	AdminLink string
}

Chrome is what every portal page shows around its content: the platform, the active section and the signed-in viewer.

type Collection

type Collection struct {
	Name      string `json:"name"`
	Documents int    `json:"documents"`
}

Collection summarizes one collection of a site's documents.

type CollectionLister

type CollectionLister interface {
	ListCollections(ctx context.Context, site string) ([]Collection, error)
}

CollectionLister is implemented by databases that can list a site's collections, which the management portal's data browser uses.

type Config

type Config struct {
	// SiteOperationsPerMinute bounds each site's API calls, event publications
	// and workflow starts independently across replicas. Zero defaults to 120.
	SiteOperationsPerMinute int
	Analytics               AnalyticsStore
	// TrafficCollector is optional operational status for the admin dashboard.
	TrafficCollector *TrafficCollector
	Files            ObjectStore
	Sites            SiteDirectory
	SiteBaseURL      string
	// ResolveOrigin optionally classifies trusted hosting origins. Unknown hosts
	// must return an error; an empty Site explicitly denotes a platform origin.
	ResolveOrigin func(*http.Request) (RequestOrigin, error)
	// PathCaseInsensitive must match the static host's path comparison.
	PathCaseInsensitive bool
	// LogoutURL is the host-owned sign-out destination; empty hides sign-out.
	LogoutURL   string
	Database    Database
	Realtime    Realtime
	Identity    IdentityResolver
	Access      AccessStore
	AdminGroups []string
	// AdminAccess stores explicit, audited, expiring privileges. When omitted,
	// an implementing Access store or Database is used automatically.
	AdminAccess AdminAccessStore
	// Actions exposes contract-validated operations implemented by app backends.
	Actions *ActionRegistry
	// Publisher enables publishing through the API. PublisherGroups limits
	// who may claim new site names; empty lets every signed-in user.
	Publisher       SitePublisher
	PublisherGroups []string
	// People remembers who has signed in, and Groups names the groups
	// offered in pickers; together they label principals without reading
	// the identity provider's directory.
	People              PeopleStore
	Groups              []NamedGroup
	MaxUploadBytes      int64
	MaxPublishFileBytes int64
	MaxPublishBytes     int64
	Connection          *ConnectionConfig
	CLIReleaseURL       string

	// Integrations are the platform's third-party systems, called by apps,
	// AI tool use and automations. IntegrationGrants gives principals their
	// endpoint permissions. IntegrationStore keeps site approvals and
	// connected accounts, whose tokens CredentialSealer encrypts; a 32-byte
	// CredentialKey configures a local KeySealer instead. Connections
	// unused for ConnectionIdleExpiry (90 days by default) are removed.
	Integrations         *IntegrationRegistry
	IntegrationGrants    []IntegrationGrant
	IntegrationStore     IntegrationStore
	CredentialSealer     CredentialSealer
	CredentialKey        []byte
	ConnectionIdleExpiry time.Duration
	// IntegrationAudit keeps the audit log of integrations with Audit set,
	// for IntegrationAuditRetention (365 days by default).
	IntegrationAudit          IntegrationAuditStore
	IntegrationAuditRetention time.Duration

	// AI enables streaming model access for apps and automations. AIUsage
	// records each model call's usage and cost and keeps the monthly AI
	// budgets that are managed in the portal.
	AI      *AIConfig
	AIUsage AIUsageStore
	// Automations stores declared automations and their runs; the host
	// runs the scheduler with Server.RunBackground.
	Automations AutomationStore
	// AutomationComputeTime bounds the JavaScript computation of one
	// automation run (or workflow attempt), excluding time spent waiting for
	// integration calls, AI and other host operations. Zero means five
	// seconds; it is capped at the ten-minute run deadline.
	AutomationComputeTime time.Duration
}

type ConnectionConfig

type ConnectionConfig struct {
	Name     string
	Server   string
	Resource string
	ClientID string
	TenantID string
	Auth     *AuthConfig
}

ConnectionConfig is the non-secret platform description the CLI imports. Auth selects the sign-in protocol, issuer, public client and scopes. Resource, ClientID and TenantID are legacy Entra settings, supported for existing installations. New platforms should configure Auth instead.

func (*ConnectionConfig) Validate

func (c *ConnectionConfig) Validate(siteBaseURL string) error

Validate checks a host's complete, non-secret connection settings before startup. Request handlers use the same validation when serving them.

type Connector

type Connector struct {
	Name        string
	Title       string
	Description string
	OAuth2      oauth2.Config
	// APIOrigins limits bearer-token destinations. Empty defaults to the token
	// endpoint's origin; configure distinct API origins explicitly.
	APIOrigins      []string
	AuthCodeOptions []oauth2.AuthCodeOption
	Account         func(ctx context.Context, client *http.Client) (string, error)
	Exchange        func(ctx context.Context, config *oauth2.Config, code string, options ...oauth2.AuthCodeOption) (*oauth2.Token, error)
}

Connector is an OAuth 2.0 authorization server that people connect their account with. The platform sets OAuth2.RedirectURL to its own callback, {platform}/api/hex/connections/{name}/callback, which must be registered with the provider. AuthCodeOptions add provider-specific parameters, such as offline access. Account optionally names the connected account, for example its email address, using a client authorized as that account; an error rejects the connection, so it can also enforce which accounts may connect (return an IntegrationError to explain why).

Exchange replaces the standard authorization code exchange for providers whose token response is not standard OAuth 2.0, such as Slack, which returns a person's token under authed_user. It receives the platform's configuration (with the redirect URL set) and the options the platform would send, including the PKCE verifier. Refreshing still uses the standard flow, so tokens it returns should either not expire or carry a standard refresh token.

type CredentialRecord

type CredentialRecord struct {
	Owner       string
	Connector   string
	Sealed      []byte
	Account     string
	ConnectedAt time.Time
	LastUsedAt  time.Time
	// Generation identifies a connection, remaining stable through token refreshes.
	Generation string
	// Version is the store-assigned revision for conditional credential operations.
	Version string
}

CredentialRecord is one person's connection to one connector.

type CredentialSealer

type CredentialSealer interface {
	Seal(ctx context.Context, plaintext, associated []byte) ([]byte, error)
	Open(ctx context.Context, sealed, associated []byte) ([]byte, error)
}

CredentialSealer encrypts connected-account tokens before they are stored. Associated data binds each sealed value to its owner and connector, so a value copied to another record does not open. The keyvault provider wraps a fresh key per credential with a Key Vault key that never leaves the vault; KeySealer uses a local AES-256 key, for development. Changing sealers makes existing connections unreadable; people then reconnect. OAuth connection state uses this same sealer with distinct associated data; all instances serving a deployment must be able to open each other's values.

type DataRule

type DataRule struct {
	Read  Audience `json:"read,omitzero"`
	Write Audience `json:"write,omitzero"`
}

DataRule decides who may read and write one collection, file prefix or realtime channel. An unset Read defaults to viewers and an unset Write to editors.

type Database

type Database interface {
	Put(ctx context.Context, site, collection, id string, data json.RawMessage, options WriteOptions) (Document, error)
	Get(ctx context.Context, site, collection, id string) (Document, error)
	List(ctx context.Context, site, collection string, options ListOptions) ([]Document, error)
	Delete(ctx context.Context, site, collection, id string, options WriteOptions) error
}

type DeclaredAction

type DeclaredAction struct {
	Version       int                        `json:"version,omitempty"`
	Exported      bool                       `json:"exported,omitempty"`
	Output        json.RawMessage            `json:"output,omitempty"`
	Select        []string                   `json:"select,omitempty"`
	Name          string                     `json:"name"`
	Description   string                     `json:"description"`
	Operation     string                     `json:"operation"`
	Collection    string                     `json:"collection"`
	IDField       string                     `json:"idField,omitempty"`
	Input         json.RawMessage            `json:"input"`
	Audience      Audience                   `json:"audience,omitzero"`
	Authorization string                     `json:"authorization,omitempty"`
	Fields        []string                   `json:"fields,omitempty"`
	Set           map[string]json.RawMessage `json:"set,omitempty"`
	Where         *RecordCondition           `json:"where,omitempty"`
	Check         *RecordCondition           `json:"check,omitempty"`
}

DeclaredAction is one action from an app's hex.json. Operation is "create" (insert the input as a new document), "update" (merge the input into an existing document) or "delete". Update and delete find the document by the input property named IDField, "id" by default, which the input schema must require. Audience defaults to the site's editors, like registered actions.

type DirectUploader

type DirectUploader interface {
	UploadTargets(ctx context.Context, site string, files []SiteFile) ([]UploadTarget, error)
}

DirectUploader is implemented by publishers whose storage accepts uploads straight from the publisher, such as pre-signed URLs. Publishers without it receive uploads through the server.

type Document

type Document struct {
	ID        string          `json:"id"`
	Data      json.RawMessage `json:"data"`
	CreatedBy string          `json:"createdBy,omitempty"`
}

Document is a site-scoped JSON object. CreatedBy is the identity ID of the caller that first stored it, recorded by the server; it is empty for documents written without an identity.

type DocumentMutation

type DocumentMutation func(current *Document) (json.RawMessage, error)

type DurableEvent

type DurableEvent struct {
	ID        string          `json:"id"`
	Site      string          `json:"site"`
	Name      string          `json:"name"`
	Version   int             `json:"version"`
	Actor     string          `json:"actor"`
	Data      json.RawMessage `json:"data"`
	CreatedAt time.Time       `json:"createdAt"`
}

type EventDelivery

type EventDelivery struct {
	Subscription EventSubscription `json:"subscription"`
	Status       string            `json:"status"`
	Attempts     int               `json:"attempts"`
	NextAttempt  time.Time         `json:"nextAttempt"`
	Lease        string            `json:"lease,omitempty"`
	LeaseUntil   time.Time         `json:"leaseUntil,omitzero"`
	RunID        string            `json:"runId,omitempty"`
	Error        string            `json:"error,omitempty"`
}

type EventSubscription

type EventSubscription struct {
	ID         string           `json:"id"`
	Site       string           `json:"site"`
	Principal  string           `json:"principal"`
	Producer   string           `json:"producer"`
	Event      string           `json:"event"`
	Version    int              `json:"version"`
	Automation string           `json:"automation"`
	Revision   string           `json:"revision"`
	Generation string           `json:"generation"`
	Disabled   bool             `json:"disabled,omitempty"`
	Where      *RecordCondition `json:"where,omitempty"`
}

type EventType

type EventType struct {
	Name        string          `json:"name"`
	Version     int             `json:"version"`
	Description string          `json:"description"`
	Schema      json.RawMessage `json:"schema"`
}

type GuardedDatabase

type GuardedDatabase interface {
	Mutate(context.Context, string, string, string, string, DocumentMutation) (Document, error)
	ListMatching(context.Context, string, string, ListOptions, *RecordCondition) ([]Document, error)
}

GuardedDatabase executes the callback and mutation under the same lock or transaction, including absent IDs. Nil data deletes; an error changes nothing. Callbacks must not reenter the database. Every writer must use the same lock.

type Identity

type Identity struct {
	Provider string   `json:"provider,omitempty"`
	ID       string   `json:"id"`
	Name     string   `json:"name,omitempty"`
	Email    string   `json:"email,omitempty"`
	Groups   []string `json:"groups,omitempty"`
	Roles    []string `json:"roles,omitempty"`
}

Identity describes the authenticated user behind a request, as resolved from the hosting layer. The framework never validates identity-provider tokens itself; a resolver translates what the trusted gateway forwarded. IDs are opaque, case-sensitive values of 1–256 non-whitespace printable ASCII characters. Providers own any claim canonicalization; core never folds case.

type IdentityResolver

type IdentityResolver interface {
	ResolveIdentity(r *http.Request) (*Identity, error)
}

IdentityResolver extracts the caller's identity from a request. A nil identity with a nil error means the request is anonymous. Resolvers must only be configured behind a hosting layer that authenticates requests and controls the headers the resolver reads.

type Integration

type Integration struct {
	Name        string
	Title       string
	Description string
	// RequiresApproval makes sites ask a platform admin before their visitors
	// and automations can call any of the integration's endpoints.
	RequiresApproval bool
	// Connector names a registered Connector; its endpoints then call with
	// the caller's connected account instead of a platform credential.
	Connector string
	// Audit records every call of the integration's endpoints in
	// Config.IntegrationAudit, cached results included: who called, from
	// which site, the input and the records the result showed. Calls fail
	// when the record cannot be written.
	Audit     bool
	Endpoints []IntegrationEndpoint
	// Events are what automations can subscribe to from the third-party
	// system; the host publishes them with Server.PublishIntegrationEvent.
	Events []IntegrationEvent
}

Integration describes one third-party system and its endpoints.

type IntegrationApproval

type IntegrationApproval struct {
	Site        string    `json:"site"`
	Integration string    `json:"integration"`
	Status      string    `json:"status"`
	Reason      string    `json:"reason,omitempty"`
	RequestedBy *Person   `json:"requestedBy,omitempty"`
	RequestedAt time.Time `json:"requestedAt,omitzero"`
	DecidedBy   *Person   `json:"decidedBy,omitempty"`
	DecidedAt   time.Time `json:"decidedAt,omitzero"`
}

IntegrationApproval records a site's request to use an integration that requires approval, and a platform admin's decision.

type IntegrationAuditFilter

type IntegrationAuditFilter struct {
	Since    time.Time
	Until    time.Time
	Site     string
	Caller   string
	Endpoint string
	Record   string
	Limit    int
}

IntegrationAuditFilter selects records from Since (inclusive) to Until (exclusive), newest first, at most Limit of them. Endpoint is "<integration>.<endpoint>" or "<integration>.*"; Record matches one record ID exactly. Empty fields match everything.

type IntegrationAuditRecord

type IntegrationAuditRecord struct {
	ID          string          `json:"id"`
	At          time.Time       `json:"at"`
	Site        string          `json:"site"`
	Integration string          `json:"integration"`
	Endpoint    string          `json:"endpoint"`
	Caller      string          `json:"caller"`
	CallerName  string          `json:"callerName,omitempty"`
	Input       json.RawMessage `json:"input"`
	Records     []string        `json:"records"`
	Cached      bool            `json:"cached"`
	Failed      bool            `json:"failed"`
}

IntegrationAuditRecord is one call of an audited integration's endpoint. Caller is the stable key of who it ran for ("user:<id>" or "automation:<site>/<name>"); Records are the IDs the endpoint's AuditRecords reported for the result.

type IntegrationAuditStore

type IntegrationAuditStore interface {
	RecordIntegrationAudit(ctx context.Context, record IntegrationAuditRecord) error
	ListIntegrationAudit(ctx context.Context, filter IntegrationAuditFilter) ([]IntegrationAuditRecord, error)
	DeleteIntegrationAuditBefore(ctx context.Context, cutoff time.Time) (int, error)
}

IntegrationAuditStore keeps the integration audit log.

type IntegrationCall

type IntegrationCall struct {
	Site       string
	Identity   *Identity
	Automation string
	// contains filtered or unexported fields
}

IntegrationCall describes who an endpoint runs for. Identity is nil when an automation calls; Automation then names it. HTTPClient returns a client authorized as the caller's connected account for connector-backed integrations. SiteOwners returns the people who own the calling site.

func NewIntegrationCall

func NewIntegrationCall(site string, identity *Identity, client *http.Client) IntegrationCall

NewIntegrationCall describes a call for tests and for hosts that invoke handlers directly. A non-nil client is what HTTPClient returns.

func (IntegrationCall) HTTPClient

func (c IntegrationCall) HTTPClient(ctx context.Context) (*http.Client, error)

HTTPClient returns a client that authorizes requests as the caller's connected account, refreshing and storing its token as needed. It fails with ErrNotConnected when the caller has not connected the account.

func (IntegrationCall) SiteOwners

func (c IntegrationCall) SiteOwners(ctx context.Context) ([]Person, error)

SiteOwners returns the people named as owners of the calling site, with the name and email remembered from their last sign-in. Owners who never signed in are returned with only their ID, and group owners are left out. Integrations use it to limit what an automation may see to what one of the people controlling it could see themselves.

func (IntegrationCall) WithSiteOwners

func (c IntegrationCall) WithSiteOwners(owners []Person) IntegrationCall

WithSiteOwners returns a copy of the call whose SiteOwners returns owners, for tests and for hosts that invoke handlers directly.

type IntegrationEndpoint

type IntegrationEndpoint struct {
	Name         string
	Description  string
	Permission   string
	Write        bool
	InputSchema  json.RawMessage
	OutputSchema json.RawMessage
	CacheTTL     time.Duration
	Handler      func(context.Context, IntegrationCall, json.RawMessage) (any, error)
	// AuditRecords names the third-party records a result shows, such as
	// "ticket:123", for the audit log of integrations with Audit set. It
	// receives the validated JSON output, also for cached results.
	AuditRecords func(output json.RawMessage) []string
}

IntegrationEndpoint is one typed operation of an integration. Both schemas are required: results are validated against OutputSchema, and apps generate their types from both. Permission defaults to "<integration>.<endpoint>"; endpoints can share a permission by naming it explicitly. Write endpoints change data in the third-party system: they need the site's editor role, are never cached, and are skipped in automation dry runs. CacheTTL caches successful read results per input, and per caller for connector-backed integrations. Other integrations share cached results between callers, so an endpoint whose result depends on IntegrationCall.Identity must not set CacheTTL.

type IntegrationEndpointInfo

type IntegrationEndpointInfo struct {
	Name         string          `json:"name"`
	Description  string          `json:"description"`
	Permission   string          `json:"permission"`
	Write        bool            `json:"write"`
	Allowed      bool            `json:"allowed"`
	InputSchema  json.RawMessage `json:"inputSchema,omitempty"`
	OutputSchema json.RawMessage `json:"outputSchema,omitempty"`
}

IntegrationEndpointInfo is an endpoint's discoverable contract.

type IntegrationError

type IntegrationError struct {
	Status  int
	Message string
}

IntegrationError reports a failure the caller should see, such as a third-party 404 or a rejected input. Status is the HTTP status returned to the app; other handler errors become a generic 502.

func (*IntegrationError) Error

func (e *IntegrationError) Error() string

type IntegrationEvent

type IntegrationEvent struct {
	Name        string
	Version     int
	Description string
	Permission  string
	Schema      json.RawMessage
	Visible     func(ctx context.Context, call IntegrationCall, data json.RawMessage) bool
}

IntegrationEvent is one versioned event type an integration produces. Schema validates every published payload and is immutable per version: publish breaking changes as a new version. Permission defaults to "<integration>.events.<name>". Visible, when set, reports whether a subscribing automation may receive a particular event. Its call names the site and automation, with no Identity, and SiteOwners returns the site's owners. It runs once per matching subscription before the event is stored, so it should answer quickly (cache lookups) and fail closed.

type IntegrationEventInfo

type IntegrationEventInfo struct {
	Name        string          `json:"name"`
	Version     int             `json:"version"`
	Description string          `json:"description"`
	Permission  string          `json:"permission"`
	Producer    string          `json:"producer"`
	Allowed     bool            `json:"allowed"`
	Schema      json.RawMessage `json:"schema,omitempty"`
}

IntegrationEventInfo is an event type's discoverable contract.

type IntegrationGrant

type IntegrationGrant struct {
	Principal   string   `json:"principal"`
	Permissions []string `json:"permissions"`
}

IntegrationGrant gives the principal the permissions. Principal is "*" (every signed-in user and every automation), a typed identity principal (user:, group:, role:), or "site:<name>" for the site's automations. Permissions are exact names, "<prefix>.*" or "*".

func ParseIntegrationGrants

func ParseIntegrationGrants(value string) ([]IntegrationGrant, error)

ParseIntegrationGrants reads grants as a JSON object mapping principals to permission lists, e.g. {"role:hubspot.deals": ["hubspot.deals"], "*": ["slack.users"]}.

type IntegrationRegistry

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

IntegrationRegistry holds the platform's integrations and connectors. Its zero value is ready to use; registration validates and compiles contracts and is safe alongside requests.

func (*IntegrationRegistry) Register

func (r *IntegrationRegistry) Register(integration Integration) error

Register validates an integration and compiles its endpoint contracts. A connector it names must be registered first.

func (*IntegrationRegistry) RegisterConnector

func (r *IntegrationRegistry) RegisterConnector(connector Connector) error

RegisterConnector adds an OAuth connector that integrations can name.

func (*IntegrationRegistry) ValidateEvent

func (r *IntegrationRegistry) ValidateEvent(integration, name string, version int, data any) error

ValidateEvent checks data against an event's schema and size limit, as PublishIntegrationEvent does; hosts use it to test their webhook adapters.

type IntegrationStore

type IntegrationStore interface {
	GetIntegrationApproval(ctx context.Context, site, integration string) (IntegrationApproval, error)
	PutIntegrationApproval(ctx context.Context, approval IntegrationApproval) error
	DeleteIntegrationApproval(ctx context.Context, site, integration string) error
	// WithdrawIntegrationApproval atomically deletes only a pending request.
	// Approved/other states return ErrForbidden; missing records succeed.
	WithdrawIntegrationApproval(ctx context.Context, site, integration string) error
	ListIntegrationApprovals(ctx context.Context) ([]IntegrationApproval, error)

	GetCredential(ctx context.Context, owner, connector string) (CredentialRecord, error)
	PutCredential(ctx context.Context, record CredentialRecord) error
	UpdateCredential(ctx context.Context, record CredentialRecord) error
	TouchCredential(ctx context.Context, owner, connector, version string, usedAt time.Time) error
	DeleteCredentialVersion(ctx context.Context, owner, connector, version string) error
	WithCredentialLock(ctx context.Context, owner, connector string, fn func(context.Context) error) error
	DeleteCredential(ctx context.Context, owner, connector string) error
	ListCredentials(ctx context.Context, owner string) ([]CredentialRecord, error)
	DeleteCredentialsUnusedSince(ctx context.Context, cutoff time.Time) (int, error)
}

IntegrationStore persists integration approvals and connected-account credentials. A credential is the owner's sealed token plus metadata that is stored in the clear so connections can be listed without opening them. ListCredentials with an empty owner lists everyone's and leaves Sealed empty. Missing records return ErrNotFound.

PutCredential creates or replaces a connection and assigns fresh, globally unique Generation and Version values, ignoring those supplied by the caller. UpdateCredential changes only Sealed and LastUsedAt, atomically if Version still matches, and assigns a fresh Version while preserving Generation and connection metadata. TouchCredential and DeleteCredentialVersion also require a matching Version; a successful touch assigns a fresh Version as well. Conditional operations return ErrCredentialChanged for both missing and replaced records; they never recreate a deleted connection. LastUsedAt updates must be monotonic.

WithCredentialLock serializes refresh callbacks for an owner/connector across all servers sharing the store. It must honor cancellation while acquiring the lock, release it on every exit, and pass a context usable for store operations inside the callback. Callbacks must use that context, limit store operations to GetCredential and the conditional credential methods, and not nest locks. Successful store mutations persist even when the callback returns an error (for example, removing a revoked credential before returning ErrNotConnected). Explicit PutCredential/DeleteCredential and idle cleanup may run concurrently with a refresh: conditional writes prevent stale refreshes from affecting them.

type KeySealer

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

KeySealer seals with AES-256-GCM under a key held in process memory.

func NewKeySealer

func NewKeySealer(key []byte) (*KeySealer, error)

func (*KeySealer) Open

func (s *KeySealer) Open(_ context.Context, sealed, associated []byte) ([]byte, error)

func (*KeySealer) Seal

func (s *KeySealer) Seal(_ context.Context, plaintext, associated []byte) ([]byte, error)

type ListOptions

type ListOptions struct {
	After     string
	Limit     int
	CreatedBy string
	// MaxDocumentBytes rejects oversized documents before copying their data.
	// Zero means unrestricted. Providers must honor this limit when nonzero.
	MaxDocumentBytes int
}

ListOptions selects a page of documents. After is exclusive, Limit is 1–100, and a non-empty CreatedBy restricts results to that creator.

type NamedGroup

type NamedGroup struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

NamedGroup is an identity-provider group the platform offers by name.

func ParseGroups

func ParseGroups(value string) []NamedGroup

ParseGroups reads a "name=id,name=id" list, such as HEX_GROUPS.

type Object

type Object struct {
	Key  string `json:"key"`
	Size int64  `json:"size"`
}

type ObjectStore

type ObjectStore interface {
	Put(ctx context.Context, key string, source io.Reader) error
	Open(ctx context.Context, key string) (io.ReadCloser, error)
	List(ctx context.Context, prefix string) ([]Object, error)
	Delete(ctx context.Context, key string) error
}

type PathRule

type PathRule struct {
	Prefix  string   `json:"prefix"`
	Viewers Audience `json:"viewers"`
}

PathRule limits the static assets under Prefix to Viewers. Matching follows Config.PathCaseInsensitive, which must agree with the host's static storage.

type PeopleStore

type PeopleStore interface {
	RememberPerson(ctx context.Context, person Person) error
	FindPeople(ctx context.Context, query string, limit int) ([]Person, error)
	GetPeople(ctx context.Context, keys []string) ([]Person, error)
}

PeopleStore remembers the people who have signed in to the platform. FindPeople matches names and emails case-insensitively; GetPeople looks people up by exact identity ID or email. Email/name search may ignore case; identity IDs must retain the resolver's canonical spelling.

type PermissionGrant

type PermissionGrant struct {
	Kind       string           `json:"kind"`
	Resource   string           `json:"resource"`
	Except     []string         `json:"except,omitempty"`
	Operations []string         `json:"operations"`
	Subjects   Subjects         `json:"subjects"`
	Scope      *PermissionScope `json:"scope,omitempty"`
	Where      *RecordCondition `json:"where,omitempty"`
	Check      *RecordCondition `json:"check,omitempty"`
	Fields     []string         `json:"fields,omitzero"`
}

PermissionGrant authorizes a complete operation. Except makes fallback selectors explicit, including lossless migration of legacy wildcard rules.

type PermissionScope

type PermissionScope struct {
	Kind  string `json:"kind"`
	Field string `json:"field"`
}

type Person

type Person struct {
	ID    string `json:"id"`
	Name  string `json:"name,omitempty"`
	Email string `json:"email,omitempty"`
}

Person is a user as resolved by the identity provider.

type Publication

type Publication struct {
	PublishedAt time.Time `json:"publishedAt"`
	PublishedBy *Person   `json:"publishedBy,omitempty"`
	Files       int       `json:"files"`
	Bytes       int64     `json:"bytes"`
}

Publication is one entry in a site's publication history.

type Realtime

type Realtime interface {
	Subscribe(ctx context.Context, room string) (Subscription, error)
	Publish(ctx context.Context, room string, message json.RawMessage) error
}

type RecordCondition

type RecordCondition struct {
	All   []RecordCondition `json:"all,omitempty"`
	Any   []RecordCondition `json:"any,omitempty"`
	Field string            `json:"field,omitempty"`
	Op    string            `json:"op,omitempty"`
	Value json.RawMessage   `json:"value,omitempty"`
}

RecordCondition is a bounded expression tree, shared by the in-memory evaluator and PostgreSQL query compiler. A nil condition matches everything. Data fields start with data.; createdBy and id refer to server metadata.

func (*RecordCondition) Matches

func (condition *RecordCondition) Matches(document Document) bool

Matches evaluates a resolved condition. Missing fields never match, even ne.

type RequestOrigin

type RequestOrigin struct {
	Site string
}

RequestOrigin is supplied by the host, never by public routing headers.

type RoleBinding

type RoleBinding struct {
	Principal string     `json:"principal"`
	Role      string     `json:"role"`
	Scope     *RoleScope `json:"scope,omitempty"`
}

A binding has a stable map key and one principal, so a concurrent revocation and role/scope change conflict instead of resurrecting access through a union.

type RoleScope

type RoleScope struct {
	Kind string `json:"kind"`
	ID   string `json:"id"`
}

type ScheduledAutomation

type ScheduledAutomation struct {
	Site       string     `json:"site"`
	Automation Automation `json:"automation"`
	Revision   string     `json:"revision"`
	NextRun    time.Time  `json:"nextRun,omitzero"`
	UpdatedAt  time.Time  `json:"updatedAt"`
	UpdatedBy  *Person    `json:"updatedBy,omitempty"`
}

ScheduledAutomation includes the store-assigned revision and next run. A zero NextRun disables scheduling, including for manual-only automations.

type Server

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

func New

func New(config Config) *Server

func (*Server) DispatchEvents

func (s *Server) DispatchEvents(ctx context.Context) error

DispatchEvents processes a bounded page; useful to hosts and deterministic recovery tests. RunBackground continually scans all pending pages.

func (*Server) DispatchWorkflows

func (s *Server) DispatchWorkflows(ctx context.Context) error

func (*Server) PublishIntegrationEvent

func (s *Server) PublishIntegrationEvent(ctx context.Context, integration, name string, version int, idempotencyKey string, data any) (DurableEvent, error)

PublishIntegrationEvent records an event an integration observed and queues it for every subscribed automation that may receive it. data is a json.RawMessage or any value that marshals to JSON; it must match the event's schema. idempotencyKey (1–128 bytes) identifies the occurrence, such as the provider's own event ID, so provider retries publish once.

Events nobody receives are not stored. The returned event has an empty ID in that case, and repeated calls are then not deduplicated.

func (*Server) RunBackground

func (s *Server) RunBackground(ctx context.Context)

RunBackground performs the platform's scheduled work until ctx ends: running due automations, removing connected accounts that went unused and integration audit records past their retention. Hosts start it once per instance; it returns after automation runs in progress have finished.

func (*Server) ServeHTTP

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

type Site

type Site struct {
	Name     string        `json:"name"`
	URL      string        `json:"url"`
	Metadata *SiteMetadata `json:"metadata,omitempty"`
}

type SiteAIRequest

type SiteAIRequest struct {
	AIRequest
	IntegrationTools []string `json:"integrationTools,omitempty"`
}

SiteAIRequest is what apps send: a conversation turn plus integration endpoints, by "<integration>.<endpoint>" or "<integration>.*", that the server offers to the model and runs itself.

type SiteAccess

type SiteAccess struct {
	Version     int                        `json:"version,omitempty"`
	Admission   Subjects                   `json:"admission,omitzero"`
	Roles       map[string]ApplicationRole `json:"roles,omitempty"`
	Bindings    map[string]RoleBinding     `json:"bindings,omitempty"`
	Grants      map[string]PermissionGrant `json:"grants,omitempty"`
	Owners      []string                   `json:"owners"`
	Editors     []string                   `json:"editors,omitempty"`
	Viewers     []string                   `json:"viewers,omitempty"`
	Paths       []PathRule                 `json:"paths,omitempty"`
	Collections map[string]DataRule        `json:"collections,omitempty"`
	Files       map[string]DataRule        `json:"files,omitempty"`
	Channels    map[string]DataRule        `json:"channels,omitempty"`
	Published   *SiteAccess                `json:"published,omitempty"`
	// contains filtered or unexported fields
}

SiteAccess is the server-owned access policy for a site.

Version 2 separates Admission, management Owners, application Roles, scoped Bindings and operation Grants. Management authority never implicitly grants application access. Editors, Viewers, Paths and resource rule maps represent historical policies only; deployed policies migrate before authorization.

Published is server-owned: the access section of the site's last publication, against which the next publication is merged. Nil means no publication has recorded one yet. It is never returned to clients and is ignored in requested policies.

func CloneSiteAccess

func CloneSiteAccess(access SiteAccess) SiteAccess

CloneSiteAccess returns a deep copy, for stores that keep policies in memory.

func MigrateSiteAccess

func MigrateSiteAccess(old SiteAccess) SiteAccess

MigrateSiteAccess translates both live state and the last local publication. The published snapshot is deliberately not replaced with the merged policy.

func NormalizeSiteAccess

func NormalizeSiteAccess(access SiteAccess) SiteAccess

NormalizeSiteAccess replaces nil principal lists with empty ones so that stored and returned policies always carry arrays.

func (*SiteAccess) UnmarshalJSON

func (access *SiteAccess) UnmarshalJSON(data []byte) error

type SiteAccessBatchReader

type SiteAccessBatchReader interface {
	GetSiteAccessBatch(context.Context, []string) (map[string]SiteAccess, error)
}

AccessStore persists site access policies. Implementations return hex.ErrNotFound for sites without a policy; such sites are open to every authenticated user. Stores persist every field, including Published. SiteAccessBatchReader reads a fresh snapshot of the requested policies. Missing names are omitted. Implementations must not serve replica-local cached policy.

type SiteCall

type SiteCall struct {
	Target         string          `json:"target"`
	Action         string          `json:"action"`
	Version        int             `json:"version"`
	Input          json.RawMessage `json:"input"`
	IdempotencyKey string          `json:"idempotencyKey,omitempty"`
}

type SiteDirectory

type SiteDirectory interface {
	ListSites(ctx context.Context) ([]string, error)
}

type SiteEvent

type SiteEvent struct {
	ID    string    `json:"id"`
	At    time.Time `json:"at"`
	Site  string    `json:"site"`
	Kind  string    `json:"kind"`
	Title string    `json:"title,omitempty"`
	Actor *Person   `json:"actor,omitempty"`
}

type SiteFile

type SiteFile struct {
	Path string `json:"path"`
	Size int64  `json:"size"`
	MD5  string `json:"md5,omitempty"`
}

SiteFile describes one file of a published site. MD5 is the base64 Content-MD5 of the file, supplied by the publisher.

type SiteIntegration

type SiteIntegration struct {
	Name             string                    `json:"name"`
	Title            string                    `json:"title"`
	Description      string                    `json:"description,omitempty"`
	RequiresApproval bool                      `json:"requiresApproval"`
	Approval         string                    `json:"approval,omitempty"`
	Connection       *connectionStatus         `json:"connection,omitempty"`
	Endpoints        []IntegrationEndpointInfo `json:"endpoints"`
	// Events lists what the site's automations can subscribe to; Allowed
	// reports the platform permission and approval for the site.
	Events []IntegrationEventInfo `json:"events,omitempty"`
}

SiteIntegration is what a caller sees of one integration on a site. The endpoint list includes endpoints the caller may not use, marked as such, so apps can explain what access to ask for.

type SiteMetadata

type SiteMetadata struct {
	Title        string    `json:"title,omitempty"`
	Description  string    `json:"description,omitempty"`
	Author       string    `json:"author,omitempty"`
	Discoverable *bool     `json:"discoverable,omitempty"`
	PublishedAt  time.Time `json:"publishedAt"`
	PublishedBy  *Person   `json:"publishedBy,omitempty"`
	CreatedAt    time.Time `json:"createdAt,omitzero"`
	CreatedBy    *Person   `json:"createdBy,omitempty"`
	// Kind is "artifact" for files and folders published without hex.json,
	// empty for apps.
	Kind string `json:"kind,omitempty"`
}

SiteMetadata describes a published site. Title, Description, Author and Discoverable come from the publisher; the server records the rest from the identity provider when one is configured, so they cannot be claimed by a publisher.

func (*SiteMetadata) DisplayAuthor

func (m *SiteMetadata) DisplayAuthor() string

DisplayAuthor is who the site is shown as coming from: the verified creator when known, otherwise the publisher-supplied author.

type SiteMetadataReader

type SiteMetadataReader interface {
	ReadSiteMetadata(context.Context, string) (*SiteMetadata, error)
}

type SitePublisher

type SitePublisher interface {
	ListSiteFiles(ctx context.Context, site string) ([]SiteFile, error)
	ReadSiteFile(ctx context.Context, site, path string) (io.ReadCloser, error)
	WriteSiteFile(ctx context.Context, site, path string, size int64, source io.Reader) error
	DeleteSiteFile(ctx context.Context, site, path string) error
	DeleteSite(ctx context.Context, site string) error
}

SitePublisher writes published site files on behalf of authorized publishers. Paths are relative to the site's directory and use forward slashes. ListSiteFiles returns every regular file, including the server-owned dotfiles; sizes must be exact, MD5 is optional.

type SiteRecordReader

type SiteRecordReader interface {
	ReadSiteFile(context.Context, string, string) (io.ReadCloser, error)
}

SiteRecordReader reads server-owned metadata/history without granting writes. Site directories and publishers may implement it independently.

type SiteTrafficReader

type SiteTrafficReader interface {
	SiteTraffic(context.Context, []string) ([]AnalyticsRow, error)
}

SiteTrafficReader supplies all recorded traffic for specific sites, without returning visitor identities. Portals call it only for authorized listings.

type StaticIdentity

type StaticIdentity struct {
	Identity Identity
}

StaticIdentity resolves every request to one fixed identity. It exists for local development, where no authenticating gateway runs.

func (StaticIdentity) ResolveIdentity

func (s StaticIdentity) ResolveIdentity(*http.Request) (*Identity, error)

type Subjects

type Subjects struct {
	// Workspace matches only authenticated, server-brokered cross-site calls.
	Workspace  bool     `json:"workspace,omitempty"`
	SignedIn   bool     `json:"signedIn,omitempty"`
	Owners     bool     `json:"owners,omitempty"`
	Principals []string `json:"principals,omitempty"`
	Roles      []string `json:"roles,omitempty"`
}

Subjects selects callers, not records. Owners is explicit: site management authority alone never bypasses a version 2 application's data permissions.

type Subscription

type Subscription interface {
	Messages() <-chan json.RawMessage
	Close()
}

type TrafficBucket

type TrafficBucket struct {
	Day    time.Time
	Site   string
	UserID string
	TrafficTotals
}

type TrafficCollector

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

TrafficCollector receives NGINX syslog datagrams on loopback only. A bounded queue isolates page delivery from database latency. Successful batches are durable/idempotent; UDP delivery itself is best effort, not billing-grade.

func StartTrafficCollector

func StartTrafficCollector(ctx context.Context, address string, store AnalyticsStore) (*TrafficCollector, error)

func (*TrafficCollector) Address

func (c *TrafficCollector) Address() string

func (*TrafficCollector) Close

func (c *TrafficCollector) Close() error

func (*TrafficCollector) Status

type TrafficCollectorStatus

type TrafficCollectorStatus struct {
	Running       bool      `json:"running"`
	Received      uint64    `json:"received"`
	Recorded      uint64    `json:"recorded"`
	Rejected      uint64    `json:"rejected"`
	Dropped       uint64    `json:"dropped"`
	WriteFailures uint64    `json:"writeFailures"`
	LastReceived  time.Time `json:"lastReceived,omitzero"`
	LastError     string    `json:"lastError,omitempty"`
}

type TrafficEvent

type TrafficEvent struct {
	ID             string
	At             time.Time
	Site           string
	UserID         string
	PageView       bool
	Status         int
	Bytes          int64
	DurationMillis int64
}

type TrafficTotals

type TrafficTotals struct {
	Requests       int64     `json:"requests"`
	PageViews      int64     `json:"pageViews"`
	Visits         int64     `json:"visits"`
	Visitors       int       `json:"visitors"`
	Errors         int64     `json:"errors"`
	Bytes          int64     `json:"bytes"`
	DurationMillis int64     `json:"durationMillis"`
	LastVisited    time.Time `json:"lastVisited,omitzero"`
}

func (TrafficTotals) AverageMillis

func (t TrafficTotals) AverageMillis() int64

type UploadTarget

type UploadTarget struct {
	Path     string            `json:"path"`
	Protocol string            `json:"protocol"`
	URL      string            `json:"url"`
	Headers  map[string]string `json:"headers,omitempty"`
}

UploadTarget tells the publisher where to send one file. Protocol "hex" is a plain PUT of the file body to URL, authenticated like other API calls; "http" is a signed HTTP PUT with optional storage headers and no Hex credentials; "azure-files" accepts Azure Create File and Put Range requests.

type Workflow

type Workflow struct {
	ActorProvider string                  `json:"actorProvider"`
	ID            string                  `json:"id"`
	Site          string                  `json:"site"`
	Actor         string                  `json:"actor"`
	Definition    ScheduledAutomation     `json:"definition"`
	Input         json.RawMessage         `json:"input"`
	Fingerprint   string                  `json:"fingerprint"`
	Status        string                  `json:"status"`
	Pending       bool                    `json:"pending"`
	Attempts      int                     `json:"attempts"`
	Failures      int                     `json:"failures"`
	CreatedAt     time.Time               `json:"createdAt"`
	NextAttempt   time.Time               `json:"nextAttempt"`
	Lease         string                  `json:"lease,omitempty"`
	LeaseUntil    time.Time               `json:"leaseUntil,omitzero"`
	RunID         string                  `json:"runId,omitempty"`
	Output        json.RawMessage         `json:"output,omitempty"`
	Error         string                  `json:"error,omitempty"`
	Steps         map[string]WorkflowStep `json:"steps"`
}

Workflow jobs pin their script and input. Completed steps are stored in the same guarded record as the lease, so stale workers cannot commit checkpoints.

type WorkflowStep

type WorkflowStep struct {
	Done   bool            `json:"done"`
	Output json.RawMessage `json:"output,omitempty"`
	WakeAt time.Time       `json:"wakeAt,omitzero"`
}

type WriteOptions

type WriteOptions struct {
	Creator     string
	CreatorOnly bool
}

WriteOptions controls document writes and deletions. Put returns the stored document, including its original creator. Creator is recorded when a document is inserted and never changed by later writes. With CreatorOnly, an existing document is replaced or deleted only when it was created by Creator; otherwise the operation returns ErrForbidden.

Directories

Path Synopsis
providers
anthropic
Package anthropic is a Hex AI provider for the Anthropic Messages API, called over plain HTTP so the same code serves the Claude API and Claude deployments in Azure AI Foundry (whose base URL and authentication differ; the Go SDK does not support Foundry).
Package anthropic is a Hex AI provider for the Anthropic Messages API, called over plain HTTP so the same code serves the Claude API and Claude deployments in Azure AI Foundry (whose base URL and authentication differ; the Go SDK does not support Foundry).
azurefiles
Package azurefiles publishes sites to an Azure Files share.
Package azurefiles publishes sites to an Azure Files share.
easyauth
Package easyauth resolves request identities from the headers that Azure App Service and Container Apps built-in authentication ("Easy Auth") injects into proxied requests.
Package easyauth resolves request identities from the headers that Azure App Service and Container Apps built-in authentication ("Easy Auth") injects into proxied requests.
foundry
Package foundry is a Hex AI provider for models deployed in Azure AI Foundry.
Package foundry is a Hex AI provider for models deployed in Azure AI Foundry.
keyvault
Package keyvault seals connected-account tokens with envelope encryption under an Azure Key Vault key.
Package keyvault seals connected-account tokens with envelope encryption under an Azure Key Vault key.
openai
Package openai is a Hex AI provider for OpenAI-compatible APIs, including the Azure OpenAI v1 API and other models in Azure AI Foundry ({endpoint}/openai/v1).
Package openai is a Hex AI provider for OpenAI-compatible APIs, including the Azure OpenAI v1 API and other models in Azure AI Foundry ({endpoint}/openai/v1).
s3
Package s3 provides opt-in S3-compatible object storage and site publishing.
Package s3 provides opt-in S3-compatible object storage and site publishing.

Jump to

Keyboard shortcuts

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