core

package
v1.20.2 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: Apache-2.0 Imports: 81 Imported by: 1 module, 0 packages

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

Documentation

Overview

Package core is Godwit's mail engine.

Index

Constants

View Source
const (
	MaxCacheBytes   = 2 << 30  // attachment cache budget; oldest files are evicted beyond it
	MaxMessageBytes = 25 << 20 // largest attachment or message accepted
)
View Source
const (
	WarningPlugin     = "plugin_warning"
	WarningNoResponse = "no_response"
)
View Source
const (
	MaskMask  = mask.Mask
	MaskWarn  = mask.Warn
	MaskBlock = mask.Block
)

What 脱敏 does with a category's values (MaskCategory.Action): 遮住 sends placeholders (the default; "" too); 仅警告 sends them as they are and records them; 拦截 sends nothing of the request.

View Source
const (
	MaxMaskRules = mask.MaxRules
	MaxMaskAllow = mask.MaxAllow
)
View Source
const (
	MCPSendOff     = "off"
	MCPSendConfirm = "confirm"
	MCPSendDirect  = "direct"
)

通过 MCP 发送's levels (Settings.MCPSend).

View Source
const (
	AuditLocalAPI = "local_api"
	AuditMCP      = "local_mcp"
)

External audit sources: the Local API's full role, and its mcp role (the godwit mcp bridge; "local_mcp", unlike the "mcp" of MCP-server tools).

View Source
const (
	ProviderOpenAI    = "openai"
	ProviderAnthropic = "anthropic"
	ProviderTypeSafe  = "typesafe"
	ProviderOther     = "other"
	ProviderChatGPT   = "chatgpt"
	ProviderGrok      = "grok"
)

Providers: which formats a service offers (the add dialog's tiles).

View Source
const (
	CapGen   = "gen"
	CapJudge = "judge"
)

Capabilities, the keys of ModelService.Status.

View Source
const (
	KeyKeep    = "keep"    // reuse the stored key; only while kind and address are unchanged
	KeyReplace = "replace" // use APIKey
	KeyClear   = "clear"   // no key
)

Key actions for ModelServiceInput.KeyAction.

View Source
const (
	MinJudgeThreshold = 0.5
	MaxJudgeThreshold = 0.95
)

MinJudgeThreshold and MaxJudgeThreshold bound the user-adjustable cutoff.

View Source
const (
	LabelDisplayBoth = "both"
	LabelDisplayIcon = "icon"
	LabelDisplayText = "text"
)

Label chips' looks (Settings.LabelDisplay): icon and name, icon only, name only.

View Source
const (
	MinThreadCollapse     = 2
	MaxThreadCollapse     = 100
	DefaultThreadCollapse = 5
)

MinThreadCollapse and MaxThreadCollapse bound ThreadCollapseThreshold.

View Source
const (
	SignatureImageMax  = 512 << 10
	SignatureImagesMax = 4
)

Signature images: png, jpeg, gif or webp, sniffed (never named), at most SignatureImageMax bytes each and SignatureImagesMax per signature. They are stored per signature, content-addressed, and referenced in the signature as cid:sig-<hash>@godwit; a sent mail carries them as inline parts. Any draft may show any of them: accounts share signatures. Their metadata (EXIF with its GPS, XMP, text) is stripped before storing.

View Source
const (
	SecurityTLS      = conn.TLS
	SecurityStartTLS = conn.StartTLS
	SecurityNone     = conn.None
)
View Source
const (
	UnsubscribeOneClick = "one_click" // Godwit POSTs List-Unsubscribe=One-Click to URL
	UnsubscribeWeb      = "web"       // the user opens URL in the browser
	UnsubscribeMail     = "mailto"    // the user sends a draft made from URL
)

The ways a message can be unsubscribed from, by its List-Unsubscribe and List-Unsubscribe-Post headers only (RFC 2369, RFC 8058); links in the body never count.

View Source
const (
	UnsubscribeFailedStatus    = "status"     // a status other than 2xx or 3xx
	UnsubscribeFailedRedirect  = "redirect"   // a 3xx, never followed
	UnsubscribeFailedTimeout   = "timeout"    // no answer in time
	UnsubscribeFailedNotPublic = "not_public" // the host is not a public address
	UnsubscribeFailedConnect   = "connect"    // no connection, or it broke
)

Why a one-click unsubscribe failed.

View Source
const AccountIconMax = 5 << 20

AccountIconMax is the most bytes an uploaded account icon may have.

View Source
const AppleIntelligencePlugin = "apple-intelligence"

AppleIntelligencePlugin uses Apple Intelligence on macOS for generation, small tasks, and classification.

View Source
const KindInvalid conn.FailureKind = "invalid"

KindInvalid marks a failed settings step: the input itself is not valid.

View Source
const MaxAIInstructions = 2000

MaxAIInstructions is the most runes an account's AI instructions have: every draft from the account sends them to the model.

View Source
const MaxLabelDescription = 500

MaxLabelDescription is the most runes a label description has: every classification sends every description to the model.

View Source
const MaxLabelName = 32

MaxLabelName is the most runes a label name has.

View Source
const MaxSignatureName = 64

MaxSignatureName is the most characters a signature's name has.

View Source
const OutboxExpiry = 3 * 24 * time.Hour

OutboxExpiry is how long an item may wait in the queue, counted from when it is sent at the earliest (SendAfter; resend restarts it). Past it, the item fails as expired instead of being sent.

View Source
const SignInCodesPlugin = "sign-in-codes"

SignInCodesPlugin recognizes sign-in codes and links: the banner, the tray's recent list and the reader's card.

View Source
const SignatureHTMLPrefix = "<!--godwit:html-->"

SignatureHTMLPrefix marks a stored signature as the settings editor's HTML; any other signature (the CLI's, the Local API's, an older one) is plain text.

View Source
const SystemTranslationPlugin = "system-translation"

SystemTranslationPlugin translates with the operating system's on-device translation (macOS 26's Translation framework).

View Source
const UndoSendWindow = 10 * time.Second

UndoSendWindow is how long a sent message waits in the outbox before it is sent, so that CancelOutbox can take it back.

Variables

View Source
var (
	ErrTooLarge       = errors.New("attachment exceeds the size limit")
	ErrNotOnServerYet = errors.New("message has not reached the server yet")
)
View Source
var (
	ErrNothingToCompact = errors.New("the conversation has nothing to compact")
	ErrCompacting       = errors.New("the conversation is being compacted")
)
View Source
var (
	ErrNeedsGrant     = errors.New("permissions are not granted")
	ErrPluginNotFound = errors.New("plugin not found")
)
View Source
var (
	ErrMaskKind         = mask.ErrKind
	ErrMaskEmptyMatch   = mask.ErrEmptyMatch
	ErrMaskReservedKind = mask.ErrReservedKind
	ErrMaskTooManyRules = mask.ErrTooManyRules
	ErrMaskTooManyAllow = mask.ErrTooManyAllow
)
View Source
var (
	// ErrMCPSendOff: 通过 MCP 发送 is 不允许, or 每次确认 with no window to confirm in (--headless).
	ErrMCPSendOff = errors.New("sending through MCP is off; the user can turn it on in Godwit under Settings › Intelligence › AI apps › Send through MCP")
	// ErrMCPSendComposing: 直接发送 of a draft open in a compose window,
	// which may hold edits not saved yet.
	ErrMCPSendComposing = errors.New("the draft is open in a compose window in Godwit; the user can send it there")
	// ErrMCPSendBusy: maxMCPSends requests wait for the user already.
	ErrMCPSendBusy = errors.New("too many sends are waiting for the user in Godwit; ask again once the user has answered them")
)
View Source
var (
	ErrAINotConfigured      = errors.New("no model configured")
	ErrModelServiceNotFound = errors.New("model service not found")
	ErrModelNotFound        = errors.New("model not found")
	// ErrTranslatorUnavailable: the settings translate with a plugin that is not running.
	ErrTranslatorUnavailable = errors.New("the translation plugin is not running")
	// ErrModelUnavailable: a reference names a plugin model whose plugin is not
	// running or no longer lists it. Unlike a removed service it never falls
	// back to the default model.
	ErrModelUnavailable = errors.New("the model's plugin is not running or no longer offers it")
)
View Source
var (
	ErrModelAuth       = ai.ErrModelAuth
	ErrBaseURLInvalid  = ai.ErrBaseURLInvalid
	ErrBaseURLScheme   = ai.ErrBaseURLScheme
	ErrKeyNeedsConfirm = errors.New("the address or protocol changed: enter the key again or choose no key")
)
View Source
var (
	ErrRegistryOff       = errors.New("no plugin registry is configured")
	ErrRegistrySignature = errors.New("the plugin registry's signature does not match")
	ErrRegistryStale     = errors.New("the plugin registry is older than the one Godwit has")
	ErrRegistryMismatch  = errors.New("the downloaded file does not match the plugin registry; it was discarded")
)
View Source
var (
	// ErrSignatureImage is an image that is not png, jpeg, gif or webp, or is over SignatureImageMax.
	ErrSignatureImage = errors.New("a signature image must be a png, jpeg, gif or webp of at most 512 KB")
	// ErrSignatureImageCount is a signature with more than SignatureImagesMax images.
	ErrSignatureImageCount = errors.New("a signature has at most 4 images")
)
View Source
var (
	// ErrSignatureNotFound is a signature id that does not exist.
	ErrSignatureNotFound = errors.New("signature not found")
	// ErrSignatureName is a name that is empty or over MaxSignatureName.
	ErrSignatureName = errors.New("a signature's name is 1 to 64 characters")
)
View Source
var (
	ErrSkillDisabled = errors.New("skill is disabled")
	ErrSkillNotFound = errors.New("skill not found")
)
View Source
var (
	// ErrSystemLanguageNotInstalled: the system translates the pair once the
	// user downloads its languages in the system's settings.
	ErrSystemLanguageNotInstalled = errors.New("the languages are not downloaded for system translation")
	// ErrSystemLanguageUnsupported: the system does not translate the pair.
	ErrSystemLanguageUnsupported = errors.New("system translation does not support these languages")
)
View Source
var (
	ErrNoUnsubscribe  = errors.New("message has no unsubscribe header")
	ErrUnsubscribeWeb = errors.New("this unsubscribe is a web page: open it in the browser")
	ErrUnsubscribing  = errors.New("already unsubscribing from this message")
)
View Source
var DefaultRegistry = func() *RegistrySource {
	key, err := base64.StdEncoding.DecodeString(registryPublicKey)
	if err != nil || len(key) != ed25519.PublicKeySize {
		return nil
	}
	return &RegistrySource{URL: registryURL, PublicKey: key}
}()

DefaultRegistry is Godwit's own registry, nil while it has no key.

View Source
var ErrAccountIcon = errors.New("an account icon must be a png, jpeg, gif, webp or svg of at most 5 MB")

ErrAccountIcon is an icon that is not png, jpeg, gif, webp or svg, or is over AccountIconMax.

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

ErrAccountNotFound is returned for an account id that does not exist.

View Source
var ErrClosed = errors.New("service is closed")

ErrClosed is returned by calls made after Close.

View Source
var ErrDraftGone = errors.New("the draft is gone")

GetDraft returns the draft with its attachments. HTML is sanitized again on ErrDraftGone: an approval made no draft, or it was sent or deleted since.

View Source
var ErrInvalidState = errors.New("item is not waiting for a decision")

ErrInvalidState is returned by ResolveOutbox and ResolveApproval for an item that is not waiting for a decision, and by CancelOutbox for one no longer queued.

View Source
var ErrKeychainUnavailable = errors.New("system keychain is unavailable")

ErrKeychainUnavailable means the system keychain cannot be used (locked, no secret service, access denied). Credentials never fall back to a file.

View Source
var ErrLabelExists = errors.New("a label with this name exists")

ErrLabelExists is a label name already taken, ignoring case and outer spaces.

View Source
var ErrLinkRef = errors.New("the draft has a link reference that could not be restored (" + linkRefPrefix + "…): replace the link before sending")

ErrLinkRef is a draft that still holds a link reference: sending it would mail the recipient a link that only works here.

View Source
var ErrMCPNotFound = errors.New("MCP server not found")
View Source
var ErrModelLogin = errors.New("sign in to add this service")

ErrModelLogin is returned when adding a subscription model service without signing in first.

View Source
var ErrModelReauth = errors.New("the model service sign-in is no longer valid; sign in again")

ErrModelReauth is returned when a subscription model service's refresh token has been revoked, expired or lost from the keychain.

View Source
var ErrNeedsAnswer = errors.New("a question needs its answers")

ErrNeedsAnswer: a question is accepted only with its answers (AnswerQuestion).

View Source
var ErrNoOutboxDraft = errors.New("the outbox item has no draft to bring back")

ErrNoOutboxDraft is CancelOutbox's and ResolveOutbox edit's error for an item queued before undo send: it has no draft to bring back.

View Source
var ErrNotGrantable = errors.New("this tool cannot be allowed for the whole conversation")

ErrNotGrantable: the approval's tool cannot be allowed for the whole conversation.

View Source
var ErrNotSynced = mailsync.ErrNotSynced

ErrNotSynced is LoadOlder on a folder whose first sync has not completed.

View Source
var ErrPlaceholder = errors.New("the draft has a placeholder that could not be restored ({{…}}): replace it with what it stands for before sending")

ErrPlaceholder is a draft that still holds a 脱敏 placeholder: sending it would mail the recipient the placeholder, not its value.

View Source
var ErrProviderMismatch = errors.New("signed in with a different provider")

ErrProviderMismatch: AccountInput.Provider names another provider than the one the OAuth flow signed in with.

View Source
var ErrRunActive = errors.New("the conversation already has an active run")

ErrRunActive: the conversation has a run that is running, waiting for approvals or resuming.

View Source
var ErrStaleApproval = errors.New("the tool changed since this was proposed")

ErrStaleApproval: what an external approval was bound to (plugin code, permissions or config; an MCP server or tool definition) changed since it was proposed; it was not run.

View Source
var ErrStaleDraft = errors.New("draft changed since it was loaded")

ErrStaleDraft means the draft changed since the revision the caller saved against, or it is in the outbox: read-only until it is taken back (CancelOutbox), or gone once the message may have gone out.

View Source
var ErrUnknownFlow = errors.New("no such sign-in flow")

ErrUnknownFlow: no such flow ID, or it was already awaited, cancelled or expired.

View Source
var ErrUseAssist = errors.New("draft skills run through AssistSkill")

ErrUseAssist: skills on drafts run through AssistSkill, which makes proposals.

