core

package
v1.39.1 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 96 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 (
	PresetICloud   = "icloud"
	PresetFastmail = "fastmail"
	PresetGoogle   = "google"
	PresetCustom   = "custom"

	ProviderGoogleCardDAV = "google_carddav"

	AddressBookSyncInterval = 30 * time.Minute
)
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 (
	MaskSourceRule       = mask.SourceRule
	MaskSourceRecognizer = mask.SourceRecognizer
)

What found a masking record's value (MaskRecord.Source): a rule, or 识别模型.

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 (
	ProxySystem = "system"
	ProxyCustom = "custom"
	ProxyOff    = "off"
)

Proxy modes (Settings.ProxyMode): the system's proxy, the user's own (Settings.ProxyURL), or none.

View Source
const (
	ReplyStatusUnreplied = "unreplied" // the newest mail is direct, from someone else, and has no reply
	ReplyStatusWaiting   = "waiting"   // the newest mail is the user's, or a reply queued after it
)

回复状态 (ADR 0031), as a thread's status in a view.

View Source
const (
	TriggerReceive  = "receive"
	TriggerLabel    = "label"    // TriggerArg is the label's slug
	TriggerSecurity = "security" // TriggerArg is SecuritySuspicious or SecurityDangerous
	TriggerDaily    = "daily"

	SecuritySuspicious = "suspicious" // needs_review or warning
	SecurityDangerous  = "dangerous"  // warning

	MatchAll = "all"
	MatchAny = "any"

	FieldFrom        = "from"
	FieldTo          = "to" // To and Cc
	FieldSubject     = "subject"
	FieldBody        = "body"
	FieldAttachments = "attachments" // is RuleYes or RuleNo
	FieldLabel       = "label"       // is or not_contains a label's slug
	FieldFolder      = "folder"      // is or not_contains a folder role or a folder's id
	FieldAge         = "age"         // older_than a number of whole days, by the message's date
	FieldAny         = "any"         // contains or not_contains what a search's text matches; 视图 only

	OpContains    = "contains"
	OpNotContains = "not_contains"
	OpIs          = "is"
	OpOlderThan   = "older_than"

	RuleYes = "yes"
	RuleNo  = "no"

	// The move actions are named after the role of the folder they move to.
	ActionLabel   = "label"
	ActionUnlabel = "unlabel"
	ActionRead    = "read"
	ActionStar    = "star"
	ActionArchive = "archive"
	ActionJunk    = "junk"
	ActionTrash   = "trash"
	ActionBlock   = "block"
	ActionStop    = "stop" // later rules do not run on the message
	// ActionForward forwards the message to RuleAction.To once the user
	// confirmed it (Rule.Confirmed); egress, so new mail only (newMailTriggers).
	ActionForward = "forward"

	// The file actions write to Dir (rulefiles.go); they cannot be undone.
	ActionPDF         = "pdf"
	ActionEML         = "eml"
	ActionAttachments = "attachments"

	// The AI actions send the message to the model, masked, and only while
	// Settings.RuleAI is on; new mail only (existingActions). draft_reply
	// saves a reply draft, never sent; key_points writes a file as the file
	// actions do.
	ActionDraftReply = "draft_reply"
	ActionKeyPoints  = "key_points"
)

Rule document ids.

View Source
const (
	RuleRunRunning = "running"
	RuleRunDone    = "done"
	RuleRunFailed  = "failed"
	RuleRunUndone  = "undone"

	RuleActionDone   = "done"
	RuleActionFailed = "failed"
	RuleActionNotRun = "not_run" // after a failed one
	RuleActionUndone = "undone"
	RuleActionKept   = "kept" // not undone: its target changed since
	// RuleActionSkipped is a forward on mail it never forwards: not new
	// (a daily or one-time run), or forwarded by a rule (mail.RuleHeader).
	RuleActionSkipped = "skipped"

	RuleFailNoFolder    = "no_folder"
	RuleFailNoLabel     = "no_label"
	RuleFailGone        = "gone" // the message
	RuleFailUnknown     = "unknown"
	RuleFailBlock       = "block"
	RuleFailUnconfirmed = "unconfirmed" // the forward's recipient is not in Rule.Confirmed
	RuleFailSendCheck   = "send_check"  // a plugin warned about or blocked the forward
	RuleFailSend        = "send"        // the forward could not be queued

	RuleFailNoDestination = "no_destination" // the file action's folder is not there
	RuleFailNoPDF         = "no_pdf"         // nothing renders PDFs here (headless)
	RuleFailUnavailable   = "unavailable"    // the mail could not be read from the server
	RuleFailTooLarge      = "too_large"
	RuleFailWrite         = "write_failed"
	RuleFailUnsafeFolder  = "unsafe_folder" // a subfolder level in the destination is a symlink or not a folder
	RuleFailAIOff         = "ai_off"        // Settings.RuleAI is off
	RuleFailModel         = "model"         // no model, or it did not answer
)

Run and action states, and why an action failed.

View Source
const (
	MaxRuleName       = 100
	MaxRuleConditions = 20
	MaxRuleActions    = 20
	MaxRuleValue      = 500
)

Rule limits: the document stays a list of choices, not a language.

View Source
const (
	FieldReply = "reply" // is ViewReplyUnreplied, or older_than a number of whole days
	FieldRead  = "read"  // is ViewReadUnread or ViewReadRead

	// FieldDate is, or isn't (OpNotContains), one of the ViewDate values or a
	// number of days, today included, in local calendar days.
	FieldDate    = "date"
	FieldStarred = "starred" // is RuleYes or RuleNo
	FieldWrote   = "wrote"   // is RuleYes: a sender the user has written to, or their own mail; RuleNo: only others

	ViewDateToday     = "today"
	ViewDateYesterday = "yesterday"
	ViewDateThisWeek  = "this_week"
	ViewDateLastWeek  = "last_week"
	ViewDateThisMonth = "this_month"
	ViewDateLastMonth = "last_month"

	ViewReplyUnreplied = "unreplied"
	ViewReadUnread     = "unread"
	ViewReadRead       = "read"

	// Exceptions: a conversation added to or removed from a view by hand.
	ViewExceptionAdded   = "added"
	ViewExceptionRemoved = "removed"

	// ViewGroupOther is the ID of a view's 其他: its conversations in no group.
	ViewGroupOther = "other"
)

Fields only views use: they read a conversation's state now, where a rule runs once on an event.

View Source
const (
	MaxViewGroups   = 20
	MaxViewWaitDays = 29 // 回复状态 reads replyStatusDays days back
	MaxViewDateDays = 3650
)

View limits: the document stays a list of choices, not a language.

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 (
	ListRowSender  = "sender"
	ListRowSubject = "subject"
)

What leads a list row (Settings.ListRowOrder).

View Source
const (
	BackgroundSyncInbox = "inbox"
	BackgroundSyncAll   = "all"
)

What syncs while the window is in the background (Settings.BackgroundSync).

View Source
const (
	BackgroundReceiveStopOnClose = "stop_on_close"
	BackgroundReceiveUntilQuit   = "until_quit"
	BackgroundReceiveAlways      = "always"
)

How long the backend keeps receiving mail (Settings.BackgroundReceive): it stops as the window closes; it stays after the window closes and stops as Godwit quits; it stays even then, quitting closing only the interface.

View Source
const (
	ReaderWidthNormal = "normal"
	ReaderWidthWide   = "wide"
	ReaderWidthFull   = "full"
)

How wide the reading column may grow (Settings.ReaderWidth).

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 (
	AuthPassword = "password"  // a password: IMAP LOGIN, SMTP AUTH, HTTP Basic
	AuthAPIToken = "api_token" // an API token sent as HTTP Bearer (JMAP)
	AuthOAuth    = "oauth"     // an OAuth access token
)

How a server slot signs in (Server.Auth).

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 AccountExportVersion = 1

AccountExportVersion is the format version ExportAccounts writes.

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 AuditRule = "rule"

AuditRule is the audit source of what a rule sends off the machine: a forward (target: the rule; destination: the recipient's domain) and a Wit action, draft_reply or key_points (target: the message; destination: the model service's host).

View Source
const AuditUI = "ui"

AuditUI is the audit source of Godwit's interface (the Local API's ui role): a same-user program can present ui-token (ADR 0002), so its sends and grants are audited, though not gated as external (no WithExternalSource).

View Source
const KindConfirm conn.FailureKind = "confirm"

KindConfirm marks an ews step stopped before Autodiscover sends the password to a host outside the address's domain: CheckReport.Confirm.

View Source
const KindInvalid conn.FailureKind = "invalid"

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

View Source
const KindLocalArchive = "local_archive"

KindLocalArchive is an account with no servers or credentials: it never syncs and never sends, and its folders are only local (ADR 0036). Its Email is a unique placeholder, never a sender address.

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 MaxImageRetentionDays = 365

MaxImageRetentionDays bounds Settings.ImageRetentionDays.

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 MaxProxyBypass = 200

MaxProxyBypass caps Settings.ProxyBypass.

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 (
	QuickLabelMaxRunes = 32
)
View Source
const RecentLogMax = 100

RecentLogMax is how many lines RecentLog keeps.

View Source
const RuleHitDays = 7

RuleHitDays is how far back RuleHits looks.

View Source
const RulePreviewDays = 30

RulePreviewDays is how far back the mail PreviewRule lists goes.

View Source
const RuleVersion = 1

RuleVersion is the rule document version SaveRule writes.

View Source
const SavedViewVersion = 1

SavedViewVersion is the document version SaveView writes.

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 StoreProduct = "9NS3Q2CGWD12"

StoreProduct is Godwit on the Microsoft Store, apps.microsoft.com/detail/9NS3Q2CGWD12.

View Source
const SystemTranslationPlugin = "system-translation"

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

View Source
const TracePrefix = conn.TracePrefix

TracePrefix 标记日志中已脱敏的 IMAP trace 行,供错误报告识别。

View Source
const TriggerExisting = "existing"

TriggerExisting is the trigger of a run RunRuleOnExisting made; never a rule's.

View Source
const UndoArchiveWindow = 10 * time.Second

UndoArchiveWindow is the existing archive toast's undo window. Removing the last visible Gmail location waits this long so an undo still has a server UID.

View Source
const UndoPurgeWindow = 10 * time.Second

UndoPurgeWindow is how long a permanent delete waits before it is pushed, so that UndoPurge can take it back.

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.

View Source
const WitBuffer = 64

WitBuffer is how many text-like events a Wit stream's reader may fall behind before the oldest go; never a run's end (Terminal). uiclient keeps the same rule on its side of the wire.

Variables

