ai

package
v1.8.3 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: AGPL-3.0 Imports: 70 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 ai is the AI assistant with the workspace's own model (design expansion, phase 3, M22): the connection in Settings › Integrations' "AI models" group (one model per workspace, a write-only key, the features switched on, a monthly cap and the prices it is estimated with), the suggestions (subject ideas, rewrites, translations of a language version, alt text, accessibility fixes, segment drafts and report summaries), the AI activity log and the usage meter.

What leaves the instance is the content a person is working on, when they ask, and only for the features switched on. Prompts are templates in this package with the person's content delimited; contact data is never put in them: personalization tokens go as written, a preview "as a contact" is never sent, segment drafts get the condition schema without any contact's values, and report summaries get the report's aggregate numbers.

Every suggestion is an answer to accept or reject: nothing here changes an email, a segment or a report by itself. Accepted text goes through the composer's own saves (the version history); a kept summary and an accepted translation are written by the operations that say so. Each request is in the AI activity log (90 days, never the content); the configuration's changes are audited.

Index

Constants

View Source
const (
	FeatureSubjectIdeas   = "subject_ideas"
	FeatureRewrite        = "rewrite"
	FeatureTranslate      = "translate"
	FeatureAltText        = "alt_text"
	FeatureAccessibility  = "accessibility_fix"
	FeatureSegment        = "segment_draft"
	FeatureSummary        = "report_summary"
	FeatureBrandVoice     = "brand_voice"
	FeatureDraft          = "draft"
	FeatureAgent          = "agent"
	FeatureConnectionTest = "connection_test"
	// FeatureAssistant is the assistant's threads (B3); it has a default
	// model already.
	FeatureAssistant = "assistant"
)

Features, each with its own switch.

View Source
const (
	OutcomePending        = "pending"
	OutcomeAccepted       = "accepted"
	OutcomeAcceptedEdits  = "accepted_edits"
	OutcomeKept           = "kept"
	OutcomeRejected       = "rejected"
	OutcomeDiscarded      = "discarded"
	OutcomeRefused        = "refused"
	OutcomeError          = "error"
	OutcomeNothingDrafted = "nothing_drafted"
	OutcomeCancelled      = "cancelled"
	// OutcomeAnswered is an assistant turn's answer (B3).
	OutcomeAnswered = "answered"
)

Outcomes of a request in the activity log.

View Source
const MaxImageWidth = 1024

MaxImageWidth is how wide an image goes to the model (1,024 px).

View Source
const NoticeShare = 0.8

NoticeShare is when the usage notice goes out (80% of the cap).

View Source
const Retention = 90 * 24 * time.Hour

Retention of the activity log.

Variables

Features in the settings' order.

Functions

func AsksAboutReputation

func AsksAboutReputation(text string) bool

AsksAboutReputation reports whether a message asks to diagnose sender reputation, a blocklisting or spam placement: HostRepute's, not the assistant's. Setup questions (DKIM, SPF, DMARC) are the model's.

func DemoToolsPassed

func DemoToolsPassed(ctx context.Context, q *store.Queries, ws, model uuid.UUID, at time.Time) error

DemoToolsPassed records the demo's sample model as having passed the tool-calling check at at, as running the check in development would (the demo seed): the assistant needs a passed check. Only the sample model.

func Register

func Register(h huma.API, s *Service)

Register adds the assistant's operations. Its settings, usage and log need integrations:view; changing them integrations:manage ⚑ (people only). The suggestions need ai:use, which API keys and MCP agents can't hold: agents bring their own model.

func RegisterJobs

func RegisterJobs(reg *jobs.Registry, s *Service)

RegisterJobs adds the assistant's job: the 90-day retention, every 6 hours.

Types

type AIAcceptedBlock

type AIAcceptedBlock struct {
	Index    int                 `json:"index" minimum:"0"`
	Segments []AIAcceptedSegment `json:"segments" maxItems:"200"`
	// Edited: the person changed the suggestion before accepting it.
	Edited bool `json:"edited,omitempty"`
}

AIAcceptedBlock is an accepted block.

type AIAcceptedSegment

type AIAcceptedSegment struct {
	Path []int  `json:"path"`
	Kind string `json:"kind" enum:"text,button,nav,image,social,table"`
	Text string `json:"text" maxLength:"60000"`
}

AIAcceptedSegment is a segment's accepted text (the suggestion, or what the person made of it).

type AIAccountInput

type AIAccountInput struct {
	Provider string `json:"provider" enum:"anthropic,openai,google,azure,compatible"`
	// Label names a server the workspace runs ("Ollama on the office network").
	Label string `json:"label,omitempty" maxLength:"80"`
	// BaseURL: the Azure endpoint, or a compatible server's address with /v1.
	BaseURL    string `json:"baseUrl,omitempty" maxLength:"500"`
	Deployment string `json:"deployment,omitempty" maxLength:"120"`
	APIVersion string `json:"apiVersion,omitempty" maxLength:"40"`
	// APIKey is write-only; optional for a server on the workspace's network.
	APIKey    string `json:"apiKey,omitempty" maxLength:"500"`
	Model     string `json:"model" minLength:"1" maxLength:"120"`
	ModelName string `json:"modelName,omitempty" maxLength:"120"`
	// Prices in dollars per million tokens; empty takes the price list's.
	InputPrice  *float64 `json:"inputPrice,omitempty" minimum:"0"`
	OutputPrice *float64 `json:"outputPrice,omitempty" minimum:"0"`
}

AIAccountInput adds a model account with its first model.

type AIAccountModelInput

type AIAccountModelInput struct {
	Model     string `json:"model" minLength:"1" maxLength:"120"`
	ModelName string `json:"modelName,omitempty" maxLength:"120"`
	// Deployment: Azure OpenAI's deployment of the model (the model's name
	// when empty).
	Deployment string `json:"deployment,omitempty" maxLength:"120"`
	// Prices follow the price list for a known model unless given.
	InputPrice  *float64 `json:"inputPrice,omitempty" minimum:"0"`
	OutputPrice *float64 `json:"outputPrice,omitempty" minimum:"0"`
}

AIAccountModelInput adds a model to an account.

type AIAccountView

type AIAccountView struct {
	ID           uuid.UUID `json:"id"`
	Provider     string    `json:"provider" enum:"anthropic,openai,google,azure,compatible"`
	ProviderName string    `json:"providerName"`
	// Preset is the hosted OpenAI-compatible service the address belongs to.
	Preset     string    `json:"preset,omitempty"`
	Label      string    `json:"label,omitempty"`
	BaseURL    string    `json:"baseUrl,omitempty"`
	APIVersion string    `json:"apiVersion,omitempty"`
	Key        AIKeyView `json:"key"`
	// Status: connected, key_rejected (the provider rejected the saved key)
	// or disconnected (the key was removed).
	Status       string      `json:"status" enum:"connected,key_rejected,disconnected"`
	StatusDetail string      `json:"statusDetail,omitempty"`
	StatusAt     *time.Time  `json:"statusAt,omitempty"`
	LastTest     *AITestView `json:"lastTest,omitempty"`
	ConnectedAt  time.Time   `json:"connectedAt"`
	ConnectedBy  string      `json:"connectedBy,omitempty"`
	// PrivateNetwork: the server's address is a private one.
	PrivateNetwork bool `json:"privateNetwork"`
	Demo           bool `json:"demo"`
	// Primary is the first account: the one the single-model settings show.
	Primary bool          `json:"primary"`
	Models  []AIModelView `json:"models"`
}

AIAccountView is a model account with its models. The key is never returned: only whether one is set, and when.

type AIActivityFilter

type AIActivityFilter struct {
	Member  string
	Feature string
	// Outcome: accepted (with edits and kept too), rejected (discarded too),
	// refused, error, or any.
	Outcome string
	Cursor  string
	Limit   int
}

AIActivityFilter narrows the log.

type AIActivityList

type AIActivityList struct {
	Items []AIActivityRow `json:"items"`
	// MonthRequests counts this month's requests; Members are the members
	// in the log, for the filter.
	MonthRequests int64              `json:"monthRequests"`
	Members       []AIActivityMember `json:"members"`
	Next          string             `json:"next,omitempty"`
	RetentionDays int                `json:"retentionDays"`
}

AIActivityList is a page of the log.

type AIActivityMember

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

AIActivityMember is a member who asked this month, for the filter.

type AIActivityRow

type AIActivityRow struct {
	ID           string    `json:"id"`
	At           time.Time `json:"at"`
	UserID       string    `json:"userId,omitempty"`
	Member       string    `json:"member"`
	MemberColor  string    `json:"memberColor,omitempty"`
	Feature      string    `` /* 159-byte string literal not displayed */
	Action       string    `json:"action,omitempty" doc:"The rewrite's action, or the language translated to"`
	TargetKind   string    `json:"targetKind,omitempty"`
	TargetID     string    `json:"targetId,omitempty"`
	On           string    `json:"on" doc:"What it was about: Weekly Digest #143"`
	Provider     string    `json:"provider"`
	Model        string    `json:"model"`
	Tokens       int64     `json:"tokens"`
	InputTokens  int64     `json:"inputTokens"`
	OutputTokens int64     `json:"outputTokens"`
	CostMicros   int64     `json:"costMicros"`
	UsageKnown   bool      `json:"usageKnown"`
	Outcome      string    `` /* 126-byte string literal not displayed */
	Detail       string    `json:"detail,omitempty" doc:"1 of 5, 529 overloaded"`
	// Personal: sent with the member's own key (personal keys), in their
	// own budget.
	Personal bool `json:"personal"`
}

AIActivityRow is one request of the AI activity log. It never holds what was sent or returned.

type AIAgentAction

type AIAgentAction struct {
	SharingReviewed bool                      `` /* 155-byte string literal not displayed */
	Version         int64                     `json:"version" minimum:"1"`
	PlanRevision    int64                     `json:"planRevision" minimum:"0"`
	Action          string                    `json:"action" enum:"build,cancel,continue,answer,revise,replan,propose,refresh"`
	Message         string                    `json:"message,omitempty" maxLength:"4000"`
	Handle          string                    `json:"handle,omitempty" pattern:"^[a-z][a-z0-9_]{0,39}$"`
	PlanDiscards    []AIAgentArtifactRevision `` /* 132-byte string literal not displayed */
}

type AIAgentArtifact

type AIAgentArtifact struct {
	ID               uuid.UUID                    `json:"id"`
	Handle           string                       `json:"handle"`
	Kind             string                       `json:"kind" enum:"campaign,segment,automation,post"`
	Bundle           string                       `json:"bundle"`
	Revision         int64                        `json:"revision"`
	Decision         string                       `json:"decision"`
	TargetID         *uuid.UUID                   `json:"targetId,omitempty"`
	ResultID         *uuid.UUID                   `json:"resultId,omitempty"`
	Name             string                       `json:"name"`
	Before           *AIDraftEmail                `json:"before,omitempty"`
	Email            *AIDraftEmail                `json:"email,omitempty"`
	Post             *AIAgentPost                 `json:"post,omitempty"`
	HTML             string                       `json:"html,omitempty"`
	Segment          *segments.SegmentDefinition  `json:"segment,omitempty"`
	Automation       *AIAutomationContent         `json:"automation,omitempty"`
	TriggerName      string                       `json:"triggerName,omitempty" doc:"Human review only; the selected list or segment name is never model context"`
	Previews         []string                     `json:"previews,omitempty"`
	BeforeAutomation *automations.AutomationGraph `json:"beforeAutomation,omitempty"`
	BeforeEmails     []AIAutomationEmailBefore    `json:"beforeEmails,omitempty"`
}

type AIAgentArtifactRevision

type AIAgentArtifactRevision struct {
	ID       uuid.UUID `json:"id"`
	Revision int64     `json:"revision" minimum:"1"`
}