View Source
var ErrWrongAccount = errors.New("signed in with a different account")

ErrWrongAccount: the OAuth sign-in was for another address than the account's.

View Source
var LabelColors = []string{"gray", "red", "orange", "amber", "yellow", "lime", "green", "teal", "sky", "blue", "violet", "pink"}

LabelColors are the colors a label may take, in the picker's order.

View Source
var LabelIcons = []string{"shield-keyhole", "bill", "truck", "plane", "calendar-event", "notification-3", "newspaper", "shopping-bag-3",
	"folder-3", "money-dollar-circle", "book-2", "graduation-cap", "pencil", "quill-pen", "braces", "terminal-box",
	"music-2", "movie-2", "tools", "palette", "stethoscope", "first-aid-kit", "seedling", "briefcase-4",
	"bar-chart-box", "run", "sticky-note", "scales-3", "earth", "global", "hammer", "footprint",
	"flask", "brain", "heart-3", "plant", "team", "home-4", "key-2", "chat-3"}

LabelIcons are the icons a label may take, in the picker's order; the GUI draws each as "label-<name>".

View Source
var PurgeDays = []int{0, 1, 7, 30}

PurgeDays are the purge periods offered: never, a day, a week and a month.

Functions

func CheckMasking added in v1.18.0

func CheckMasking(rules []MaskRule, allow []string, kept ...MaskRule) error

CheckMasking says what is wrong with rules and allow, as SetSettings would; a rule in kept, the ones stored, may keep a built-in kind.

func MaskBlocked added in v1.18.0

func MaskBlocked(err error) []string

MaskBlocked is the categories (mask's names) whose values blocked err's request (拦截), nil if masking did not block it.

func ModelEndpoint

func ModelEndpoint(kind, base string) string

ModelEndpoint is the URL requests to a service at base will hit.

func ModelProviderLogin added in v1.1.0

func ModelProviderLogin(p string) string

ModelProviderLogin returns "oauth" if provider p signs in with OAuth, else "".

func ModelProviderURL added in v1.1.0

func ModelProviderURL(p string) string

ModelProviderURL returns the fixed BaseURL of a subscription model provider, or "".

func NormalizeModelBaseURL

func NormalizeModelBaseURL(raw string) (string, error)

NormalizeModelBaseURL is the address a service is saved with, whatever its formats: ErrBaseURLInvalid or ErrBaseURLScheme says why raw is refused.

func ProviderFormats

func ProviderFormats(p string) (gen, judge []string)

ProviderFormats are the generate kinds and judge formats provider p offers, in the dialog's order.

func SerializeKeyringForTest

func SerializeKeyringForTest()

SerializeKeyringForTest makes keychain calls one at a time. Tests only: go-keyring's mock (keyring.MockInit) is not safe for concurrent use, and sync workers read credentials while a test writes them. Call it before any Service starts; later calls do nothing.

func SignatureEditorHTML

func SignatureEditorHTML(sig string, cids map[string]bool) string

SignatureEditorHTML is sig as safe compose HTML, without the draft marker or the "-- " delimiter: a marked one sanitized (user markers stripped, the images in cids kept), a plain one escaped into a paragraph; "" for none.

func SignatureImageURL

func SignatureImageURL(data []byte) (string, error)

SignatureImageURL is data as a data: URL for the signature editor, or ErrSignatureImage.

func SignaturePreview added in v1.9.0

func SignaturePreview(html string, n int) []string

SignaturePreview is a stored signature's text (Signature.HTML), its first n non-empty lines: a list row's preview.

func SyncDevDatabase added in v1.2.0

func SyncDevDatabase(ctx context.Context, src, dst string) (err error)

SyncDevDatabase replaces dst's database with an isolated copy of src's. It requires both data directories to be offline and never migrates src.

func WithTimeZone added in v1.17.0

func WithTimeZone(ctx context.Context, name string) context.Context

WithTimeZone is ctx with the user's IANA time zone (the UI's, sent with each call) for the local time Wit's runs give the model. Go loads time.Local once per process, so it goes stale when the OS zone changes while the app runs. An empty or unknown name leaves ctx as it is: time.Local holds.

Types

type Account

type Account struct {
	ID                                      int64
	Email, Name, Alias, Signature, Username string // Signature is SignatureID's (Signature.HTML), "" for none
	SignatureID                             int64  // its default signature, 0 none
	Icon                                    string // ” the provider's mark, label:<name>, brand:<provider id> or image:<n> (AccountIcon)
	AIInstructions                          string // the user's facts and guidelines for Wit drafting from this account
	IsDefault                               bool
	Sync                                    SyncRange
	Folders                                 int // folders synced so far: 0 before the first sync
	AuthType, Status                        string
	IMAPHost                                string
	IMAPPort                                int
	IMAPSecurity                            Security
	SMTPHost                                string
	SMTPPort                                int
	SMTPSecurity                            Security
	Provider, StatusDetail                  string
}

Account is a stored account. The password lives only in the system keychain. Status is ok; reauth_required when the password is missing from the keychain (StatusDetail credentials_missing) or the IMAP or SMTP server refuses it (auth_rejected) or the provider revoked an OAuth grant (token_revoked); or error when the keychain is unavailable (keychain_unavailable). An OAuth account's keychain entry holds its refresh token; access tokens stay in memory.

type AccountIcon added in v1.9.0

type AccountIcon struct {
	ContentType string
	Data        []byte
}

AccountIcon is an account's uploaded icon image.

type AccountInput

type AccountInput struct {
	Email, Name, Alias, Signature, Username, Password string
	IsDefault                                         bool
	Sync                                              *SyncRange // nil: the newest 2000 per folder
	IMAPHost                                          string
	IMAPPort                                          int
	IMAPSecurity                                      Security
	SMTPHost                                          string
	SMTPPort                                          int
	SMTPSecurity                                      Security
	Provider                                          string // auth.Provider ID; empty is stored as other
	// OAuthFlowID names a finished AwaitOAuth flow: the account signs in with its
	// tokens instead of Password, and Email must be the signed-in address.
	OAuthFlowID string
}

AccountInput is what the user supplies to add or test an account.

type AccountPatch

type AccountPatch struct {
	Name, Alias, Signature *string
	SignatureID            *int64
	IsDefault              *bool
	Sync                   *SyncRange
	Servers                *ServerSettings
	Icon                   *string // ”, label:<name> or brand:<provider id>
	IconImage              []byte  // an uploaded png, jpeg, gif, webp or svg: Icon becomes image:<n>
	AIInstructions         *string // trimmed, at most MaxAIInstructions runes
}

AccountPatch changes the account settings that are not nil. Signature rewrites the account's default signature (for every account using it), making one named as the account if it has none; SignatureID picks it, 0 for none.

type ActionInfo

type ActionInfo struct {
	ID, Plugin string
	Label      plugins.Text
	On         []string
}

ActionInfo is an action a running plugin registered; ID is <plugin>/<id>.

type ActionResult

type ActionResult struct {
	Text, HTML string
	DraftID    int64
}

ActionResult is what an action returned: text, HTML sanitized for reading, or a draft it made for the UI to open.

type AppleIntelligence added in v1.9.0

type AppleIntelligence interface {
	// Generate generates text for the given prompt with system instructions.
	Generate(ctx context.Context, system, prompt string) (string, error)
	// Judge evaluates typed questions against input.
	Judge(ctx context.Context, input string, qs []ai.Question) ([]ai.Answer, error)
	// Version changes when system model or OS update may change outputs.
	Version() string
}

AppleIntelligence is the system's on-device AI provider on macOS, offering text generation and classification.

type AppliedLabel added in v0.3.0

type AppliedLabel struct {
	LabelID int64
	Auto    bool
}

AppliedLabel is a label on a message or thread. Auto: the model set it, and no message of the thread has it set by hand.

type Approval

type Approval struct {
	ID, RunID, ConversationID int64
	Seq                       int
	CallID, Tool              string
	Args                      json.RawMessage
	Summary, State, Error     string
	Destinations              []string
	// SessionAllow: 本次对话都允许 can approve it (ResolveApprovalForConversation).
	SessionAllow bool
	// DraftID is the draft it made (an allowed create_draft), while that
	// draft exists: 0 once it is sent or deleted.
	DraftID int64
	// DraftEdit: it edits the draft of its conversation (update_draft,
	// update_selection), which the compose window shows in place.
	DraftEdit bool
	// Form is the form an MCP server asks the user to fill (formView JSON),
	// nil for none: AnswerQuestion answers it.
	Form json.RawMessage
}