View Source
var (
	// ErrBadAccountExport refuses a corrupted or invalid account export file.
	ErrBadAccountExport = errors.New("the account export file is invalid")
	// ErrUnsupportedExportVersion refuses an account export file with an unknown format version.
	ErrUnsupportedExportVersion = errors.New("the account export file version is not supported")
)
View Source
var (
	ErrAddressBookNotFound = errors.New("address book not found")
	ErrNoAddressBooks      = errors.New("no address books found on this server")
)
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 (
	// ErrNotLocalArchive is a local folder call on a mail account's folder:
	// those folders are the server's.
	ErrNotLocalArchive = errors.New("only a local archive has local folders")
	// ErrRoleFolder is a rename or delete of a local archive's inbox or trash.
	ErrRoleFolder = errors.New("the inbox and trash cannot be renamed or deleted")
	// ErrFolderNotEmpty is a delete of a local folder that still holds mail.
	ErrFolderNotEmpty = errors.New("the folder is not empty")
	// ErrFolderNameEmpty is a local folder name that is blank once trimmed.
	ErrFolderNameEmpty = errors.New("a folder needs a name")
	// ErrFolderExists is a local folder name the account already has.
	ErrFolderExists = errors.New("a folder with that name already exists")
)
View Source
var (
	ErrMaskKind         = mask.ErrKind
	ErrMaskEmptyMatch   = mask.ErrEmptyMatch
	ErrMaskReservedKind = mask.ErrReservedKind
	ErrMaskTooManyRules = mask.ErrTooManyRules
	ErrMaskTooManyAllow = mask.ErrTooManyAllow
)
View Source
var (
	ErrMCPNotFound = errors.New("MCP server not found")
	// ErrMCPManaged: an agent gateway's file owns the server (ADR 0041).
	ErrMCPManaged = errors.New("this MCP server is managed by another app: change it there")
)
View Source
var (
	// ErrMCPSendOff: 通过 MCP 发送 is 不允许.
	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")
	// ErrMCPSendNoUI: 每次确认 with no window to confirm in and no
	// notification to open one (no interface, no graphical session): the
	// setting is on, so the agent must not tell the user to turn it on.
	ErrMCPSendNoUI = errors.New("Godwit cannot ask the user to confirm right now: no Godwit window is open and it cannot post a notification; ask again once the user has opened Godwit")
	// 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")
	// ErrModelServiceManaged: an agent gateway's file owns the service (ADR 0041).
	ErrModelServiceManaged = errors.New("this service is managed by another app: change it there")
)
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 ActionFeatures = map[string]backend.Feature{
	"inbox": backend.FeatureMove, "archive": backend.FeatureMove, "junk": backend.FeatureMove, "delete": backend.FeatureMove,
	"purge": backend.FeaturePurge,
	"read":  backend.FeatureSeen, "unread": backend.FeatureSeen,
	"star": backend.FeatureFlagged, "unstar": backend.FeatureFlagged,
}

ActionFeatures are the 协议能力 the mail actions need (ADR 0037), by the action: the UI greys out one the account's server cannot do, and Wit's tool for it answers "unsupported:".

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 ErrAccountExists = errors.New("this address is already an account")

ErrAccountExists refuses to add an address that is already an account: sign it in again (Reauthorize, UpdatePassword) instead.

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 ErrEWSOff = errors.New("EWS is experimental: turn it on in settings to add an Exchange (EWS) account")

ErrEWSOff refuses to add an EWS account while Settings.ExperimentalEWS is off.

View Source
var ErrGraphOff = errors.New("Microsoft Graph is experimental: turn it on in settings to add an Outlook (Graph) account")

ErrGraphOff refuses to add a Microsoft Graph account while Settings.ExperimentalGraph is off.

View Source
var ErrInvalidRule = errors.New("invalid rule")

ErrInvalidRule is a rule document SaveRule refuses.

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 ErrInvalidView = errors.New("invalid view")

ErrInvalidView is a document SaveView refuses.

View Source
var ErrJMAPOff = errors.New("JMAP is experimental: turn it on in settings to add a JMAP account")

ErrJMAPOff refuses to add a JMAP account while Settings.ExperimentalJMAP is off.

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; see Keyring for the file a user can choose instead.

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 ErrLocalArchive = errors.New("a local archive has no mail server")

ErrLocalArchive is a server, sending or sync call on a local archive account, which has none of these.

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 ErrNoUI = errors.New("this needs the user's approval in Godwit, and no Godwit window is open; ask again once the user has opened Godwit")

ErrNoUI: a Wit run or a plugin action that waits on the user's approval, asked over the Local API while no Godwit window is open to take it.

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 ErrNotProgramDraft = errors.New("no program wrote this draft")
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 ErrPurgeTooLate = errors.New("cannot undo: messages already permanently deleted")

ErrPurgeTooLate is UndoPurge finding none of the messages still waiting: they are deleted for good, or being deleted.

View Source
var ErrReceiveOnly = errors.New("the account only receives mail")

ErrReceiveOnly is a send, or a sender choice, from a receive-only account (Account.ReceiveOnly), or a reply with no other account that sends.

View Source
var ErrRecipientUnconfirmed = errors.New("the forward recipient is not confirmed")

ErrRecipientUnconfirmed: a rule proposal that forwards is saved only once the user confirmed each recipient in Godwit (ResolveApprovalWithArgs).

View Source
var ErrRecognitionModelMismatch = errors.New("a downloaded file of the recognition model does not match its checksum; it was discarded")

ErrRecognitionModelMismatch: a downloaded file of 识别模型 was not the one its revision has, and was discarded.

View Source
var ErrRecognitionModelMissing = errors.New("the recognition model's files are not on this device")

ErrRecognitionModelMissing refuses to turn 识别模型 on: its files are not in the cache (recognitionModelDir).

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 ErrSecretNotFound = keyring.ErrNotFound

ErrSecretNotFound is what a Keyring's Get returns for a missing entry.

View Source
var ErrSecurityScanBusy = errors.New("security scan or synchronization already in progress")

ErrSecurityScanBusy prevents a second request from resetting an active queue.

View Source
var ErrSecurityScanDisabled = errors.New("security scan disabled")

ErrSecurityScanDisabled is returned when attempting to scan while security is turned off.

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", "emerald", "teal", "cyan", "sky", "blue", "indigo", "violet", "fuchsia", "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 NamingPresets = []string{"{date} {subject}", "{from}/{date} {subject}", "{year}/{month}/{date} {subject}"}

NamingPresets are the templates the editor offers before 自定义; the first is the default.

View Source
var NamingTokens = []string{"date", "subject", "from", "domain", "year", "month", "account"}

NamingTokens are the token ids a 命名模板 may use, in the order the token field offers them.

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

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

View Source
var RecentLog = &LogRing{}

RecentLog keeps the process's last log lines in memory, never on disk, for a bug report to carry redacted.

RuleAIActions are the rule actions Wit does: they send the message to the default model, masked (featureRules), only while Settings.RuleAI is on.

RuleFileActions are the actions that write files.

View Source
var SidebarSections = []string{"views", "labels", "accounts"}

SidebarSections are the mail sidebar's movable sections, in the default order.

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 ExtractQuickLabel added in v1.21.0

func ExtractQuickLabel(text string) string

ExtractQuickLabel extracts a concise intent clause directly from a reply's preview text (Superhuman style, 0 latency). It isolates the core action/question using universal punctuation delimiters (?, !, ., —, comma) and word boundaries, completely language-agnostic.

func FileName added in v1.26.0

func FileName(s, fallback string) string

FileName makes s a file name: separators and control characters become _, leading and trailing dots and spaces go, and a name Windows reserves (CON, COM1.txt…) gets a _ in front. Empty, it is fallback.

func FillNaming added in v1.26.0

func FillNaming(tpl string, vals map[string]string) ([]string, error)

FillNaming fills tpl with vals (by token id) and returns its folder levels, each a safe file name. It refuses a template with no token (every message would land in one folder) and an empty, "." or ".." level.

func FormatQuickLabel added in v1.21.0

func FormatQuickLabel(s string) string

FormatQuickLabel cleans, capitalizes and bounds an explicit label provided by the model.

func LinkedAddressBookPreset added in v1.36.0

func LinkedAddressBookPreset(acc Account) string

LinkedAddressBookPreset is the preset of the address book acc's credentials reach, "" when its provider has no CardDAV of its own.

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 NumberedName added in v1.33.0

func NumberedName(name string, n int) string

NumberedName is name's n-th candidate: "invoice.pdf", "invoice (2).pdf", …

func ParseProxyURL added in v1.25.0

func ParseProxyURL(s string) (*url.URL, error)

ParseProxyURL checks a custom proxy (Settings.ProxyURL): http or socks5, a host, a port from 1 to 65535, and nothing else.

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 RuleUndoable added in v1.26.0

func RuleUndoable(kind string) bool

RuleUndoable reports whether UndoRuleRun puts back an action of kind, for the hit history's 撤销, which shows only for a run with one done.

func RunsOnExisting added in v1.26.0

func RunsOnExisting(kind string) bool

RunsOnExisting reports whether an action of kind runs over existing mail.

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 SetAddressBookPresetURLForTest added in v1.36.0

func SetAddressBookPresetURLForTest(t interface{ Cleanup(func()) }, preset, rawURL string)

SetAddressBookPresetURLForTest overrides a preset's default URL until t ends.

func SetChatterWithinForTest added in v1.36.0

func SetChatterWithinForTest(t interface{ Cleanup(func()) }, d time.Duration)

SetChatterWithinForTest replaces chatterWithin until t ends. Tests only.

func SetOAuthConfigForTest added in v1.35.0

func SetOAuthConfigForTest(t interface{ Cleanup(func()) }, fn func(string) (auth.OAuthConfig, error))

SetOAuthConfigForTest replaces oauthConfig until t ends. Tests only.

func SetRecognitionModelFilesForTest added in v1.36.0

func SetRecognitionModelFilesForTest(t interface{ Cleanup(func()) }, files map[string][]byte)

SetRecognitionModelFilesForTest replaces recognitionModelFiles with files (keyed by guard.Files names) until t ends. Tests only.

func SidebarOrder added in v1.35.0

func SidebarOrder(st Settings) []string

SidebarOrder is st's sidebar sections in the order the user chose, or the default one when none was, or the choice is not a permutation of SidebarSections.

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 TimeZone added in v1.36.0

func TimeZone(ctx context.Context) (name string, ok bool)

TimeZone returns the IANA time zone name attached by WithTimeZone, if any.

func WithExternalSource added in v1.35.0

func WithExternalSource(ctx context.Context, source string) context.Context

WithExternalSource marks ctx as coming from an external API source (AuditLocalAPI or AuditMCP): such a call is audited as that source and gated as external (needUI).

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 falls back to time.Local.

func WithUISession added in v1.36.0

func WithUISession(ctx context.Context, s *Service) context.Context

WithUISession binds a fresh UI session to ctx's lifetime for a RoleUI connection; cancelling ctx clears the session's foreground and compose state.

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
	LabelKeywords                           bool // labels and the server's IMAP keywords follow each other (ADR 0035)
	Sync                                    SyncRange
	Folders                                 int // folders synced so far: 0 before the first sync
	AuthType, Status                        string
	SendRefused                             bool   // the reauth_required is only SMTP's (or Graph's) refusal: receiving signs in
	Receiving, Sending                      Server // a local archive's are zero
	Provider, StatusDetail                  string
	OAuthClientID                           string // the user's own OAuth client (OAuthClient), "" the provider's
	Kind                                    string // "" a mail account, KindLocalArchive
	ReceiveOnly                             bool   // added without working SMTP: it syncs but never sends (ErrReceiveOnly)
	Position                                int    // its place in the accounts list, shared with standalone address books (ReorderAccountEntries)
	// Features is what its receiving server can do (协议能力), recorded at
	// the add-account check, a server change and each sign-in (ADR 0034);
	// nil before the first. See Unsupported.
	Features map[backend.Feature]backend.Support
}

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 refuses the user's own OAuth client (client_rejected); or error when the keychain is unavailable (keychain_unavailable). An OAuth account's keychain entry holds its refresh token; access tokens stay in memory.

func (Account) Unsupported added in v1.33.0

func (a Account) Unsupported(f backend.Feature) string

Unsupported is the reason key (backend.Support.Reason, such as "imap.no_uidplus") why the account's server cannot do f, or "" when it can or is not known yet: nothing is refused before the first sign-in.

type AccountEntry added in v1.36.0

type AccountEntry struct{ Account, AddressBook int64 }

AccountEntry is one row of the accounts list: a mail account (Account) or a standalone address book (AddressBook).

type AccountExport added in v1.36.0

type AccountExport struct {
	Version  int               `json:"version"`
	Accounts []ExportedAccount `json:"accounts"`
}

AccountExport is an exported accounts file: configuration only, never passwords, tokens, OAuth client secrets or mail.

type AccountIcon added in v1.9.0

type AccountIcon struct {
	ContentType string
	Data        []byte
}