type AIAgentAudienceSnapshot

type AIAgentAudienceSnapshot struct {
	Count    *int64    `json:"count,omitempty"`
	Total    *int64    `json:"total,omitempty"`
	Status   string    `json:"status"`
	At       time.Time `json:"at"`
	Rounding int64     `json:"rounding"`
}

type AIAgentAutomationSelection

type AIAgentAutomationSelection struct {
	Trigger      string     `json:"trigger" enum:"joined_list,segment_entered,segment_left"`
	ListID       *uuid.UUID `json:"listId,omitempty"`
	SegmentID    *uuid.UUID `json:"segmentId,omitempty"`
	FromAudience bool       `json:"fromAudience"`
}

Audience semantics are selected by a person, not inferred from model text. FromAudience binds to a segment in the same confirmed dependency bundle.

type AIAgentBrief

type AIAgentBrief struct {
	SharingReviewed bool                        `` /* 143-byte string literal not displayed */
	Brief           string                      `json:"brief" minLength:"1" maxLength:"4000"`
	Language        string                      `json:"language" enum:"en,vi,de,es,fr"`
	Kind            string                      `json:"kind,omitempty" enum:"campaign,post" doc:"Primary draft kind; campaign when omitted"`
	CampaignID      *uuid.UUID                  `json:"campaignId,omitempty"`
	BaseRevision    int64                       `json:"baseRevision,omitempty" minimum:"0"`
	TemplateID      string                      `json:"templateId,omitempty" maxLength:"100"`
	Links           []string                    `json:"links,omitempty" maxItems:"10"`
	VoiceRevision   *int32                      `json:"voiceRevision,omitempty" minimum:"0"`
	Audience        *segments.SegmentDefinition `json:"audience,omitempty" doc:"Explicit builder conditions; literal values stay on this instance"`
	Automation      *AIAgentAutomationSelection `json:"automation,omitempty"`
	ReportID        *uuid.UUID                  `json:"reportId,omitempty" doc:"Explicitly selected completed campaign; only its fixed aggregate snapshot reaches the model"`
	PoolID          *uuid.UUID                  `json:"poolId,omitempty" doc:"Selected discount pool for new emails; codes are never read or reserved"`
	RequestKey      string                      `` /* 191-byte string literal not displayed */
}

Agent runs never store product objects until a human keeps their staging bundle. Resource IDs and bindings below stay local, outside model messages.

type AIAgentCapability

type AIAgentCapability struct {
	State     string     `json:"state" enum:"untested,supported,unsupported"`
	CheckedAt *time.Time `json:"checkedAt,omitempty"`
}

type AIAgentCostEstimate

type AIAgentCostEstimate struct {
	LowMicros  int64     `json:"lowMicros"`
	HighMicros int64     `json:"highMicros"`
	PricingAt  time.Time `json:"pricingAt"`
}

Cost scenarios are planning aids, not reservations or invoice guarantees. They exclude work already staged and use the connection's current prices.

type AIAgentDecision

type AIAgentDecision struct {
	Version   int64                     `json:"version" minimum:"1"`
	Decision  string                    `json:"decision" enum:"kept,discarded,accepted,rejected"`
	Artifacts []AIAgentArtifactRevision `json:"artifacts" minItems:"1" maxItems:"10"`
}

type AIAgentLimitChange

type AIAgentLimitChange struct {
	Version int64         `json:"version" minimum:"1"`
	Limits  AIAgentLimits `json:"limits"`
}

type AIAgentLimits

type AIAgentLimits struct {
	ToolCalls  int32 `json:"toolCalls" minimum:"1" maximum:"200"`
	Tokens     int64 `json:"tokens" minimum:"1000" maximum:"2000000"`
	CostMicros int64 `json:"costMicros" minimum:"1" maximum:"100000000"`
}

type AIAgentMessage

type AIAgentMessage struct {
	Role   string    `json:"role" enum:"user,assistant"`
	Text   string    `json:"text"`
	Handle string    `json:"handle,omitempty"`
	At     time.Time `json:"at"`
}

Conversation contains only visible user/assistant text. Provider messages, function arguments and private thought parts remain separate checkpoints.

type AIAgentOperation

type AIAgentOperation struct {
	Tool   string `json:"tool" enum:"propose_plan,stage_campaign,stage_segment,stage_automation,stage_post,inspect_audience,read_report,denied"`
	Handle string `json:"handle,omitempty"`
	Code   string `json:"code"`
	Failed bool   `json:"failed"`
}

type AIAgentPlan

type AIAgentPlan struct {
	Summary   string            `json:"summary" minLength:"1" maxLength:"2000"`
	Items     []AIAgentPlanItem `json:"items" maxItems:"10"`
	Questions []string          `json:"questions" maxItems:"3"`
}

type AIAgentPlanItem

type AIAgentPlanItem struct {
	Handle    string   `json:"handle" pattern:"^[a-z][a-z0-9_]{0,39}$"`
	Kind      string   `json:"kind" enum:"campaign,segment,automation,post"`
	Name      string   `json:"name" minLength:"1" maxLength:"200"`
	Purpose   string   `json:"purpose" minLength:"1" maxLength:"1000"`
	Bundle    string   `json:"bundle" pattern:"^[a-z][a-z0-9_]{0,39}$"`
	Target    string   `json:"target,omitempty" maxLength:"40"`
	DependsOn []string `json:"dependsOn" maxItems:"10" uniqueItems:"true"`
}

type AIAgentPoolSnapshot

type AIAgentPoolSnapshot struct {
	Name      string    `json:"name"`
	Slug      string    `json:"slug"`
	Source    string    `json:"source"`
	Free      int64     `json:"free"`
	At        time.Time `json:"at"`
	UpdatedAt time.Time `json:"updatedAt"`
}

Names and Liquid expressions are human review data. The model receives only fixed inventory metadata and the source's existing opaque bindings.

type AIAgentPost

type AIAgentPost struct {
	Title   string `json:"title" minLength:"1" maxLength:"200"`
	Excerpt string `json:"excerpt" maxLength:"200"`
	MJML    string `json:"mjml" minLength:"1" maxLength:"100000"`
}

type AIAgentRunList

type AIAgentRunList struct {
	Items []AIAgentRunListItem `json:"items"`
	Next  string               `json:"next,omitempty"`
}

type AIAgentRunListItem

type AIAgentRunListItem struct {
	ID         uuid.UUID `json:"id"`
	OwnerID    uuid.UUID `json:"ownerId"`
	OwnerName  string    `json:"ownerName"`
	Title      string    `json:"title"`
	Model      string    `json:"model"`
	State      string    `json:"state"`
	UpdatedAt  time.Time `json:"updatedAt"`
	ExpiresAt  time.Time `json:"expiresAt"`
	Tokens     int64     `json:"tokens"`
	CostMicros int64     `json:"costMicros"`
	Uncertain  bool      `json:"uncertain"`
}

type AIAgentRunView

type AIAgentRunView struct {
	ID               uuid.UUID                 `json:"id"`
	OwnerID          uuid.UUID                 `json:"ownerId"`
	State            string                    `json:"state" enum:"brief,planning,needs_answers,ready,queued,building,paused,review,completed,cancelled,expired"`
	Version          int64                     `json:"version"`
	PlanRevision     int64                     `json:"planRevision"`
	AcceptedRevision int64                     `json:"acceptedRevision"`
	PauseReason      string                    `json:"pauseReason"`
	Limits           AIAgentLimits             `json:"limits"`
	ToolCalls        int32                     `json:"toolCalls"`
	Tokens           int64                     `json:"tokens"`
	CostMicros       int64                     `json:"costMicros"`
	Uncertain        bool                      `json:"uncertain"`
	Model            string                    `json:"model"`
	QueuePosition    int64                     `json:"queuePosition,omitempty" doc:"Waiting position snapshot; per-user execution limits can change ordering"`
	CreatedAt        time.Time                 `json:"createdAt"`
	UpdatedAt        time.Time                 `json:"updatedAt"`
	ExpiresAt        time.Time                 `json:"expiresAt"`
	Brief            *AIAgentBrief             `json:"brief,omitempty"`
	Plan             *AIAgentPlan              `json:"plan,omitempty"`
	PlanDiscards     []AIAgentArtifactRevision `json:"planDiscards" doc:"Exact staging revisions that confirming this plan discards; kept resources are never included"`
	Audience         *AIAgentAudienceSnapshot  `json:"audience,omitempty"`
	Report           *reports.ModelSnapshot    `json:"report,omitempty"`
	Pool             *AIAgentPoolSnapshot      `json:"pool,omitempty"`
	Estimate         *AIAgentCostEstimate      `` /* 152-byte string literal not displayed */
	Artifacts        []AIAgentArtifact         `json:"artifacts"`
	Steps            []AIAgentStepView         `json:"steps"`
	Conversation     []AIAgentMessage          `json:"conversation"`
}

type AIAgentSettings

type AIAgentSettings struct {
	Enabled    bool               `json:"enabled"`
	Limits     AIAgentLimits      `json:"limits"`
	Revision   int64              `json:"revision"`
	Capability *AIAgentCapability `json:"capability,omitempty" readOnly:"true"`
}

type AIAgentStepView

type AIAgentStepView struct {
	Sequence   int32              `json:"sequence"`
	State      string             `json:"state"`
	CreatedAt  time.Time          `json:"createdAt"`
	UpdatedAt  time.Time          `json:"updatedAt"`
	Operations []AIAgentOperation `json:"operations"`
}

A public step names operations and fixed outcomes, never provider messages, arguments, reasoning, credentials or a raw validator/database error.

type AIAltText

type AIAltText struct {
	RequestID  string `json:"requestId,omitempty"`
	Text       string `json:"text"`
	Characters int    `json:"characters"`
	// FileName is the image's file name ("oncall-heatmap.png").
	FileName string `json:"fileName"`
	// Checks: under 150 characters, doesn't start with "Image of", more
	// than the file name.
	Short     bool   `json:"short"`
	NoImageOf bool   `json:"noImageOf"`
	SaysWhat  bool   `json:"saysWhat"`
	Sent      AISent `json:"sent"`
	Refusal   string `json:"refusal,omitempty"`
}

AIAltText is an alt text suggestion with its checks.

type AIAltTextInput

type AIAltTextInput struct {
	CampaignID string `json:"campaignId" format:"uuid"`
	// Src is the image's address (the media library's, or any https URL).
	Src string `json:"src" maxLength:"2000"`
	// Context is the text around the image.
	Context  string `json:"context,omitempty" maxLength:"4000"`
	Language string `json:"language,omitempty" maxLength:"12"`
}

AIAltTextInput asks for an image's alt text.

type AIAssistantModel

type AIAssistantModel struct {
	ID           uuid.UUID    `json:"id"`
	AccountID    uuid.UUID    `json:"accountId"`
	Provider     string       `json:"provider" enum:"anthropic,openai,google,azure,compatible"`
	ProviderName string       `json:"providerName"`
	Model        string       `json:"model"`
	ModelName    string       `json:"modelName"`
	ImageInput   bool         `json:"imageInput"`
	Prices       AIPricesView `json:"prices"`
	// Personal: the model is on the caller's own key.
	Personal bool `json:"personal"`
	// Tools is its tool-calling check; the assistant needs one that passed.
	Tools AIAgentCapability `json:"tools"`
	// Usable: a thread can use it now; Reason says why it can't.
	Usable bool   `json:"usable"`
	Reason string `json:"reason,omitempty" enum:"disconnected,key_rejected,tools_unchecked,personal_keys_off"`
}

AIAssistantModel is a model the assistant can use, as the model picker shows it: its account, prices and whether a thread can use it now.

type AIAssistantModelList

