ai

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: AGPL-3.0 Imports: 58 Imported by: 0

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"
)

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"
)

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 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 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    `json:"feature" enum:"subject_ideas,rewrite,translate,alt_text,accessibility_fix,segment_draft,report_summary"`
	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"`
	Outcome      string    `json:"outcome" enum:"pending,accepted,accepted_edits,kept,rejected,discarded,refused,error,nothing_drafted,cancelled"`
	Detail       string    `json:"detail,omitempty" doc:"1 of 5, 529 overloaded"`
}

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

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 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).
	Features []string `json:"features,omitempty" maxItems:"7"`
}

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"`
}

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

type AIFeatureInput

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

AIFeatureInput switches a feature.

type AIFeatureState

type AIFeatureState struct {
	Key string `json:"key" enum:"subject_ideas,rewrite,translate,alt_text,accessibility_fix,segment_draft,report_summary"`
	On  bool   `json:"on"`
	// Available is false for alt text with a model that doesn't read images.
	Available bool `json:"available"`
}

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 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 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"`
}

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 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"`
	// 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"`
}

AIProviderEntry is a provider of the catalog.

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"`
}

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"`
}

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"`
}

AISettings is Settings › Integrations › AI assistant.

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     []AIFeatureState `json:"features"`
	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"`
}

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.

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"`
}

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"`
}

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 `json:"feature" enum:"subject_ideas,rewrite,translate,alt_text,accessibility_fix,segment_draft,report_summary"`
	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"`
	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 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
	// 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
	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) Activity

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

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) 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, the connected one with this month's use.

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) Connect

Connect connects the workspace's model, after the fixed test prompt passes. One model per workspace: another provider needs a disconnect first.

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) 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) LinkText

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

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) Purge

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

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

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) 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) ReplaceKey

ReplaceKey tests a new key and saves it.

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) 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) 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) 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.

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) 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
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