AccountIcon is an account's uploaded icon image.

type AccountImportEntry added in v1.36.0

type AccountImportEntry struct {
	Email             string `json:"email"`
	Name              string `json:"name,omitempty"`
	ReceivingProtocol string `json:"receiving_protocol"`
	ReceivingHost     string `json:"receiving_host"`
	ReceivingPort     int    `json:"receiving_port"`
	SendingProtocol   string `json:"sending_protocol"`
	SendingHost       string `json:"sending_host"`
	SendingPort       int    `json:"sending_port"`
	ReceiveOnly       bool   `json:"receive_only,omitempty"`
	Auth              string `json:"auth"`
	// Username is the sign-in name, the address when the file gives none.
	Username string `json:"username"`
	// AIInstructions and Signature are what the account would carry from the
	// file: text Wit reads on every run, and HTML added to every mail sent.
	AIInstructions bool   `json:"ai_instructions,omitempty"`
	Signature      string `json:"signature,omitempty"` // its name; "" for none
	// Existing marks an address already on this device or earlier in the file: ImportAccounts skips it.
	Existing bool `json:"existing,omitempty"`
	// ExistingProtocol is the local account's receiving protocol when it differs from the file's.
	ExistingProtocol string `json:"existing_protocol,omitempty"`
}

AccountImportEntry is one account in an AccountImportPreview.

type AccountImportPreview added in v1.36.0

type AccountImportPreview struct {
	Accounts []AccountImportEntry `json:"accounts"`
	// Digest is the previewed file's SHA-256 (PreviewAccountImportFile):
	// ImportAccountsFile imports it only while the file still has it.
	Digest string `json:"digest,omitempty"`
}

AccountImportPreview describes the accounts in an export file before ImportAccounts writes them.

type AccountImportResult added in v1.36.0

type AccountImportResult struct {
	Imported []Account           `json:"imported"`
	Skipped  []AccountImportSkip `json:"skipped"`
}

AccountImportResult reports the accounts ImportAccounts created and the addresses it skipped.

type AccountImportSkip added in v1.36.0

type AccountImportSkip struct {
	Email            string `json:"email"`
	ExistingProtocol string `json:"existing_protocol,omitempty"`
}

AccountImportSkip is one address ImportAccounts skipped. ExistingProtocol is the local account's receiving protocol when it differs from the file's; empty when the address already exists with the same protocol.

type AccountInput

type AccountInput struct {
	Email, Name, Alias, Signature, Username, Password string // Password: Receiving.Auth's secret, an API token for AuthAPIToken
	// SendPassword is the sending server's own password; "" signs in to it
	// with Password.
	SendPassword       string
	IsDefault          bool
	Sync               *SyncRange // nil: the newest 2000 per folder
	Receiving, Sending Server
	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
	// ReceiveOnly adds the account although its SMTP check fails (the settings
	// and IMAP steps must pass); it then only receives mail. A passing SMTP
	// check adds it as usual.
	ReceiveOnly bool
	// ConfirmedHosts are hosts outside Email's domain the user agreed to
	// send the password to while Autodiscover looks for an EWS URL
	// (CheckReport.Confirm).
	ConfirmedHosts []string
	// contains filtered or unexported fields
}

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
	LabelKeywords          *bool   // turning it on imports the server's keywords at once
}

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 AddressBook added in v1.36.0

type AddressBook struct {
	ID                                                          int64
	Preset, Name, URL, AuthType, Username, Status, StatusDetail string
	SortOrder                                                   int
	LastSyncedAt                                                time.Time
	Collections                                                 []AddressBookCollection
	Account                                                     int64
}

AddressBook is one sign-in to a CardDAV server and its cached collections. Account is the mail account it is linked to, 0 for a standalone one. SortOrder is its place in the accounts list (a linked one's is its account's Position), which is its priority.

type AddressBookCollection added in v1.36.0

type AddressBookCollection struct {
	ID, AddressBookID int64
	Href, Name        string
	Enabled           bool
	CardCount         int
}

type AddressBookInput added in v1.36.0

type AddressBookInput struct {
	Preset, Name, URL, Username, Password, OAuthFlowID string
	Client                                             OAuthClient
	Account                                            int64
	SyncLater                                          bool
}

AddressBookInput adds an address book. With Account set it is that mail account's (Preset must be LinkedAddressBookPreset's): a password preset signs in with the account's username and keychain password, Google with OAuthFlowID. SyncLater returns once the address book is saved and runs its first sync in the background (AddressBooksChanged when done), for a window that should not wait on a server with many cards.

type AddressBookPreset added in v1.36.0

type AddressBookPreset struct {
	ID, Name, DefaultURL, AuthType, HelpURL string
}

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. Left out of the JSON when
	// none, so it stays nil over the Local API rather than null.
	Form json.RawMessage `json:",omitempty"`
}

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 ArchiveMarkBefore added in v1.30.0

type ArchiveMarkBefore struct {
	ThreadID int64
	Had      bool
	MID      string
	Date     int64
}

ArchiveMarkBefore is a conversation's archive mark before an archive (Had false: none).

type ArchiveUndo added in v1.30.0

type ArchiveUndo struct {
	Moved []ArchivedMessage
	Marks []ArchiveMarkBefore
}

ArchiveUndo is what UndoArchiveThreads puts back.

type ArchivedMessage added in v1.22.0

type ArchivedMessage struct{ ID, From, To int64 }

ArchivedMessage is a message ArchiveSender moved From a folder To another.

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 CachedImageFile added in v1.36.0

type CachedImageFile struct {
	Path          string
	Format        string
	Width, Height int
}

CachedImageFile is a remote mail image cached on disk.

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
	Host    string
	URL     string
	Confirm string
	// contains filtered or unexported fields
}

Folders is how many selectable folders the imap step listed (0 if LIST failed). Host is the host the receiving step signed in to, as host:port: for JMAP the session's, which may be another than the one typed in. URL is the EWS URL Autodiscover found for an EWS account given none. Confirm is the host, outside the address's domain, Autodiscover stopped before sending the password to (the ews step's Kind is KindConfirm): the user confirms it by checking again with it in AccountInput.ConfirmedHosts.

func (CheckReport) OK

func (r CheckReport) OK() bool

OK reports whether every step passed.

func (CheckReport) OnlySendingFailed added in v1.35.0

func (r CheckReport) OnlySendingFailed() bool

OnlySendingFailed reports whether settings and the receiving step passed and the sending step failed: what AccountInput.ReceiveOnly lets through.

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 (jmap for a JMAP account, ews for an EWS one, pop3 for a POP3 one) and the sending step: smtp, or jmap_send for a JMAP account (whose session must allow email submission). An EWS account sends through the server it receives from, so its check has no sending step. 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, Subtitle, Address       string
	Addresses                     []ContactAddress
	SearchTerms                   []string
	FromAddressBook               bool
	Messages                      int
	Last                          time.Time
	Received, Sent, Unread, Inbox int
	Latest, ListMessage           int64
	Blocked                       bool
}

Contact is someone the user exchanged synced mail with or keeps in an enabled CardDAV address book, merged across shared addresses (gomail.AddrKey); the user's own accounts are excluded. Name comes from the highest-priority card when non-empty, else the display name their mail used most, else the one the user wrote to them. Subtitle joins the highest-priority card's ORG and TITLE with " · ". Addresses lists every address of the contact, preferred and recent-mail first, with Address equal to Addresses[0].Address. Received counts their mail outside Sent, Drafts, Trash and Junk, Sent the user's mail in Sent to or copying them (once per message), Messages both. Unread and Inbox count within Received; Latest is their newest received message (0 none), ListMessage the newest with a List-Unsubscribe header (0 none); Blocked is whether all of their addresses are blocked senders.

type ContactAddress added in v1.36.0

type ContactAddress struct {
	Address string
	Pref    bool
	Blocked bool
}

ContactAddress is one normalized email address belonging to a Contact.

type ContactCompletion added in v1.36.0

type ContactCompletion struct {
	Name, Subtitle, Address string
}

ContactCompletion is one single-address recipient completion candidate.

type ContactDetail added in v1.22.0

type ContactDetail struct {
	Archivable, Kept int
}

ContactDetail is what ArchiveSender would do with a contact's inbox mail now: move Archivable messages, leave Kept in the inbox.

type ContactMatch added in v1.36.0

type ContactMatch struct {
	Name, Subtitle, Address string
	Addresses               []string
}

ContactMatch is a lightweight, read-only contact summary without binary avatars.

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
	// FromProgram: a program (the Local API, godwit mcp, a plugin or Wit)
	// created or changed it, so the interface labels it and offers
	// ApproveDraft. Local only; the user's own edits keep it (ADR 0043).
	FromProgram bool
}

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 ExportedAccount added in v1.36.0

type ExportedAccount struct {
	Email          string             `json:"email"`
	Name           string             `json:"name,omitempty"`
	Alias          string             `json:"alias,omitempty"`
	Username       string             `json:"username"`
	Provider       string             `json:"provider,omitempty"`
	OAuthClientID  string             `json:"oauth_client_id,omitempty"`
	IsDefault      bool               `json:"is_default,omitempty"`
	ReceiveOnly    bool               `json:"receive_only,omitempty"`
	Receiving      ExportedServer     `json:"receiving"`
	Sending        ExportedServer     `json:"sending"`
	Sync           ExportedSyncRange  `json:"sync"`
	LabelKeywords  bool               `json:"label_keywords,omitempty"`
	AIInstructions string             `json:"ai_instructions,omitempty"`
	Signature      *ExportedSignature `json:"signature,omitempty"`
}

ExportedAccount is one mail account in an AccountExport. Local archives (KindLocalArchive) have no server and are not exported.

type ExportedServer added in v1.36.0

type ExportedServer struct {
	Protocol string   `json:"protocol"`
	Host     string   `json:"host"`
	Port     int      `json:"port"`
	Security Security `json:"security"`
	Path     string   `json:"path,omitempty"`
	Auth     string   `json:"auth"`
}

ExportedServer is an account's receiving or sending server in an AccountExport.

type ExportedSignature added in v1.36.0

type ExportedSignature struct {
	Name string `json:"name"`
	HTML string `json:"html"`
}

ExportedSignature is an account's default signature in an AccountExport. Inline signature images are carried as data: URLs inside HTML.

type ExportedSyncRange added in v1.36.0

type ExportedSyncRange struct {
	Limit  int `json:"limit,omitempty"`
	Months int `json:"months,omitempty"`
}

ExportedSyncRange is an account's sync range in an AccountExport; both zero means all mail.

type FetchedAttachment added in v1.36.0

type FetchedAttachment struct {
	Path string
	Info AttachmentInfo
	Err  error `json:"-"`
}

FetchedAttachment is one attachment cached on disk by FetchAttachmentsStream.

func (FetchedAttachment) StreamError added in v1.36.0

func (a FetchedAttachment) StreamError() error

StreamError returns the mid-stream failure, if any.

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
	Total         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 ImageDims added in v1.36.0

type ImageDims struct {
	Width, Height int
	OK            bool
}

ImageDims is the cached pixel size of a remote mail image, when on disk.

type ImportFailure added in v1.31.0

type ImportFailure struct {
	Path, Reason string
}

ImportFailure is a file ImportEML did not import, and why.

type ImportSummary added in v1.31.0

type ImportSummary struct {
	Imported, Duplicates int
	Failed               []ImportFailure
	Canceled             bool
}

ImportSummary is what an ImportEML did. Canceled: its ctx ended first, and the mail imported until then stays.

type InlineImage added in v1.36.0

type InlineImage struct {
	CID         string
	Path        string
	ContentType string
	Err         error `json:"-"`
}

InlineImage is a message body's inline image cached on disk.

func (InlineImage) StreamError added in v1.36.0