type AIAssistantModelList struct {
	Models []AIAssistantModel `json:"models"`
	// DefaultID is the model a new thread uses: the caller's own pick for
	// the assistant, or else the workspace's.
	DefaultID *uuid.UUID `json:"defaultId,omitempty" format:"uuid"`
}

AIAssistantModelList is the models the caller may pick for a thread.

type AIAssistantSettings

type AIAssistantSettings struct {
	Enabled bool          `json:"enabled"`
	Limits  AIAgentLimits `json:"limits"`
	// PerPerson and PerWorkspace bound the turns answering at once (one per
	// thread), apart from agent runs.
	PerPerson    int32 `json:"perPerson" minimum:"1" maximum:"10"`
	PerWorkspace int32 `json:"perWorkspace" minimum:"1" maximum:"100"`
	// Revision is the settings' version: a change names the one it read.
	Revision int64 `json:"revision" minimum:"0"`
}

AIAssistantSettings are the assistant's settings. Limits are each new thread's cumulative ceilings.

type AIAutomationBriefInput

type AIAutomationBriefInput struct {
	SharingReviewed bool       `` /* 143-byte string literal not displayed */
	Brief           string     `json:"brief" minLength:"1" maxLength:"4000"`
	Name            string     `json:"name" minLength:"1" maxLength:"200"`
	Language        string     `json:"language" enum:"en,vi,de,es,fr"`
	ListID          uuid.UUID  `json:"listId"`
	AutomationID    *uuid.UUID `json:"automationId,omitempty"`
	BaseRevision    int64      `json:"baseRevision,omitempty" minimum:"0"`
	TemplateID      string     `json:"templateId,omitempty" maxLength:"100"`
	Links           []string   `json:"links,omitempty" maxItems:"10"`
	VoiceRevision   *int32     `json:"voiceRevision,omitempty" minimum:"0"`
}

AIAutomationBriefInput keeps enrollment semantics outside model output. This one-shot recipe supports consented, future list joins only. More complex audience conditions require the full agent's reviewed plan.

type AIAutomationContent

type AIAutomationContent struct {
	Graph  automations.AutomationGraph `json:"graph"`
	Emails []automations.ProposedEmail `json:"emails" minItems:"1" maxItems:"5"`
}

type AIAutomationEmailBefore

type AIAutomationEmailBefore struct {
	Key     string       `json:"key"`
	ID      uuid.UUID    `json:"id"`
	Version int32        `json:"version"`
	Name    string       `json:"name"`
	Content AIDraftEmail `json:"content"`
	HTML    string       `json:"html"`
}

type AIAutomationProposal

type AIAutomationProposal struct {
	ID           uuid.UUID                    `json:"id"`
	Name         string                       `json:"name"`
	AutomationID *uuid.UUID                   `json:"automationId,omitempty"`
	BaseRevision int64                        `json:"baseRevision"`
	ListID       uuid.UUID                    `json:"listId"`
	Before       *automations.AutomationGraph `json:"before,omitempty"`
	BeforeEmails []AIAutomationEmailBefore    `json:"beforeEmails"`
	Content      AIAutomationContent          `json:"content"`
	Previews     []string                     `json:"previews" doc:"Compiled email previews, in content.emails order; no personalization rendering"`
	Sent         AISent                       `json:"sent"`
	ExpiresAt    time.Time                    `json:"expiresAt"`
	Decision     string                       `json:"decision" enum:",accepted,rejected"`
}

type AIBudgetHold

type AIBudgetHold struct {
	ID                 uuid.UUID `json:"id"`
	Provider           string    `json:"provider"`
	Model              string    `json:"model"`
	CreatedAt          time.Time `json:"createdAt"`
	ReservedTokens     int64     `json:"reservedTokens"`
	ReservedCostMicros int64     `json:"reservedCostMicros"`
	ReconcileAfter     time.Time `json:"reconcileAfter"`
}

AIBudgetHold is content-free; projections never expose the saved prompt, tool results, credentials or a resource's title to integration managers.

type AIBudgetHolds

type AIBudgetHolds struct {
	Items []AIBudgetHold `json:"items"`
}

type AIBudgetReconcileInput

type AIBudgetReconcileInput struct {
	InputTokens  int  `json:"inputTokens" minimum:"0" maximum:"1000000000"`
	OutputTokens int  `json:"outputTokens" minimum:"0" maximum:"1000000000"`
	Confirmed    bool `json:"confirmed" doc:"The manager verified these counts with the provider; zero means confirmed non-billable, not unknown"`
}

type AICampaignBriefInput

type AICampaignBriefInput struct {
	SharingReviewed bool       `` /* 143-byte string literal not displayed */
	Brief           string     `json:"brief" minLength:"1" maxLength:"4000"`
	Name            string     `json:"name" minLength:"1" maxLength:"200"`
	Language        string     `json:"language" enum:"en,vi,de,es,fr"`
	TemplateID      string     `json:"templateId,omitempty" maxLength:"100"`
	CampaignID      *uuid.UUID `json:"campaignId,omitempty"`
	BaseRevision    int64      `json:"baseRevision,omitempty" minimum:"0"`
	Links           []string   `json:"links,omitempty" maxItems:"10"`
	VoiceRevision   *int32     `json:"voiceRevision,omitempty" minimum:"0"`
}

AICampaignBriefInput names only explicit editorial context. No audience, recipient preview, automatic history search or remote fetch is available.

type AICampaignProposal

type AICampaignProposal struct {
	ID           uuid.UUID     `json:"id"`
	Name         string        `json:"name"`
	CampaignID   *uuid.UUID    `json:"campaignId,omitempty"`
	BaseRevision int64         `json:"baseRevision"`
	Before       *AIDraftEmail `json:"before,omitempty"`
	Content      AIDraftEmail  `json:"content"`
	HTML         string        `json:"html"`
	SubjectCheck AISubjectIdea `json:"subjectCheck"`
	Sent         AISent        `json:"sent"`
	ExpiresAt    time.Time     `json:"expiresAt"`
	Decision     string        `json:"decision" enum:",accepted,rejected"`
}

type AICapInput

type AICapInput struct {
	Kind   string  `json:"kind" enum:"usd,tokens,none"`
	USD    float64 `json:"usd,omitempty" minimum:"0"`
	Tokens int64   `json:"tokens,omitempty" minimum:"0"`
}

AICapInput sets the monthly cap.

type AICapView

type AICapView struct {
	Kind   string     `json:"kind" enum:"usd,tokens,none"`
	USD    float64    `json:"usd"`
	Tokens int64      `json:"tokens"`
	SetBy  string     `json:"setBy,omitempty"`
	SetAt  *time.Time `json:"setAt,omitempty"`
}

AICapView is the monthly cap.

type AIConnectInput

type AIConnectInput struct {
	Provider string `json:"provider" enum:"anthropic,openai,google,azure,compatible"`
	// Label names a server the workspace runs ("Ollama on the office network").
	Label string `json:"label,omitempty" maxLength:"80"`
	// BaseURL: the Azure endpoint, or a compatible server's address with /v1.
	BaseURL    string `json:"baseUrl,omitempty" maxLength:"500"`
	Deployment string `json:"deployment,omitempty" maxLength:"120"`
	APIVersion string `json:"apiVersion,omitempty" maxLength:"40"`
	// APIKey is write-only; optional for compatible servers.
	APIKey    string  `json:"apiKey,omitempty" maxLength:"500"`
	Model     string  `json:"model" minLength:"1" maxLength:"120"`
	ModelName string  `json:"modelName,omitempty" maxLength:"120"`
	CapKind   string  `json:"capKind" enum:"usd,tokens,none"`
	CapUSD    float64 `json:"capUsd,omitempty" minimum:"0"`
	CapTokens int64   `json:"capTokens,omitempty" minimum:"0"`
	// Prices in dollars per million tokens; empty takes the price list's.
	InputPrice  *float64 `json:"inputPrice,omitempty" minimum:"0"`
	OutputPrice *float64 `json:"outputPrice,omitempty" minimum:"0"`
	// Features to switch on (all when empty): at most one of each in
	// Features, which TestAIConnectionCapAndErrors connects with in full.
	Features []string `json:"features,omitempty" maxItems:"9"`
}

AIConnectInput connects a model.

type AIConnectionView

type AIConnectionView struct {
	Provider     string    `json:"provider" enum:"anthropic,openai,google,azure,compatible"`
	ProviderName string    `json:"providerName"`
	Label        string    `json:"label,omitempty"`
	BaseURL      string    `json:"baseUrl,omitempty"`
	Deployment   string    `json:"deployment,omitempty"`
	APIVersion   string    `json:"apiVersion,omitempty"`
	Model        string    `json:"model"`
	ModelName    string    `json:"modelName"`
	ImageInput   bool      `json:"imageInput"`
	Key          AIKeyView `json:"key"`
	ConnectedAt  time.Time `json:"connectedAt"`
	ConnectedBy  string    `json:"connectedBy,omitempty"`
	// Status: connected, or key_rejected (the provider rejected the saved key).
	Status       string       `json:"status" enum:"connected,key_rejected"`
	StatusDetail string       `json:"statusDetail,omitempty"`
	StatusAt     *time.Time   `json:"statusAt,omitempty"`
	LastTest     *AITestView  `json:"lastTest,omitempty"`
	Cap          AICapView    `json:"cap"`
	Prices       AIPricesView `json:"prices"`
	// PrivateNetwork: the server's address is a private one ("Runs on your
	// own network").
	PrivateNetwork bool `json:"privateNetwork"`
	// Demo is the demo's sample connection (answers from recordings).
	Demo bool `json:"demo"`
	// Preset is the hosted OpenAI-compatible service the address belongs to.
	Preset string `json:"preset,omitempty"`
}

AIConnectionView is the workspace's model. The key is never returned.

type AIDraftDecided

type AIDraftDecided struct {
	Decision string     `json:"decision" enum:"accepted,rejected"`
	ID       *uuid.UUID `json:"id,omitempty"`
	Revision *int64     `json:"revision,omitempty"`
}

type AIDraftDecision

type AIDraftDecision struct {
	Decision string `json:"decision" enum:"accepted,rejected"`
}

type AIDraftEmail

type AIDraftEmail struct {
	Subject   string `json:"subject" minLength:"1" maxLength:"250"`
	Preheader string `json:"preheader" maxLength:"500"`
	MJML      string `json:"mjml" minLength:"1" maxLength:"200000"`
}

AIDraftEmail is unrendered content; HTML is always compiled on the server.

type AIFeatureDefault

type AIFeatureDefault struct {
	Feature string    `` /* 143-byte string literal not displayed */
	ModelID uuid.UUID `json:"modelId"`
}

AIFeatureDefault is the model a feature uses.

type AIFeatureInput

type AIFeatureInput struct {
	On bool `json:"on"`
}

AIFeatureInput switches a feature.

type AIFeatureModelInput

type AIFeatureModelInput struct {
	ModelID uuid.UUID `json:"modelId" format:"uuid"`
}

AIFeatureModelInput picks the model a feature uses.

type AIFeatureState

type AIFeatureState struct {
	Key string `json:"key" enum:"subject_ideas,rewrite,translate,alt_text,accessibility_fix,segment_draft,report_summary,brand_voice,draft"`
	On  bool   `json:"on"`
	// Available is false for alt text with a model that doesn't read images.
	Available bool `json:"available"`
	// ModelID is the model the feature uses.
	ModelID *uuid.UUID `json:"modelId,omitempty" format:"uuid"`
}

AIFeatureState is a feature's switch.

type AIKeepSummaryInput

type AIKeepSummaryInput struct {
	RequestID string `json:"requestId" format:"uuid"`
	// Summary is the suggestion, or what the person made of it (Edit).
	Summary string `json:"summary" minLength:"1" maxLength:"4000"`
	Edited  bool   `json:"edited,omitempty"`
}