Approval is a call waiting for the user or decided. State goes pending → executing → done or failed, or pending → rejected or stale. Error is what the model was told for any end state but done. Destinations are the hosts (host[:port]) the call sends data to, if any. CallID is the tool call it answers ("skill" for a skill's proposal).

type AttachmentInfo

type AttachmentInfo struct {
	ID                    int64
	Filename, ContentType string
	Size                  int
	Inline                bool
}

AttachmentInfo describes one attachment; its bytes are fetched lazily.

type Avatar added in v0.3.0

type Avatar struct {
	Data           []byte
	Format, Source string
	Width, Height  int
}

Avatar is a sender image; empty Data means there is no permitted image.

type CapStatus

type CapStatus struct {
	State      string // "ok" or "fail"
	LatencyMs  int
	HTTPStatus int    // the status that failed it, when known
	Code       string // why it failed: auth, forbidden, no_list, timeout, bad_answer, error, unreachable
	At         time.Time
}

CapStatus is a capability's last test. It holds codes, never error text: errors can echo a key, a response body or mail.

type Card

type Card struct {
	Plugin, Title string
	Fields        []CardField
	Buttons       []CardButton
}

Card is a plugin's declarative card for a message.

type CardButton

type CardButton struct{ Label, Kind, Value string }

CardButton: Kind copy (Value is the text), open-url (an http or https URL) or run-action (Value is the action's full ID, <plugin>/<id>).

type CardField

type CardField struct{ Label, Value string }

type CheckError

type CheckError struct {
	Report CheckReport
	// contains filtered or unexported fields
}

CheckError is returned by TestAccount and AddAccount when a check fails.

func (*CheckError) Error

func (e *CheckError) Error() string

func (*CheckError) Unwrap

func (e *CheckError) Unwrap() error

type CheckReport

type CheckReport struct {
	Steps   []CheckStep
	Folders int
}

Folders is how many selectable folders the imap step listed (0 if LIST failed).

func (CheckReport) OK

func (r CheckReport) OK() bool

OK reports whether every step passed.

type CheckStep

type CheckStep struct {
	Name    string
	OK      bool
	Skipped bool
	Kind    conn.FailureKind
	Detail  string
}

CheckStep is one item of a connection check. Name is settings, imap or smtp. Detail comes from conn's already redacted errors: no password, token or server text.

type Citation

type Citation struct {
	N             int
	MessageID     int64
	Subject, From string
	Date          time.Time
	Suspect       bool
	Quote         string // the suspect text, from where it starts (ai.InjectionQuote): show as plain text
	Snippet       string // the message's snippet, for the card that shows it
	Gone          bool   // the message was deleted since: nothing to open or quote
	RunID         int64
	CallID        string
	Source        string
}

Citation is a message a run's tools showed the model: RunID's call CallID (its tool_result), or when CallID is "" what Source says: mail the user quoted (citeQuote) or an assist run's context (citeContext). N is the message's citation number in the conversation (from 1, by first citation): the model knows the mail by it alone (its id) and cites it as <mail id="N"/>.

type Cited added in v1.12.0

type Cited struct {
	Citation
	CallIDs   []string
	InContext bool
}

Cited is a message a turn's runs showed the model, as the conversation cites it (suspect once any citation is): every call of the turn that showed it, and whether its runs' context did (an assist run's).

type Clock added in v1.14.0

type Clock interface {
	Now() time.Time
	AfterFunc(d time.Duration, f func()) (stop func() bool)
}

Clock is the Service's time source; tests swap in a fake one.

type ConfigValue

type ConfigValue struct {
	Key   string
	Value json.RawMessage
	Set   bool
}

ConfigValue is a plugin setting as the settings form shows it: the stored value, or with Set false the default. A secret's Value is always empty.

type Contact added in v1.18.0

type Contact struct {
	Name, Address string
	Messages      int
	Last          time.Time
}

Contact is a sender of synced mail, by address: the latest name it used, how many messages it sent and when the latest came.

type Conversation

type Conversation struct {
	ID                 int64
	Kind, Title, Model string
	Effort             string // the reasoning effort its runs ask for; "" sends none
	DraftID            int64
	Turns              []Turn
	ActiveRunID        int64
	UpdatedAt          time.Time
	// Usage sums its runs' tokens; Last is the latest run's that reported any.
	// HistoryUse is how full the history budget is, its summary standing in
	// (from 0; past 1, its oldest turns are summarized or left out). ListConversations
	// leaves both empty. Compactable: CompactConversation has turns to
	// summarize.
	Usage      ai.Usage
	HistoryUse float64
	// SummaryUse is the part of HistoryUse its summary takes (0: none).
	SummaryUse  float64
	Compactable bool
	// Answering means a run of it is running or resuming (or an allowed
	// call of it executes); Awaiting that one waits for the user to decide
	// its calls.
	Answering, Awaiting bool
}

Conversation is a Wit chat: kind "ask" (the mailbox panel) or "assist" (one draft's compose panel, DraftID set). Turns are its questions and answers; ActiveRunID is its run that is running, resuming or waiting for approvals (0: none). ListConversations leaves both empty.

type DefaultAppleIntelligence added in v1.9.0

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

DefaultAppleIntelligence is the built-in Apple Intelligence implementation: FoundationModels through the bundled helper binary.

func NewDefaultAppleIntelligence added in v1.9.0

func NewDefaultAppleIntelligence(helperPath, version string) *DefaultAppleIntelligence

NewDefaultAppleIntelligence runs the helper at helperPath; version names what may change its outputs (the OS build, the app that ships the helper).

func (*DefaultAppleIntelligence) Available added in v1.9.0

func (d *DefaultAppleIntelligence) Available() bool

Available reports whether Apple Intelligence is available on this Mac.

func (*DefaultAppleIntelligence) Generate added in v1.9.0

func (d *DefaultAppleIntelligence) Generate(ctx context.Context, system, prompt string) (string, error)

Generate produces text for the prompt using Apple's FoundationModels.

func (*DefaultAppleIntelligence) GenerateWithTemperature added in v1.9.0

func (d *DefaultAppleIntelligence) GenerateWithTemperature(ctx context.Context, system, prompt string, temp float64) (string, error)

GenerateWithTemperature produces text for the prompt using Apple's FoundationModels with a custom temperature.

func (*DefaultAppleIntelligence) Judge added in v1.9.0

func (d *DefaultAppleIntelligence) Judge(ctx context.Context, input string, qs []ai.Question) ([]ai.Answer, error)

Judge evaluates questions against input using Apple Intelligence.

func (*DefaultAppleIntelligence) Version added in v1.9.0

func (d *DefaultAppleIntelligence) Version() string

type DigestLine added in v1.19.0

type DigestLine []DigestRun

DigestLine is a line of a digest in runs: text, or a cite of the thread's message Message (Text "").

type DigestRun added in v1.19.0

type DigestRun struct {
	Text    string
	Message int64
}

DigestRun is a run of a DigestLine.

type Draft

type Draft struct {
	ID, AccountID          int64
	Mode                   string
	SourceMessageID        int64
	To, Cc, Bcc            []string
	ReplyTo, Subject, HTML string
	Attachments            []DraftAttachment
	UpdatedAt              time.Time
	// Revision grows by one on every update, an attachment added or removed
	// included (refetch it after one). SaveDraft with a non-zero Revision
	// fails with ErrStaleDraft unless it is still the stored one.
	Revision int64
}

Draft is an unsent message. Mode is new, reply, reply_all or forward.

type DraftAttachment

type DraftAttachment struct {
	ID                    int64
	Filename, ContentType string
	Size                  int
}

DraftAttachment is a file copied into the draft's directory.

type EgressApprovalRequired

type EgressApprovalRequired struct {
	Plugin string
	Hosts  []string
}

EgressApprovalRequired: the run may send mail content to Hosts (every host the plugin declares); ask the user, then run again with ApproveEgress.

func (*EgressApprovalRequired) Error

func (e *EgressApprovalRequired) Error() string

type ErrNoRoleFolder

type ErrNoRoleFolder struct{ Role string }

ErrNoRoleFolder is MoveToRole's error for an account without a folder of Role.

func (*ErrNoRoleFolder) Error

func (e *ErrNoRoleFolder) Error() string

type FindGroup added in v1.18.0

type FindGroup[T any] struct {
	Items []T
	Total int
}

FindGroup is the first hits of a kind and how many there are in all.

type FindQuery added in v1.18.0

type FindQuery struct {
	SearchQuery
	Kind  string
	Limit int
}

FindQuery is a search across kinds: Kind "" finds every kind, or one of "mail", "conversation", "contact" and "attachment". Limit caps each group (0: the default). The filters apply to mail and attachments; with one set, the other groups find nothing.

type FindResult added in v1.18.0

type FindResult struct {
	Mail          FindGroup[MessageSummary]
	Conversations FindGroup[Conversation] // Wit's (kind "ask"), as ListConversations lists them
	Contacts      FindGroup[Contact]
	Attachments   FindGroup[FoundAttachment]
}

FindResult is Find's hits by kind.

type Folder

type Folder struct {
	ID, AccountID int64
	Name, Role    string
	Delim         string // the server's hierarchy delimiter in Name, "" when flat
	Unread        int
}

Folder is a mailbox of an account. Role is inbox, sent, trash, drafts, junk, archive or empty.

type FoundAttachment added in v1.18.0

type FoundAttachment struct {
	AttachmentInfo
	MessageID     int64
	Subject, From string
	Date          time.Time
}

FoundAttachment is an attachment and the message it came with.

type Label added in v0.3.0

type Label struct {
	ID                                   int64
	Slug, Name, Description, Color, Icon string
	Builtin                              bool
	Position                             int
	Count, Unread                        int
}

Label is a mail label. Count is the messages it is on, Unread those unread.

type LabelInput added in v0.3.0

type LabelInput struct{ Name, Description, Color, Icon string }

LabelInput is what the user sets on a label.

type MCPSend added in v1.13.0

type MCPSend struct {
	ID        int64
	Draft     Draft
	From      string
	FirstTime []string
}

MCPSend is a send request of godwit mcp waiting for the user, as the confirmation window shows it: the draft at the revision it is bound to, the sending account's address and the recipients that account had never written to when it was asked.

type MCPServer

type MCPServer struct {
	ID                        int64
	Name, Transport, Command  string
	Args, EnvKeys, HeaderKeys []string
	URL                       string
	Version                   int64
	Enabled, Granted          bool
	Tools                     []MCPTool
	Error                     string
}

MCPServer is a configured server. Granted means the current Version is granted; Tools are the last listed for this version; Error is why it last failed to connect or was stopped.

type MCPServerInput

type MCPServerInput struct {
	Name, Transport, Command string
	Args                     []string
	Env                      map[string]string
	URL                      string
	Headers                  map[string]string
}

MCPServerInput configures a server. Transport is "stdio" (Command, Args, Env) or "http" (URL, Headers). Env and Header values go to the keychain; an empty value in an update keeps the stored one, a key left out is removed.

type MCPTool

type MCPTool struct {
	Name, Description     string
	ReadOnlyHint, Trusted bool
	DefinitionHash        string
}

MCPTool is a tool of a server. ReadOnlyHint is the server's own claim, for display only; Trusted holds while the user trusted this DefinitionHash.

type MaskCategories added in v1.18.0

type MaskCategories struct{ Secrets, IDs, Codes, Phones, Emails, Names MaskCategory }

MaskCategories are 脱敏's categories, as mask names them.

func (*MaskCategories) All added in v1.18.0

All is each category by its mask name (mask.Secrets …), in the order the settings show them, to read or change.

type MaskCategory added in v1.18.0

type MaskCategory struct {
	On     bool
	Action string
}

MaskCategory is one category of 脱敏: whether it is found, and what is done with its values (MaskMask, MaskWarn or MaskBlock).

type MaskRecord added in v1.18.0

type MaskRecord struct {
	At                             time.Time
	Request                        int64
	Feature, Kind, Category, First string
	Len                            int
	Action                         string
}

MaskRecord is a value a request to a model service or a translation plugin held (脱敏记录): which request (the values of one share it; 0 for records kept from before requests were told apart) and feature sent it, its kind and category ("": the user's own), its first character and length, never the value; and what was done with it (MaskMask, MaskWarn or MaskBlock). A value of maskShortLen characters or fewer keeps no first character: of a two-character name it would be half.

type MaskRule added in v1.18.0

type MaskRule = mask.Rule

MaskRule is one of the user's patterns, masking what it finds as its kind.

type MaskRuleError added in v1.18.0

type MaskRuleError = mask.RuleError

MaskRuleError says which rule can't be used: ErrMaskKind, ErrMaskReservedKind, ErrMaskEmptyMatch, or the pattern RE2 can't compile.

type Message

type Message struct {
	MessageSummary
	ReplyTo             string
	HTML, Text          string
	Truncated           bool
	RemoteImagesBlocked int
	// TrackersBlocked counts the tracking pixels dropped from HTML, whatever
	// the remote images setting or the sender's trust.
	TrackersBlocked int
	// InJunk: the folder is junk, detected or given (even where another
	// folder holds the role), so its sender's images are never trusted.
	InJunk      bool
	Attachments []AttachmentInfo
}

Message is a fully loaded message. HTML is always sanitized. Truncated means HTML and Text hold only the start of the body; GetRawMessage has all of it.

type MessagePage

type MessagePage struct {
	Items      []MessageSummary
	NextCursor string
}

MessagePage is one page of a flat message list.

type MessageSummary

type MessageSummary struct {
	ID, ThreadID, FolderID int64
	Subject, From, Snippet string
	To, Cc                 []string
	Date                   time.Time
	Flags                  []string
	HasAttachments         bool
}

MessageSummary is a message as listed.

type MessageText

type MessageText struct {
	MessageSummary
	AccountID   int64
	ReplyTo     string
	Text        string
	Truncated   bool
	Attachments []AttachmentInfo
}

MessageText is a message as stored: its text as a model reads it (modelBody) and metadata, with the attachments listed but never fetched.

type ModelError added in v1.7.0

type ModelError struct {
	Code      string `json:"code"`
	Message   string `json:"message"`
	Retryable bool   `json:"retryable"`
}

ModelError is why a model cannot be used now; Code is machine-readable.

func (*ModelError) Error added in v1.7.0

func (e *ModelError) Error() string

type ModelService

type ModelService struct {
	ID                      int64
	Name, Kind, BaseURL     string
	Provider                string // ProviderOpenAI, …: the formats it offers; fixed once added
	Slug                    string // the service part of its "slug/model" references; kept on rename
	Models                  []string
	Names                   map[string]string // model ID -> models.dev's display name, for the IDs it lists (ListModelServices)
	JudgeFormat, JudgeModel string
	Email                   string // OAuth sign-in address (chatgpt, grok); "" for API-key services
	HasKey                  bool
	Version                 int64
	// Status is the last test of each capability (CapGen, CapJudge), absent
	// when untested or when what it tested changed since.
	Status map[string]CapStatus
	// contains filtered or unexported fields
}

ModelService is a model service and its two capabilities. Kind is the generate format: ai.KindOpenAI (chat), ai.KindResponses or ai.KindAnthropic (messages); "" turns generate off. JudgeFormat is ai.FormatDecisions or ai.FormatSystemOne; "" turns judge off. BaseURL is one base for both, normalized the same for every format.

func (ModelService) Input

func (m ModelService) Input() ModelServiceInput

Input is m as it is saved, keeping its key.

type ModelServiceInput

type ModelServiceInput struct {
	Name, Kind, BaseURL, APIKey string
	KeyAction                   string
	OAuthFlowID                 string
	Models                      []string
	Provider                    string
	JudgeFormat, JudgeModel     string
	// contains filtered or unexported fields
}

ModelServiceInput is a service as the user entered it. An empty KeyAction means replace when APIKey is set, else keep (update) or none (add). Provider "" is the stored one, or for a new service the one its address implies (inferProvider). A capability that is on needs its models.

type ModelState added in v1.7.0

type ModelState string

ModelState is a model's state as the model list shows it.

const (
	ModelNotDownloaded ModelState = "not-downloaded"
	ModelDownloading   ModelState = "downloading"
	ModelVerifying     ModelState = "verifying"
	ModelDownloaded    ModelState = "downloaded"
	ModelLoading       ModelState = "loading"
	ModelReady         ModelState = "ready"
	ModelErrorState    ModelState = "error"
)

type ModelStatus added in v1.7.0

type ModelStatus struct {
	State           ModelState  `json:"state"`
	DownloadedBytes int64       `json:"downloadedBytes"`
	TotalBytes      int64       `json:"totalBytes"`
	Error           *ModelError `json:"error,omitempty"`
}

ModelStatus is a model's download state; Error is set in state error, and with model_not_ready in state not-downloaded.

type Op

type Op struct {
	ID          int64
	Kind, State string // Kind: flags, move or purge. State: pending, awaiting_claim, conflict or failed
	Attempts    int
	LastError   string
}

Op is a queued local change that has not reached the server yet, or could not.

type Options

type Options struct {
	DataDir  string
	AutoSync bool // run a background sync worker per account
	// LabelMail runs the label classifier in the background (the apps set it;
	// tests call it by hand or leave it off so their scripted models stay theirs).
	LabelMail bool
	// SystemLanguage is the operating system language (BCP 47) the GUI passes in; empty means "en".
	SystemLanguage string
	// ImageClient downloads remote mail images; nil is imagefetch.NewClient(false)
	// (public hosts only). Tests give one that reaches loopback.
	ImageClient *http.Client
	// LookupTXT finds sender logos (BIMI) in DNS; nil is the system resolver,
	// unless ImageClient is set, which keeps tests off real DNS.
	LookupTXT avatar.LookupTXT
	// UnsubscribeClient sends one-click unsubscribes; nil is one dialing as
	// ImageClient's default does (public hosts only). Core never lets it
	// follow a redirect or keep cookies. Tests give one that reaches loopback.
	UnsubscribeClient *http.Client
	// Registry is where reviewed plugins are listed; nil turns the plugin
	// directory off (DefaultRegistry is Godwit's own). The apps set it.
	Registry *RegistrySource
	// AppVersion is this build's version, for a release's minGodwit; "" or "dev" takes any.
	AppVersion string
	// SystemTranslator is the system's on-device translation, offered as the
	// built-in system-translation plugin; nil leaves that plugin out.
	SystemTranslator SystemTranslator
	// AppleIntelligence is the system's on-device intelligence on macOS,
	// offered as the built-in apple-intelligence plugin; nil leaves that plugin out.
	AppleIntelligence AppleIntelligence
	// ModelsDev is models.dev's catalog (ai.ModelsDevURL), where models'
	// display names and context windows come from; "" fetches none (the apps set it).
	ModelsDev string
	// ConfirmWindow: a window can confirm godwit mcp's sends (每次确认); the
	// GUI sets it. Without one (--headless) 每次确认 refuses them, as 不允许.
	ConfirmWindow bool
	// ComposeOpen reports whether draftID's compose window is open or
	// opening; the GUI sets it, and 直接发送 leaves such a draft alone. nil: none is.
	ComposeOpen func(draftID int64) bool
	// OpenURL opens an external URL in the user's default browser.
	OpenURL func(url string) error
}

Options configures a Service.

type OutboxFailure added in v1.14.0

type OutboxFailure struct {
	// Reason is "rejected": the server refused the message for good (a 5xx
	// reply), described by the other fields; or "expired": it waited in the
	// queue longer than OutboxExpiry and was not sent.
	Reason string `json:"reason"`
	// Stage is the refused SMTP command, "MAIL", "RCPT" or "DATA" (rejected).
	Stage string `json:"stage,omitempty"`
	// Recipient is the refused address at RCPT (rejected).
	Recipient string `json:"recipient,omitempty"`
	// Code is the SMTP reply code, such as 550 (rejected).
	Code int `json:"code,omitempty"`
	// Enhanced is the enhanced status code, such as "5.1.1"; "" if the server
	// sent none (rejected).
	Enhanced string `json:"enhanced,omitempty"`
	// Message is the server's reply text, untranslated (rejected).
	Message string `json:"message,omitempty"`
}

OutboxFailure is why an outbox item failed. It is stored as JSON in these field names.

type OutboxItem

type OutboxItem struct {
	ID               int64
	Subject          string
	State, LastError string
	CreatedAt        time.Time
	// DraftID is the draft it was sent from, read-only until CancelOutbox or
	// ResolveOutbox edit brings it back; 0 once the message may have gone
	// out, and for items queued before undo send.
	DraftID int64
	// SendAfter is when it is sent at the earliest (the end of the undo
	// window), NextAttempt when it is retried; zero means now.
	SendAfter, NextAttempt time.Time
	Attempts               int
	// Failure is why a failed item failed, for the host to explain in the
	// user's language; nil otherwise, and for a failure without one (its raw
	// copy could not be read; LastError says why).
	Failure *OutboxFailure
}

OutboxItem is a message that has not finished sending and archiving. State is queued, sending, sent, archiving, send_uncertain, archive_uncertain or failed.

type PluginInfo

type PluginInfo struct {
	Name, Version         string
	Title                 plugins.Text // a built-in plugin's display name; others show Name
	Builtin               bool         // ships with Godwit (builtins.go): a switch only
	Description           plugins.Text
	Permissions           plugins.Permissions
	Enabled, NeedsGrant   bool
	DisabledReason, Error string
	Config                []plugins.ConfigField
	// Native: a shared library, run with all of Godwit's rights (no
	// permissions apply); its grant is for the file LibraryHash names.
	Native       bool
	Trust        string // native: "user" once the user allowed the current file, "" not allowed
	Capabilities []string
	LibraryHash  string // native: SHA-256 of the shared library
}

PluginInfo is an installed plugin. Error is why it cannot run (its files are damaged or an update was interrupted); such a plugin is listed, not hidden.

type PluginInstallProgress added in v1.2.0

type PluginInstallProgress struct {
	Stage       string // "download", "verify", or "install"
	Done, Total int64
}

PluginInstallProgress reports download bytes, then the verify and install stages. Done and Total are set only for download; completing it does not complete installation.

type PluginModels added in v1.7.0

type PluginModels struct {
	Plugin string
	Models []plugins.ProviderModel
	Files  map[string]ModelStatus
	Err    string
}

PluginModels are a running plugin's models, or Err when it could not list them. Files are the file states of its models with registry-hosted assets, by model ID.

type Purge

type Purge struct {
	Days    int
	Blocked bool
}

Purge is an account's junk or trash purge. Days 0 is never. Blocked is set while the server lacks UIDPLUS, so the purge is skipped.

type QuickReply

type QuickReply struct{ Label, Preview, HTML string }

QuickReply is one suggested reply: sanitized HTML, a plain-text preview, and a short label naming its intent ("" from answers cached before it).

type RegistryEntry added in v1.2.0

type RegistryEntry struct {
	Name                                            string
	Title, Summary                                  plugins.Text
	Homepage                                        string
	Native, Script                                  bool
	Version, Unavailable, Installed, InstalledTrust string
	Update                                          bool
}

RegistryEntry is one registry plugin for this build: Version is the release it would install ("" none, Unavailable says why: "platform", "abi" or "godwit:<min>"); Installed and InstalledTrust describe what is installed under its name; Update is a newer listed release for a listed install. Native and Script are its kind, neither when this build reads no release.

type RegistrySource added in v1.2.0

type RegistrySource struct {
	URL       string // registry.json; its signature is URL + ".sig"
	PublicKey ed25519.PublicKey
	Client    *http.Client // nil: a client with registryTimeout
}

RegistrySource is where the registry comes from and the key it is signed with.

type RegistryView added in v1.2.0

type RegistryView struct {
	On      bool
	Updated time.Time
	Stale   string
	Entries []RegistryEntry
}

RegistryView is what the extensions page shows of the registry. Stale is why the last refresh failed ("" once one succeeds); the entries are then the cached registry's.

type RunActionOptions

type RunActionOptions struct {
	// ApproveEgress is the user's approval of the plugin's declared hosts
	// (EgressApprovalRequired) for this one run.
	ApproveEgress bool
}

type SearchQuery

type SearchQuery struct {
	AccountID      int64
	Text           string
	From           string    // a substring of the From header, any case
	FromAddr       string    // the From header's address exactly, any case: one contact's mail
	Since, Until   time.Time // the date from Since, before Until
	HasAttachments bool
	LabelID        int64 // mail with this label on
	Unread         *bool // true for unread (\Seen absent), false for read (\Seen present)
	Starred        *bool // true for starred (\Flagged present), false for unstarred
	// contains filtered or unexported fields
}

SearchQuery is a search: free text ANDed with the filters set. Zero fields filter nothing; AccountID 0 is every account.

func (SearchQuery) Filtered

func (q SearchQuery) Filtered() bool

Filtered reports whether a filter beyond the account is set: such a query needs no text.

type Security

type Security = conn.Security

Security is the transport protection of an IMAP or SMTP connection.

type Selection

type Selection struct {
	Revision   int64
	Start, End int
}

Selection is a byte range [Start, End) of the draft's editable HTML (the first value mail.SplitDraft returns) at Revision. Neither end may fall inside a tag or a character reference.

type SendBlockedError

type SendBlockedError struct{ Plugin, Message string }

SendBlockedError: a plugin refused the draft. It cannot be acknowledged; the user edits the draft or disables the plugin.

func (*SendBlockedError) Error

func (e *SendBlockedError) Error() string

type SendCheck

type SendCheck struct {
	DraftID, Revision int64
	Plugins           []string
	Warnings          []SendWarning
	Digest            string
}

SendCheck is a draft revision's beforeSend outcome with warnings. Plugins are the checking plugins as name@source_hash@config_version, sorted by name. Digest binds all of it: SendAcknowledged(DraftID, Digest) queues that revision without checking again while the draft and the plugins are unchanged.

type SendWarning

type SendWarning struct{ Plugin, Code, Message string }

SendWarning is a plugin's warning about a draft; the user may still send. Code is WarningPlugin (Message is the plugin's) or WarningNoResponse (the check failed or timed out; Message is a fallback in English).

type SendWarningsError

type SendWarningsError struct{ Check SendCheck }

SendWarningsError: nothing was queued; show the warnings and call SendAcknowledged with Check.Digest to send anyway.

func (*SendWarningsError) Error

func (e *SendWarningsError) Error() string

type ServerSettings

type ServerSettings struct {
	Username     string
	IMAPHost     string
	IMAPPort     int
	IMAPSecurity Security
	SMTPHost     string
	SMTPPort     int
	SMTPSecurity Security
}

ServerSettings replaces an account's username and IMAP and SMTP servers. An empty Username means the email address.

type Service

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

Service owns the database and event bus of one Godwit data directory.

func New

func New(ctx context.Context, opts Options) (*Service, error)

New creates DataDir if needed and opens DataDir/godwit.db.

func (*Service) AccountIcon added in v1.9.0

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

AccountIcon is the image of an account whose Icon is image:<n>.

func (*Service) AddAccount

func (s *Service) AddAccount(ctx context.Context, in AccountInput) (Account, error)

AddAccount tests in, stores the account and saves the password in the keychain. With OAuthFlowID it uses up the flow's grant and saves its refresh token instead.

func (*Service) AddAttachment

func (s *Service) AddAttachment(ctx context.Context, draftID int64, srcPath string) (DraftAttachment, error)

AddAttachment copies the file at srcPath into the draft.

func (*Service) AddAttachmentAt

func (s *Service) AddAttachmentAt(ctx context.Context, draftID, revision int64, srcPath string) (DraftAttachment, int64, error)

AddAttachmentAt is AddAttachment for exactly that revision of the draft (else ErrStaleDraft, nothing added); it returns the new revision.

func (*Service) AddMCPServer

func (s *Service) AddMCPServer(ctx context.Context, in MCPServerInput) (MCPServer, error)

AddMCPServer adds a server, disabled and not granted.

func (*Service) AddModelService

func (s *Service) AddModelService(ctx context.Context, in ModelServiceInput) (ModelService, error)

AddModelService stores the service, then its key in the keychain (entry 1); if the keychain fails the row is removed again. A crash between the two leaves a service without a key.

func (*Service) AnswerQuestion added in v1.13.0

func (s *Service) AnswerQuestion(ctx context.Context, id int64, round int, answers [][]string) error

AnswerQuestion accepts pending question id with answers, one list per question: one answer each, several where it is multiSelect, none where the user skipped it. An answer is an option's label or the user's own words. Every question skipped skips the call (rejects it). round is the round of the MCP form the user answered (Form's); an answer to another round, which the call asked since, is ErrInvalidState. ask_user_question has no rounds.

func (*Service) ApplyEditedProposal

func (s *Service) ApplyEditedProposal(ctx context.Context, approvalID int64, edited string) error

ApplyEditedProposal accepts a pending draft proposal with html, the editable part the user settled on in the GUI, in place of the proposed one: markers removed, sanitized, then applied like ResolveApproval (same revision check: a changed draft makes it stale, ErrStaleDraft).

func (*Service) Ask

func (s *Service) Ask(ctx context.Context, conversationID int64, input string) (<-chan WitEvent, error)

Ask runs input in the "ask" conversation with the mailbox tools. Mail the tools show the model comes back as Citations on their tool_result events; create_draft calls become approvals. The first input titles the conversation. The channel ends with done, error or interrupted (see startRun).

func (*Service) AskAgain added in v1.7.0

func (s *Service) AskAgain(ctx context.Context, conversationID int64, turn string, input string, quoted []int64) (<-chan WitEvent, error)

AskAgain is AskWith asked in place of the question of turn (Turn.ID) and what followed it: they are replaced once the run is done (launch), so a refused question, or a run that fails or is stopped, leaves the conversation as it was.

func (*Service) AskWith

func (s *Service) AskWith(ctx context.Context, conversationID int64, input string, quoted []int64) (<-chan WitEvent, error)

AskWith is Ask with the mail the user quoted (message IDs, at most maxQuoted after dedupe): the run reads it through mailContext, in its scope, and the model gets it before the question, cited like the tools' mail (a "context" event first). An ID that does not exist fails AskWith.

func (*Service) Assist

func (s *Service) Assist(ctx context.Context, draftID int64, input string) (<-chan WitEvent, error)

Assist runs input in the draft's assist conversation. The model sees the draft's editable part, the email it replies to or forwards, the names of its attachments and the latest mail with its recipients; it can read mail and propose a new editable part (update_draft). A proposal for an empty draft is applied at once (see applyInitial); the others wait for the user. The channel ends with done, error or interrupted, as Ask's.

func (*Service) AssistConversation added in v1.12.0

func (s *Service) AssistConversation(ctx context.Context, draftID int64, create bool) (int64, error)

AssistConversation is the ID of the draft's assist conversation, the one Assist and AssistSkill run in; with create, one is made if it has none, else it is 0.

func (*Service) AssistSkill

func (s *Service) AssistSkill(ctx context.Context, draftID int64, skill string, opts SkillOptions) (<-chan WitEvent, error)

AssistSkill runs a replace-draft skill (tone, length, proofreading, translate-draft) on the draft's editable part, or on opts.Selection of it if the skill runs on selections; the model sees that and nothing else. The skill has no tools, as every skill: the host turns its output into an update_draft proposal in the draft's assist conversation, which the user decides like any other (an empty draft's is applied at once). The conversation's history is left as it is. The channel streams the skill's text and ends with interrupted (the proposal) or error.

func (*Service) AssistWith

func (s *Service) AssistWith(ctx context.Context, draftID int64, input string, quoted []int64) (<-chan WitEvent, error)

AssistWith is Assist with the mail the user quoted, as AskWith.

func (*Service) AttachmentCacheUsage

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

AttachmentCacheUsage is the bytes the account's downloaded attachments take on disk.

func (*Service) AuditExternal

func (s *Service) AuditExternal(ctx context.Context, source, action string, target int64) error

AuditExternal writes an audit_log row for a call made from outside the app: source (AuditLocalAPI or AuditMCP), the method as action, and the target's ID (0 = none). No content is stored.

func (*Service) AwaitOAuth

func (s *Service) AwaitOAuth(ctx context.Context, flowID string) (email string, err error)

AwaitOAuth waits for the browser to come back and returns the signed-in email. The flow is over either way; on success its Grant stays in memory for grantTTL. Cancelling ctx cancels the flow.

func (*Service) BeginOAuth

func (s *Service) BeginOAuth(ctx context.Context, providerID, loginHint string) (flowID, authURL string, err error)

BeginOAuth starts an authorization flow for the provider and returns its ID and the URL to open in the browser. The flow ends after auth.FlowTimeout.

func (*Service) BlockSender added in v1.17.0

func (s *Service) BlockSender(ctx context.Context, from string) error

BlockSender blocks the address of from (a From header), keyed as gomail.AddrKey so arrivals and the reader match it the same way.

func (*Service) BlockedSenders added in v1.19.0

func (s *Service) BlockedSenders(ctx context.Context) ([]string, error)

BlockedSenders are the addresses the user blocked, keyed as gomail.AddrKey.

func (*Service) CancelOAuth

func (s *Service) CancelOAuth(flowID string)

CancelOAuth ends the flow (a pending AwaitOAuth returns an error) and drops its grant. Unknown IDs are ignored.

func (*Service) CancelOutbox added in v1.14.0

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

CancelOutbox takes a queued message back before it is sent: the item and its raw copy go, and its draft is listed and writable again. An item no longer queued (sending started, or later) is ErrInvalidState, one without a draft ErrNoOutboxDraft. It does not wait for a running sync: the sync claims the item for sending, or CancelOutbox deletes it, never both.

func (*Service) CancelRun

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

CancelRun ends a run when its panel closes. A run in flight is cancelled; an approved call executing outside the lock (external mode) is waited for; an interrupted one has its pending approvals rejected ("cancelled") and those results added to the conversation state without asking the model, so the conversation can take a new run. A run already over is left as it is.

func (*Service) CheckAccount

func (s *Service) CheckAccount(ctx context.Context, in AccountInput) (CheckReport, error)

CheckAccount runs the settings, imap and smtp checks in order; after a failure the remaining steps are Skipped.

func (*Service) CheckModelService

func (s *Service) CheckModelService(ctx context.Context, id int64, in ModelServiceInput) (ServiceCheck, error)

CheckModelService probes in as service id (0: a new one) would be saved, without saving: the key action decides the key, and a kept key never goes to a changed address or protocol (ErrKeyNeedsConfirm, no request).

func (*Service) ClearAttachmentCache

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

ClearAttachmentCache deletes the account's downloaded attachments; opening one downloads it again. Other accounts' caches stay.

func (*Service) ClearImageCache added in v0.1.0

func (s *Service) ClearImageCache() error

ClearImageCache deletes the cached remote images.

func (*Service) ClearMaskingLog added in v1.19.0

func (s *Service) ClearMaskingLog(ctx context.Context) error

ClearMaskingLog deletes the masking log (清空记录).

func (*Service) Close

func (s *Service) Close() error

Close refuses new calls with ErrClosed, cancels the explicit network calls and background workers, waits for them (each records its outcome) and releases the database. Concurrent and repeated calls all wait for the same shutdown.

func (*Service) CompactConversation added in v1.11.0

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

CompactConversation summarizes conversation id's turns before its last two now, whatever its size: ErrNothingToCompact when its summary already reaches them (Conversation.Compactable false), ErrCompacting while one is under way.

func (*Service) CreateLabel added in v0.3.0

func (s *Service) CreateLabel(ctx context.Context, in LabelInput) (Label, error)

CreateLabel adds a label at the end; its slug is "u" and its id.

func (*Service) CreateSignature added in v1.9.0

func (s *Service) CreateSignature(ctx context.Context, name string) (Signature, error)

CreateSignature makes an empty signature named name, used by no account.

func (*Service) Delete

func (s *Service) Delete(ctx context.Context, ids []int64) error

Delete moves the messages to their account's Trash; ones already there stay.

func (*Service) DeleteConversation

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

DeleteConversation deletes the conversation with its runs and approvals. A run in flight or an approval executing makes it ErrRunActive; cancel first.

func (*Service) DeleteDraft

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

DeleteDraft deletes the draft and its attachment files, cancelling the Wit runs of its conversations first. A draft in the outbox stays (ErrStaleDraft).

func (*Service) DeleteDraftIfEmpty

func (s *Service) DeleteDraftIfEmpty(ctx context.Context, id, revision int64) (deleted bool, err error)

DeleteDraftIfEmpty deletes the draft, as DeleteDraft, if it is still at revision and holds nothing the user added: no attachments, no text outside the quote and the signature, and the addresses and subject a new draft of its mode starts with (none for a new one; a reply's own). A draft Wit is working on (an assist run active, or an approval pending) is in use, never empty; one in the outbox is ErrStaleDraft. deleted reports whether it went.

func (*Service) DeleteForever added in v1.17.0

func (s *Service) DeleteForever(ctx context.Context, ids []int64) error

DeleteForever queues a permanent delete of the messages in their account's Trash; ones elsewhere stay. A move out of Trash before the push cancels it, and the fetch after the push drops the rows.

func (*Service) DeleteLabel added in v0.3.0

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

DeleteLabel removes a label and takes it off every message.

func (*Service) DeleteSignature added in v1.9.0

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

DeleteSignature removes the signature: the accounts using it write without one. Its images stay while a draft shows them.

func (*Service) DetectProvider

func (s *Service) DetectProvider(ctx context.Context, email string) (auth.Provider, auth.Source, error)

DetectProvider finds the provider for an email address; DNS gets 5 seconds in total.

func (*Service) DraftForApproval added in v1.11.0

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

DraftForApproval is the draft approval approvalID made (a create_draft the user allowed), to open from where it was asked for.

func (*Service) DraftFromQuickReply

func (s *Service) DraftFromQuickReply(ctx context.Context, messageID int64, r QuickReply) (Draft, error)

DraftFromQuickReply starts a reply draft to messageID with r's HTML, sanitized again, at the start of the editable part, above the quote and signature.

func (*Service) FailQuestion added in v1.18.0

func (s *Service) FailQuestion(ctx context.Context, conv int64, question string, quoted []int64, reason string) error

FailQuestion keeps question, which a run of conv never answered (refused, or failed before any reply), with the mail it quoted (message IDs) as conv's last turn with reason, what the user is shown (opaque here); an untitled conv takes its title from it. The next run claimed in conv drops it.

func (*Service) FetchModels

func (s *Service) FetchModels(ctx context.Context, id int64) ([]string, error)

FetchModels lists the service's models, sorted. It saves nothing.

func (*Service) Find added in v1.18.0

func (s *Service) Find(ctx context.Context, q FindQuery) (FindResult, error)

Find searches mail, Wit conversations, contacts and attachments at once, each group newest first. With no text and no filter each group is what is recent, contacts those who sent the most mail.

func (*Service) FollowConversation added in v1.12.0

func (s *Service) FollowConversation(ctx context.Context, id int64) (Conversation, <-chan WitEvent, func(), error)

FollowConversation is the conversation as it is now (GetConversation) and its runs' events from then on, none missed and none twice: a run whose saved history is in what was read sends nothing more, and one waiting on the user sends what comes after its interrupt. stop ends the events, as SubscribeConversation's.

func (*Service) GetAttachment

func (s *Service) GetAttachment(ctx context.Context, attachmentID int64) (string, AttachmentInfo, error)

GetAttachment returns the attachment's cached file, downloading it first if needed.

func (*Service) GetConversation

func (s *Service) GetConversation(ctx context.Context, id int64) (Conversation, error)

GetConversation returns the conversation with its messages.

func (*Service) GetDraft

func (s *Service) GetDraft(ctx context.Context, id int64) (Draft, error)

read, covering rows stored before SaveDraft sanitized.

func (*Service) GetMessage

func (s *Service) GetMessage(ctx context.Context, id int64, loadRemoteImages bool) (Message, error)

downloaded first if needed and embedded.

func (*Service) GetMessageText

func (s *Service) GetMessageText(ctx context.Context, id int64) (MessageText, error)

GetMessageText reads the message's text and metadata from the database: the text a model reads, without what the reader never shows. Unlike GetMessage it sanitizes no HTML and reads or downloads no attachment or inline image.

func (*Service) GetPluginConfig

func (s *Service) GetPluginConfig(ctx context.Context, name string) ([]ConfigValue, error)

GetPluginConfig returns the plugin's settings in declaration order.

func (*Service) GetRawMessage

func (s *Service) GetRawMessage(ctx context.Context, messageID int64) ([]byte, error)

GetRawMessage downloads the message's full original from the server, for a Truncated message or for saving. Messages over MaxMessageBytes give ErrTooLarge.

func (*Service) GetSettings

func (s *Service) GetSettings(ctx context.Context) (Settings, error)

GetSettings returns the stored settings, defaults for anything unset. Fields a newer build added are ignored.

func (*Service) GetThread

func (s *Service) GetThread(ctx context.Context, id int64) (Thread, error)

GetThread returns the thread's messages by date ascending.

func (*Service) GrantMCPServer

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

GrantMCPServer grants the server's current version: it may then be started.

func (*Service) GrantPermission

func (s *Service) GrantPermission(ctx context.Context, name string) error

GrantPermission grants the plugin's current permissions.

func (*Service) ImageCache added in v0.1.0

func (s *Service) ImageCache() *imagecache.Cache

ImageCache is the shared disk cache of remote mail images, which the reader's image proxy serves from and prefetch fills.

func (*Service) ImageCacheSize added in v0.1.0

func (s *Service) ImageCacheSize() int64

ImageCacheSize is the bytes the cached remote images take on disk.

func (*Service) ImagesAllowed added in v0.1.0

func (s *Service) ImagesAllowed(ctx context.Context, message int64) (bool, error)

ImagesAllowed is whether message's remote images load without asking, by the RemoteImages setting: never in a junk folder (From is unauthenticated); "auto" otherwise; "trusted" for the trusted From addresses; "ask" never.

func (*Service) InlineSignatureImages

func (s *Service) InlineSignatureImages(ctx context.Context, html string) (string, error)

InlineSignatureImages is html (sanitized compose HTML: a draft, a signature) with its signature images as data: URLs, for showing only: never save it as a draft, as saving drops data: sources.

func (*Service) InstallPlugin

func (s *Service) InstallPlugin(ctx context.Context, srcDir string) (PluginInfo, error)

InstallPlugin installs or updates the plugin in srcDir: it snapshots the directory, builds the snapshot (a plugin that does not build is not installed), moves it into a new version directory and points the row at it. An update with other permissions is disabled until they are granted; with the same ones a running plugin restarts on the new code, and is disabled if that fails.

func (*Service) InstallPluginFromRegistry added in v1.2.0

func (s *Service) InstallPluginFromRegistry(ctx context.Context, name string) (PluginInfo, error)

InstallPluginFromRegistry installs or updates plugin name from the cached registry: the newest release this build can take, its file downloaded and checked against the registry's size and SHA-256 (a mismatch is ErrRegistryMismatch and nothing is installed), then installed as listed.

func (*Service) InstallPluginFromRegistryWithProgress added in v1.2.0

func (s *Service) InstallPluginFromRegistryWithProgress(ctx context.Context, name string, progress func(PluginInstallProgress)) (PluginInfo, error)

InstallPluginFromRegistryWithProgress is InstallPluginFromRegistry with an optional callback invoked synchronously on the calling goroutine, never after return.

func (*Service) KeychainStatus

func (s *Service) KeychainStatus(ctx context.Context) error

KeychainStatus writes, reads back and deletes a fresh probe entry; any failure is ErrKeychainUnavailable. Onboarding calls it before showing the account form.

func (*Service) LabelModelReady added in v0.3.0

func (s *Service) LabelModelReady(ctx context.Context) bool

LabelModelReady reports whether a model can classify mail.

func (*Service) ListAccounts

func (s *Service) ListAccounts(ctx context.Context) ([]Account, error)

ListAccounts returns all accounts in their order (ReorderAccounts), new ones last.

func (*Service) ListActions

func (s *Service) ListActions(ctx context.Context, kind string) ([]ActionInfo, error)

ListActions lists the running plugins' actions that run on kind (message, thread, selection or draft; "" for all), by ID.

func (*Service) ListApprovals

func (s *Service) ListApprovals(ctx context.Context, conversationID int64) ([]Approval, error)

ListApprovals returns the conversation's approvals by run and seq, so the cards survive a restart.

func (*Service) ListConversations

func (s *Service) ListConversations(ctx context.Context, kind string) ([]Conversation, error)

ListConversations returns the conversations of kind, most recent first.

func (*Service) ListDrafts

func (s *Service) ListDrafts(ctx context.Context, accountID int64) ([]Draft, error)

ListDrafts returns the account's drafts, most recently saved first. Drafts in the outbox are not listed.

func (*Service) ListFolders

func (s *Service) ListFolders(ctx context.Context, accountID int64) ([]Folder, error)

ListFolders returns the account's folders with their unread counts. Each role is on one folder at most, the one mailsync.RoleFolder resolves; inbox and Gmail's Starred (flagged) are detected only.

func (*Service) ListLabels added in v0.3.0

func (s *Service) ListLabels(ctx context.Context) ([]Label, error)

ListLabels returns the labels in the user's order.

func (*Service) ListMCPServers

func (s *Service) ListMCPServers(ctx context.Context) ([]MCPServer, error)

ListMCPServers lists the configured servers by ID.

func (*Service) ListMessages

func (s *Service) ListMessages(ctx context.Context, v View, cursor string, limit int) (MessagePage, error)

ListMessages lists the view's messages as flat rows, newest first.

func (*Service) ListModelServices

func (s *Service) ListModelServices(ctx context.Context) ([]ModelService, error)

ListModelServices lists the services in the order they were added.

func (*Service) ListOutbox

func (s *Service) ListOutbox(ctx context.Context, accountID int64) ([]OutboxItem, error)

ListOutbox returns the account's unfinished outbox items, oldest first.

func (*Service) ListPluginModels added in v1.7.0

func (s *Service) ListPluginModels(ctx context.Context) ([]PluginModels, error)

ListPluginModels lists the models of every running plugin declaring models, by name.

func (*Service) ListPluginRegistry added in v1.2.0

func (s *Service) ListPluginRegistry(ctx context.Context) (RegistryView, error)

ListPluginRegistry is the cached registry as this build sees it.

func (*Service) ListPlugins

func (s *Service) ListPlugins(ctx context.Context) ([]PluginInfo, error)

ListPlugins lists the installed plugins, including ones that cannot run.

func (*Service) ListProviders

func (s *Service) ListProviders() []auth.Provider

func (*Service) ListSignatures added in v1.9.0

func (s *Service) ListSignatures(ctx context.Context) ([]Signature, error)

ListSignatures returns every signature, oldest first.

func (*Service) ListSkills

func (s *Service) ListSkills(ctx context.Context) ([]SkillInfo, error)

ListSkills lists built-in and user skills, including user skills that failed to load.

func (*Service) ListThreads

func (s *Service) ListThreads(ctx context.Context, v View, cursor string, limit int) (ThreadPage, error)

ListThreads lists threads with at least one message in the view, newest first.

func (*Service) ListTranslators added in v1.2.0

func (s *Service) ListTranslators(ctx context.Context) ([]TranslatorInfo, error)

ListTranslators lists the model, the built-in translating plugins, and the installed plugins declaring translate, by name.

func (*Service) LoadOlder

func (s *Service) LoadOlder(ctx context.Context, folderID int64) (more bool, err error)

LoadOlder imports one page (about 200) of the folder's mail that the sync range left out, newest first, and keeps it. more is false once the server holds nothing more the folder lacks. It takes the account's sync lock, so a sync runs before or after it, never alongside; cancelling ctx stops it.

func (*Service) MaskingLog added in v1.18.0

func (s *Service) MaskingLog(ctx context.Context) ([]MaskRecord, error)

MaskingLog is the masking log of the last 30 days, newest first.

func (*Service) MessageExists added in v1.11.0

func (s *Service) MessageExists(ctx context.Context, id int64) (bool, error)

GetMessage returns the message with sanitized HTML. Inline images are MessageExists says whether message id is still stored: a row lookup, nothing loaded.

func (*Service) MessageGist added in v1.19.0

func (s *Service) MessageGist(ctx context.Context, messageID int64) (string, error)

MessageGist is a message's one-line gist, which its folded row in a thread shows in place of the start of its text: by the small model (resolveTask), in the reading language, cached by the message's content and the model as RunSkill's outputs are. "" when the model wrote nothing.

func (*Service) MessageLabels added in v0.3.0

func (s *Service) MessageLabels(ctx context.Context, ids []int64) (map[int64][]AppliedLabel, error)

MessageLabels returns the labels on each of the messages, in the labels' order.

func (*Service) ModelName added in v1.11.0

func (s *Service) ModelName(ctx context.Context, ref string) string

ModelName is models.dev's display name for a "slug/model" ref's model; "" when it lists none.

func (*Service) ModelServiceAvatar added in v1.1.0

func (s *Service) ModelServiceAvatar(ctx context.Context, id int64) (Avatar, error)

ModelServiceAvatar is the favicon of the site a model service talks to; empty Data when it has none, or the service signs in with a subscription (those have a mark of their own) or runs on a local host.

func (*Service) Move

func (s *Service) Move(ctx context.Context, ids []int64, folderID int64) error

Move moves the messages to folderID, which must belong to their account. The local message IDs stay the same.

func (*Service) MoveToRole

func (s *Service) MoveToRole(ctx context.Context, ids []int64, role string) error

MoveToRole moves the messages to their account's folder of role (inbox, trash, junk or archive); ones already there stay.

func (*Service) NewConversation

func (s *Service) NewConversation(ctx context.Context, kind string, draftID int64) (Conversation, error)

NewConversation starts an empty conversation: kind "ask" without a draft, or "assist" on draftID.

func (*Service) NewDraft

func (s *Service) NewDraft(ctx context.Context, accountID int64, mode string, sourceMessageID int64) (Draft, error)

NewDraft starts and saves a draft. reply and reply_all address the source's sender (and everyone, for reply_all) and quote it; forward quotes it and copies its non-inline attachments, downloading them if needed. The account signature ends the body.

func (*Service) NewMailtoDraft added in v1.14.0

func (s *Service) NewMailtoDraft(ctx context.Context, accountID int64, link string) (Draft, error)

NewMailtoDraft starts a new draft from account to a mailto: link's addresses, with its subject and (as plain text) body; it is never sent.

func (*Service) PendingLabels added in v0.3.0

func (s *Service) PendingLabels(ctx context.Context) (int, error)

PendingLabels counts the rescan targets not classified yet.

func (*Service) PendingMCPSends added in v1.13.0

func (s *Service) PendingMCPSends(ctx context.Context) ([]MCPSend, error)

PendingMCPSends are the send requests waiting for the user, oldest first. One whose draft changed or went, or that waited mcpSendTTL, goes stale instead.

func (*Service) PendingOps

func (s *Service) PendingOps(ctx context.Context, accountID int64) ([]Op, error)

PendingOps lists the account's ops that are not done (or cancelled), oldest first.

func (*Service) PluginCards

func (s *Service) PluginCards(ctx context.Context, messageID int64) ([]Card, error)

PluginCards runs each running plugin's card on the message, by plugin name: match(message), then render(message) if it matched, within one 5 s budget, read-only and with no egress. A failed, late or invalid card is left out and counts as a plugin failure.

func (*Service) PluginTags added in v1.5.0

func (s *Service) PluginTags(ctx context.Context, messageID int64) ([]Tag, error)

PluginTags are the tags the plugins that are on put after the message's subject. Only built-in plugins contribute tags so far.

func (*Service) PrepareModel added in v1.7.0

func (s *Service) PrepareModel(ctx context.Context, ref string) (ModelStatus, error)

PrepareModel downloads what plugin model ref is missing of its files and verifies them all, then returns their state; ModelsChanged follows.

func (*Service) PrepareModelWithProgress added in v1.7.0

func (s *Service) PrepareModelWithProgress(ctx context.Context, ref string, progress func(ModelStatus)) (ModelStatus, error)

PrepareModelWithProgress is PrepareModel reporting downloading and verifying through progress, called on the calling goroutine, never after return.

func (*Service) PreviewMasking added in v1.18.0

func (s *Service) PreviewMasking(ctx context.Context, st Settings, text string) (string, error)

PreviewMasking is text as it would go to a model off this device under st's 脱敏 settings, saved or not (实时预览). It stores nothing and leaves the Service's masker alone: its placeholders are a throwaway key's.

func (*Service) Purges

func (s *Service) Purges(ctx context.Context, accountID int64) (map[string]Purge, error)

Purges returns the account's junk and trash purges by role.

func (*Service) QuickReplies

func (s *Service) QuickReplies(ctx context.Context, messageID int64) ([]QuickReply, error)

QuickReplies suggests up to three replies to a message with the default model. It returns none, without asking the model, when Settings.QuickReplies is off or the message is from the account itself. Results are cached like RunSkill's; an answer that is not the requested JSON is an error.

func (*Service) ReadingLanguage

func (s *Service) ReadingLanguage(ctx context.Context) string

ReadingLanguage is the language Wit reads and writes in: the setting, else the UI language, else the system language, else "en".

func (*Service) Reauthorize

func (s *Service) Reauthorize(ctx context.Context, id int64, flowID string) error

Reauthorize gives an OAuth account the tokens of a finished flow, which must have signed in to the account's address with its provider (ErrWrongAccount, ErrProviderMismatch; the old tokens stay). It clears reauth_required and a paused outbox; the worker resumes.

func (*Service) RebuildSearchIndex

func (s *Service) RebuildSearchIndex(ctx context.Context) error

RebuildSearchIndex recreates the full-text index from the messages table in one transaction, repairing an index that drifted or was damaged.

func (*Service) RecentSignInCodes added in v1.5.0

func (s *Service) RecentSignInCodes(ctx context.Context, now time.Time) ([]SignInCode, error)

RecentSignInCodes reads the arrival log so a dropped UI event cannot lose a code. Initial imports and backfills never enter that log. Fifteen minutes is a display window, not a claim about the server's validity period. The arrival time bounds recency; a sender's clock running ahead does not hide a code. None while the built-in plugin is off.

func (*Service) RecordCapStatus

func (s *Service) RecordCapStatus(ctx context.Context, id, version int64, c string, st CapStatus) error

RecordCapStatus stores st, a TestCapability result for capability c of what service id now is at version: the dialog tests before it saves.

func (*Service) Redact

func (s *Service) Redact(text string) string

Redact replaces every credential and extension secret this Service knows of in text. Not for RPC. Values under 8 characters are skipped (ai.Redact): replacing them would mangle ordinary text, and the ones that matter (keys, tokens) are longer; a short password is a known gap, not leaked by core's own errors, which never carry credentials.

func (*Service) RefreshMCPTools

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

RefreshMCPTools connects to the server again and lists its tools; a disabled server is disconnected afterwards. Needs the current version granted.

func (*Service) RefreshPluginRegistry added in v1.2.0

func (s *Service) RefreshPluginRegistry(ctx context.Context) error

RefreshPluginRegistry fetches the registry, verifies it and, if it is not older than the cached one, caches it and applies it to the installed plugins: files it no longer lists stop (trust_revoked), and files the user allowed that it lists become listed. On any failure the cache and the plugins stay as they were.

func (*Service) RemoveAccount

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

RemoveAccount deletes the account, its keychain entry and its cache directory. It first cancels the account's explicit calls and worker and waits for them.

func (*Service) RemoveAttachment

func (s *Service) RemoveAttachment(ctx context.Context, draftID, attachmentID int64) error

RemoveAttachment deletes the attachment from the draft and its file.

func (*Service) RemoveAttachmentAt

func (s *Service) RemoveAttachmentAt(ctx context.Context, draftID, attachmentID, revision int64) (int64, error)

RemoveAttachmentAt is RemoveAttachment for exactly that revision of the draft (else ErrStaleDraft, nothing removed); it returns the new revision.

func (*Service) RemoveMCPServer

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

RemoveMCPServer stops a server and deletes it with its keychain entries; its pending approvals become stale.

func (*Service) RemoveModelFiles added in v1.7.0

func (s *Service) RemoveModelFiles(ctx context.Context, ref string) error

RemoveModelFiles deletes plugin model ref's own files, keeping those other models share; a model the plugin has loaded is in use and stays.

func (*Service) RemoveModelService

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

func (*Service) ReorderAccounts added in v1.11.0

func (s *Service) ReorderAccounts(ctx context.Context, ids []int64) error

ReorderAccounts puts the accounts in the order of ids, which names every account once. An account added meanwhile fails the check or, added after it, goes last.

func (*Service) ReorderLabels added in v0.3.0

func (s *Service) ReorderLabels(ctx context.Context, ids []int64) error

ReorderLabels puts the labels in the order of ids, which names every label once.

func (*Service) RequestMCPSend added in v1.13.0

func (s *Service) RequestMCPSend(ctx context.Context, draftID, revision int64) (sent bool, err error)

RequestMCPSend is godwit mcp's send_draft: what it does follows Settings.MCPSend. 不允许 (or 每次确认 headless) is ErrMCPSendOff. 每次确认 records a request bound to the draft's revision, one per draft (a newer revision's replaces the older), at most maxMCPSends (ErrMCPSendBusy), for the user to confirm (PendingMCPSends, ResolveMCPSend), and announces mcp_sends.changed; sent is false. 直接发送 queues the draft as Send does, audited as an MCP send, unless a compose window has it (ErrMCPSendComposing); sent is true. A revision other than the draft's is ErrStaleDraft.

func (*Service) RescanLabels added in v0.3.0

func (s *Service) RescanLabels(ctx context.Context, days int, all bool) (int, error)

RescanLabels makes the Inbox mail of the last days (0: all of it) the classifier's targets again: all of it, or only mail with no label on. Model labels are replaced only once the judge answers for that message, so a judge failing or a stop midway loses none; hand-set labels stay. It returns how many.

func (*Service) ResolveAll

func (s *Service) ResolveAll(ctx context.Context, runID int64, accept bool) error

ResolveAll resolves the run's pending approvals one by one in seq order; accepting leaves its questions pending: only AnswerQuestion accepts them.

func (*Service) ResolveApproval

func (s *Service) ResolveApproval(ctx context.Context, id int64, accept bool) error

ResolveApproval accepts or rejects a pending approval, exactly once: the call that claims it (pending → executing) decides it; any other gets ErrInvalidState. Accepting applies the recorded arguments and marks it done in one transaction, after checking the target draft's revision (changed → stale, ErrStaleDraft). An external tool's approval runs outside the lock instead and records its outcome afterwards (see decideExternal; a changed binding makes it stale, ErrStaleApproval). The call that ends the run's last open approval resumes the run in the background; SubscribeConversation streams it.

func (*Service) ResolveApprovalForConversation

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

ResolveApprovalForConversation accepts pending approval id and allows its tool for the rest of its conversation (本次对话都允许): the run's other pending calls of the tool are accepted too, and later ones as soon as they come (applyInitial), audited auto:session. The tool and the conversation come from the approval. Only sessionTools qualify, else ErrNotGrantable.

func (*Service) ResolveApprovalWithArgs added in v1.17.0

func (s *Service) ResolveApprovalWithArgs(ctx context.Context, id int64, accept bool, args json.RawMessage) error

ResolveApprovalWithArgs accepts or rejects pending approval id with edited arguments args.

func (*Service) ResolveMCPSend added in v1.13.0

func (s *Service) ResolveMCPSend(ctx context.Context, id int64, accept bool) error

ResolveMCPSend sends (accept) or drops the pending send request id, exactly once: another decision of it is ErrInvalidState. Accepted, it sends the revision the request is bound to, as SendRevision does; one changed since, or a request that waited mcpSendTTL, is stale (ErrStaleDraft) and sends nothing. A plugin's warnings (SendWarningsError) keep it executing until the user answers them (ResolveMCPSendAcknowledged) or it waited mcpSendTTL.

func (*Service) ResolveMCPSendAcknowledged added in v1.13.0

func (s *Service) ResolveMCPSendAcknowledged(ctx context.Context, id int64, digest string, send bool) error

ResolveMCPSendAcknowledged answers the warnings ResolveMCPSend returned for request id, exactly once: send sends the revision acknowledged with digest, as SendAcknowledgedRevision does, else drops the request. A request not waiting on warnings is ErrInvalidState.

func (*Service) ResolveOutbox

func (s *Service) ResolveOutbox(ctx context.Context, id int64, action string) error

ResolveOutbox decides an item in send_uncertain, archive_uncertain or failed: confirm_sent treats it as sent (it is archived next), resend queues it again for now (OutboxExpiry counts from then; never archive_uncertain, which the server already accepted) and discard drops it; all three clear its Failure, and confirm_sent and discard delete its draft. edit takes a failed item back as CancelOutbox does. resend also retries a queued item now, its undo window still kept.

func (*Service) RewriteSelection

func (s *Service) RewriteSelection(ctx context.Context, draftID int64, sel Selection, instruction string) (<-chan WitEvent, error)

RewriteSelection rewrites sel of the draft's editable part as instruction says, in a new assist conversation of its own. The model gets only the selected HTML and up to 500 characters of read-only context on each side, and answers with update_selection; the proposal splices its HTML into the range, so nothing outside it can change. A sel made on another revision is ErrStaleDraft.

func (*Service) RunAction

func (s *Service) RunAction(ctx context.Context, id string, t Target, opts RunActionOptions) (ActionResult, error)

RunAction runs action id (<plugin>/<id>) on t. The plugin gets {kind, id} and, for a selection, text: never other mail content (it reads that itself with mail:read). A plugin holding net that may hold mail content (mail:read, or a selection) returns *EgressApprovalRequired unless opts approves. A failed run or an invalid result counts as a plugin failure.

func (*Service) RunConversation added in v1.12.0

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

RunConversation is the conversation runID is a run of.

func (*Service) RunSkill

func (s *Service) RunSkill(ctx context.Context, name string, t Target) (<-chan ai.Event, error)

RunSkill runs an enabled skill on t with no tools. The first event is "context": Text is a JSON list of {message_id, suspect} for the mail the model sees, so the UI can flag suspected prompt injection, and Model is the "slug/model" the run uses (skill godwit-model, else SmallModel for the small tier, else DefaultModel). message and thread runs are cached by everything that changes their output; a hit replays context, one text event and done without asking the model. The channel ends with exactly one of done or error and is closed after it; cancel ctx to stop early.

func (*Service) SaveDraft

func (s *Service) SaveDraft(ctx context.Context, d Draft) (Draft, error)

SaveDraft inserts d (ID 0) or updates its addresses, subject and body. The HTML is sanitized for composing (no scripts, handlers or remote resources). Attachments are changed with AddAttachment and RemoveAttachment.

func (*Service) Search

func (s *Service) Search(ctx context.Context, accountID int64, query string, limit int) ([]MessageSummary, error)

Search finds synced messages; accountID 0 searches every account.

func (*Service) SearchWith

func (s *Service) SearchWith(ctx context.Context, q SearchQuery, limit int) ([]MessageSummary, error)

SearchWith finds synced messages matching q, newest first. A query with neither text nor a filter finds nothing.

func (*Service) Send

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

Send moves the draft into the outbox; the next sync submits it. Nothing is sent and the draft stays when validation or building fails. Plugins' message.beforeSend handlers check it first (hooks.go): a block returns *SendBlockedError, warnings *SendWarningsError (see SendAcknowledged). A draft changed during the checks is checked again; changed twice in a row, Send returns ErrStaleDraft.

func (*Service) SendAcknowledged

func (s *Service) SendAcknowledged(ctx context.Context, draftID int64, digest string) error

SendAcknowledged sends the draft despite the warnings of the check with digest: if the draft's revision and the checking plugins are still the checked ones it is queued without checking again; otherwise (or with no such check, e.g. expired) it is a plain Send, which may warn again. A block has no check, so it can never be acknowledged.

func (*Service) SendAcknowledgedRevision

func (s *Service) SendAcknowledgedRevision(ctx context.Context, draftID, revision int64, digest string) error

SendAcknowledgedRevision is SendAcknowledged for exactly that revision of the draft: if the stored one differs, nothing is sent and the error is ErrStaleDraft.

func (*Service) SendRevision

func (s *Service) SendRevision(ctx context.Context, draftID, revision int64) error

SendRevision is Send for exactly that revision of the draft: if the stored one differs, nothing is sent and the error is ErrStaleDraft.

func (*Service) SenderAvatar added in v0.3.0

func (s *Service) SenderAvatar(ctx context.Context, messageID int64, allowRemote bool) (Avatar, error)

SenderAvatar loads the ordinary sender avatar under the current message's remote-image policy. allowRemote is the user's explicit permission for this message. Missing or unavailable sources are normal empty results.

func (*Service) SetClockForTest added in v1.14.0

func (s *Service) SetClockForTest(c Clock)

SetClockForTest replaces the Service's clock. Tests only: with a fake clock they step past waits instead of sleeping. Call it right after New, before any account is added.

func (*Service) SetConversationModel added in v1.7.0

func (s *Service) SetConversationModel(ctx context.Context, id int64, ref, effort string) error

SetConversationModel makes the conversation's next runs use ref ("slug/model" or a plugin's; "" goes back to Settings.DefaultModel) and ask for effort ("low", "medium" or "high"; "" asks for none, as non-reasoning models need). Both are checked before either is kept: a ref that does not resolve or an unknown effort changes nothing. A run going on keeps what it started with.

func (*Service) SetDraftAccount

func (s *Service) SetDraftAccount(ctx context.Context, id, accountID, revision int64) (Draft, error)

SetDraftAccount moves the draft to accountID: the body's signature becomes that account's, attachments and the reply's source stay, and the revision grows by one. revision must be the stored one (ErrStaleDraft).

func (*Service) SetDraftModel added in v1.16.0

func (s *Service) SetDraftModel(ctx context.Context, draftID int64, model string) error

SetDraftModel sets the model of draftID's assist conversation, keeping its effort, as picked before its next question asks on it.

func (*Service) SetFlags

func (s *Service) SetFlags(ctx context.Context, ids []int64, add, remove []string) error

SetFlags adds then removes flags on the messages locally and queues the change for the server.

func (*Service) SetLabel added in v0.3.0

func (s *Service) SetLabel(ctx context.Context, messageIDs []int64, labelID int64, on bool) error

SetLabel puts the label on the messages (on) or takes it off, by hand: the classifier leaves these rows alone from then on. All or none are written.

func (*Service) SetMCPServerEnabled

func (s *Service) SetMCPServerEnabled(ctx context.Context, id int64, enabled bool) error

SetMCPServerEnabled starts (connects and lists tools) or stops a server. Starting needs its current version granted (ErrNeedsGrant).

func (*Service) SetMCPToolTrusted

func (s *Service) SetMCPToolTrusted(ctx context.Context, id int64, tool string, trusted bool) error

SetMCPToolTrusted trusts (or stops trusting) a tool as listed now: trust is bound to its definition hash, so any change to the definition ends it.

func (*Service) SetNativeHostForTest added in v1.2.0

func (s *Service) SetNativeHostForTest(env ...string)

SetNativeHostForTest adds env to the environment of native plugins' processes. Tests only: with coretest.NativeChildEnv the test binary serves as plugin-host. Call it right after New, before any plugin starts.

func (*Service) SetPluginConfig

func (s *Service) SetPluginConfig(ctx context.Context, name string, values map[string]json.RawMessage) error

SetPluginConfig saves the settings form. Non-secret fields take the given value; absent, null or "" unsets one (its default applies). A secret absent or "" keeps its value and null clears it. Fields their when hides are ignored and keep what they had. Nothing is written unless every shown field is valid and every shown required one has a value; a write bumps config_version.

func (*Service) SetPluginEnabled

func (s *Service) SetPluginEnabled(ctx context.Context, name string, enabled bool) error

SetPluginEnabled starts or stops a plugin. Starting needs its current permissions granted (ErrNeedsGrant) and intact files; it resets the failure count.

func (*Service) SetPluginNetForTest

func (s *Service) SetPluginNetForTest(n plugins.NetOptions)

SetPluginNetForTest replaces the network plugins and MCP servers over HTTP use (resolver, dialer, plain HTTP and loopback allowed or not). Tests only: it lets fixture plugins reach a local server. Call it right after New, before any plugin or MCP server starts.

func (*Service) SetPurge

func (s *Service) SetPurge(ctx context.Context, accountID int64, role string, days int) error

SetPurge sets how many days mail stays in the account's junk or trash folder before it is expunged on the server; 0 is never. Any change restarts the clock: only mail that stays that long from now on is purged.

func (*Service) SetRoleFolder

func (s *Service) SetRoleFolder(ctx context.Context, accountID int64, role string, folderID int64) error

SetRoleFolder gives role (drafts, sent, junk, trash or archive) to the folder; 0 leaves the account without a folder of the role. The choice survives sync; once the folder is gone the role follows detection again. INBOX takes no role, and a folder holding another role cannot take this one (junk and trash would purge its mail): that role moves elsewhere first.

func (*Service) SetSettings

func (s *Service) SetSettings(ctx context.Context, st Settings) (Settings, error)

SetSettings validates and stores st, then announces settings.changed.

func (*Service) SetSkillEnabled

func (s *Service) SetSkillEnabled(ctx context.Context, name string, enabled bool) error

SetSkillEnabled turns a skill on or off.

func (*Service) SignatureCode added in v1.9.0

func (s *Service) SignatureCode(ctx context.Context, id int64) (string, error)

SignatureCode is signature id as stored, for the editor's HTML mode: sanitized, its images as cid:, one block per line.

func (*Service) SignatureEditor

func (s *Service) SignatureEditor(ctx context.Context, id int64) (string, error)

SignatureEditor is signature id as the settings editor's HTML: sanitized, a plain one escaped into a paragraph, its images as data: URLs.

func (*Service) SignatureShown added in v1.9.0

func (s *Service) SignatureShown(ctx context.Context, block string) (string, error)

SignatureShown is a draft's signature block (mail.SplitDraft's) as the compose page shows it, read-only: sanitized first (SanitizeDraft, the stored images kept, markers dropped), then its images as data: URLs. "" for none.

func (*Service) StopRescan added in v0.3.0

func (s *Service) StopRescan(ctx context.Context) error

StopRescan gives up on the rescan targets not classified yet.

func (*Service) StoredHTML added in v1.16.0

func (s *Service) StoredHTML(ctx context.Context, id int64) (string, error)

StoredHTML is message id's HTML body as synced, unsanitized; "" when it has none. It needs no connection, unlike GetRawMessage.

func (*Service) Subscribe

func (s *Service) Subscribe() (<-chan events.Event, func())

Subscribe returns UI notifications and a func that unsubscribes.

func (*Service) SubscribeConversation

func (s *Service) SubscribeConversation(id int64) (<-chan WitEvent, func())

SubscribeConversation streams the events of the conversation's runs, including resumes after approvals, until the returned func is called or the Service closes; either closes the channel and discards what is still queued. A slow reader loses the oldest text but never an event that ends a run. After Close the channel is closed.

func (*Service) SyncNow

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

SyncNow connects to the account's IMAP server, pushes queued local changes, sends and files the outbox, and fetches new mail. Calls for the same account run one at a time.

func (*Service) SystemLanguage added in v1.7.0

func (s *Service) SystemLanguage() string

SystemLanguage is the operating system language tag passed in Options.

func (*Service) SystemTranslator added in v1.9.0

func (s *Service) SystemTranslator() SystemTranslator

SystemTranslator returns the operating system's translator, if any.

func (*Service) TaskModel

func (s *Service) TaskModel(ctx context.Context, skill string) (string, error)

TaskModel is the "slug/model" skill runs on (quick replies when skill is ""), resolved as RunSkill and QuickReplies resolve it, without running it. ErrAINotConfigured, ErrModelServiceNotFound or ErrModelNotFound: it has none.

func (*Service) TestAccount

func (s *Service) TestAccount(ctx context.Context, in AccountInput) error

TestAccount runs the connection check; a failure is a *CheckError.

func (*Service) TestCapability

func (s *Service) TestCapability(ctx context.Context, id int64, in ModelServiceInput, c string) (CapStatus, error)

TestCapability tests capability c (CapGen, CapJudge) of in as service id (0: a new one) would be saved, without saving it: generate runs the shortest real generation on its first model (or the first one it lists), judge asks a yes/no about a fixed sample. A failed test returns its status and the error; an invalid in returns no status. When in is service id as saved (same address, stored key, and format), the status is stored, unless the service changed while the test ran.

func (*Service) TestPluginModel added in v1.16.0

func (s *Service) TestPluginModel(ctx context.Context, ref string) (CapStatus, error)

TestPluginModel tests the plugin's model ref names, as the model settings list does: a judge answers a yes/no, any other model the shortest real generation. Nothing is stored: a plugin's model has no service row.

func (*Service) ThreadLabels added in v0.3.0

func (s *Service) ThreadLabels(ctx context.Context, threadIDs []int64) (map[int64][]AppliedLabel, error)

ThreadLabels returns the labels on any message of each thread, in the labels' order.

func (*Service) TrustImageSender

func (s *Service) TrustImageSender(ctx context.Context, from string) error

TrustImageSender trusts the address of from (a From header) to load remote images; from must parse as an address.

func (*Service) TrustedImageSenders added in v1.19.0

func (s *Service) TrustedImageSenders(ctx context.Context) ([]string, error)

TrustedImageSenders are the lower-cased From addresses whose remote images load at once (始终信任此发件人).

func (*Service) UnblockSender added in v1.17.0

func (s *Service) UnblockSender(ctx context.Context, addr string) error

UnblockSender removes addr from the blocked senders list.

func (*Service) UndoLastAssist

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

UndoLastAssist puts back the editable part the draft's latest applied proposal (by approval ID, not by clock) replaced. ErrInvalidState: there is none, or the draft changed since it was written (an undo counts as a change).

func (*Service) UninstallPlugin

func (s *Service) UninstallPlugin(ctx context.Context, name string) error

UninstallPlugin stops the plugin and removes its row (with its config, storage and cursor) and its files.

func (*Service) Unsubscribe added in v1.14.0

func (s *Service) Unsubscribe(ctx context.Context, messageID int64) (UnsubscribeResult, error)

Unsubscribe unsubscribes from message by its headers, read again (no address is taken from the caller): a one-click one is audited (its host only) and POSTed; a mailto one becomes a draft from message's account, never sent. A web one is ErrUnsubscribeWeb, none ErrNoUnsubscribe; a second one-click call while one is under way is ErrUnsubscribing.

func (*Service) UnsubscribeMethod added in v1.14.0

func (s *Service) UnsubscribeMethod(ctx context.Context, messageID int64) (Unsubscribe, error)

UnsubscribeMethod is how message can be unsubscribed from; none in a junk folder. A message synced before these headers were stored has them fetched first, from its account's IMAP server only; one not there (not pushed yet, UIDVALIDITY changed, offline, gone) has none until asked again.

func (*Service) UntrustImageSender

func (s *Service) UntrustImageSender(ctx context.Context, addr string) error

UntrustImageSender stops trusting addr.

func (*Service) UpdateAccount

func (s *Service) UpdateAccount(ctx context.Context, id int64, p AccountPatch) (Account, error)

UpdateAccount writes p's fields in one transaction. New Servers are first checked with the stored credentials (a failure is a *CheckError and nothing is saved). IsDefault true makes the account the only default; false fails on the default account, as one account is always the default. Sync is a Limit of 1–100000, Months of 1–120, or neither (all).

func (*Service) UpdateLabel added in v0.3.0

func (s *Service) UpdateLabel(ctx context.Context, id int64, in LabelInput) (Label, error)

UpdateLabel changes a label's name, description, color and icon; its slug stays.

func (*Service) UpdateMCPServer

func (s *Service) UpdateMCPServer(ctx context.Context, id int64, in MCPServerInput) (MCPServer, error)

UpdateMCPServer changes a server: its version goes up, its connection closes, its grant and tool trust are cleared, it is disabled, and its pending approvals become stale.

func (*Service) UpdateModelService

func (s *Service) UpdateModelService(ctx context.Context, id int64, in ModelServiceInput) (ModelService, error)

UpdateModelService replaces the service's fields, applies the key action and bumps its version. A new key goes to a new keychain entry first; then one transaction switches the address and the entry together; then the old entry is deleted. A crash at any point never pairs a key with an address it was not saved for: the row names the old entry or the new one, never a half-written one, and the next start deletes the other (sweepModelKeys).

func (*Service) UpdatePassword

func (s *Service) UpdatePassword(ctx context.Context, id int64, password string) error

UpdatePassword checks password against the account's servers and, if both accept it, saves it and clears reauth_required and a paused outbox; the worker resumes and the outbox sends in its next round. A failed check is a *CheckError and leaves the keychain unchanged.

func (*Service) UpdateSignature added in v1.9.0

func (s *Service) UpdateSignature(ctx context.Context, id int64, p SignaturePatch) (Signature, error)

UpdateSignature writes p's fields: every account using the signature writes with it from then on. Too many images is ErrSignatureImageCount, an image it cannot take ErrSignatureImage; nothing is saved then.

type ServiceCheck

type ServiceCheck struct {
	BaseURL, Endpoint string
	Models            []string
	Names             map[string]string // model ID -> display name, the service's or else models.dev's, for the IDs either names
	ListSupported     bool              // false: the service has no model list; models are typed by hand
	NoListStatus      int               // the HTTP status that said so, when known
	JudgeEndpoint     string
	JudgeModels       []string // nil until there is a key, except for ProviderOther
}

ServiceCheck is what probing a service before saving found. Endpoint and Models are generate's ("" and nil when it is off); JudgeEndpoint and JudgeModels judge's.

type Settings

type Settings struct {
	Theme, Density                                   string
	FontSize, BodyFontSize                           int // BodyFontSize 0 follows FontSize
	UILanguage, ReadingLanguage, ReplyLanguage       string
	NoTranslate                                      []string
	LaunchAtLogin, KeepInBackground, UnreadInMenuBar bool
	UnreadOnAppIcon                                  bool
	NotifyNewMail, NotifyPreview                     bool
	QuickReplies, Summary, ThreadView                bool
	ThreadCollapse                                   bool // collapse runs of folded messages into an expandable card
	ThreadCollapseThreshold                          int  // a longer thread keeps its newest this many messages in sight and collapses the older; MinThreadCollapse to MaxThreadCollapse
	DefaultModel, SmallModel                         string
	// Translator is the reader's translation channel: "" the model, or
	// "plugin/<name>" a plugin declaring translate (ListTranslators).
	Translator string
	// JudgeService is the slug of the service whose judge answers typed
	// questions; "" (or one gone or with judge off): the DefaultModel does.
	JudgeService string
	// JudgeThreshold is the minimum predicate probability treated as yes by
	// app features, from MinJudgeThreshold to MaxJudgeThreshold. Raw judge
	// answers keep their probabilities.
	JudgeThreshold float64
	LocalAPI       bool // the GUI serves the Local API; off by default
	// MCPSend is what godwit mcp's send_draft does (通过 MCP 发送):
	// MCPSendOff, MCPSendConfirm (the default; "" too) or MCPSendDirect.
	MCPSend string
	// SignatureDelimiter puts the RFC 3676 "-- " line before a new draft's
	// signature, which clients such as Mutt and Thunderbird recognize and
	// fold; off by default.
	SignatureDelimiter bool
	// AutoLabel lets the classifier label new Inbox mail; on by default.
	// A rescan runs either way.
	AutoLabel bool
	// Masking is 脱敏 (docs/adr/0025-mask-at-cloud-egress.md): keys, ID and
	// card numbers go to a model off this device as placeholders. On by
	// default, for settings stored before it too.
	Masking bool
	// MaskCategories say which categories masking finds, and what is done
	// with each one's values.
	MaskCategories MaskCategories
	// MaskWords are the user's own words to mask (自定义词), as TERM: in either
	// letter case unless MaskWordsCase, inside longer words unless MaskWordsWhole.
	MaskWords                     []string
	MaskWordsCase, MaskWordsWhole bool
	// MaskRules are the user's patterns (自定义正则), each masking as its kind;
	// at most mask.MaxRules, checked as they are saved.
	MaskRules []mask.Rule
	// MaskAllow are the values never masked (白名单), whatever their letter case; at most mask.MaxAllow.
	MaskAllow []string
	// LabelDisplay is how label chips show: LabelDisplayBoth (the default;
	// "" too), LabelDisplayIcon or LabelDisplayText.
	LabelDisplay string
	// SidebarWidth is the page sidebars' width in DIPs, the user's drag:
	// 0 for the default, else 240 to 480.
	SidebarWidth int
	// ListWidth is the mail list's width in DIPs, the user's drag: 0 for the
	// default, else 280 to 560.
	ListWidth int
	// RemoteImages is when a message's remote images and sender avatars load, through the image
	// proxy: "auto" (default, "" too) at once, "trusted" for the trusted
	// senders only, "ask" after 加载图片. Mail in Junk never loads them by itself.
	RemoteImages string
	// SettingsVersion is 2 once the default text grew from 13 to 14 px and a
	// stored FontSize was raised by one to keep its sizes; 3 once a stored
	// BodyFontSize of 14, the old default, became 0 (follow FontSize); 4 once
	// Chinese language tags name the script (zh-CN → zh-Hans, zh-TW → zh-Hant).
	SettingsVersion int
}

Settings are the app-wide preferences, stored as one JSON row. ReplyLanguage is "match" (the mail's language) or "reading".

type SignInCode added in v1.5.0

type SignInCode struct {
	MessageID        int64
	Code, Link, From string
	LinkKind         string // what Link does: mail.LinkSignIn, LinkConfirm or LinkReset
	ReceivedAt       time.Time
}

SignInCode is a locally extracted sign-in code or sign-in link (or both) from a recent inbox arrival.

type Signature added in v1.9.0

type Signature struct {
	ID       int64
	Name     string
	HTML     string
	Accounts []int64
}

Signature is a signature accounts share. Name is only the user's, to tell them apart; HTML is as stored: SignatureHTMLPrefix and sanitized editor HTML, or plain text (the CLI's, the Local API's); "" is empty. Accounts are the accounts using it by default, in creation order.

type SignaturePatch added in v1.9.0

type SignaturePatch struct{ Name, HTML *string }

SignaturePatch changes the signature's fields that are not nil. HTML is as AccountPatch.Signature: marked editor HTML (its data: images become the signature's), or plain text.

type SkillInfo

type SkillInfo struct {
	Name, Description string
	On                []string
	Output            string
	Model             string // godwit-model; "" is the default model
	Tier              string // godwit-model-tier: "small" or ""
	Builtin, Enabled  bool
	UI                bool // has godwit-action-*
	Error             string
}

type SkillOptions

type SkillOptions struct {
	Selection      *Selection
	TargetLanguage string
}

SkillOptions are AssistSkill's options. Selection, if set, limits the skill to that range; TargetLanguage is translate-draft's target (empty: the reading language).

type SyncRange

type SyncRange struct{ Limit, Months int }

SyncRange is how much of each folder a sync fetches: the newest Limit messages, the mail of the last Months months, or (both 0) all of it. Narrowing it only stops fetching older mail; nothing stored is deleted.

type SystemTranslator added in v1.8.0

type SystemTranslator interface {
	// Translate translates texts into target, one answer per text in order;
	// source "" detects it, and detected is the source used (BCP 47).
	Translate(ctx context.Context, texts []string, source, target string) (out []string, detected string, err error)
	// Version changes when the system's translations may, as with an OS update.
	Version() string
	// InstalledLanguages returns the BCP 47 language identifiers downloaded for system translation.
	InstalledLanguages() []string
}

SystemTranslator is the operating system's on-device translation, which the built-in system-translation plugin offers (builtins.go); the apps set Options.SystemTranslator where the system has one.

type Tag added in v1.5.0

type Tag struct {
	Plugin            string
	Builtin           bool
	Kind, Label, Text string
	Value             string
}

Tag is a plugin's small action shown right after a message's subject: copy a value (Kind "copy") or open a link ("open-url"). Text is what the tag shows (a code; a link's host), Value what it copies or opens. A built-in plugin's Label is a key the app words ("signin", "confirm", "reset" for a link); a copy tag needs none.

type Target

type Target struct {
	Kind string
	ID   int64
	Text string
	// PreserveHTML translates message text nodes for the reader, without rewriting markup.
	PreserveHTML bool
}

Target is what a skill runs on: message, thread, selection (ID is the message the text was selected in) or draft.

type Thread

type Thread struct {
	ID       int64
	Subject  string
	Messages []MessageSummary
}

Thread is a conversation with its messages, oldest first.

type ThreadDigest added in v1.19.0

type ThreadDigest struct {
	Progress []DigestLine
	Todo     DigestLine
}

ThreadDigest is a thread's summary as summarize writes it for a thread: its steps, oldest first, and what the user is to do (nil for nothing).

func ParseThreadDigest added in v1.19.0

func ParseThreadDigest(text string, ids []int64) (d ThreadDigest, ok bool)

ParseThreadDigest reads a thread's summary in threadDigestFormat; a cite of a message not in ids is dropped. ok is false for an answer with no step: the caller shows it as written.

type ThreadPage

type ThreadPage struct {
	Items      []ThreadSummary
	NextCursor string
}

ThreadPage is one page of threads.

type ThreadSummary

type ThreadSummary struct {
	ID               int64
	Subject, Snippet string
	Participants     []string
	Count, Unread    int
	Flagged          int // messages starred
	LastDate         time.Time
	HasAttachments   bool
}

ThreadSummary is a conversation as listed. Count, Unread and Flagged cover the whole thread.

type TranslatorInfo added in v1.2.0

type TranslatorInfo struct {
	ID, Name                 string
	Title                    plugins.Text
	Native, Running, Builtin bool
}

TranslatorInfo is a translation channel: ID "" is the model, else "plugin/<name>" for an installed plugin declaring translate or a built-in one that translates, whose Title is its display name.

type Turn added in v1.12.0

type Turn struct {
	// ID is what AskAgain takes and a run's events carry (WitEvent.Turn);
	// it never changes and means nothing else.
	ID       string
	Question string
	Command  *ai.Command // a command's question: a skill run on the draft (Question is then "")
	Quoted   []Citation  // the mail the user quoted with the question
	// Text and Reasoning are the answer's, its messages' joined; Calls its
	// tool calls in order, each with its result and its approval, if any.
	Text, Reasoning string
	Calls           []TurnCall
	// Steps are the answer in the order it came: each message's reasoning,
	// its text, then its calls.
	Steps []TurnStep
	// Approvals are its runs' approvals that answer none of Calls (a skill's
	// proposal), in order.
	Approvals []Approval
	// Cited is each message its runs showed the model, by their calls or
	// their context, once, with its number in the conversation.
	Cited   []Cited
	Runs    []int64
	Elapsed time.Duration // how long its runs worked (Run.Active)
	// Masked is how many values 脱敏 masked in what its runs sent (已脱敏 N
	// 处), Warned how many it sent as they are (仅警告).
	Masked, Warned int
	// Asked is when its first run began, Answered when its last one last
	// moved on (zero: none).
	Asked, Answered time.Time
	// CanAskAgain: AskAgain takes it now.
	CanAskAgain bool
	// Failed is why the question was never answered (FailQuestion's reason);
	// such a turn, ID "failed", is only ever the last.
	Failed string
}

Turn is one question of a conversation, a command included, and its answer: everything Wit did for it up to the next question.

type TurnCall added in v1.12.0

type TurnCall struct {
	ai.ToolCall
	Result   *ai.ToolResult
	Approval *Approval
}

TurnCall is a tool call of a turn's answer, with its result (nil: none yet) and the approval it waits on or waited on (nil: none).

type TurnStep added in v1.16.0

type TurnStep struct {
	Kind string // "reasoning", "text" or "call"
	Text string
	Call int
}

TurnStep is a step of a turn's answer: its reasoning or text (Text), or a call (Call, its index in the turn's Calls).

type Unsubscribe added in v1.14.0

type Unsubscribe struct {
	Method, Host, List, URL string
}

Unsubscribe is how a message can be unsubscribed from: Method ("" none), Host the request or mail goes to, List the List-Id's name (shown only) and URL the address used.

type UnsubscribeResult added in v1.14.0

type UnsubscribeResult struct {
	Method, Host string
	Failure      string
	Status       int
	DraftID      int64
}

UnsubscribeResult is what Unsubscribe did. A one-click one was sent when Failure is "", else it is why not (an UnsubscribeFailed* value, Status the HTTP status for a redirect or a refusal); a mailto one made DraftID.

type View

type View struct {
	FolderID int64
	Unified  string
	LabelID  int64
}

View selects what a list shows: one folder, a unified view ("inbox", "starred") or one label's mail across accounts. Exactly one is set.

type WitEvent

type WitEvent struct {
	ai.Event
	ConversationID int64
	RunID          int64
	Turn           string
	Ends           bool
	Citations      []Citation
	Approvals      []Approval
}

WitEvent is one event of a Wit run of conversation ConversationID, for its turn Turn (Turn.ID). A run that starts (not a resume) sends "start" first; an Assist run then a "context" event whose Citations are the mail its context shows the model. An interrupted event carries the approvals it recorded, in call order. Ends: the run is over for now, done, failed, or waiting on the user (an interrupt whose calls were all decided at once goes on in a resume instead).

Directories

Path Synopsis
ai
Package ai talks to model services.
Package ai talks to model services.
mask
Package mask is 脱敏 (docs/adr/0025-mask-at-cloud-egress.md): the keys, ID and card numbers in what goes to a model service off this device are replaced by placeholders, {{KIND_<12 base32>}}, and the placeholders in what comes back are restored to their values.
Package mask is 脱敏 (docs/adr/0025-mask-at-cloud-egress.md): the keys, ID and card numbers in what goes to a model service off this device are replaced by placeholders, {{KIND_<12 base32>}}, and the placeholders in what comes back are restored to their values.
pi
Package pi runs pi-ai, the model layer of the pi agent harness, on moejs, a JavaScript runtime in pure Go (docs/adr/0024-pi-moejs-agent-runtime.md).
Package pi runs pi-ai, the model layer of the pi agent harness, on moejs, a JavaScript runtime in pure Go (docs/adr/0024-pi-moejs-agent-runtime.md).
Package auth holds the provider table and account auto-detection.
Package auth holds the provider table and account auto-detection.
Package conn dials and authenticates IMAP and SMTP connections.
Package conn dials and authenticates IMAP and SMTP connections.
Package coretest is a real core.Service for tests outside core: a mocked keychain, fake IMAP / SMTP servers per account, a fake model service, a fake MCP server and fixture plugins, all on this machine.
Package coretest is a real core.Service for tests outside core: a mocked keychain, fake IMAP / SMTP servers per account, a fake model service, a fake MCP server and fixture plugins, all on this machine.
Package events is a lossy in-process event bus for UI notifications.
Package events is a lossy in-process event bus for UI notifications.
Package gateway decides whether an AI tool call may run, needs approval, or is denied, and audits every decision.
Package gateway decides whether an AI tool call may run, needs approval, or is denied, and audits every decision.
internal
testclock
Package testclock is a fake clock for tests: time moves only on Advance.
Package testclock is a fake clock for tests: time moves only on Advance.
testllm
Package testllm is a fake model service for tests: the model-list endpoint and a scripted, streaming chat endpoint for each protocol (openai, openai-responses, anthropic).
Package testllm is a fake model service for tests: the model-list endpoint and a scripted, streaming chat endpoint for each protocol (openai, openai-responses, anthropic).
testmail
Package testmail provides in-memory IMAP and SMTP servers for tests.
Package testmail provides in-memory IMAP and SMTP servers for tests.
testoauth
Package testoauth is a fake OAuth 2.0 authorization and token server for tests, with a stand-in for the user's browser.
Package testoauth is a fake OAuth 2.0 authorization and token server for tests, with a stand-in for the user's browser.
Package mail parses MIME messages and sanitizes HTML bodies.
Package mail parses MIME messages and sanitizes HTML bodies.
Package mailsync pulls folders and messages from IMAP into the store.
Package mailsync pulls folders and messages from IMAP into the store.
Package plugins runs third-party TypeScript plugins: manifest validation, the sandbox and the ctx API.
Package plugins runs third-party TypeScript plugins: manifest validation, the sandbox and the ctx API.
Package send submits messages over SMTP.
Package send submits messages over SMTP.
Package skills loads SKILL.md directories (Agent Skills standard).
Package skills loads SKILL.md directories (Agent Skills standard).
Package store is Godwit's SQLite storage layer.
Package store is Godwit's SQLite storage layer.

Jump to

Keyboard shortcuts

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