func (i InlineImage) StreamError() error

StreamError returns the mid-stream failure, if any.

type Keyring added in v1.33.0

type Keyring interface {
	Get(service, user string) (string, error)
	Set(service, user, secret string) error
	Delete(service, user string) error
}

Keyring stores credentials (passwords, refresh tokens, model keys, extension secrets), each under a service name and a user key. The default is the system keychain through go-keyring; a shell on a platform go-keyring cannot reach (iOS, whose keychain is only available in-process) gives its own in Options.Keyring. Get returns ErrSecretNotFound for a missing entry; any other error makes the keychain unavailable (ErrKeychainUnavailable). Credentials never fall back to a file on their own: a file is used only when the shell passes one here because the user asked for it (cmd/godwit's encrypted file keyring for headless servers, under GODWIT_KEYRING_FILE).

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 LogRing added in v1.36.0

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

LogRing is a thread-safe in-memory ring of recent log lines.

func (*LogRing) String added in v1.36.0

func (r *LogRing) String() string

func (*LogRing) Write added in v1.36.0

func (r *LogRing) Write(p []byte) (int, error)

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
	// ManagedBy names the agent gateway whose file added it (ADR 0041); "" for
	// the user's own. Only that file changes or removes it; the user grants it.
	ManagedBy 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
	// contains filtered or unexported fields
}

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
	// Addresses and Accounts only 识别模型 finds: off, they find nothing.
	Addresses, Accounts 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, Source                 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; what was done with it (MaskMask, MaskWarn or MaskBlock); and what found it (MaskSourceRule or MaskSourceRecognizer). 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
	AuthResults string
	Security    gomail.SecurityReport
}

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
	FolderIDs               []int64
	Subject, From, FromName string
	Snippet                 string
	To, Cc                  []string
	Date                    time.Time
	Flags                   []string
	HasAttachments          bool
	AuthResults             string
	Security                gomail.SecurityReport
}

MessageSummary is a message as listed. FolderIDs are every folder it shows in (several on Gmail); FolderID is one of them: the view's folder in a folder's list, else the inbox, another folder, All Mail, in that order.

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
	// ManagedBy names the agent gateway that wrote it into Options.ExternalDir
	// (ADR 0041); "" for the user's own. Only that file changes or removes it.
	ManagedBy string
	// 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 OAuthClient added in v1.22.0

type OAuthClient struct {
	ID, Secret  string
	Account     int64 // reauthorizing: the client that account was added with, if any
	AddressBook int64 // reauthorizing: the client that address book was added with, if any
}

OAuthClient is the user's own OAuth client for a mail provider without one of Godwit's (Gmail: a Workspace admin's Internal client). The zero value is the provider's.

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
	// SecurityMail runs the single background security worker. The apps enable
	// it; deterministic tests may drive scanSecurityBatch explicitly.
	SecurityMail bool
	// SystemLanguage is the operating system language (BCP 47) the GUI passes in; empty means "en".
	SystemLanguage string
	// Keyring 存储凭据;进程内首次设置的非 nil 实现由所有 Service 共用。
	// nil 沿用当前实现,未设置时使用 go-keyring。iOS 等平台由外壳提供实现;
	// cmd/godwit 仅在用户设置 GODWIT_KEYRING_FILE 时传入加密文件实现。
	Keyring Keyring
	// 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
	// SystemProxy is the proxy the computer's settings give for a request to
	// u, nil for none; nil is sysproxy.For. Tests stand in for it.
	SystemProxy func(u *url.URL) *url.URL
	// EWSNet is how Autodiscover reaches the network when an EWS account is
	// added without its URL; zero is the system's. Tests point it at a fake.
	EWSNet ews.Net
	// 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
	// NotifyMCPSend posts a notification, with no mail content, pointing to
	// send request id that waits for the user (每次确认) while no ui client is
	// connected to show it; false: it cannot post one, and 每次确认 refuses the
	// send. nil: none is posted, as false.
	NotifyMCPSend func(id int64) bool
	// OpenURL opens an external URL in the user's default browser.
	OpenURL func(url string) error
	// Recognizer reads for 识别模型 while it is on; nil is AstrLink Guard
	// from its files in the cache (recognitionModelDir). Tests give a fake.
	Recognizer mask.Recognizer
	// GuardCoreML is the CoreML bridge AstrLink Guard reads with on a Mac
	// (libgodwit-guard-coreml.dylib); "" leaves it on the CPU.
	GuardCoreML string
	// RecognitionModelSources are where 识别模型's files are downloaded from, in
	// order, each a URL their paths follow; nil is Hugging Face, then its
	// mirror. Tests give httptest servers'.
	RecognitionModelSources []string
	// RecognitionModelClient downloads them; nil is one through the system proxy
	// (imagefetch.SystemProxy), to public hosts only. Tests give one that
	// reaches loopback.
	RecognitionModelClient *http.Client
	// PrintPDF lays out an HTML document as a PDF, for rules that export
	// one; the GUI sets it. nil fails those actions (RuleFailNoPDF).
	PrintPDF func(ctx context.Context, html string) ([]byte, error)
	// RecentLog reads the process's recent log lines for RecentLog(); nil reads
	// package-level RecentLog.
	RecentLog func() string
	// TrayShown reports whether the backend's tray shows Godwit's icon; nil:
	// it has none (no graphical session).
	TrayShown func() bool
	// StopUIBackend shuts this backend down through its usual close path; set
	// when the interface started it (ADR 0038). nil: the user started it, and
	// the ui role's StopUIBackend is refused.
	StopUIBackend func()
	// ExternalDir is where an agent gateway such as magpie writes the model
	// services, MCP servers, skills and instructions Godwit mirrors (ADR 0041);
	// "" turns that off. The apps set ~/.godwit/external.
	ExternalDir string
	// StopWithUI runs StopUIBackend once the last interface's connection
	// ends, however it ended and whatever 后台收信 says: the backend of a
	// mygo dev session goes with its interface (ADR 0038).
	StopWithUI bool
}

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
	// SendAt is the time SendLater scheduled it for (ADR 0042); zero for a
	// send of now.
	SendAt   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 OwnModel added in v1.37.0

type OwnModel struct {
	Name    string `json:"name,omitempty"`
	Context int    `json:"context,omitempty"`
}

OwnModel is what an agent gateway says of one of its models (ADR 0041): its display name and context window in tokens, each 0 or "" when unsaid.

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 PluginInstallEvent added in v1.36.0

type PluginInstallEvent struct {
	Progress PluginInstallProgress
	Plugin   *PluginInfo `json:",omitempty"`
	Err      error       `json:"-"`
}

PluginInstallEvent is one update of InstallPluginFromRegistryStream: a progress step, the installed PluginInfo on completion (Plugin != nil), or a mid-stream failure (Err != nil).

func (PluginInstallEvent) StreamError added in v1.36.0

func (e PluginInstallEvent) StreamError() error

StreamError returns the mid-stream failure, if any.

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 PluginLogin added in v1.30.0

type PluginLogin struct {
	SignedIn bool         `json:"signedIn"`
	Account  string       `json:"account"`
	Notice   plugins.Text `json:"notice"`
}

PluginLogin is whether the user is signed in to a plugin's service. Notice is what they must read before signing in.

type PluginLoginState added in v1.30.0

type PluginLoginState struct {
	State   string `json:"state"`
	URL     string `json:"url,omitempty"`
	Account string `json:"account,omitempty"`
	Message string `json:"message,omitempty"`
}

PluginLoginState is where a sign-in stands: State is "preparing", "open" (URL is the page to open), "done" (Account signed in) or "failed" (Message says why).

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 PrepareModelEvent added in v1.36.0

type PrepareModelEvent struct {
	Status ModelStatus
	Done   bool  `json:",omitempty"`
	Err    error `json:"-"`
}

PrepareModelEvent is one update of PrepareModelStream: a progress or final ModelStatus (Done == true), or a mid-stream failure (Err != nil).

func (PrepareModelEvent) StreamError added in v1.36.0

func (e PrepareModelEvent) StreamError() error

StreamError returns the mid-stream failure, if any.

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 RecognitionModelBackend added in v1.21.0

type RecognitionModelBackend struct {
	Device    string
	NotCoreML string
}

RecognitionModelBackend is what reads 识别模型: CoreML on Device, or with Device "" the CPU, NotCoreML saying why not CoreML on a Mac.

type RecognitionModelProgress added in v1.36.0

type RecognitionModelProgress struct {
	Got, Total int64
	Err        error `json:"-"`
}

RecognitionModelProgress is one update of DownloadRecognitionModelStream.

func (RecognitionModelProgress) StreamError added in v1.36.0

func (p RecognitionModelProgress) StreamError() error

StreamError returns the mid-stream failure, if any.

type RegistryEntry added in v1.2.0