AIKeepSummaryInput keeps a summary on the report.

type AIKeptSummary

type AIKeptSummary struct {
	Kept       *AIKeptSummaryView `json:"kept,omitempty"`
	HostRepute bool               `json:"hostRepute"`
}

AIKeptSummary is the report's kept summary, if any. HostRepute says whether "Ask HostRepute's assistant" shows.

type AIKeptSummaryView

type AIKeptSummaryView struct {
	Summary   string    `json:"summary"`
	Model     string    `json:"model"`
	ModelName string    `json:"modelName"`
	KeptBy    string    `json:"keptBy"`
	KeptAt    time.Time `json:"keptAt"`
	// NumbersMatch: every number in it is still the report's ("Every number
	// matches this report"); results that kept coming in can change them.
	NumbersMatch bool     `json:"numbersMatch"`
	Unmatched    []string `json:"unmatched"`
}

AIKeptSummaryView is a summary someone kept.

type AIKeyInput

type AIKeyInput struct {
	APIKey string `json:"apiKey" minLength:"1" maxLength:"500"`
}

AIKeyInput replaces the key.

type AIKeyReplaced

type AIKeyReplaced struct {
	Settings AISettings   `json:"settings"`
	Test     AITestResult `json:"test"`
}

AIKeyReplaced is the settings after a new key passed its test.

type AIKeyView

type AIKeyView struct {
	Set     bool       `json:"set"`
	AddedAt *time.Time `json:"addedAt,omitempty"`
	AddedBy string     `json:"addedBy,omitempty"`
}

AIKeyView is the key, write-only: only whether it is set, and when.

type AILearnVoiceInput

type AILearnVoiceInput struct {
	CampaignIDs     []uuid.UUID `json:"campaignIds" minItems:"1" maxItems:"10" uniqueItems:"true"`
	SharingReviewed bool        `` /* 136-byte string literal not displayed */
}

type AILearnedVoice

type AILearnedVoice struct {
	RequestID    string                     `json:"requestId"`
	BaseRevision int32                      `json:"baseRevision"`
	Content      brandkit.BrandVoiceContent `json:"content"`
	Sent         AISent                     `json:"sent"`
	Refusal      string                     `json:"refusal,omitempty"`
	ExpiresAt    time.Time                  `json:"expiresAt"`
}

type AILinkText

type AILinkText struct {
	RequestID string `json:"requestId,omitempty"`
	Text      string `json:"text"`
	// SaysWhere: the new text isn't one that says nothing; Href is the same
	// link, unchanged.
	SaysWhere bool   `json:"saysWhere"`
	Href      string `json:"href"`
	Sent      AISent `json:"sent"`
	Refusal   string `json:"refusal,omitempty"`
}

AILinkText is a link text suggestion with its checks.

type AILinkTextInput

type AILinkTextInput struct {
	CampaignID string `json:"campaignId" format:"uuid"`
	Text       string `json:"text" maxLength:"500"`
	Href       string `json:"href" maxLength:"2000"`
	// Context is the sentence around the link.
	Context  string `json:"context,omitempty" maxLength:"4000"`
	Language string `json:"language,omitempty" maxLength:"12"`
}

AILinkTextInput asks for link text that says where a link goes.

type AIMemberRole

type AIMemberRole struct {
	Name string `json:"name"`
	Role string `json:"role"`
}

AIMemberRole is a member and their role.

type AIModelInput

type AIModelInput struct {
	Model     string `json:"model" minLength:"1" maxLength:"120"`
	ModelName string `json:"modelName,omitempty" maxLength:"120"`
	// Prices follow the price list for a known model unless given.
	InputPrice  *float64 `json:"inputPrice,omitempty" minimum:"0"`
	OutputPrice *float64 `json:"outputPrice,omitempty" minimum:"0"`
}

AIModelInput changes the model (Change model).

type AIModelList

type AIModelList struct {
	Models []AIModelOption `json:"models"`
	// FromProvider: the list came from the provider; otherwise it is the
	// price list's (the key wasn't given yet, or the provider didn't answer).
	FromProvider bool   `json:"fromProvider"`
	Error        string `json:"error,omitempty"`
}

AIModelList is a provider's models, the price list's first.

type AIModelOption

type AIModelOption struct {
	ID         string  `json:"id"`
	Name       string  `json:"name"`
	Known      bool    `json:"known" doc:"On ReputeCast's price list"`
	Input      float64 `json:"input" doc:"Dollars per million input tokens"`
	Output     float64 `json:"output" doc:"Dollars per million output tokens"`
	ImageInput bool    `json:"imageInput"`
}

AIModelOption is a model to pick, with its prices from the price list.

type AIModelView

type AIModelView struct {
	ID         uuid.UUID    `json:"id"`
	Model      string       `json:"model"`
	ModelName  string       `json:"modelName"`
	Deployment string       `json:"deployment,omitempty"`
	ImageInput bool         `json:"imageInput"`
	Prices     AIPricesView `json:"prices"`
	// Tools is the tool-calling check the agent and the assistant need.
	Tools AIAgentCapability `json:"tools"`
	// Features are the features this model is the default of.
	Features []string `` /* 144-byte string literal not displayed */
}

AIModelView is a model of an account, with its prices and what it can do.

type AIModelsInput

type AIModelsInput struct {
	Provider   string `json:"provider" enum:"anthropic,openai,google,azure,compatible"`
	BaseURL    string `json:"baseUrl,omitempty" maxLength:"500"`
	Deployment string `json:"deployment,omitempty" maxLength:"120"`
	APIVersion string `json:"apiVersion,omitempty" maxLength:"40"`
	APIKey     string `json:"apiKey,omitempty" maxLength:"500"`
	// AccountID lends that account's saved key (at the same address)
	// instead of the first account's.
	AccountID *uuid.UUID `json:"accountId,omitempty" format:"uuid"`
}

AIModelsInput asks for a provider's models.

type AIOutcomeInput

type AIOutcomeInput struct {
	Outcome string `json:"outcome" enum:"accepted,accepted_edits,kept,rejected,discarded"`
	// Detail: "1 of 5" for subject ideas.
	Detail string `json:"detail,omitempty" maxLength:"40"`
}

AIOutcomeInput records what a person did with a suggestion.

type AIPendingDraft

type AIPendingDraft struct {
	ID        uuid.UUID `json:"id"`
	Name      string    `json:"name"`
	ExpiresAt time.Time `json:"expiresAt"`
}

type AIPendingDrafts

type AIPendingDrafts struct {
	Items []AIPendingDraft `json:"items"`
	Next  *uuid.UUID       `json:"next,omitempty"`
}

type AIPersonalAccount

type AIPersonalAccount struct {
	ID           uuid.UUID `json:"id"`
	Provider     string    `json:"provider" enum:"anthropic,openai,google,azure,compatible"`
	ProviderName string    `json:"providerName"`
	Status       string    `json:"status" enum:"connected,key_rejected,disconnected"`
	Models       []string  `json:"models"`
}

AIPersonalAccount is a member's personal account as managers see it: the provider and its models' names, never the key.

type AIPersonalKeyReplaced

type AIPersonalKeyReplaced struct {
	Personal AIPersonalSettings `json:"personal"`
	Test     AITestResult       `json:"test"`
}

AIPersonalKeyReplaced is the personal settings after a new key passed its test.

type AIPersonalKeysInput

type AIPersonalKeysInput struct {
	Enabled bool `json:"enabled"`
	// CapUSD is each person's monthly budget for their own keys, in dollars.
	CapUSD float64 `json:"capUsd" minimum:"0"`
}

AIPersonalKeysInput sets the personal-keys switch and each person's cap.

type AIPersonalPerson

type AIPersonalPerson struct {
	UserID     uuid.UUID           `json:"userId"`
	Name       string              `json:"name"`
	Accounts   []AIPersonalAccount `json:"accounts"`
	CostMicros int64               `json:"costMicros"`
	Requests   int64               `json:"requests"`
}

AIPersonalPerson is a member's personal accounts and their use this month, as managers see them.

type AIPersonalSettings

type AIPersonalSettings struct {
	// Enabled: integration managers allow personal keys.
	Enabled bool `json:"enabled"`
	// CapUSD is each person's monthly budget for their own keys, in dollars.
	CapUSD   float64    `json:"capUsd"`
	CapSetBy string     `json:"capSetBy,omitempty"`
	CapSetAt *time.Time `json:"capSetAt,omitempty"`
	// CanAdd: personal keys are on and the caller holds ai:use.
	CanAdd bool `json:"canAdd"`
	// Accounts are the caller's own accounts with their models; a model's
	// features are the ones the caller picked it for.
	Accounts []AIAccountView `json:"accounts"`
	// Choices are the caller's own models per feature, for their requests.
	Choices []AIFeatureDefault  `json:"choices"`
	Usage   AIPersonalUsageView `json:"usage"`
	// People are the members with personal accounts or personal use this
	// month, for integration managers (empty otherwise). Never a key.
	People []AIPersonalPerson `json:"people"`
	// Catalog is every provider a personal account may use, with the
	// models and prices of ReputeCast's price list (as /ai gives them);
	// PriceListDate is that list's date.
	Catalog       []AIProviderEntry `json:"catalog"`
	PriceListDate time.Time         `json:"priceListDate"`
}

AIPersonalSettings are the personal keys' part of the AI settings: the switch, the cap, the caller's own accounts and, for managers, who has personal accounts.

type AIPersonalUsageView

type AIPersonalUsageView struct {
	CostMicros         int64     `json:"costMicros"`
	ReservedCostMicros int64     `json:"reservedCostMicros"`
	UncertainRequests  int64     `json:"uncertainRequests"`
	Requests           int64     `json:"requests"`
	Share              float64   `json:"share" doc:"Share of the cap used, 0 to 1"`
	State              string    `json:"state" enum:"ok,notice,reached"`
	ResetsAt           time.Time `json:"resetsAt"`
}

AIPersonalUsageView is a person's use of their own keys this month against their cap.

type AIPricesInput

type AIPricesInput struct {
	Input  float64 `json:"input" minimum:"0" doc:"Dollars per million input tokens"`
	Output float64 `json:"output" minimum:"0" doc:"Dollars per million output tokens"`
}

AIPricesInput sets the prices.

type AIPricesView

type AIPricesView struct {
	Input  float64 `json:"input" doc:"Dollars per million input tokens"`
	Output float64 `json:"output" doc:"Dollars per million output tokens"`
	Known  bool    `json:"known" doc:"Prices are configured, including an explicitly free model"`
	// From is the price list's date when the prices came from it.
	From *time.Time `json:"from,omitempty"`
}

AIPricesView are the prices the cap is estimated with.

type AIProviderEntry

type AIProviderEntry struct {
	Kind         string   `json:"kind" enum:"anthropic,openai,google,azure,compatible"`
	Name         string   `json:"name"`
	NeedsKey     bool     `json:"needsKey"`
	NeedsBaseURL bool     `json:"needsBaseUrl"`
	Capabilities []string `json:"capabilities" enum:"text,image_input,structured_output,own_network,data_region"`
	DefaultModel string   `json:"defaultModel,omitempty"`
	// Models are the price list's models of the provider.
	Models []AIModelOption `json:"models"`
	// Presets are hosted services that speak this provider's API, with their
	// address filled in (OpenAI-compatible only).
	Presets []AIProviderPreset `json:"presets"`
}

AIProviderEntry is a provider of the catalog.

type AIProviderPreset

type AIProviderPreset struct {
	ID      string `json:"id"`
	Name    string `json:"name"`
	BaseURL string `json:"baseUrl"`
}

AIProviderPreset is a hosted OpenAI-compatible service. It needs a key; its models come from the service and its prices from the person.

type AIReportAnswer

type AIReportAnswer struct {
	RequestID string `json:"requestId,omitempty"`
	Answer    string `json:"answer"`
	// NumbersMatch: every number is the report's; Unmatched lists the ones
	// that aren't.
	NumbersMatch bool     `json:"numbersMatch"`
	Unmatched    []string `json:"unmatched"`
	Sent         AISent   `json:"sent"`
	Refusal      string   `json:"refusal,omitempty"`
}

AIReportAnswer is the answer to a question about a report: its numbers are the report's, filled in, and checked (review AN-14).

type AIReportQuestionInput

type AIReportQuestionInput struct {
	CampaignID string `json:"campaignId" format:"uuid"`
	Question   string `json:"question" minLength:"1" maxLength:"500"`
}

AIReportQuestionInput asks a question about a report.

type AIReportSummary

type AIReportSummary struct {
	RequestID string `json:"requestId,omitempty"`
	// Summary has the report's numbers filled in, in the reader's format.
	Summary string `json:"summary"`
	// NumbersMatch: every number is the report's number for the metric the
	// model named (review AN-6); Unmatched lists what isn't.
	NumbersMatch bool     `json:"numbersMatch"`
	Unmatched    []string `json:"unmatched"`
	// NoCauses: it describes the numbers and doesn't diagnose causes.
	NoCauses bool   `json:"noCauses"`
	Sent     AISent `json:"sent"`
	Refusal  string `json:"refusal,omitempty"`
}

AIReportSummary is a summary suggestion and its checks.

type AIReportSummaryInput

type AIReportSummaryInput struct {
	CampaignID string `json:"campaignId" format:"uuid"`
}

AIReportSummaryInput asks for a report's summary.

type AIReputation

type AIReputation struct {
	// HostRepute: HostRepute is connected, so its assistant can answer.
	HostRepute bool `json:"hostRepute"`
}

AIReputation is the answer to a question about sender reputation: the assistant doesn't look at those, and nothing was sent.

type AIRewrite

type AIRewrite struct {
	RequestID string `json:"requestId,omitempty"`
	// HTML is the suggestion, tokens and link addresses restored.
	HTML           string        `json:"html"`
	WordsBefore    int           `json:"wordsBefore"`
	WordsAfter     int           `json:"wordsAfter"`
	Tokens         []string      `json:"tokens" doc:"The variables of the tokens kept: first_name"`
	TokensRestored int           `json:"tokensRestored"`
	Links          int           `json:"links"`
	LinksRestored  int           `json:"linksRestored"`
	Sent           AISent        `json:"sent"`
	Refusal        string        `json:"refusal,omitempty"`
	Reputation     *AIReputation `json:"reputation,omitempty"`
}

AIRewrite is a rewrite suggestion.

type AIRewriteInput

type AIRewriteInput struct {
	CampaignID string `json:"campaignId" format:"uuid"`
	Action     string `json:"action" enum:"shorten,friendlier,formal,direct,instruction"`
	// Instruction is what to change, for "With an instruction…".
	Instruction string `json:"instruction,omitempty" maxLength:"500"`
	// HTML is the selected text, or the whole paragraph, as the editor holds it.
	HTML string `json:"html" maxLength:"60000"`
	// Field is "subject" or "preheader" when those are rewritten.
	Field         string `json:"field,omitempty" enum:"subject,preheader"`
	Language      string `json:"language,omitempty" maxLength:"12"`
	VoiceRevision *int32 `` /* 127-byte string literal not displayed */
}

AIRewriteInput asks for a rewrite of a text.

type AISegmentDraft

type AISegmentDraft struct {
	RequestID string `json:"requestId,omitempty"`
	// Groups show the draft over the current conditions; Definition is the
	// draft alone, what Accept puts in the builder.
	Groups     []AISegmentDraftGroup      `json:"groups"`
	Definition segments.SegmentDefinition `json:"definition"`
	Added      int                        `json:"added"`
	Removed    int                        `json:"removed"`
	// Note is the model's note: what it couldn't express.
	Note string `json:"note,omitempty"`
	// Nothing is set when nothing could be drafted, with why.
	Nothing string                       `json:"nothing,omitempty"`
	Count   *segments.SegmentCountResult `json:"count,omitempty"`
	Sent    AISent                       `json:"sent"`
	Refusal string                       `json:"refusal,omitempty"`
}

AISegmentDraft is a draft as a diff on the builder, with its live count.

type AISegmentDraftCondition

type AISegmentDraftCondition struct {
	segments.SegmentCondition
	// Mark: added by the draft, removed by it (struck through), or kept.
	Mark string `json:"mark" enum:"added,removed,kept"`
}

AISegmentDraftCondition is a condition of the draft, marked.

type AISegmentDraftGroup

type AISegmentDraftGroup struct {
	Match      string                    `json:"match" enum:"all,any"`
	Conditions []AISegmentDraftCondition `json:"conditions"`
}

AISegmentDraftGroup is a group of the draft.

type AISegmentDraftInput

type AISegmentDraftInput struct {
	Description string `json:"description" minLength:"1" maxLength:"500"`
	// Current is the builder's conditions as they are.
	Current segments.SegmentDefinition `json:"current"`
	// SegmentID names the segment being edited (empty for a new one).
	SegmentID string `json:"segmentId,omitempty"`
}

AISegmentDraftInput describes a segment.

type AISent

type AISent struct {
	Provider     string `json:"provider" enum:"anthropic,openai,google,azure,compatible"`
	ProviderName string `json:"providerName"`
	Model        string `json:"model"`
	ModelName    string `json:"modelName"`
	// Characters of the person's content that were sent.
	Characters int `json:"characters"`
	// CostMicros is the estimated cost in millionths of a dollar.
	CostMicros    int64 `json:"costMicros"`
	InputTokens   int   `json:"inputTokens"`
	OutputTokens  int   `json:"outputTokens"`
	VoiceRevision int32 `json:"voiceRevision,omitempty"`
}

AISent says what went to the model, for the card's footer.

type AISettings

type AISettings struct {
	Connected bool `json:"connected"`
	// Connection is the model, also while disconnected (Disconnected says
	// so): its model, cap and prices are kept for the next connection.
	Connection   *AIConnectionView `json:"connection,omitempty"`
	Disconnected bool              `json:"disconnected"`
	Catalog      []AIProviderEntry `json:"catalog"`
	Usage        AIUsageView       `json:"usage"`
	ByFeature    []AIUsageFeature  `json:"byFeature"`
	ByMember     []AIUsageMember   `json:"byMember"`
	Features     []AIFeatureState  `json:"features"`
	// CanManage: the caller holds integrations:manage; Helpers hold it.
	CanManage bool     `json:"canManage"`
	Helpers   []string `json:"helpers"`
	// AIUseRoles are the roles whose members hold ai:use; WithoutAIUse the
	// members who don't (the board's "Aisha Bello, a Viewer").
	AIUseRoles   []string       `json:"aiUseRoles"`
	WithoutAIUse []AIMemberRole `json:"withoutAiUse"`
	// PriceListDate is the date of ReputeCast's price list.
	PriceListDate time.Time `json:"priceListDate"`
	// AllowPrivate: this instance lets model servers resolve to private
	// addresses; InstanceAdmins can change that.
	AllowPrivate   bool     `json:"allowPrivate"`
	InstanceAdmins []string `json:"instanceAdmins"`
	// Accounts are the model accounts with their models, the first
	// (Connection's) first; Defaults the model each feature uses.
	Accounts []AIAccountView    `json:"accounts"`
	Defaults []AIFeatureDefault `json:"defaults"`
	// Personal is the personal-keys switch, each person's cap, the caller's
	// own accounts and, for managers, who has personal accounts.
	Personal AIPersonalSettings `json:"personal"`
	// Assistant is the assistant's switch, its limits per thread and the
	// turns answering at once.
	Assistant AIAssistantSettings `json:"assistant"`
}

AISettings is Settings › Integrations › AI models.

type AIStatus

type AIStatus struct {
	// State: ready, not_configured, key_rejected or cap_reached.
	State        string            `json:"state" enum:"ready,not_configured,key_rejected,cap_reached"`
	Provider     string            `json:"provider,omitempty" enum:"anthropic,openai,google,azure,compatible,"`
	ProviderName string            `json:"providerName,omitempty"`
	Model        string            `json:"model,omitempty"`
	ModelName    string            `json:"modelName,omitempty"`
	ImageInput   bool              `json:"imageInput"`
	Features     []AIStatusFeature `json:"features"`
	Agent        AIAgentSettings   `json:"agent"`
	Usage        AIUsageView       `json:"usage"`
	Cap          AICapView         `json:"cap"`
	Prices       AIPricesView      `json:"prices"`
	// CanManage: the person can connect a model, raise the cap or turn a
	// feature on; Helpers can.
	CanManage bool     `json:"canManage"`
	Helpers   []string `json:"helpers"`
	// HostRepute: HostRepute is connected, so reputation questions go to
	// its assistant.
	HostRepute bool `json:"hostRepute"`
	// Accounts are the model accounts with their models; Defaults the
	// model each feature uses.
	Accounts []AIAccountView    `json:"accounts"`
	Defaults []AIFeatureDefault `json:"defaults"`
}

AIStatus is what the entry points need: whether a model is connected and works, its name, the features on, this month's use and who can help. State, the model, Cap, Usage and Prices are the workspace's model's; a feature on the person's own model has its own in Features.

type AIStatusFeature

type AIStatusFeature struct {
	// State is as the top-level State, for this feature's model and budget;
	// On says whether the switches (the feature's, personal keys) allow it.
	State string `json:"state" enum:"ready,not_configured,key_rejected,cap_reached"`
	// Personal: the model is the person's own.
	Personal     bool         `json:"personal"`
	Provider     string       `json:"provider,omitempty" enum:"anthropic,openai,google,azure,compatible,"`
	ProviderName string       `json:"providerName,omitempty"`
	Model        string       `json:"model,omitempty"`
	ModelName    string       `json:"modelName,omitempty"`
	Usage        AIUsageView  `json:"usage"`
	Cap          AICapView    `json:"cap"`
	Prices       AIPricesView `json:"prices"`
	// Key, On, Available and ModelID are as AIFeatureState's. The agent's On
	// is its switch (the agent's settings) with a model whose tool check
	// lets runs start; Available is false when the check doesn't.
	Key       string     `` /* 129-byte string literal not displayed */
	On        bool       `json:"on"`
	Available bool       `json:"available"`
	ModelID   *uuid.UUID `json:"modelId,omitempty" format:"uuid"`
}