type RegistryEntry struct {
	Name                                            string
	Title, Summary                                  plugins.Text
	Category, Publisher, DataFlow                   string
	Homepage                                        string
	Permissions                                     plugins.Permissions
	Capabilities                                    []string
	Configurable                                    bool
	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. Category, Publisher and DataFlow are the reviewers' (ADR 0032), "" in a registry from before them; Permissions, Capabilities and Configurable are the release's manifest.

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 Rule added in v1.26.0

type Rule struct {
	ID         int64
	Enabled    bool
	Background bool
	Doc        RuleDoc
	Confirmed  []string
	// contains filtered or unexported fields
}

Rule is a stored rule, in the order rules run. Background keeps Godwit running after the window closes (运行方式 后台运行). Confirmed are the forward recipients the user confirmed in Godwit, lower-cased bare addresses, kept apart from Doc: a forward to any other does not send.

type RuleAction added in v1.26.0

type RuleAction struct {
	Kind      string `json:"kind"`
	Label     string `json:"label,omitempty"`
	To        string `json:"to,omitempty"`
	Dir       string `json:"dir,omitempty"`
	Subfolder bool   `json:"subfolder,omitempty"`
	Naming    string `json:"naming,omitempty"`
}

RuleAction is one step; Label is a label's slug (ActionLabel), To an address (ActionForward). A file action writes to Dir, an absolute path, into a subfolder per message when Subfolder is set; Naming, a 命名模板, names that subfolder and the PDF or EML. File actions with one Dir share Subfolder and Naming.

type RuleActionResult added in v1.26.0

type RuleActionResult struct {
	Kind, State, Failure string
	Paths                []string
	Action               RuleAction
}

RuleActionResult is an action's outcome; Failure (a RuleFail id) is why it failed, Paths the files a file action wrote. Action is the action as the run started (its recipient, label, folder), the rule since edited or not; zero for a run from before runs kept it.

type RuleCondition added in v1.26.0

type RuleCondition struct {
	Field string          `json:"field"`
	Op    string          `json:"op"`
	Value string          `json:"value"`
	Match string          `json:"match,omitempty"`
	Group []RuleCondition `json:"group,omitempty"`
}

RuleCondition compares a field of the message with Value (typed by the user), or is a group: Match of the conditions in Group, and no field. A doc's Conditions are all conditions or at least two groups, one level deep. A build without groups reads one as a condition on no field, which never matches.

type RuleDoc added in v1.26.0

type RuleDoc struct {
	Version    int             `json:"version"`
	Name       string          `json:"name"`
	Trigger    string          `json:"trigger"`
	TriggerArg string          `json:"trigger_arg,omitempty"`
	Account    int64           `json:"account,omitempty"`
	Match      string          `json:"match"`
	Conditions []RuleCondition `json:"conditions"`
	Actions    []RuleAction    `json:"actions"`
}

RuleDoc is a rule as stored: when (Trigger, on mail of Account, an account's id; 0 every account), if (Match of Conditions; none matches every message), then (Actions, in order).

func (RuleDoc) Rows added in v1.29.0

func (d RuleDoc) Rows() []RuleCondition

Rows is the doc's conditions, out of their groups.

type RuleHit added in v1.26.0

type RuleHit struct {
	RunID     int64
	MessageID int64 // 0: the message is gone
	From      string
	Subject   string
	At        time.Time
	State     string // a RuleRun state
	Actions   []RuleActionResult
}

RuleHit is a rule's run on a message, its actions' results in order.

type RulePreview added in v1.26.0

type RulePreview struct {
	Count    int
	Messages []MessageSummary
}

RulePreview is the existing mail a rule matches: how many, and the newest of the last RulePreviewDays days.

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 SavedView added in v1.30.0

type SavedView struct {
	ID       int64
	Name     string
	Icon     string
	Doc      SavedViewDoc
	Revision int64
	Unread   int
}

SavedView is a stored view. Unread counts its conversations with unread mail.

type SavedViewDoc added in v1.30.0

type SavedViewDoc struct {
	Version    int             `json:"version"`
	Account    int64           `json:"account,omitempty"`
	Match      string          `json:"match"`
	Conditions []RuleCondition `json:"conditions"`
	Groups     []ViewGroup     `json:"groups"`
}

SavedViewDoc is what a view shows: conversations of Account (0: every account) meeting Match of Conditions, placed in the first of Groups they meet, the rest in 其他. As in a rule, no conditions is met by all.

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 a connection to a server.

type SecurityScanProgress added in v1.21.0

type SecurityScanProgress struct {
	Busy      bool `json:"busy"`
	Importing bool `json:"importing"`
	Total     int  `json:"total"`
	Pending   int  `json:"pending"`
}

SecurityScanProgress is the active manual run's fixed scope, plus global busy state. Background/newly arrived messages cannot inflate its pending counter.

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 SenderArchive added in v1.22.0

type SenderArchive struct {
	Moved   []ArchivedMessage
	Skipped int
}

SenderArchive is what ArchiveSender moved, each message with the folder it left and the one it went to, and how many it left in the inbox.

type Server added in v1.33.0

type Server struct {
	Protocol string
	Host     string
	Port     int
	Security Security // JMAP: SecurityTLS is https, SecurityNone http (localhost only)
	// Path is JMAP's session resource on Host, as a session URL typed in
	// gives it; "" discovers it at /.well-known/jmap. For EWS it is the EWS
	// URL's path; an EWS slot with neither Host nor Path is found by
	// Autodiscover from the address. Other protocols have none.
	Path string
	// Auth is how the slot signs in: AuthPassword ("" in input), AuthAPIToken
	// (JMAP only) or AuthOAuth, which only an OAuth flow sets.
	Auth string
}

Server is one of an account's two server slots, receiving and sending: a protocol and where its server is. Receiving is auth.IMAP, auth.JMAP (only with Settings.ExperimentalJMAP to add one), auth.EWS (only with Settings.ExperimentalEWS to add one), auth.POP3 (only with Settings.ExperimentalPOP3) or auth.Graph (only with Settings.ExperimentalGraph). JMAP, EWS and Graph accounts send through their receiving protocol; other accounts send through auth.SMTP (or auth.Graph once OAuth SMTP AUTH is refused). An empty Protocol in input is auth.IMAP and auth.SMTP.

type ServerSettings

type ServerSettings struct {
	Username           string
	Receiving, Sending Server
}

ServerSettings replaces an account's username and 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) AddAddressBook added in v1.36.0

func (s *Service) AddAddressBook(ctx context.Context, in AddressBookInput) (AddressBook, error)

AddAddressBook discovers, verifies, stores credentials in the keychain, saves the address book and its collections, and performs an initial sync.

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) AddLocalArchive added in v1.31.0

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

AddLocalArchive adds a local archive account (KindLocalArchive) named name, with a local inbox and trash. It is never the default and has no worker.

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) AllAccountLabels added in v1.21.0

func (s *Service) AllAccountLabels(ctx context.Context) (map[int64][]Label, error)

AllAccountLabels returns labels with their counts and unread counts grouped by account ID.

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) ApproveDraft added in v1.39.0

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

ApproveDraft is the user's 批准并发送 on a draft a program wrote (FromProgram, ADR 0043): Send for exactly the revision the interface showed, else ErrStaleDraft, so a program's change after the user looked voids it; any other draft is ErrNotProgramDraft. Plugins' message.beforeSend checks run as for Send (warnings: SendAcknowledgedRevision, same revision), and the send is audited with its outbox item. Only the interface may call it (uiOnly): the approval stands for the user's click.

func (*Service) ArchiveMessages added in v1.30.0

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

ArchiveMessages moves the messages to folderID, the archive folder of their account, and marks the conversations whose newest message is among them, so that 回复状态 leaves them until newer mail comes. Gmail removes INBOX only; folderID may be 0 when All Mail is hidden.

func (*Service) ArchiveSender added in v1.22.0

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

ArchiveSender moves the inbox mail from addr (covering all addresses of addr's merged contact) to each account's archive, as archivePlan says. An account without an archive folder fails before anything moves. The plan and the moves hold the edit lock together, so a change meanwhile is planned with.

func (*Service) ArchiveThreads added in v1.30.0

func (s *Service) ArchiveThreads(ctx context.Context, threadIDs []int64) (ArchiveUndo, error)

ArchiveThreads archives whole conversations, as a view does: copies in the inbox move to their account's archive, Sent copies never, and each conversation is marked, so one of only sent mail just records it. An account with mail to move and no archive folder is ErrNoRoleFolder, and nothing of it is recorded.

func (*Service) ArchiveUsage added in v1.31.0

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

ArchiveUsage is the bytes a local archive's or an inbox-only (POP3) account's originals, and the files extracted from them, take on disk (ADR 0036, spec #627); 0 for other accounts.

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 the draft account's sender block, 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) 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, client OAuthClient) (flowID, authURL string, err error)

BeginOAuth starts an authorization flow for the provider, with client when it is not zero, and returns its ID and the URL to open in the browser. The flow ends after auth.FlowTimeout.

func (*Service) BeginPluginLogin added in v1.30.0

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

BeginPluginLogin starts signing in to the plugin's service and returns the flow to poll. The plugin may download and reach its hosts from here on, which is why a call over the Local API is audited first (ADR 0003).

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) CachedImage added in v1.36.0

func (s *Service) CachedImage(ctx context.Context, src string) (CachedImageFile, error)

CachedImage returns src's cached image file on disk, downloading it first if needed.

func (*Service) CachedImageDims added in v1.36.0

func (s *Service) CachedImageDims(src string) ImageDims

CachedImageDims returns src's pixel size when src is already cached on disk.

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) CancelPluginLogin added in v1.30.0

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

CancelPluginLogin ends a flow the user gave up on.

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) CancelTrayQuit added in v1.36.0

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

CancelTrayQuit disarms the tray's 退出并停止收信 (StopWhenUIQuits): the interface's user cancelled the quit, at its unsaved-changes prompt or a compose window. Without one pending it does nothing.

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) CheckAddressBook added in v1.36.0

func (s *Service) CheckAddressBook(ctx context.Context, in AddressBookInput) ([]AddressBookCollection, string, error)

CheckAddressBook discovers the CardDAV addressbook-home-set and verifies credentials without saving anything to the database or keychain.

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) CompleteContacts added in v1.36.0

func (s *Service) CompleteContacts(ctx context.Context, query string, limit int) ([]ContactCompletion, error)

CompleteContacts expands matching contacts into single-address candidates for recipient completion, with preferred and recent-mail addresses first. A blank query returns no candidates.

func (*Service) ContactAvatar added in v1.36.0

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

ContactAvatar loads a contact's avatar for the native UI: an enabled address-book card's cached PHOTO across the contact's connected component first (even with zero received messages), else SenderAvatar on the newest received message across that component.

func (*Service) ContactDetail added in v1.22.0

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

ContactDetail is what ArchiveSender would do with addr's inbox mail now.

func (*Service) ContactMail added in v1.22.0

func (s *Service) ContactMail(ctx context.Context, addr, cursor string, limit int) (MessagePage, error)

ContactMail is a page of the mail between the user and addr (covering all addresses of addr's merged contact), newest first: theirs as Contact.Received counts it and the user's to them as Contact.Sent does, so a contact's pages hold Contact.Messages in all. cursor "" starts; NextCursor is "" past the last page. A page may hold fewer than limit with more to come.

func (*Service) Contacts added in v1.22.0

func (s *Service) Contacts(ctx context.Context) ([]Contact, error)

Contacts lists everyone the user exchanged mail with and enabled address-book contacts, contacts with mail first (most mail first) followed by zero-mail contacts.

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) CreateLocalFolder added in v1.31.0

func (s *Service) CreateLocalFolder(ctx context.Context, accountID int64, name string) (Folder, error)

CreateLocalFolder adds a folder named name to the local archive accountID.

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 or Junk; ones elsewhere stay. They leave lists and counts at once, and the push waits UndoPurgeWindow for an UndoPurge. A move out of Trash/Junk before the push cancels it, and the fetch after the push drops the rows. In a local archive they and their originals are deleted at once, with no undo (ADR 0036).

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) DeleteLocalFolder added in v1.31.0

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

DeleteLocalFolder deletes an empty folder of a local archive other than its inbox and trash. A folder still holding mail is refused with ErrFolderNotEmpty: its mail moves out first.

func (*Service) DeleteRule added in v1.26.0

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

DeleteRule deletes a rule with its hits (rule_runs cascade); files it wrote and mail it forwarded stay.

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) DeleteView added in v1.30.0

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

DeleteView removes the view; its mail and rules stay as they are.

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) DevPreviewSignInCode added in v1.36.0

func (s *Service) DevPreviewSignInCode(ctx context.Context, messageID int64, link bool) error

DevPreviewSignInCode asks the backend's tray to show messageID's sign-in code card (link: its sign-in link card), the development build's preview (SignInCodePreview); a release backend ignores it. It reads and sends nothing.

func (*Service) DownloadRecognitionModel added in v1.21.0

func (s *Service) DownloadRecognitionModel(ctx context.Context, progress func(got, total int64)) error

DownloadRecognitionModel downloads 识别模型's files into recognitionModelDir, each checked against its SHA-256 (ErrRecognitionModelMismatch), from the first of its sources that serves it (Options.RecognitionModelSources): a source that fails is not asked for the rest. What an earlier download left is resumed; a file already here is checked, not downloaded again. progress (nil: none) gets the bytes so far of all of them. Turning 识别模型 on is the caller's, once this succeeds.

func (*Service) DownloadRecognitionModelStream added in v1.36.0

func (s *Service) DownloadRecognitionModelStream(ctx context.Context) (<-chan RecognitionModelProgress, error)

DownloadRecognitionModelStream downloads 识别模型's files into recognitionModelDir, streaming byte progress across all files.

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) EditProposedRule added in v1.26.0

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

EditProposedRule returns pending propose_rule approval id's rule for the editor (在编辑器里修改), turned on. The proposal stays pending, its card in the conversation too: the rule is saved only if the user saves it in the editor, confirming any forward recipient (ProposedRuleSaved), or back in the conversation from its card.

func (*Service) EmptyFolder added in v1.21.0

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

EmptyFolder permanently deletes every message in a trash or junk folder, as DeleteForever, and returns the IDs it queued for an UndoPurge; mail already being deleted is left to its own purge. On an error it returns those queued before it. A local archive's Trash is emptied at once, as DeleteForever does there, and the IDs are nil: nothing is left to undo.

func (*Service) ExportAccounts added in v1.36.0

func (s *Service) ExportAccounts(ctx context.Context) ([]byte, error)

ExportAccounts exports every mail account's configuration as versioned, human-readable JSON, without passwords, tokens, OAuth client secrets, mail or local archives.

func (*Service) ExportAccountsFile added in v1.36.0

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