AIStatusFeature is a feature for the person: its switch, and whether it can be asked for now with the model it uses for them (their own pick, or the workspace's) in the budget that model's requests count against (the workspace's cap, or the person's own for their own model). The features are the settings' and then the agent, for the model a new run of theirs takes.

type AISubjectIdea

type AISubjectIdea struct {
	Subject    string   `json:"subject"`
	Characters int      `json:"characters"`
	Verdict    string   `json:"verdict" enum:"pass,warn"`
	Heuristics []string `json:"heuristics"`
	// Phrase is the words that trip a heuristic ("you won't believe").
	Phrase string `json:"phrase,omitempty"`
}

AISubjectIdea is one idea with the subject checks.

type AISubjectIdeas

type AISubjectIdeas struct {
	RequestID string          `json:"requestId,omitempty"`
	Ideas     []AISubjectIdea `json:"ideas"`
	Sent      AISent          `json:"sent"`
	Language  string          `json:"language"`
	Refusal   string          `json:"refusal,omitempty"`
}

AISubjectIdeas are five ideas.

type AISubjectIdeasInput

type AISubjectIdeasInput struct {
	CampaignID string `json:"campaignId" format:"uuid"`
	Subject    string `json:"subject" maxLength:"500"`
	Preheader  string `json:"preheader,omitempty" maxLength:"500"`
	// MJML is the email as it is on the canvas; its text goes, without images.
	MJML string `json:"mjml" maxLength:"2000000"`
	// Language is the version open ("" is the source).
	Language      string `json:"language,omitempty" maxLength:"12"`
	VoiceRevision *int32 `` /* 127-byte string literal not displayed */
}

AISubjectIdeasInput asks for subject ideas.

type AITestInput

type AITestInput struct {
	Provider    string   `json:"provider,omitempty" enum:"anthropic,openai,google,azure,compatible"`
	BaseURL     string   `json:"baseUrl,omitempty" maxLength:"500"`
	Deployment  string   `json:"deployment,omitempty" maxLength:"120"`
	APIVersion  string   `json:"apiVersion,omitempty" maxLength:"40"`
	APIKey      string   `json:"apiKey,omitempty" maxLength:"500"`
	Model       string   `json:"model,omitempty" maxLength:"120"`
	InputPrice  *float64 `json:"inputPrice,omitempty" minimum:"0" maximum:"1000"`
	OutputPrice *float64 `json:"outputPrice,omitempty" minimum:"0" maximum:"1000"`
	// ModelID tests a saved model instead of the first account's; AccountID
	// tests an account's first model, or lends its saved key to a model
	// being set up on it.
	ModelID   *uuid.UUID `json:"modelId,omitempty" format:"uuid"`
	AccountID *uuid.UUID `json:"accountId,omitempty" format:"uuid"`
}

AITestInput tests a connection: empty tests the saved one.

type AITestResult

type AITestResult struct {
	OK           bool      `json:"ok"`
	Prompt       string    `json:"prompt"`
	SentAt       time.Time `json:"sentAt"`
	AnsweredAt   time.Time `json:"answeredAt"`
	Ms           int       `json:"ms"`
	Answer       string    `json:"answer,omitempty"`
	Model        string    `json:"model,omitempty"`
	InputTokens  int       `json:"inputTokens"`
	OutputTokens int       `json:"outputTokens"`
	// Error: what the provider answered when the test failed.
	ErrorKind    string `` /* 126-byte string literal not displayed */
	ErrorStatus  int    `json:"errorStatus,omitempty"`
	ErrorDetail  string `json:"errorDetail,omitempty" doc:"401 authentication_error: invalid x-api-key"`
	ErrorMessage string `json:"errorMessage,omitempty" doc:"What it means, as a sentence"`
	// Private network: the server's address is private (and allowed).
	PrivateHost string `json:"privateHost,omitempty"`
	PrivateIP   string `json:"privateIp,omitempty"`
}

AITestResult is Test connection: the fixed prompt, the answer and the time.

type AITestView

type AITestView struct {
	At time.Time `json:"at"`
	OK bool      `json:"ok"`
	Ms int       `json:"ms"`
}

AITestView is the last test of the connection.

type AITranslateInput

type AITranslateInput struct {
	CampaignID string `json:"campaignId" format:"uuid"`
	Language   string `json:"language" pattern:"^[a-z]{2,3}$"`
}

AITranslateInput asks for a translation of a campaign's source into a workspace language.

type AITranslation

type AITranslation struct {
	RequestID     string `json:"requestId,omitempty"`
	Language      string `json:"language"`
	LanguageName  string `json:"languageName"`
	Source        string `json:"source"`
	SourceName    string `json:"sourceName"`
	SourceVersion int    `json:"sourceVersion"`
	// Status is the version's status before accepting: missing, draft,
	// outdated or up_to_date.
	Status              string               `json:"status"`
	Subject             string               `json:"subject"`
	SubjectSuggestion   string               `json:"subjectSuggestion"`
	SubjectHeuristics   []string             `json:"subjectHeuristics"`
	Preheader           string               `json:"preheader"`
	PreheaderSuggestion string               `json:"preheaderSuggestion"`
	Blocks              []AITranslationBlock `json:"blocks"`
	Tokens              int                  `json:"tokens"`
	TokensRestored      int                  `json:"tokensRestored"`
	Links               int                  `json:"links"`
	LinksRestored       int                  `json:"linksRestored"`
	// Readers get the language once it is accepted.
	Readers *int64 `json:"readers,omitempty"`
	Sent    AISent `json:"sent"`
	Refusal string `json:"refusal,omitempty"`
}

AITranslation is a suggested translation of a language version.

type AITranslationAcceptInput

type AITranslationAcceptInput struct {
	RequestID string `json:"requestId" format:"uuid"`
	// SourceVersion is the source the translation was made from.
	SourceVersion int `json:"sourceVersion" minimum:"0"`
	// Subject and Preheader are set when accepted.
	Subject   *string           `json:"subject,omitempty" maxLength:"998"`
	Preheader *string           `json:"preheader,omitempty" maxLength:"500"`
	Blocks    []AIAcceptedBlock `json:"blocks" maxItems:"200"`
	// Items is how many the suggestion had (its blocks, the subject and the
	// preheader): accepting all of them marks the version translated.
	Items  int  `json:"items" minimum:"1"`
	Edited bool `json:"edited,omitempty"`
}

AITranslationAcceptInput accepts a translation, or some of its blocks.

type AITranslationAccepted

type AITranslationAccepted struct {
	Language string `json:"language"`
	// Status: up_to_date (every block accepted: "Translated by AI · not
	// reviewed") or draft (some blocks still to translate).
	Status   string `json:"status" enum:"up_to_date,draft"`
	Version  int    `json:"version"`
	Accepted int    `json:"accepted"`
	Items    int    `json:"items"`
	Model    string `json:"model"`
}

AITranslationAccepted is the language version written.

type AITranslationBlock

type AITranslationBlock struct {
	Index    int                    `json:"index"`
	Name     string                 `json:"name"`
	Segments []AITranslationSegment `json:"segments"`
	// SourceText and SuggestionText read the block as text.
	SourceText     string `json:"sourceText"`
	SuggestionText string `json:"suggestionText"`
	Tokens         int    `json:"tokens"`
	TokensRestored int    `json:"tokensRestored"`
	Links          int    `json:"links"`
	LinksRestored  int    `json:"linksRestored"`
	// Buttons are links drawn as buttons (a poll's answers): their
	// addresses aren't part of the text and never change.
	Buttons int `json:"buttons"`
}

AITranslationBlock is one block's suggestion.

type AITranslationMark

type AITranslationMark struct {
	Language string `json:"language"`
	Model    string `json:"model"`
	// Reviewed: someone marked it reviewed, or edited it since.
	Reviewed bool `json:"reviewed"`
}

AITranslationMark is a language version written by an AI translation.

type AITranslationMarks

type AITranslationMarks struct {
	Items []AITranslationMark `json:"items"`
}

AITranslationMarks lists a campaign's AI-translated versions.

type AITranslationSegment

type AITranslationSegment struct {
	Path []int  `json:"path"`
	Kind string `json:"kind" enum:"text,button,nav,image,social,table"`
	// Source and Suggestion are HTML for text, plain text for the rest
	// (an image's alt text).
	Source     string `json:"source"`
	Suggestion string `json:"suggestion"`
}

AITranslationSegment is one piece of a block: its source and the suggestion.

type AIUsageFeature

type AIUsageFeature struct {
	Feature    string `` /* 159-byte string literal not displayed */
	CostMicros int64  `json:"costMicros"`
	Tokens     int64  `json:"tokens"`
	Requests   int64  `json:"requests"`
}

AIUsageFeature is one feature's use this month.

type AIUsageMember

type AIUsageMember struct {
	UserID     string `json:"userId,omitempty"`
	Name       string `json:"name"`
	CostMicros int64  `json:"costMicros"`
	Tokens     int64  `json:"tokens"`
	Requests   int64  `json:"requests"`
}

AIUsageMember is one member's use this month.

type AIUsageView

type AIUsageView struct {
	CostMicros         int64     `json:"costMicros"`
	ReservedCostMicros int64     `json:"reservedCostMicros"`
	ReservedTokens     int64     `json:"reservedTokens"`
	UncertainRequests  int64     `json:"uncertainRequests"`
	InputTokens        int64     `json:"inputTokens"`
	OutputTokens       int64     `json:"outputTokens"`
	Tokens             int64     `json:"tokens"`
	Requests           int64     `json:"requests"`
	Share              float64   `json:"share" doc:"Share of the cap used, 0 to 1 (0 without a cap)"`
	State              string    `json:"state" enum:"ok,notice,reached"`
	MonthStart         time.Time `json:"monthStart"`
	ResetsAt           time.Time `json:"resetsAt"`
}

AIUsageView is this month's use against the cap.

type AgentArgs

type AgentArgs struct {
	WorkspaceID uuid.UUID `json:"workspaceId"`
	RunID       uuid.UUID `json:"runId"`
	Version     int64     `json:"version"`
}

func (AgentArgs) InsertOpts

func (AgentArgs) InsertOpts() river.InsertOpts

func (AgentArgs) Kind

func (AgentArgs) Kind() string

type AgentWorker

type AgentWorker struct {
	river.WorkerDefaults[AgentArgs]
	S *Service
}

func (*AgentWorker) Timeout

func (w *AgentWorker) Timeout(*river.Job[AgentArgs]) time.Duration

func (*AgentWorker) Work

func (w *AgentWorker) Work(ctx context.Context, job *river.Job[AgentArgs]) error

type AssistantAttachment

type AssistantAttachment struct {
	Kind     string
	ID       uuid.UUID
	Title    string
	Revision int64
	// Snapshot is a report's fixed numbers (reports.ModelSnapshot), taken
	// when it is attached.
	Snapshot json.RawMessage
}

AssistantAttachment is a resource attached to a thread, as its owner may read it now.

type AssistantCampaign

type AssistantCampaign struct {
	ID        uuid.UUID `json:"id"`
	Name      string    `json:"name"`
	Status    string    `json:"status"`
	Revision  int64     `json:"revision"`
	Subject   string    `json:"subject"`
	Preheader string    `json:"preheader"`
	Source    string    `json:"source"`
	Links     []string  `json:"links"`
	Images    []string  `json:"images"`
	Tokens    []string  `json:"tokens"`
}

AssistantCampaign is an attached campaign as the model reads it: its editorial text, with links, images and Liquid tokens as opaque handles that stay on the server.

type AssistantLedger

type AssistantLedger struct {
	ThreadID                    uuid.UUID
	TokenLimit, CostLimitMicros int64
}

AssistantLedger is a thread's cumulative ceilings.

type AssistantModel

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

AssistantModel is a model an assistant thread uses, with its account and the workspace's AI settings as they were read.

func (*AssistantModel) ContextTokens

func (m *AssistantModel) ContextTokens() int

ContextTokens is the model's context window, as the price list knows it.

func (*AssistantModel) ID

func (m *AssistantModel) ID() uuid.UUID

ID is the model's id.

func (*AssistantModel) Personal

func (m *AssistantModel) Personal() bool

Personal reports whether the model is on its owner's own key.

type AssistantRequest

type AssistantRequest struct {
	ID, WorkspaceID, UserID, ThreadID uuid.UUID
	Action, Outcome                   string
	CreatedAt                         time.Time
}

AssistantRequest is a thread's request as the activity log keeps it: never its content, nor the thread's title.

type RetentionArgs

type RetentionArgs struct{}

RetentionArgs drops the activity log's rows older than 90 days.

func (RetentionArgs) InsertOpts

func (RetentionArgs) InsertOpts() river.InsertOpts

InsertOpts runs it on the maintenance queue, once at a time.

func (RetentionArgs) Kind

func (RetentionArgs) Kind() string

Kind implements river.JobArgs.

type RetentionWorker

type RetentionWorker struct {
	river.WorkerDefaults[RetentionArgs]
	S *Service
}

RetentionWorker purges the activity log.

func (*RetentionWorker) Work

Work implements river.Worker.

type Service

type Service struct {
	Pool  *pgxpool.Pool
	Q     *store.Queries
	Audit *audit.Logger
	Box   *secrets.Box
	Log   *slog.Logger
	Jobs  func() *jobs.Client
	// AllowPrivate reports whether model servers may resolve to private
	// addresses (providers.allow_private_networks: the setting SMTP
	// servers and community adapters use).
	AllowPrivate func() bool
	// Development lets the demo's sample connection answer from its
	// recordings; elsewhere it refuses.
	Development bool
	// HTTP overrides the client that calls providers (tests).
	HTTP *http.Client
	// Provider overrides how a connection is reached (tests).
	Provider func(cfg llm.Config) (llm.Provider, error)
	// Retries and RetryWait override how an overloaded provider is retried.
	Retries   *int
	RetryWait time.Duration
	// Segments, Reports and Languages are the domains the drafts, the
	// summaries and the translations read and write (wired in internal/app).
	Segments    *segments.Service
	Reports     *reports.Service
	Languages   *languages.Service
	BrandKit    *brandkit.Service
	Campaigns   *campaigns.Service
	Automations *automations.Service
	Website     *website.Service
	Now         func() time.Time
}

Service is the AI assistant.

func (*Service) AcceptTranslation

AcceptTranslation writes the accepted blocks into the language version (added when missing), on the source's layout. Accepting every block marks it translated, "Translated by AI · not reviewed" until someone reviews or edits it; otherwise it stays a Draft. The save is a content edit in the version's history.

func (*Service) AccountAssistant

func (s *Service) AccountAssistant(ctx context.Context, q *store.Queries, r AssistantRequest, res llm.Response, callErr error) (bool, error)

AccountAssistant settles a reservation with what the provider reported (or keeps it held when that is unknown) and logs the request. It reports whether the usage is known.

func (*Service) Activity

Activity lists the last 90 days of requests, newest first.

func (*Service) AddAccount

func (s *Service) AddAccount(ctx context.Context, ws *store.Workspace, p *authz.Principal, in AIAccountInput) (AISettings, error)

AddAccount adds a model account, after the fixed test prompt passes with its first model. A workspace's first model is every feature's default.

func (*Service) AddModel

func (s *Service) AddModel(ctx context.Context, ws *store.Workspace, p *authz.Principal, account uuid.UUID, in AIAccountModelInput) (AISettings, error)

AddModel adds a model to a connected account.

func (*Service) AddPersonalAccount

func (s *Service) AddPersonalAccount(ctx context.Context, ws *store.Workspace, p *authz.Principal, in AIAccountInput) (AIPersonalSettings, error)

AddPersonalAccount adds one of the caller's own accounts with its first model, after the fixed test prompt passes (in the caller's own budget).

func (*Service) AddPersonalModel

func (s *Service) AddPersonalModel(ctx context.Context, ws *store.Workspace, p *authz.Principal, account uuid.UUID, in AIAccountModelInput) (AIPersonalSettings, error)

AddPersonalModel adds a model to one of the caller's own accounts.

func (*Service) AfterAssistant

func (s *Service) AfterAssistant(ctx context.Context, ws *store.Workspace, m *AssistantModel, callErr error)

AfterAssistant follows up a thread's request once its result is saved: a key the provider rejected is marked so (and its managers or owner are told), and the monthly cap's notices go out.

func (*Service) AgentAction

func (s *Service) AgentAction(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID, in AIAgentAction) error

func (*Service) AgentRun

func (s *Service) AgentRun(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID) (AIAgentRunView, error)

func (*Service) AgentRuns

func (s *Service) AgentRuns(ctx context.Context, ws *store.Workspace, p *authz.Principal, cursor string) (AIAgentRunList, error)

func (*Service) AgentSettings

func (s *Service) AgentSettings(ctx context.Context, ws *store.Workspace) (AIAgentSettings, error)

func (*Service) AltText

AltText looks at an image, resized to 1,024 px, and the text around it.

func (*Service) Ask

Ask answers a question about a report with the workspace's own model: it sends the report's aggregate numbers and the question, never an address.

func (*Service) AssistantAttachment

func (s *Service) AssistantAttachment(ctx context.Context, q *store.Queries, ws *store.Workspace, p *authz.Principal, kind string, id uuid.UUID, snapshot bool) (AssistantAttachment, error)

AssistantAttachment checks that p may read a resource to attach and returns what the thread shows of it; with snapshot, a report's numbers as the model reads them (the agent's report rules). Each read checks the person's current access: a resource they can't read isn't found.

func (*Service) AssistantFeatureOn

func (s *Service) AssistantFeatureOn(ctx context.Context, q *store.Queries, ws uuid.UUID, feature string) (bool, error)

AssistantFeatureOn reports whether managers left a feature on.

func (*Service) AssistantModelView

func (s *Service) AssistantModelView(ctx context.Context, q *store.Queries, ws, user uuid.UUID, model *uuid.UUID) (*AIAssistantModel, error)

AssistantModelView is how a thread shows its model, also when the assistant can no longer use it; nil when it is gone or isn't user's.

func (*Service) AssistantModels

func (s *Service) AssistantModels(ctx context.Context, ws *store.Workspace, p *authz.Principal) (AIAssistantModelList, error)

AssistantModels lists the workspace's models and the caller's own, each with whether a thread can use it.

func (*Service) AssistantProposeCampaign

func (s *Service) AssistantProposeCampaign(ctx context.Context, ws *store.Workspace, p *authz.Principal, thread, id uuid.UUID, base int64, email AIDraftEmail) (uuid.UUID, error)

AssistantProposeCampaign saves the model's edit of a draft campaign as a proposal for the person's review (the drafts' own: accepting it is the person's, with campaigns:edit, at the exact revision it was made on). The email is the projection read_attached gave, edited; its handles are restored here, and it must still be valid saved content.

func (*Service) AssistantProvider

func (s *Service) AssistantProvider(m *AssistantModel) (llm.Provider, error)

AssistantProvider is how a thread's requests reach the model.

func (*Service) AssistantReadCampaign

func (s *Service) AssistantReadCampaign(ctx context.Context, q *store.Queries, ws *store.Workspace, p *authz.Principal, id uuid.UUID) (AssistantCampaign, error)

AssistantReadCampaign is an attached campaign as the model may read it now: the person's current access decides, and Liquid stays unexpanded.

func (*Service) AssistantRewrite

func (s *Service) AssistantRewrite(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID, text, action, instruction string) (AIRewrite, error)

AssistantRewrite runs the rewrite on a passage of an attached campaign: its own switch, model and reservation. The campaign must pass the editorial projection, and the passage and the instruction (the model wrote both) its privacy checks, as read_attached's text does.

func (*Service) AssistantSettings

func (s *Service) AssistantSettings(ctx context.Context, q *store.Queries, ws uuid.UUID) (AIAssistantSettings, error)

AssistantSettings returns the assistant's settings, its defaults when they were never set.

func (*Service) AssistantSubjectIdeas

func (s *Service) AssistantSubjectIdeas(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID) (AISubjectIdeas, error)

AssistantSubjectIdeas runs the subject ideas on an attached campaign as it is saved: their own switch, model and reservation. What they send is the editorial projection read_attached gives (the same privacy checks, refused the same way), its Liquid tokens as written.

func (*Service) AutomationProposal

func (s *Service) AutomationProposal(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID) (AIAutomationProposal, error)

func (*Service) BudgetHolds

func (s *Service) BudgetHolds(ctx context.Context, ws *store.Workspace, p *authz.Principal) (AIBudgetHolds, error)

BudgetHolds also shows abandoned reserved calls before the maintenance sweep runs. Reconciliation waits longer than every possible HTTP timeout.

func (*Service) CampaignProposal

func (s *Service) CampaignProposal(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID) (AICampaignProposal, error)

func (*Service) CatalogEntries

func (s *Service) CatalogEntries(ctx context.Context, ws *store.Workspace) ([]integrations.IntegrationEntry, error)

CatalogEntries are the "AI models" group of Settings › Integrations: the five providers, each connected one with this month's use. A provider without a connected account names the connected one, which Connect waits for (it changes the first account).

func (*Service) ChangeModel

func (s *Service) ChangeModel(ctx context.Context, ws *store.Workspace, p *authz.Principal, in AIModelInput) (AISettings, error)

ChangeModel picks another model of the same provider.

func (*Service) ClearPersonalFeatureModel

func (s *Service) ClearPersonalFeatureModel(ctx context.Context, ws *store.Workspace, p *authz.Principal, feature string) (AIPersonalSettings, error)

ClearPersonalFeatureModel goes back to the workspace's model for the caller's own requests of a feature.

func (*Service) Connect

Connect connects the workspace's model (its first account's first model), after the fixed test prompt passes. Here another provider needs a disconnect first. A first model becomes every feature's default.

func (*Service) DecideAgent

func (s *Service) DecideAgent(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID, in AIAgentDecision) error

DecideAgent is deliberately absent from the model registry. A person decides exact revisions of a whole dependency bundle, and domain writes, history, provenance and decisions share the same transaction.

func (*Service) DecideAutomation

func (s *Service) DecideAutomation(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID, in AIDraftDecision) (AIDraftDecided, error)

func (*Service) DecideCampaign

func (s *Service) DecideCampaign(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID, in AIDraftDecision) (AIDraftDecided, error)

func (*Service) Disconnect

func (s *Service) Disconnect(ctx context.Context, ws *store.Workspace, p *authz.Principal) (AISettings, error)

Disconnect removes the key. The model, the cap and the prices stay for the next connection; the activity log, kept summaries and accepted text stay too.

func (*Service) DraftSegment

DraftSegment asks for the conditions a description means. Only the builder's own conditions are drafted (never the SQL editor), and the draft is counted like the builder counts.

func (*Service) ExecuteAgent

func (s *Service) ExecuteAgent(ctx context.Context, args AgentArgs) error

ExecuteAgent performs at most one paid request per job. Before HTTP, the reservation and requested checkpoint commit together. A crash there is uncertain, never an implicit second charge. Saved responses resume tools.

func (*Service) GenerateAutomation

func (*Service) GenerateCampaign

func (*Service) KeepSummary

KeepSummary saves a summary at the top of the report, labelled "Summary by AI, kept by …". Its numbers are checked again first, edits included: a number the report doesn't have isn't kept (review AN-6). It is a content change on the report (audited; the activity log says Kept), never shown on read-only links.

func (*Service) KeptSummary

func (s *Service) KeptSummary(ctx context.Context, ws *store.Workspace, id uuid.UUID) (AIKeptSummary, error)

KeptSummary returns the summary kept on a campaign's report, checked against the report as it is now.

func (*Service) LearnVoice

func (*Service) LinkText

LinkText suggests link text for an accessibility issue: the link text, its address and the sentence around it.

func (*Service) LockAssistantConfig

func (s *Service) LockAssistantConfig(ctx context.Context, q *store.Queries, ws uuid.UUID) error

LockAssistantConfig takes the workspace's AI configuration lock for a turn's claim or next round, before its thread's: shared with the workspace's other turns, never with a change to the configuration (a change waits for the turns holding it; turns that ask after a waiting change wait for it). Removing a model clears the threads using it under the exclusive lock. The turn's reservation then takes the budget's lock (ReserveAssistant): one turn at a time reserves.

func (*Service) MarkReviewed

func (s *Service) MarkReviewed(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID, lang string) error

MarkReviewed ends "Translated by AI · not reviewed".

func (*Service) Models

func (s *Service) Models(ctx context.Context, ws *store.Workspace, in AIModelsInput) (AIModelList, error)

Models lists the models a key can use.

func (*Service) Personal

Personal returns the personal keys' settings for the caller.

func (*Service) PersonalBudgetHolds