ExportAccountsFile is ExportAccounts written to a new 0600 file in the data directory, its path returned, for the interface: signatures with images, once per account, can outgrow one Local API response. The caller removes it.

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) FetchAttachments added in v1.33.0

func (s *Service) FetchAttachments(ctx context.Context, attachmentIDs []int64, fn func(path string, info AttachmentInfo) error) error

FetchAttachments gets each attachment's cached file over one connection, downloading first if needed, and calls fn for each in order: the FetchAttachmentsStream that the interface reads over the Local API, taken in process.

func (*Service) FetchAttachmentsStream added in v1.36.0

func (s *Service) FetchAttachmentsStream(ctx context.Context, attachmentIDs []int64) (<-chan FetchedAttachment, error)

FetchAttachmentsStream streams each attachment's cached file path and info in order over one connection, downloading first if needed.

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) FirstTimeRecipients added in v1.26.0

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

FirstTimeRecipients are the addresses none of the accounts has written to, for the confirmation a rule's forward recipient needs.

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) ForgetImageFailure added in v1.36.0

func (s *Service) ForgetImageFailure(urls []string)

ForgetImageFailure clears cached download failures for urls so the next CachedImage call retries them at once.

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)

GetMessage returns the message with sanitized HTML. Inline images are downloaded first if needed and embedded.

func (*Service) GetMessageLazyImages added in v1.29.0

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

GetMessageLazyImages is GetMessage without touching the network: an inline image keeps its src as cid:<id>, for InlineImages to fill in, so the reader shows the body before its images have downloaded.

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. A local archive's message is read from its original file, offline.

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) ImportAccounts added in v1.36.0

func (s *Service) ImportAccounts(ctx context.Context, data []byte) (AccountImportResult, error)

ImportAccounts validates data and imports every new account in a single transaction with status reauth_required (credentials_missing), without dialing any server. Addresses already on this device are skipped and reported in Skipped, with the local protocol when it differs.

func (*Service) ImportAccountsFile added in v1.36.0

func (s *Service) ImportAccountsFile(ctx context.Context, path, digest string) (AccountImportResult, error)

ImportAccountsFile is ImportAccounts of the file at path, refusing it as a bad export unless it still has digest, the one its preview showed.

func (*Service) ImportEML added in v1.31.0

func (s *Service) ImportEML(ctx context.Context, accountID, folderID int64, paths []string) (ImportSummary, error)

ImportEML imports .eml files into folderID of the local archive accountID (ADR 0036): each of paths is a file, or a folder searched recursively for .eml files. Each file is copied to the data directory as the message's original, then stored like synced mail, but as old mail: no receive event, rule, plugin hook or AI classification. A file whose content the account already has is a duplicate; a damaged, non-email or too large one (MaxMessageBytes) fails alone. Each message commits on its own, so a failure or a cancelled ctx keeps what was imported. It reports progress as import.progress events and connects to no host.

func (*Service) InboxOnly added in v1.35.0

func (s *Service) InboxOnly() bool

InboxOnly reports whether background rounds cover the inbox only.

func (*Service) InlineImages added in v1.29.0

func (s *Service) InlineImages(ctx context.Context, id int64, each func(cid string, a gomail.Attachment)) error

InlineImages calls each with the inline images message id's body shows, downloading the missing ones in turn over one connection: the InlineImagesStream the interface reads over the Local API, its files read in process. One that cannot be had is left out, so its image stays blocked; the error is for the database or an ended ctx.

func (*Service) InlineImagesStream added in v1.36.0

func (s *Service) InlineImagesStream(ctx context.Context, id int64) (<-chan InlineImage, error)

InlineImagesStream streams the cached disk paths of message id's inline body images over one connection. Images that cannot be downloaded are skipped; database or context failures fail the call or stream.

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) InstallPluginFromRegistryStream added in v1.36.0

func (s *Service) InstallPluginFromRegistryStream(ctx context.Context, name string) (<-chan PluginInstallEvent, error)

InstallPluginFromRegistryStream installs plugin name from the cached registry, streaming download, verify and install progress and ending with the installed PluginInfo.

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) IsComposeOpen added in v1.36.0

func (s *Service) IsComposeOpen(draftID int64) bool

IsComposeOpen reports whether draftID currently has an open compose window in any connected RoleUI client.

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) ListAccountLabels added in v1.21.0

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

ListAccountLabels returns the labels with their counts and unread counts for one account.

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) ListAddressBookPresets added in v1.36.0

func (s *Service) ListAddressBookPresets() []AddressBookPreset

ListAddressBookPresets returns the built-in CardDAV presets and custom option.

func (*Service) ListAddressBooks added in v1.36.0

func (s *Service) ListAddressBooks(ctx context.Context) ([]AddressBook, error)

ListAddressBooks returns all configured CardDAV address books in priority order: the accounts list's (ReorderAccountEntries).

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) MarkAllAsRead added in v1.21.0

func (s *Service) MarkAllAsRead(ctx context.Context, v View) (int, error)

MarkAllAsRead marks every unread message in view v as read. Returns the number of messages marked.

func (*Service) MarkViewRead added in v1.30.0

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

MarkViewRead marks the view's conversations read and returns how many messages that changed.

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)

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. A merged-away ID gets the labels of the message it went into.

func (*Service) ModelName added in v1.11.0

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

ModelName is the display name for a "slug/model" ref's model (its gateway's, else models.dev's); "" 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, as MoveFrom does from a view with no single folder. The local message IDs stay the same.

func (*Service) MoveFrom added in v1.30.0

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

MoveFrom moves the messages to folderID, which must belong to their account, out of from, the folder of the view the move came from (0 for a view with no single folder). A message in several folders (Gmail) leaves only from; one not shown there leaves the inbox, else every folder but All Mail. A move to Trash or Junk takes it out of every folder. 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), as Move; ones already there stay. Archiving a message in the inbox takes it out of the inbox only.

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) PendingSecurity added in v1.21.0

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

PendingSecurity reports the eligible global queue (not a run's progress).

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) PluginLoginStatus added in v1.30.0

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

PluginLoginStatus asks the plugin whether the user is signed in; it starts the plugin's process if it went idle.

func (*Service) PluginLogout added in v1.30.0

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

PluginLogout signs out of the plugin's service.

func (*Service) PluginReadme added in v1.30.0

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

PluginReadme is a directory plugin's README for lang, read from GitHub when the user opens its install dialog (ADR 0032): README.<lang>.md, then README.md, at the branch's head. "" when its homepage is not on GitHub. It is not reviewed and not pinned, so it is only ever shown as text, and the reviewers' words in the directory stay what states the risk.

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) PollPluginLogin added in v1.30.0

func (s *Service) PollPluginLogin(ctx context.Context, name, flow string) (PluginLoginState, error)

PollPluginLogin says where a flow stands. The page of an "open" state is https and audited as the user's own step, by host alone, once per flow.

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) PrepareModelStream added in v1.36.0

func (s *Service) PrepareModelStream(ctx context.Context, ref string) (<-chan PrepareModelEvent, error)

PrepareModelStream downloads and verifies plugin model ref's files, streaming progress updates and ending with a Done event holding the final ModelStatus.

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) PreviewAccountImport added in v1.36.0

func (s *Service) PreviewAccountImport(ctx context.Context, data []byte) (AccountImportPreview, error)

PreviewAccountImport validates an exported accounts file and lists each account with the servers it will connect to and whether it already exists.

func (*Service) PreviewAccountImportFile added in v1.36.0

func (s *Service) PreviewAccountImportFile(ctx context.Context, path string) (AccountImportPreview, error)

PreviewAccountImportFile is PreviewAccountImport of the file at path, which the interface's user picked: read here, the file need not fit one Local API message. Its Digest binds ImportAccountsFile to these bytes.

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) PreviewRule added in v1.26.0

func (s *Service) PreviewRule(ctx context.Context, d RuleDoc, limit int) (RulePreview, error)

PreviewRule is the existing mail, Sent and Drafts aside, that d's trigger and conditions match: how many (all of it, as RunRuleOnExisting runs on), and the newest limit of it of the last RulePreviewDays days. It gives what the rule's evaluator does, read with SQL and the full-text index, so a cancelled ctx stops it.

func (*Service) PreviewView added in v1.30.0

func (s *Service) PreviewView(ctx context.Context, d SavedViewDoc, viewID int64, limit int) (ViewContents, error)

PreviewView lists a document as ViewContents would once saved: with viewID (0: a new one), that view's exceptions apply.

func (*Service) ProposedRuleSaved added in v1.26.0

func (s *Service) ProposedRuleSaved(ctx context.Context, id int64, r Rule) error

ProposedRuleSaved ends pending propose_rule approval id as saved, with r, the rule the user saved for it in the editor (SaveRule): its card shows r saved, and the model is told. A proposal no longer pending, saved from its card meanwhile, say, is left as it is.

func (*Service) Proxy added in v1.25.0

func (s *Service) Proxy(u *url.URL) *url.URL

Proxy is the proxy for a connection to u (http or https; a mail server is asked as https://host:port), nil to connect direct. Mail, remote images, unsubscribes and the update check all take it from here. Not exposed over RPC: a custom proxy's URL carries its password.

func (*Service) Publish added in v1.36.0

func (s *Service) Publish(ev events.Event)

Publish announces ev to every Subscribe stream, the ui client's among them: the owner process's own events (a notification clicked, a quit from its tray). Not exposed over RPC.

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 small model, which reads the message's thread up to it. It returns none, without asking the model, when Settings.QuickReplies is off, the message is from the account itself or under the Newsletters, Notices or Codes label. Results are cached like RunSkill's, by the thread's content; an answer that is not the requested JSON is an error.

func (*Service) RawMessageFile added in v1.36.0

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

RawMessageFile is GetRawMessage written to a new file (0600) in the data directory, its path returned, for the interface: an original of up to MaxMessageBytes would not fit one Local API response as base64. The caller removes the file once read; what is left is removed at start.

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), and the flow's OAuth client, which may be another one than before (a rotated secret). It clears reauth_required and a paused outbox; the worker resumes. A receive-only account sends again if the check passes with the new sign-in (RecheckSending).

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) RecentLog added in v1.36.0

func (s *Service) RecentLog() string

RecentLog returns the recent process log lines with every credential and extension secret this Service knows of replaced by "[redacted]".

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) RecheckSending added in v1.32.0

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

RecheckSending runs the account's connection check with its stored servers and credentials. If it passes, a receive-only account sends again and its worker wakes; otherwise it stays receive-only and the report says which step failed. It logs in to the user's own servers and sends nothing.

func (*Service) RecognitionModelBackend added in v1.21.0

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

RecognitionModelBackend is what reads 识别模型 now, loading it if need be: nil while it is off, or for an Options.Recognizer that doesn't say.

func (*Service) RecognitionModelError added in v1.21.0

func (s *Service) RecognitionModelError() error

RecognitionModelError is why 识别模型 last failed to read, nil once it reads again or is turned off: meanwhile the rules alone mask. Files it lost are ErrRecognitionModelMissing until they are downloaded again, or why that download failed.

func (*Service) RecognitionModelInstalled added in v1.21.0

func (s *Service) RecognitionModelInstalled() bool

RecognitionModelInstalled says 识别模型's files are all on this device: only then can it be turned on.

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, its cache directory and, for a local archive, its originals (ADR 0036). It first cancels the account's explicit calls and worker and waits for them.

func (*Service) RemoveAddressBook added in v1.36.0

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

RemoveAddressBook deletes the address book, cascades all cached collections, cards, emails and avatars, removes keychain credentials, and emits AddressBooksChanged.

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) RenameAddressBook added in v1.36.0

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

RenameAddressBook sets the name the address book shows under; blank names are refused.

func (*Service) RenameLocalFolder added in v1.31.0