func (s *Service) PersonalBudgetHolds(ctx context.Context, ws *store.Workspace, p *authz.Principal) (AIBudgetHolds, error)

PersonalBudgetHolds lists the caller's own holds on their personal keys.

func (*Service) Purge

func (s *Service) Purge(ctx context.Context) (int64, error)

Purge removes temporary generation content and the 90-day activity log.

func (*Service) ReadyAssistant

func (s *Service) ReadyAssistant(ctx context.Context, q *store.Queries, ws *store.Workspace, m *AssistantModel) error

ReadyAssistant checks that a thread's model can take a request now: the key works, the switch and the caps allow it.

func (*Service) ReconcileBudget

func (s *Service) ReconcileBudget(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID, in AIBudgetReconcileInput) error

ReconcileBudget records provider-verified counts. It does not restart a run, recover a lost response, accept a draft or reset cumulative limits.

func (*Service) ReconcilePersonalBudget

func (s *Service) ReconcilePersonalBudget(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID, in AIBudgetReconcileInput) error

ReconcilePersonalBudget records provider-verified counts for one of the caller's own holds on their personal keys, in their own budget.

func (*Service) RecordOutcome

func (s *Service) RecordOutcome(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID, in AIOutcomeInput) error

RecordOutcome stores the outcome of a suggestion the person asked for.

func (*Service) RemoveAccount

func (s *Service) RemoveAccount(ctx context.Context, ws *store.Workspace, p *authz.Principal, account uuid.UUID) (AISettings, error)

RemoveAccount removes an account, its key and its models. The activity log keeps their requests. An account a feature uses stays.

func (*Service) RemoveMemberAccount

func (s *Service) RemoveMemberAccount(ctx context.Context, ws *store.Workspace, p *authz.Principal, account uuid.UUID) (AISettings, error)

RemoveMemberAccount removes a member's personal account, its key and its models, for integration managers (offboarding). The member's picks of its models go with it.

func (*Service) RemoveModel

func (s *Service) RemoveModel(ctx context.Context, ws *store.Workspace, p *authz.Principal, account, model uuid.UUID) (AISettings, error)

RemoveModel removes a model no feature uses. An account keeps at least one model: removing the last one is removing the account.

func (*Service) RemovePersonalAccount

func (s *Service) RemovePersonalAccount(ctx context.Context, ws *store.Workspace, p *authz.Principal, account uuid.UUID) (AIPersonalSettings, error)

RemovePersonalAccount removes one of the caller's own accounts, its key and its models; refused while the caller picked one of them for a feature.

func (*Service) RemovePersonalModel

func (s *Service) RemovePersonalModel(ctx context.Context, ws *store.Workspace, p *authz.Principal, account, model uuid.UUID) (AIPersonalSettings, error)

RemovePersonalModel removes one of the caller's models; refused while they picked it for a feature.

func (*Service) RemoveSummary

func (s *Service) RemoveSummary(ctx context.Context, ws *store.Workspace, id uuid.UUID) error

RemoveSummary takes a kept summary off the report (audited, review AN-6).

func (*Service) ReplaceAccountKey

func (s *Service) ReplaceAccountKey(ctx context.Context, ws *store.Workspace, p *authz.Principal, account uuid.UUID, in AIKeyInput) (AISettings, AITestResult, error)

ReplaceAccountKey tests a new key with the account's first model and saves it.

func (*Service) ReplaceKey

ReplaceKey tests a new key and saves it.

func (*Service) ReplacePersonalKey

func (s *Service) ReplacePersonalKey(ctx context.Context, ws *store.Workspace, p *authz.Principal, account uuid.UUID, in AIKeyInput) (AIPersonalSettings, AITestResult, error)

ReplacePersonalKey tests a new key for one of the caller's own accounts and saves it; an account whose key was removed is connected again.

func (*Service) ReserveAssistant

func (s *Service) ReserveAssistant(ctx context.Context, q *store.Queries, ws *store.Workspace, p *authz.Principal, m *AssistantModel, req *llm.Request, l AssistantLedger, id uuid.UUID) error

ReserveAssistant reserves one model request of a thread: against the monthly cap (the workspace's or the key owner's) and the thread's ceilings, at the model's prices. It bounds req's answer to what is left. The caller holds the configuration lock (LockAssistantConfig) and the thread's, and read p (as the workspace knows them now) and m (ResolveAssistantModel) under them in this transaction: they aren't read again. id is the request's.

func (*Service) ResolveAssistantModel

func (s *Service) ResolveAssistantModel(ctx context.Context, q *store.Queries, ws, user uuid.UUID, model *uuid.UUID) (*AssistantModel, error)

ResolveAssistantModel is the model a thread of user uses: the one named, or else their own pick for the assistant, or the workspace's. Another person's personal model isn't there; a model the assistant can't use (disconnected, its key rejected, its tool check not passed, personal keys off) is refused with the reason.

func (*Service) Rewrite

Rewrite asks for a shorter, friendlier, more formal or more direct text, or a rewrite as instructed. An instruction about sender reputation isn't sent: the answer points at HostRepute's assistant.

func (*Service) SetAgentRunLimits

func (s *Service) SetAgentRunLimits(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID, in AIAgentLimitChange) error

SetAgentRunLimits changes only the cumulative ceiling, never counters or execution state. Continuation remains the initiator's explicit decision.

func (*Service) SetAgentSettings

func (s *Service) SetAgentSettings(ctx context.Context, ws *store.Workspace, p *authz.Principal, in AIAgentSettings) error

func (*Service) SetAssistantSettings

func (s *Service) SetAssistantSettings(ctx context.Context, ws *store.Workspace, p *authz.Principal, in AIAssistantSettings) (AISettings, error)

SetAssistantSettings turns the assistant on or off and sets each new thread's limits and the turns at once. It takes the AI configuration lock, like every change a request is bound by.

func (*Service) SetCap

SetCap changes the monthly cap.

func (*Service) SetFeature

func (s *Service) SetFeature(ctx context.Context, ws *store.Workspace, p *authz.Principal, feature string, on bool) (AISettings, error)

SetFeature switches a feature on or off.

func (*Service) SetFeatureModel

func (s *Service) SetFeatureModel(ctx context.Context, ws *store.Workspace, p *authz.Principal, feature string, in AIFeatureModelInput) (AISettings, error)

SetFeatureModel picks the model a feature uses: a model of a connected account whose key works, that reads images for alt text, and that passed the tool-calling check for the agent and the assistant. Requests already prepared with the previous model are refused, not moved.

func (*Service) SetModelPrices

func (s *Service) SetModelPrices(ctx context.Context, ws *store.Workspace, p *authz.Principal, account, model uuid.UUID, in AIPricesInput) (AISettings, error)

SetModelPrices changes the prices a model's requests are estimated with.

func (*Service) SetPersonalFeatureModel

func (s *Service) SetPersonalFeatureModel(ctx context.Context, ws *store.Workspace, p *authz.Principal, feature string, in AIFeatureModelInput) (AIPersonalSettings, error)

SetPersonalFeatureModel picks one of the caller's own models for their own requests of a feature, with the rules of the workspace's defaults. Requests already prepared with another model aren't sent; the caller's agent runs keep the model they began with.

func (*Service) SetPersonalKeys

func (s *Service) SetPersonalKeys(ctx context.Context, ws *store.Workspace, p *authz.Principal, in AIPersonalKeysInput) (AISettings, error)

SetPersonalKeys turns personal keys on or off and sets each person's monthly cap. Turning them off keeps the accounts; their requests are refused until they are turned on again.

func (*Service) SetPersonalModelPrices

func (s *Service) SetPersonalModelPrices(ctx context.Context, ws *store.Workspace, p *authz.Principal, account, model uuid.UUID, in AIPricesInput) (AIPersonalSettings, error)

SetPersonalModelPrices changes the prices of one of the caller's models.

func (*Service) SetPrices

func (s *Service) SetPrices(ctx context.Context, ws *store.Workspace, p *authz.Principal, in AIPricesInput) (AISettings, error)

SetPrices changes the prices the cap is estimated with.

func (*Service) Settings

func (s *Service) Settings(ctx context.Context, ws *store.Workspace, p *authz.Principal) (AISettings, error)

Settings returns the AI assistant's page.

func (*Service) StartAgent

func (*Service) Status

func (s *Service) Status(ctx context.Context, ws *store.Workspace, p *authz.Principal) (AIStatus, error)

Status describes the assistant for a person with ai:use. Each feature is on when its own model's account is connected, and has that model's state and budget. The model it names is the first account's, or else the first connected model a feature uses.

func (*Service) SubjectIdeas

SubjectIdeas asks for five subject lines and checks each one.

func (*Service) Summarize

Summarize asks for a plain-language summary of a report's numbers. The model writes each number as its metric's key; the numbers are filled in from the report in the reader's format, so each is the metric's own, and anything else is listed as unmatched. The A/B test's decision goes with its confidence, so a test without a clear winner reads as one.

func (*Service) Test

Test runs Test connection on the saved model, or on the one being set up.

func (*Service) TestAgentTools

func (s *Service) TestAgentTools(ctx context.Context, ws *store.Workspace, p *authz.Principal) (AIAgentCapability, error)

TestAgentTools has one harmless schema, no domain dispatcher and no user content. Managers without ai:use can test, but cannot supply a prompt or start a task. The ordinary reservation ledger accounts this fixed probe. It tests the agent's model.

func (*Service) TestModelTools

func (s *Service) TestModelTools(ctx context.Context, ws *store.Workspace, p *authz.Principal, account, model uuid.UUID) (AIAgentCapability, error)

TestModelTools runs the tool-calling check on one model of an account.

func (*Service) TestPersonalModel

func (s *Service) TestPersonalModel(ctx context.Context, ws *store.Workspace, p *authz.Principal, account, model uuid.UUID) (AITestResult, error)

TestPersonalModel runs Test connection on one of the caller's models.

func (*Service) TestPersonalModelTools

func (s *Service) TestPersonalModelTools(ctx context.Context, ws *store.Workspace, p *authz.Principal, account, model uuid.UUID) (AIAgentCapability, error)

TestPersonalModelTools runs the tool-calling check on one of the caller's models: the agent and the assistant use a personal model only once it passed.

func (*Service) Translate

Translate asks for a translation of the source, block by block, with its subject and preheader. Every token and link of the source must still be there: what the model changed is restored, and the blocks say so.

func (*Service) TranslationMarks

func (s *Service) TranslationMarks(ctx context.Context, ws *store.Workspace, id uuid.UUID) (AITranslationMarks, error)

TranslationMarks says which versions are "Translated by AI · not reviewed".

Directories

Path Synopsis
Package assistant is the AI assistant's threads (assistant brief D1, D7; milestone B3): a person's conversations in a workspace, with the model each uses, what the person attached and confirmed sharing, and their cumulative ceilings.
Package assistant is the AI assistant's threads (assistant brief D1, D7; milestone B3): a person's conversations in a workspace, with the model each uses, what the person attached and confirmed sharing, and their cumulative ceilings.
llm
Package llm talks to the AI model a workspace connects (design expansion, phase 3): Anthropic, OpenAI, Google Gemini, Azure OpenAI and servers that speak the OpenAI API (Ollama, vLLM, LM Studio).
Package llm talks to the AI model a workspace connects (design expansion, phase 3): Anthropic, OpenAI, Google Gemini, Azure OpenAI and servers that speak the OpenAI API (Ollama, vLLM, LM Studio).
contracttest
Package contracttest is the shared test suite every AI provider adapter passes (design expansion, plan §8: each new provider kind gets one, like the sending adapters' internal/providers/contracttest).
Package contracttest is the shared test suite every AI provider adapter passes (design expansion, plan §8: each new provider kind gets one, like the sending adapters' internal/providers/contracttest).

Jump to

Keyboard shortcuts

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