func (s *Service) RenameLocalFolder(ctx context.Context, folderID int64, name string) error

RenameLocalFolder renames a local archive's folder other than its inbox and trash.

func (*Service) ReorderAccountEntries added in v1.36.0

func (s *Service) ReorderAccountEntries(ctx context.Context, entries []AccountEntry) error

ReorderAccountEntries puts the accounts list in the order of entries, which names every mail account and standalone address book once. The order is also the address books' priority: a linked one goes with its account.

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. Standalone address books keep their places; ReorderAccountEntries orders both.

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) ReorderRules added in v1.26.0

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

ReorderRules puts the rules in the order of ids, which names every rule once: rules run top to bottom, and a stop action skips those below.

func (*Service) ReorderViews added in v1.30.0

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

ReorderViews sets the sidebar order.

func (*Service) ReplaceUIBackend added in v1.36.0

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

ReplaceUIBackend shuts down a backend the interface started so that an interface of another version can start its own: like StopUIBackend, but even when 后台收信 is BackgroundReceiveAlways, since the new backend goes on receiving. A backend the user started (--headless) still refuses.

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 每次确认 with no way to confirm it: neither a connected ui client nor a notification NotifyMCPSend posts) is ErrMCPSendNoUI. 每次确认 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), notifies it while no ui client is connected, 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) RescanSecurity added in v1.21.0

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

RescanSecurity admits one run only while no earlier work/import is active. The fixed cutoff and highest ID are reused by SecurityProgress.

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; none (empty or null, as nil crosses the Local API) is ResolveApproval's.

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) RetryRuleRun added in v1.26.0

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

RetryRuleRun runs a failed run again from the action that failed, in the same run, with the actions as the run started and the rule's settings (confirmed recipients) as they are now. A disabled rule's run is not retried.

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) RuleHitCounts added in v1.26.0

func (s *Service) RuleHitCounts(ctx context.Context) (map[int64]int, error)

RuleHitCounts is each rule's number of runs in the last RuleHitDays days; a rule with none is absent.

func (*Service) RuleHits added in v1.26.0

func (s *Service) RuleHits(ctx context.Context, ruleID int64) ([]RuleHit, error)

RuleHits returns the rule's runs of the last RuleHitDays days, newest first.

func (*Service) Rules added in v1.26.0

func (s *Service) Rules(ctx context.Context) ([]Rule, error)

Rules returns the rules in the order they run.

func (*Service) RulesInBackground added in v1.26.0

func (s *Service) RulesInBackground(ctx context.Context) (bool, error)

RulesInBackground reports whether an enabled rule runs in the background, so closing the window keeps Godwit running.

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, and ErrNoUI over the Local API while no Godwit window is open. 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) RunRuleOnExisting added in v1.26.0

func (s *Service) RunRuleOnExisting(ctx context.Context, ruleID int64) (int, error)

RunRuleOnExisting runs the stored rule once over the mail PreviewRule counts for it, with only the actions that RunsOnExisting, and returns how many messages it ran on. A message the rule already ran on is skipped.

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) SaveRule added in v1.26.0

func (s *Service) SaveRule(ctx context.Context, r Rule) (int64, error)

SaveRule validates r and stores it: a new one (ID 0) after the others. Of r.Confirmed it keeps the recipients the rule forwards to: the caller passes only those the user confirmed in Godwit, with the address shown. It returns the rule's id.

func (*Service) SaveView added in v1.30.0

func (s *Service) SaveView(ctx context.Context, b SavedView) (int64, error)

SaveView stores a view (ID 0: a new one, last in the sidebar) and returns its id.

func (*Service) SavedViews added in v1.30.0

func (s *Service) SavedViews(ctx context.Context) ([]SavedView, error)

SavedViews returns the views in sidebar order, with their unread counts.

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) SearchContacts added in v1.36.0

func (s *Service) SearchContacts(ctx context.Context, query string, limit int) ([]ContactMatch, error)

SearchContacts searches local mail-derived and cached address-book contacts without touching the network or returning binary avatars.

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) SecurityProgress added in v1.21.0

func (s *Service) SecurityProgress(ctx context.Context) (SecurityScanProgress, error)

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) SendLater added in v1.39.0

func (s *Service) SendLater(ctx context.Context, draftID, revision int64, at time.Time, digest string) error

SendLater is SendRevision, or SendAcknowledgedRevision for a digest, that holds the message in the outbox until at (ADR 0042): until it is sent it is listed with its OutboxItem.SendAt and CancelOutbox takes it back. Only a running backend sends it, so one due while Godwit was closed goes when it starts (OutboxExpiry still counts from at). The send checks run now, on the draft that is sent. Only Godwit's interface can call it (rpcbind uiOnly); the audit row, written with the item, says when it is due.

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) SetAddressBookCollectionEnabled added in v1.36.0

func (s *Service) SetAddressBookCollectionEnabled(ctx context.Context, collectionID int64, enabled bool) error

SetAddressBookCollectionEnabled toggles a sub-collection; disabling immediately deletes its cached cards, emails, and avatars and resets sync_token in the same transaction.

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) SetComposeOpen added in v1.36.0

func (s *Service) SetComposeOpen(ctx context.Context, draftIDs []int64) error

SetComposeOpen records the draft IDs with open compose windows in the calling UI session, replacing that session's previous list. Called without a UI session it changes nothing.

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) SetInboxOnly added in v1.35.0

func (s *Service) SetInboxOnly(on bool)

SetInboxOnly narrows the workers' rounds to the inbox while on: the window is in the background, where only new mail needs to arrive for its notification, and every other folder would cost a round each. Turning it off wakes every worker so the folders catch up at once. SyncNow is never narrowed: a sync the user asks for is whole.

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) SetMessageSecurity added in v1.26.0

func (s *Service) SetMessageSecurity(ctx context.Context, messageIDs []int64, reason string) error

SetMessageSecurity sets the user's classification of the messages: reason is manual_safe, manual_suspicious or manual_warning, stored under the status gomail.ManualSecurityStatus maps it to and kept from later scans; "" drops it and queues the messages for a fresh scan.

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) SetRuleEnabled added in v1.26.0

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

SetRuleEnabled turns a rule on or off; an off rule keeps its setup and runs on nothing.

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) SetTimeZone added in v1.36.0

func (s *Service) SetTimeZone(name string)

SetTimeZone sets the UI's current IANA time zone for Wit runs when a call's context carries none (as over JSON-RPC); empty or unknown falls back to time.Local. shortcut: one zone for the whole Service, as one interface connects today; keep it per ui session (uiSession) if several ever connect.

func (*Service) SetUIForeground added in v1.36.0

func (s *Service) SetUIForeground(ctx context.Context, on bool) error

SetUIForeground records whether the calling UI session's main window is in the foreground, updating background sync narrowing accordingly. Called without a UI session it changes nothing.

func (*Service) SetUIReady added in v1.36.0

func (s *Service) SetUIReady(ctx context.Context, on bool) error

SetUIReady records whether the calling interface takes requests on its events: on once it has started, off as it closes for a quit.

func (*Service) SetViewException added in v1.30.0

func (s *Service) SetViewException(ctx context.Context, id, threadID int64, kind string) error

SetViewException adds a conversation to a view or removes it by hand; kind "" takes that back.

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) StarredCounts added in v1.21.0

func (s *Service) StarredCounts(ctx context.Context) (map[int64]int, int, error)

StarredCounts returns the unread count of starred messages by account ID, and total unread across all accounts.

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) StopSecurityRescan added in v1.21.0

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

StopSecurityRescan preserves existing verdicts and prevents in-flight writes.

func (*Service) StopUIBackend added in v1.36.0

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

StopUIBackend shuts down a backend the interface started (Options.StopUIBackend), as quitting Godwit does; it returns before the shutdown runs. A backend the user started (--headless), or one whose 后台收信 is BackgroundReceiveAlways, refuses and keeps running, unless the tray's 退出并停止收信 asked for it (StopWhenUIQuits). So does one another interface is still connected to; one that is quitting (SetUIReady off, or it asked here) does not count, though its connection may not have ended yet.

func (*Service) StopWhenUIQuits added in v1.36.0

func (s *Service) StopWhenUIQuits(stop func())

StopWhenUIQuits arms the tray's 退出并停止收信 while an interface quits first: stop runs once the last interface has gone or asks to stop the backend (StopUIBackend), whatever 后台收信 says or who started the backend. An interface whose user cancels the quit disarms it (CancelTrayQuit).

func (*Service) StoreLatestVersion added in v1.36.0

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

StoreLatestVersion is the newest version of Godwit published on the Microsoft Store, as 1.21.0, asked of the Store's catalog (displaycatalog.mp.microsoft.com) through Proxy, for the About page of the Store's package. shortcut: displaycatalog is undocumented; if it changes this errors and About only offers the Store's page.

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) SyncAddressBook added in v1.36.0

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

SyncAddressBook immediately syncs one address book (id > 0) or all address books that have at least one enabled collection (id == 0).

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) SystemTranslatorLanguages added in v1.36.0

func (s *Service) SystemTranslatorLanguages() []string

SystemTranslatorLanguages returns the BCP 47 language identifiers downloaded for system translation, an empty non-nil slice when none are downloaded, or nil when the operating system offers no translator.

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) TrayShown added in v1.36.0

func (s *Service) TrayShown(ctx context.Context) (bool, error)

TrayShown reports whether this backend's tray shows Godwit's icon, for the interface: closing its window hides it only where the tray can bring it back.

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) UIConnected added in v1.36.0

func (s *Service) UIConnected() bool

UIConnected reports whether any RoleUI client connection is currently open.

func (*Service) UIForeground added in v1.36.0

func (s *Service) UIForeground() bool

UIForeground reports whether any connected RoleUI client has its main window in the foreground.

func (*Service) UIReady added in v1.36.0

func (s *Service) UIReady() bool

UIReady reports whether a connected interface takes requests on its events (SetUIReady): one still starting or already quitting would drop them.

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) UndoArchive added in v1.22.0

func (s *Service) UndoArchive(ctx context.Context, a SenderArchive) error

UndoArchive moves a's messages back to the folders they left, those still where it put them; ones moved since or gone stay. The check and the move hold the edit lock together, so a move elsewhere meanwhile wins.

func (*Service) UndoArchiveThreads added in v1.30.0

func (s *Service) UndoArchiveThreads(ctx context.Context, u ArchiveUndo) error

UndoArchiveThreads puts back what an archive moved and marked.

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) UndoPurge added in v1.26.0

func (s *Service) UndoPurge(ctx context.Context, ids []int64) (gone int, err error)

UndoPurge takes back DeleteForever and EmptyFolder for the messages: their permanent deletes still waiting are cancelled and they show again. gone counts those already deleted for good; when none was restored the error is ErrPurgeTooLate. A purge whose UID EXPUNGE is under way still completes, as with a rescue.

func (*Service) UndoRuleRun added in v1.26.0

func (s *Service) UndoRuleRun(ctx context.Context, runID int64) (kept int, err error)

UndoRuleRun puts back what the run's local actions changed, last first. One whose target changed since (moved on, the flag or label changed by hand) is kept as it is; kept counts them. The checks and the writes hold the edit lock together, as UndoArchive's do. It waits for a run still going (one at a time, ruleRunMu): undone in the middle, the actions after would still be applied.

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 or a local archive. 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; a receive-only account's failing SMTP step alone still saves them and keeps it receive-only, a passing one makes it send again). 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) UpdateAddressBookAuth added in v1.36.0

func (s *Service) UpdateAddressBookAuth(ctx context.Context, id int64, password, oauthFlowID string, client OAuthClient) (AddressBook, error)

UpdateAddressBookAuth updates the password or OAuth grant for an existing address book, clears error/reauth status, and syncs immediately.

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 (an API token for a receiving slot that signs in with one) against the account's servers and, if both accept it, saves it as the receiving slot's and clears reauth_required and a paused outbox; the worker resumes and the outbox sends in its next round. A sending slot with a password of its own keeps it (UpdateSendPassword). A failed check is a *CheckError and leaves the keychain unchanged; for a receive-only account only the receiving step must pass, and a passing sending step makes it send again. A JMAP API token whose session may not send is saved too, and the account becomes receive-only.

func (*Service) UpdateSendPassword added in v1.33.0

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

UpdateSendPassword is UpdatePassword for the sending slot's own password: the one SMTP signs in with when it differs from the receiving slot's. The receiving slot keeps its secret.

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.

func (*Service) ViewContents added in v1.30.0

func (s *Service) ViewContents(ctx context.Context, id int64, limit int) (ViewContents, error)

ViewContents lists a view: its non-empty groups, in order, then 其他, each with its total and a first page of limit conversations.

func (*Service) ViewExceptions added in v1.30.0

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

ViewExceptions lists a view's exceptions, to see and undo them.

func (*Service) ViewGroupPage added in v1.30.0

func (s *Service) ViewGroupPage(ctx context.Context, id int64, groupID, cursor string, limit int) (ViewGroupPage, error)

ViewGroupPage is the next page of one group, or of 其他 (ViewGroupOther). A cursor from before an edit to the view gives the first page.

func (*Service) ViewTemplates added in v1.30.0

func (s *Service) ViewTemplates(ctx context.Context) ([]ViewTemplate, error)

ViewTemplates are the views to start from, in the UI language.

func (*Service) ViewWhy added in v1.30.0

func (s *Service) ViewWhy(ctx context.Context, id, threadID int64) (ViewReason, error)

ViewWhy says why a conversation is in a view, for the reader.

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 // what the service lists for judge; nil when it lists none
	JudgeListed       bool     // JudgeModels came from the service: false before a key, for a format without a list, or when /models has none
	JudgeNoListStatus int      // the HTTP status that said there is no list, when known
}

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, ShowTrayIcon, UnreadInMenuBar bool
	UnreadOnAppIcon                              bool
	// BackgroundReceive is 后台收信, how long the backend keeps receiving
	// once the interface goes: BackgroundReceiveStopOnClose,
	// BackgroundReceiveUntilQuit (the default) or BackgroundReceiveAlways.
	// Enabled background rules raise it to at least BackgroundReceiveUntilQuit.
	BackgroundReceive string
	// BackgroundSync is what syncs while the window is behind another app:
	// BackgroundSyncInbox (the default; "" too), whose other folders catch up
	// when the window comes back, or BackgroundSyncAll.
	BackgroundSync                    string
	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
	// DefaultModelBy names the agent gateway whose file chooses DefaultModel
	// (ADR 0041); "" when it is the user's own. Read, never saved: the user's
	// own default stays stored beneath it and is the default again once the
	// gateway's file stops choosing.
	DefaultModelBy 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
	// ExperimentalJMAP (实验性 JMAP) offers JMAP when adding an account; off
	// by default. Off, JMAP accounts already added keep working.
	ExperimentalJMAP bool
	// ExperimentalEWS (实验性 EWS) offers Exchange (EWS) when adding an
	// account; off by default. Off, EWS accounts already added keep working.
	ExperimentalEWS bool
	// ExperimentalPOP3 (实验性 POP3) offers POP3 when adding an account; off
	// by default. Off, POP3 accounts already added keep working.
	ExperimentalPOP3 bool
	// ExperimentalGraph (实验性 Microsoft Graph) offers Microsoft Graph when
	// adding an Outlook account; off by default. Off, Graph accounts already
	// added keep working.
	ExperimentalGraph bool
	// ExperimentalGmailAPI (实验性 Gmail API) offers Gmail API when adding a
	// Gmail account with the user's own OAuth client; off by default. Off,
	// Gmail API accounts already added keep working.
	ExperimentalGmailAPI bool
	// 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
	// SecurityWarnings shows potential spoofing and authentication failure warnings
	// in the reader; on by default.
	SecurityWarnings bool
	// VerifiedBadge shows a verified badge for authenticated senders (DKIM/DMARC);
	// on by default.
	VerifiedBadge bool
	// SecurityAI analyzes unverified email contents with the configured judge
	// model, which may be remote, to detect fraud and phishing; off by default.
	SecurityAI bool
	// RuleAI lets rules take AI actions (让 Wit 起草回复, 让 Wit 提取要点),
	// which send the mail to the default model, masked, unattended
	// (docs/adr/0030-mail-rules.md); off by default (ADR 0010).
	RuleAI bool
	// RecognitionModel is 识别模型 (docs/adr/0028-recognition-model-for-masking.md): a
	// model on this device finds names, addresses, accounts, phone numbers,
	// email addresses, secrets and card numbers the rules can't. Off by default; it turns on only once its
	// files are here (ErrRecognitionModelMissing), and turns names on with it.
	RecognitionModel bool
	// LabelDisplay is how label chips show: LabelDisplayBoth (the default;
	// "" too), LabelDisplayIcon or LabelDisplayText.
	LabelDisplay string
	// CollapseQuotes folds the quoted text of a mail (what it replies to or forwards)
	// behind a button in the reader, leaving what its sender wrote.
	CollapseQuotes bool
	// ImageRetentionDays deletes a cached remote image that has gone unread this
	// many days: 0 keeps it until the cache is full, then evicts the least
	// recently used (MaxBytes). Attachments are not in that cache.
	ImageRetentionDays int
	// SidebarOrder is the mail sidebar's sections, top to bottom, as a comma-separated
	// permutation of SidebarSections ("" is the default, views, labels, accounts).
	SidebarOrder string
	// SidebarAccountsOpen is which accounts' folders the mail sidebar shows,
	// by account ID, as the user left them; an account not in it takes the
	// default (only the first is open).
	SidebarAccountsOpen map[int64]bool
	// ListRowOrder is what leads a mail list row: ListRowSender (the default; "" too)
	// puts who it is with first, ListRowSubject the subject.
	ListRowOrder string
	// ReaderWidth is how wide the reading column may grow: ReaderWidthNormal (the
	// default; "" too), ReaderWidthWide or ReaderWidthFull.
	ReaderWidth 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
	// ProxyMode is what mail, remote images, unsubscribes and the update
	// check connect through (网络代理, Service.Proxy): ProxySystem (the
	// default; "" too), ProxyCustom or ProxyOff. Only the user sets it: a
	// proxy reroutes mail.
	ProxyMode string
	// ProxyURL is 自定义's proxy, http://host:port or socks5://host:port
	// (ParseProxyURL), with no credentials. Checked only in ProxyCustom: the
	// other modes keep it as it is, so switching back loses nothing.
	ProxyURL string
	// ProxyBypass is 自定义's 不使用代理的主机: names, *-patterns, .suffixes,
	// addresses and CIDR ranges (sysproxy.Bypassed), at most MaxProxyBypass.
	ProxyBypass []string
	// ProxyUser is 自定义's username, "" for none.
	ProxyUser string
	// ProxyPassword is write-only: a SetSettings with one puts it in the
	// keychain (proxyKeyringUser); it is never stored here nor handed back.
	// ProxyPasswordSet says the keychain has one; a save turning it off
	// deletes it, and an empty ProxyPassword keeps it as it is. So a client
	// must send back the ProxyPasswordSet it loaded: a zero one clears the
	// password.
	ProxyPassword    string `json:",omitempty"`
	ProxyPasswordSet bool
	// 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);
	// 5 once the LightBackground switch became BackgroundSync; 6 once the
	// KeepInBackground switch became BackgroundReceive; 7 once the default
	// Density "compact" was renamed "standard".
	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
	DisplayName, Icon 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
	ManagedBy         string // the agent gateway whose library it comes from (ADR 0041); "" otherwise
}

func (SkillInfo) Label added in v1.34.0

func (s SkillInfo) Label() 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
	ReplyTarget int64
	// Drafts are the drafts a program wrote (FromProgram) that answer or
	// forward a message of the thread and are not in the outbox, oldest first:
	// the reply bar names the newest, to open in the compose window (ADR 0043).
	Drafts []Draft
}

Thread is a conversation with its messages, oldest first. A message the server keeps in several folders (Gmail's INBOX, labels and All Mail) is one message, in all of its FolderIDs. One in the account's Sent folder is your own mail and reads as read (\Seen), as ListThreads counts it, whatever the server's flags. ReplyTarget is the message a reply to the whole thread answers: the newest that is not the user's own forward, whose recipient the reply is not for; 0 when all are, and the newest then is the one.

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
	From             string
	Participants     []string
	Count, Unread    int
	Flagged          int // messages starred
	LastDate         time.Time
	HasAttachments   bool
	Security         gomail.SecurityReport
}

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
	AccountID 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 ViewContents added in v1.30.0

type ViewContents struct {
	Groups []ViewGroupPage
}

ViewContents is a view's non-empty groups, in order, then 其他.

type ViewException added in v1.30.0

type ViewException struct {
	ThreadID      int64
	Kind          string
	Subject, From string
}

ViewException is a conversation added to or removed from a view by hand.

type ViewGroup added in v1.30.0

type ViewGroup struct {
	ID         string          `json:"id"`
	Name       string          `json:"name"`
	Match      string          `json:"match"`
	Conditions []RuleCondition `json:"conditions"`
}

ViewGroup is a named group of conditions; ID stays when it is renamed or moved.

type ViewGroupPage added in v1.30.0

type ViewGroupPage struct {
	ID         string
	Name       string
	Total      int
	Items      []ViewRow
	NextCursor string
}

ViewGroupPage is one page of a group or of 其他; Total counts all of it.

type ViewReason added in v1.30.0

type ViewReason struct {
	Member    bool
	GroupID   string
	GroupName string
	Condition RuleCondition
	Manual    bool
	Status    string
	NewReply  bool
	Days      int
}

ViewReason says why a conversation is in a view: the group it is in ("" for none, or 其他), the condition it met, and whether it was added by hand. Condition is the zero value for a hand-added one.

type ViewRow added in v1.30.0

type ViewRow struct {
	ThreadSummary
	Status      string
	NewReply    bool
	WaitingDays int
	Manual      bool
}

ViewRow is a conversation in a view: Status is ReplyStatusUnreplied, ReplyStatusWaiting or none, WaitingDays since the user's last mail, NewReply that it is newer than its last archive, and Manual that it was added by hand.

type ViewTemplate added in v1.30.0

type ViewTemplate struct {
	ID, Name, Icon string
	Doc            SavedViewDoc
}

ViewTemplate is a view to start from.

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

func (WitEvent) Terminal added in v1.36.0

func (ev WitEvent) Terminal() bool

Terminal reports whether ev ends its run's events (done, error, interrupted): a reader that falls behind never loses one.

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.
mask/guard
Package guard runs AstrLink Guard (QuantumNous/astrlink-guard, Apache-2.0), a token classifier for secrets and personal data in Chinese and English text: its int8 ONNX model (37 MB) read by onnx.go and run by bert.go on the CPU in pure Go, or on a Mac by CoreML through a Swift bridge loaded with purego (coreml.go), its tokenizer by tokenizer.go.
Package guard runs AstrLink Guard (QuantumNous/astrlink-guard, Apache-2.0), a token classifier for secrets and personal data in Chinese and English text: its int8 ONNX model (37 MB) read by onnx.go and run by bert.go on the CPU in pure Go, or on a Mac by CoreML through a Swift bridge loaded with purego (coreml.go), its tokenizer by tokenizer.go.
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 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 stores what an account's protocol backend reports (ADR 0037): folders, server locations, claims, orphans, merges and threads.
Package mailsync stores what an account's protocol backend reports (ADR 0037): folders, server locations, claims, orphans, merges and threads.
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 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