models

package
v0.252.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 29 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package models holds the structs shared between the database, the API and the mail path. They carry no behavior beyond enum helpers.

Index

Constants

View Source
const (
	AgentNotifyOff       = "off"
	AgentNotifyDashboard = "dashboard"
	AgentNotifyMail      = "mail"
)

The three ways a person may be told.

View Source
const (
	AgentDefaultHoldMinutes     = 10
	AgentDefaultDailyReplyLimit = 20
	AgentDefaultMinimumMessages = 3
)

The defaults the zero values stand for.

View Source
const (
	DreamFromDefault  = "01:00"
	DreamUntilDefault = "06:00"
)

The night window a nightly run keeps to, when the person has not said. Three to six in their own zone: late enough that somebody working is finished, early enough to be done before they look.

View Source
const (
	AgentUsagePromptTokens     = 0
	AgentUsageCompletionTokens = 1
	AgentUsageCacheReadTokens  = 2
	AgentUsageCacheWriteTokens = 3
	AgentUsageCalls            = 4
	// AgentUsageAudioInputTokens was added after the others; a row written
	// before it has five values, and a missing sixth reads as zero.
	AgentUsageAudioInputTokens = 5
	AgentUsageValueCount       = 6
)

AgentUsageValues is what each ordinal of an agent_usage row's values holds.

View Source
const (
	AgentReachSkill  = "skill"
	AgentReachServer = "server"
)

The two kinds of thing whose requests can go through a computer.

View Source
const (
	FeedDestinationFeed = "feed"
	FeedDestinationMain = "main"
)

The destinations of what the agent says unasked.

View Source
const (
	// FeedFactRowsMost is how many rows the short table of a card may have.
	FeedFactRowsMost = 8

	// FeedChoicesMost is how many buttons a card may have.
	FeedChoicesMost = 4

	// FeedExpiryDays is how long a card that needs no answer is kept in the
	// list, and how long a settled one is.
	FeedExpiryDays = 30

	// FeedAnsweredLifetime is how long a card answered with a choice stays
	// in the feed before it moves to the dismissed cards: long enough to see
	// what came of the answer, short enough that the answered do not crowd
	// out what still needs the person.
	FeedAnsweredLifetime = 24 * time.Hour

	// FeedSourceURLDays is how far back a post is refused for linking a page
	// an open card already links.
	FeedSourceURLDays = 30
)

The limits on a card.

View Source
const (
	// FeedMediaMost is how many pictures and videos a card may show as its
	// own, and FeedRowMediaMost how many thumbnails the rows of a list card
	// may have.
	FeedMediaMost    = 6
	FeedRowMediaMost = 10
)
View Source
const (
	// FeedChartsMost is how many charts a card carries.
	FeedChartsMost = 2

	FeedChartLabelsLeast   = 2
	FeedChartLabelsMost    = 60
	FeedChartSeriesMost    = 3
	FeedChartMarkersMost   = 3
	FeedChartBarsMost      = 8
	FeedProvenanceMost     = 120
	FeedStillReasonMost    = 120
	FeedResolutionNoteMost = 160
)

The limits on a chart.

View Source
const (
	AlertSignalNone = "none"
	AlertSignalSoon = "soon"
	AlertSignalNow  = "now"
)

The signals the sorting gives a message about telling the person unasked: nothing to say, worth saying today, or worth saying now.

View Source
const (
	WeekStartsSunday = "sunday"
	WeekStartsMonday = "monday"
)

Week starts, which are the two conventions worth keeping: much of the world writes a week from Sunday and much of the rest from Monday.

View Source
const (
	CalendarMethodRequest = "REQUEST"
	CalendarMethodReply   = "REPLY"
	CalendarMethodCancel  = "CANCEL"
)

CalendarInvitationMethod is what a calendar part asks for.

View Source
const (
	// ChatTitleMostCharacters is the most characters a group's title may have.
	ChatTitleMostCharacters = 100

	// ChatMessageMostCharacters is the most characters a message may have.
	ChatMessageMostCharacters = 16000

	// ChatMessagesPerMinute is how many messages one person may send a
	// minute on one instance, which stops a runaway script and nobody typing.
	ChatMessagesPerMinute = 60

	// ChatMembersMost is how many people a group chat holds at once.
	ChatMembersMost = 50

	// GroupChatsMadePerDayMost is how many group chats one person starts in
	// a day.
	GroupChatsMadePerDayMost = 20
)

The limits on what a person writes in a chat.

View Source
const (
	ChatCallTranscriptWaiting = "waiting"
	ChatCallTranscriptDone    = "done"
	ChatCallTranscriptFailed  = "failed"
)

ChatCallTranscriptState says how a call's transcript stands: empty when it was not asked for.

View Source
const (
	// CirclesMadeMost is how many circles one person made and still has.
	CirclesMadeMost = 20

	// CircleInvitationsPerHourMost is how many calls that invite somebody one
	// person makes in an hour, whether the invitation is new, renewed, or
	// none at all because nobody has that name.
	CircleInvitationsPerHourMost = 30
)

The most one person does with circles. Making circles and inviting people to them is what a stranger on a server with open accounts would do first, and each invitation puts a card in someone's conversation with their agent, so neither is without a bound.

View Source
const (
	FinanceStatementTokenSecretKey      = "statementImportToken"
	FinanceStatementAccountKeySecretKey = "statementAccountKey"
)

The source secrets of the finance source that holds imported statements (provider kind "statement"): the token that makes its import address, which is what lets mail in, and the key its accounts' identifiers are hashed with, so the institution's account identifier is never stored.

View Source
const (
	FinanceCursorProviderCursor                 = "providerCursor"
	FinanceCursorIsSignInRequired               = "isSignInRequired"
	FinanceCursorIsCredentialRefused            = "isCredentialRefused"
	FinanceCursorIsTransferHistoryDetected      = "isTransferHistoryDetected"
	FinanceCursorProviderCategoryMappingVersion = "providerCategoryMappingVersion"
)

The keys of a finance source's cursor, which only its sync reads and writes: the provider's own cursor; whether the institution is waiting for the person to sign in again, while which the sync does not call the provider; whether the provider refused the credential itself, after which the sync never calls the provider again, since only deleting the finance source and linking the institution again mends it; whether transfers have been looked for across the source's whole history once, after which each sync looks at the last week only; and the version of the provider category mapping the agent's transactions were last judged by (finance.ProviderCategoryMappingVersion).

View Source
const (
	PathSelf     = "self"
	PathPeople   = "people"
	PathProjects = "projects"
	PathPlaces   = "places"
	PathThings   = "things"
	PathTopics   = "topics"
	PathNotes    = "notes"
	PathTime     = "time"

	// PathWork is the child of "self" where the ingest files the person's
	// own span on each checkout. A hundred checkouts are a hundred lines,
	// which would bury the page that says who they are.
	PathWork = "self/work"

	// PathThemes is where the night keeps the themes it finds by
	// clustering the links: groups of pages more linked to one another
	// than to the rest. Not one of the roots every graph starts with; the
	// night makes it the first time it has a theme to put there.
	PathThemes = "themes"

	// PathReflections is the person's own page of the night's
	// observations across their themes, written about once a week.
	PathReflections = "self/reflections"
)

The roots every agent has, made the first time its graph is touched. "self" is the person; the rest are folders things are filed under.

View Source
const (
	// PathSegments is how deep a path may go, and PathLength how long it
	// may be. Eight segments is more than any hierarchy a person keeps in
	// their head, and a path longer than this is a description rather than
	// an address.
	PathSegments = 8
	PathLength   = 500

	// NameLength and AliasCount bound what a page is called.
	NameLength = 200
	AliasCount = 16

	// EvidenceCount is how many places one fact may cite.
	//
	// A page's opening, a fact's text and a quote have no bound. Each
	// had one, and what was written past it was cut off where it was
	// stored, with nothing to say a sentence had ended early: the words
	// were gone for every reader. A prompt that cannot hold all of a
	// long text cuts it where it shows it, and says there is more and
	// how to read it.
	EvidenceCount = 12
)

The bounds a page and a fact are held to.

View Source
const (
	HappenedDay   = "day"
	HappenedMonth = "month"
	HappenedYear  = "year"
)

The precisions a fact's date can be given with.

View Source
const (
	GroupNameAdministrators = "Administrators"
	GroupNameMembers        = "Members"
)

The seeded groups, by name.

View Source
const (
	MailProposalEvent   = "event"
	MailProposalContact = "contact"

	MailProposalOffered   = ""
	MailProposalAccepted  = "accepted"
	MailProposalDismissed = "dismissed"
)

The kinds of proposal, and the states one can be in.

View Source
const (
	// AttachmentMessageShared is a file the agent handed over in a
	// conversation, or sent to the main chat.
	AttachmentMessageShared = "shared"
	// AttachmentMessageUpload is a file a program is to upload to the main
	// chat, kept with no bytes until it does.
	AttachmentMessageUpload = "upload"
	// AttachmentMessageFeed is a file a card of the feed shows, kept while
	// the card holds it.
	AttachmentMessageFeed = "feed"
	// AttachmentMessageUploadFeed is a file a program is to upload to the
	// feed, kept with no bytes until it does.
	AttachmentMessageUploadFeed = "upload_feed"
)

The message ids a file of the agent's carries besides a real message's.

View Source
const (
	InteractionApproved = "approved"
	InteractionDeclined = "declined"
	InteractionStopped  = "stopped"
)

The answers an approval can have, and the one a card gets when the turn waiting on it was stopped.

View Source
const (
	JournalMoodAwful = 1
	JournalMoodLow   = 2
	JournalMoodOkay  = 3
	JournalMoodGood  = 4
	JournalMoodGreat = 5
)

JournalMoodLevels are the moods a person can choose, 1 to 5.

View Source
const (
	// FormatFiles is the default: a tree of files, git-aware.
	FormatFiles = "files"

	// FormatJournal is a folder of dated notes: a file per day or per
	// month, or one file with date headings.
	FormatJournal = "journal"

	// FormatRecords is a folder of JSON lines, one record a line, in the
	// one shape any script can write: what it is, when it happened, who
	// wrote it, what it says. It is how everything that is not one of the
	// shapes above gets in without a reader being written for it.
	FormatRecords = "records"

	// FormatTyped is read by running the source's type: the commands and
	// requests it declares, run on the computer. Specification.Type names
	// the type and Specification.Settings holds what the person filled in.
	FormatTyped = "typed"
)

The formats an archive or a computer source can be read in.

View Source
const (
	ChunkCharacters = 2000
	ChunkOverlap    = 200
)

ChunkCharacters is how long a chunk may be, and ChunkOverlap how much of the one before it each carries so that a sentence cut in half is still found whole somewhere.

View Source
const (
	PlaceRadiusMinimumMeters = 25
	PlaceRadiusMaximumMeters = 2000
	// PlaceRadiusDefaultMeters is the radius of a place made from a report.
	PlaceRadiusDefaultMeters = 75
)

The bounds of a place's radius, in meters. Below the lower bound the phone's own error puts a person outside the place they are standing in, and above the upper one a place swallows its neighbors.

View Source
const (
	OSMTypeNode     = "node"
	OSMTypeWay      = "way"
	OSMTypeRelation = "relation"
)

OSM types of a place, as OpenStreetMap names its kinds of object.

View Source
const (
	// UnsubscribeOneClick is the request RFC 8058 describes: one POST, which
	// the sender undertook to honour without asking anything further.
	UnsubscribeOneClick = "oneClick"

	// UnsubscribeMail is a message sent to the address the sender named.
	UnsubscribeMail = "mail"

	// UnsubscribeLink is a page handed to the reader, because a page that
	// wants a human cannot be pressed by a server.
	UnsubscribeLink = "link"
)

How a subscription was left, or asked to be.

View Source
const (
	// MeasurementSystemAutomatic reads the system from the person's language
	// and region.
	MeasurementSystemAutomatic = ""

	// MeasurementSystemMetric is degrees Celsius, kilometers and kilograms.
	MeasurementSystemMetric = "metric"

	// MeasurementSystemUS is degrees Fahrenheit, miles and pounds.
	MeasurementSystemUS = "us"
)

The measurement systems a person can read numbers in. The server keeps every measurement in metric units whatever the choice; the choice is only how a temperature, a distance or a weight is written for that person.

View Source
const (
	WrittenByPerson = "person"
	WrittenByAgent  = "agent"
	// WrittenByBuiltIn is a goal TeaNode started because the person pressed
	// a switch. Its description is handed to the turn as the person's words,
	// but the turn reads untrusted content (the brief reads the inbox), so it
	// does not count as the person asking for Passwords.
	WrittenByBuiltIn = "built_in"
)

Who wrote a goal's description.

View Source
const (
	PasswordsLockAfterMinutesDefault = 15
	PasswordsLockAfterMinutesLeast   = 1
	PasswordsLockAfterMinutesMost    = 10080
)

PasswordsLockAfterMinutesDefault is the time a device stays unlocked when the person has not chosen one. PasswordsLockAfterMinutesLeast and ...Most bound what they may choose: a minute to a week.

View Source
const (
	PasswordItemVersionSpacing         = time.Hour
	PasswordItemVersionDays            = 30
	PasswordItemVersionsMost           = 60
	PasswordItemVersionsByPersonMost   = 20
	PasswordsUnlockRefusedAuditSpacing = 5 * time.Minute
)

Earlier versions of an item are kept so that a save that overwrote an item with a mistake, or with garbage from a program that holds a token, can be undone by the person (ListPasswordItemVersions, RestorePasswordItemVersion). A save keeps the version it replaces only when the item has no kept version younger than PasswordItemVersionSpacing, so that a burst of saves keeps the content from before the burst and not the burst itself. Versions are kept PasswordItemVersionDays days, and at most PasswordItemVersionsMost for one item; past that the one just before the newest is dropped, never the oldest.

A save that did not come from the person's own tap (a command line token, the extension) always keeps the version it replaces when that content was saved by a tap, whatever the spacing, so that the person's newest edit cannot be lost to a program that saves within the hour. Those versions have a count of their own, PasswordItemVersionsByPersonMost for one item, the oldest of them dropped first, so that a flood of saves cannot push them out and they cannot push out the others.

View Source
const (
	PhonePlatformIOS     = "ios"
	PhonePlatformAndroid = "android"
)

Platforms a phone may run the TeaNode app on.

View Source
const (
	// NotificationMessage is the agent saying something on its own: an
	// alert, a goal that needs the person, the agent starting a conversation.
	NotificationMessage = "message"
	// NotificationApproval is a card waiting for the person's approval.
	NotificationApproval = "approval"
	// NotificationQuestion is the agent asking the person something, and one
	// of their coding sessions asking (which opens the session on the
	// iPhone's Coding screen).
	NotificationQuestion = "question"
	// NotificationAnswer is an answer finished after the person left: to
	// something asked from the app, or asked in the main conversation on
	// the dashboard.
	NotificationAnswer = "answer"
	// NotificationCircle is an invitation to join a circle.
	NotificationCircle = "circle"
	// NotificationChat is a message from another person in a chat.
	NotificationChat = "chat"
	// NotificationSkillShareCall is a call of a shared skill waiting for its
	// owner's approval, and how it came out for the person who made it. It
	// opens the app and never answers from the notification: a lock screen
	// tap must not spend money.
	NotificationSkillShareCall = "skill_share_call"
	// NotificationPhoto is photos another person added to an album the
	// person reads.
	NotificationPhoto = "photo"

	// NotificationLocation is a person who shares their location arriving at
	// or leaving a place they named or labeled. It opens the app on Location
	// with that person.
	NotificationLocation = "location"

	// NotificationShopping is what the person's shopping lists need at a
	// store they just arrived at, and somebody starting to shop a list the
	// person shares. It opens the app on Shopping, at that store or list.
	NotificationShopping = "shopping"

	// NotificationCall is a call ringing: somebody started a call in a chat
	// the person is in. It is not one of NotificationKinds a phone chooses
	// among, and a phone's own choice never drops it, since a call that does
	// not ring is a missed call. Whether to ring a member at all is for
	// whoever starts the call to decide: a member who turned the chat's
	// notifications off is never rung.
	NotificationCall = "call"

	// NotificationCallEnded tells a phone still ringing for a call to stop:
	// the person answered or declined on another device, or the call ended.
	// It goes only to phones that can be rung, and is never shown.
	NotificationCallEnded = "call_ended"

	// NotificationJournalEveningQuestion is the journal's "How was today?",
	// with five mood buttons. It is not one of NotificationKinds a phone
	// chooses among: the person turns it on and off, and sets its time, in the
	// journal's settings, so a phone that chose only some kinds still gets it.
	NotificationJournalEveningQuestion = "journalEveningQuestion"
)

Kinds of notification a phone may receive.

View Source
const (
	ReactionEmojiMaximumCount = 2
	ReactionEmojiMaximumBytes = 32
)

The bounds of a reaction's emoji. Two allows a pair a person means together, such as a heart and a pair of hands; more than that is a message, not a reaction.

View Source
const (
	RoleNameAdministrator = "Administrator"
	RoleNameOperator      = "Operator"
	RoleNameMember        = "Member"
)

The seeded roles, by name.

View Source
const (
	SpamTrainingLabelSpam = "spam"
	SpamTrainingLabelHam  = "ham"
)

SpamTrainingLabelSpam and SpamTrainingLabelHam are what a message can be marked as. "Ham" is the word the field has used for "not spam" since the first Bayesian mail filters, and is kept because every other tool an operator meets uses it.

View Source
const (
	StorageFileKindPhotoOriginal     = "photoOriginal"
	StorageFileKindPhotoPreview      = "photoPreview"
	StorageFileKindRecordingOriginal = "recordingOriginal"
	StorageFileKindRecordingDerived  = "recordingDerived"
	StorageFileKindMail              = "mail"
	StorageFileKindAgentAttachment   = "agentAttachment"
)

The kinds of file the blob store holds, as keys of a file kind sample and of the rows the API answers.

View Source
const (
	// VoiceTranscriptWaiting: the words are being written.
	VoiceTranscriptWaiting = "waiting"

	// VoiceTranscriptDone: TranscriptText holds the words, which may be
	// empty when nothing was said.
	VoiceTranscriptDone = "done"

	// VoiceTranscriptFailed: the words could not be written and will not be
	// tried again.
	VoiceTranscriptFailed = "failed"

	// VoiceTranscriptOff: there is nothing to pay for the words (voice is
	// off for the server, or no member of the chat has an agent that is on
	// and within its budget), so there will be none unless a member asks
	// later. The recording still plays.
	VoiceTranscriptOff = "off"
)

A voice message is a chat message that is one recording. The server writes its words after it is posted, so a message passes through these states.

View Source
const AgentDefaultName = "Agent"

AgentDefaultName is what an agent is called until the person names it.

View Source
const AgentMessageNote = "note"

AgentMessageNote is the role of a message that is neither side of the conversation: what a run did, in its own words, for the activity view.

View Source
const AlertKindBudget = "budget"

AlertKindBudget is the kind a mute names to silence every budget and savings target alert.

View Source
const AlertKindBurst = "burst"

AlertKindBurst is the kind a mute names to silence every burst, whatever it is of.

View Source
const AlertKindFollowUp = "follow_up"

AlertKindFollowUp is the kind a mute names to silence every alert about a follow-up; the kind of follow-up (bill, parcel, deadline, event) silences those alone.

View Source
const AlertMarker = "[alert]"

AlertMarker begins the message an alert is written under in the main conversation: the agent telling the person, unasked, what their mail showed. Nobody wrote it and no turn ran; the agent's words follow it.

View Source
const BackgroundCommandMarker = "[background command]"

BackgroundCommandMarker begins the message the agent is woken with when a command it left running in the background on the person's computer ends. Like the goal's marker, it tells the transcript's readers that the person did not write it.

View Source
const BackgroundWorkMarker = "[background work]"

BackgroundWorkMarker begins the message the agent is woken with when a survey or a subagent it left running in the background finishes, and each finished piece of work within that message.

View Source
const CircleInvitationLifetime = 30 * 24 * time.Hour

CircleInvitationLifetime is how long an invitation can be accepted.

View Source
const CircleNameLength = 100

CircleNameLength is the most characters a circle's name may have.

View Source
const DefaultGoalEmoji = "🎯"

DefaultGoalEmoji is what a goal is marked with when no keyword of its words says better.

View Source
const DefaultSpamFilterScoreThreshold = 5.0

DefaultSpamFilterScoreThreshold is the score at which mail is rejected for a domain that never chose one. SpamAssassin's own default.

View Source
const FeedStackKeyIdeas = "idea"

FeedStackKeyIdeas is the stack every idea goes in when its poster named none, whatever suggested it, before the day is added to it.

View Source
const FileSentMarker = "[file sent]"

FileSentMarker begins the line a file sent to the person's main chat is posted under: by a program over MCP, from another conversation, or by a run nobody is present for. What follows says who sent it.

View Source
const FinanceCredentialSecretKey = "credential"

FinanceCredentialSecretKey is the source secret a finance source keeps its credential under.

View Source
const FinanceCursorLastStatementImport = "lastStatementImport"

FinanceCursorLastStatementImport is the cursor key of the statement finance source that holds its last import, a FinanceStatementImport.

View Source
const FinanceSourceCron = "0 */6 * * *"

FinanceSourceCron is how often a finance source syncs unless the person sets another schedule: four times a day. Institutions post a day's transactions in one or two batches, and a provider may charge per call, so more often buys nothing.

View Source
const GoalCardEngagementRecentDays = 30

GoalCardEngagementRecentDays is how far back a goal's recent card engagement looks, so a goal can see a change in how its cards land.

View Source
const GoalCheckInMarker = "[goal check-in]"

GoalCheckInMarker begins the message a goal turn is given, so that everything reading the transcript can tell the agent's own check-in from the person's words: the dashboard draws such a message as a muted line rather than as a person's bubble.

Named here rather than in the agent package because the API hands the same transcript to the dashboard, and a marker only one side knows is a marker that drifts.

View Source
const GoalDoneMarker = "[goal done]"

GoalDoneMarker begins the line a goal is written under in the main conversation when a turn nobody was present for finished it, followed by the goal's id and title, as GoalNeedsYouMarker is.

View Source
const GoalEmojiMaximumBytes = 32

GoalEmojiMaximumBytes is the most bytes a goal's emoji takes: one emoji, as a person sees it, however many code points a flag, a skin tone or a family joins into it.

View Source
const GoalNeedsYouMarker = "[goal needs you]"

GoalNeedsYouMarker begins the line a goal is written under in the main conversation when it comes to need the person: the goal's id follows it, then its title. The agent's sentence saying what it needs comes after, as an alert's words do. It is the only thing a goal says there.

View Source
const GoalRelayMarker = "[from the person, in the main conversation]"

GoalRelayMarker begins the message the person's answer is written into a goal's conversation as, when they gave it in the main conversation: their words, carried over by the agent.

View Source
const HealthDeletedSampleDays = 30

HealthDeletedSampleDays is how many days what is known of a deleted reading is kept, which is how long a phone may take to learn that its deletion went through.

View Source
const HealthDeletedSampleForgetMost = 2000

HealthDeletedSampleForgetMost is how many rows of deleted readings older than that one call to forget them deletes: every report and every erase makes the call, so a table that grows slower than that is emptied.

View Source
const HealthSampleCountMost = 100000

HealthSampleCountMost is the most readings a count of a range goes on to count: counting more of a person's millions of readings would make every page slow.

View Source
const HerdrQuestionMarker = "[herdr question]"

HerdrQuestionMarker began the line a question from one of the person's herdr coding sessions was written under in the main conversation, followed by the computer, the pane and the question's fingerprint. Questions are told to the phone and shown on the Coding page now, and written nowhere; it is kept so the conversations that hold one still read as they did.

View Source
const HerdrSessionMarker = "[herdr session]"

HerdrSessionMarker begins the message the agent is woken with when a herdr coding session it watched has finished.

View Source
const InteractionHandedBack = "[handed back]"

InteractionHandedBack begins the answer a take-over card gets when the person hands the tab back, followed by what they said, if anything. A typed reply to the card is anything else.

View Source
const JournalFactsVersion = 7

JournalFactsVersion is the way a day's numbers are worked out now. It goes up when the counting changes, so that the days already counted are counted again: 2 counts work by project, 3 measures each stretch from its own first and last post, 4 puts the photos taken before screenshots, 5 counts work by the person's own posts, 6 counts the trips to the shops, 7 counts the time between posts in sessions run side by side.

View Source
const JournalNarrativeDepthDays = 92

JournalNarrativeDepthDays is how far back from today dreams write the narratives of days on their own. An older day gets one when the person asks for it.

View Source
const LocalUsername = "(local)"

LocalUsername is the name the console — the command line run on the server itself, with the server secret — acts as. It is not an account: a request carrying it is handled as holding every permission, so no account may have it as a name.

View Source
const MaximumAliasPatternLength = 512

MaximumAliasPatternLength bounds an alias's pattern. It is matched against a local part of at most 64 characters, so a longer one is no use, and each pattern a mail has been matched against stays compiled in memory.

View Source
const MaximumGoalArrivals = 50

MaximumGoalArrivals is how many messages a goal keeps for its next turn; a flood past that is counted by the newest ones alone.

View Source
const MaximumPhotoAlbumTitleLength = 255

MaximumPhotoAlbumTitleLength is the most characters an album's title holds.

View Source
const MemoryCheckOpening = "It is time for a memory check"

MemoryCheckOpening begins what a memory check's turn is told, after the speak-first marker: where the questions of the current check start.

View Source
const PasswordAgentKeyLabel = "teanode passwords: agent key-v1"

PasswordAgentKeyLabel is the secretbox label the server's agent key is sealed under.

View Source
const PasswordItemDeletedDays = 30

PasswordItemDeletedDays is how many days a deleted item can be restored, and so how long it is kept.

View Source
const PasswordItemsMost = 20000

PasswordItemsMost is how many items one person may keep that are not deleted. Deleted items are bounded by PasswordsKeptBytesMost and PasswordRowsMost instead, so that a program holding a token cannot use up the places by saving junk that the person then cannot make room from.

View Source
const PasswordRowsForProgramsMost = 36000

PasswordRowsForProgramsMost is how many items, deleted ones included, one person may have before a save that is not the person's own tap stops making new ones. The last PasswordRowsMost minus this many places are the person's: without it a token could save and delete its way to PasswordRowsMost and leave the person's own tap unable to add an item until they deleted something forever.

View Source
const PasswordRowsMost = 40000

PasswordRowsMost is how many items one person may have in all, deleted ones (kept 30 days) included. A deleted item still takes a row that every first read of the list has to answer, and a program holding a token can delete as fast as it saves, so the places that PasswordItemsMost counts are not enough. A save that makes a new item is refused at it (ErrLimitReached); deleting, deleting forever and restoring make no new row and are never refused for it, so the person always makes room.

View Source
const PasswordSharePairsMost = 50000

PasswordSharePairsMost is how many pairs of an item and a person it reaches one owner's items may have together. The owner's list names every person each share reaches, about 300 bytes of JSON for each pair, so this bounds that part of the answer to about 15 MB. A change of shares that would take the owner past it is refused (ErrPasswordSharesFull in the db package); one that does not increase the number is always allowed, so that an owner whose circle grew can narrow.

View Source
const PasswordWaitingSharesMost = 2000

PasswordWaitingSharesMost is how many entries ListWaitingPasswordShares answers. The newest items come first; when more wait, every entry says so.

View Source
const PasswordsBytesMost = 64 << 20

PasswordsBytesMost is how many bytes of sealed text (the fields and the sealed keys) one person's items that are not deleted may hold together. It is the only limit a save is refused for, by whomever it comes: deleting an item frees its room at once. A listing answers these items, so it also bounds what one request costs the server.

View Source
const PasswordsKeptBytesMost = 128 << 20

PasswordsKeptBytesMost is how many bytes of sealed text one person's deleted items (kept 30 days) and the versions that saves replaced may hold together. When it is full, a change that is not the person's own tap and would add to it is refused, so that a program holding a token cannot fill it with junk and leave the person unable to save; a tap's save, delete or restore always goes ahead (a tap's save then does not keep the version it replaces). The person empties it with PurgePasswordItem.

View Source
const PasswordsSharedBytesFromOneOwnerMost = 8 << 20

PasswordsSharedBytesFromOneOwnerMost is how many of those bytes the items one owner shared with one person may hold. Without it one member could use the whole of PasswordsSharedBytesMost of another person, and every item shared by anybody else would not reach them. A key that would take a recipient past it is not stored, as for PasswordsSharedBytesMost.

View Source
const PasswordsSharedBytesMost = 64 << 20

PasswordsSharedBytesMost is how many bytes of sealed text, the fields of each item and the key sealed for the person, the items other people shared with one person may hold together, whoever shared them. The person cannot decline a share, so without it a circle of 40 people could each push the 64 MiB their own allowance permits at one member. A key that would take a recipient past it is not stored (the recipient is reported as having too much shared with them), and a listing answers the keys already stored, the oldest first, only up to it.

View Source
const PasswordsSharedItemsFromOneOwnerMost = 5000

PasswordsSharedItemsFromOneOwnerMost is how many items one owner may have shared with one person. Without it one member could push the whole of PasswordsSharedItemsMost tiny items at another person and every item shared by anybody else would not reach them. A key past it is not stored, as for PasswordsSharedBytesMost.

View Source
const PasswordsSharedItemsMost = 20000

PasswordsSharedItemsMost is how many items other people may have shared with one person together. The list names each of them in one answer, so small items need a bound of their own beside the bytes. A key past it is not stored, as for PasswordsSharedBytesMost.

View Source
const PhotoDescriptionRequestLifetime = 24 * time.Hour

PhotoDescriptionRequestLifetime is how long a request for a description counts as pending. The job retries for hours, and then gives up.

View Source
const PhotoUploadPartBytes int64 = 8 << 20

PhotoUploadPartBytes is the most one stored part of an upload holds.

View Source
const RecordingShareConsentWords = "" /* 127-byte string literal not displayed */

RecordingShareConsentWords is what the person is told when they are about to share a recording, in one wording for the dashboard, the app, the command line and the card the agent's share asks about. The people who spoke in a recording did not agree to its being shared, and only the person who shares it can decide that is all right.

View Source
const RecordingUploadPartBytes int64 = 8 << 20

RecordingUploadPartBytes bounds transport memory independently of chat files.

View Source
const ReflectionEvidencePrefix = "reflection: "

ReflectionEvidencePrefix begins the night's own line of evidence on a reflection, which names what kind of observation it is: "reflection: pattern", "reflection: risk".

View Source
const RefreshWindow = 60 * 24 * time.Hour

RefreshWindow is how long after its access expires a program's token can still be renewed.

A program that is still in use renews when its access runs out, and many only renew once a request has been refused, so the renewal has to outlive the access. One that nobody has run for two months past that has been forgotten, and has to be approved again.

View Source
const RelationshipNoticeInterval = 24 * time.Hour

RelationshipNoticeInterval is how often one person tells another about a relationship between them: what they say, change and take back in between is shown on the Circles page at once but told no more, so that saying it and taking it back over and over is not a way to fill somebody's conversation and phone.

View Source
const RestartResumeMarker = "[resuming after a restart]"

RestartResumeMarker begins the message the agent is given when the server restarted in the middle of a turn that answered the person: the turn is carried on in the same conversation. Nobody wrote it.

View Source
const ScheduleMarker = "[schedule]"

ScheduleMarker begins the message a schedule's turn is given when it answers in a conversation: the agent's own turn, at a time somebody set, and not the person's words.

View Source
const ShareScopeAllAccounts = "allAccounts"

ShareScopeAllAccounts is the scope of a finance share that covers all of the owner's accounts, now and later, instead of one.

View Source
const SharedOverviewNotice = "The owner's longer overview of this page is not shared."

SharedOverviewNotice is said in every view of a shared page, so that a reader who knows pages have longer overviews does not take the missing one for a page without it. The overview is written by a model from the page's links, children and quotes, so it can name pages that are not shared and repeat quotes the owner did not share; it is not shown to a reader at all.

View Source
const ShoppingPurchaseUndoableFor = 3 * time.Hour

ShoppingPurchaseUndoableFor is how long after a purchase it can be taken back: a finished trip resumed (what it bought goes back in the cart), or an item checked off on its list unchecked (it is needed again, last bought when it was before). Later, a trip is over, and an item unchecked is needed again having been bought.

View Source
const ShoppingReceiptBoughtWithin = 12 * time.Hour

ShoppingReceiptBoughtWithin is how recently an item bought must have been bought for a receipt to still be matched to it: a receipt snapped as the shopper finishes is read after their Done has bought the cart, and its prices still belong to those items.

View Source
const ShoppingTripStaleAfter = 6 * time.Hour

ShoppingTripStaleAfter is how long after it started an unfinished trip is taken as over: a new trip on one of its lists finishes it, and what it had in the cart is bought.

View Source
const SkillShareCallWaitFor = 24 * time.Hour

SkillShareCallWaitFor is how long a call waits for the owner before it expires.

View Source
const SkillShareNoLimitsWords = "No limits: every call waits for approval, except one that only works on something an earlier call through this share made"

SkillShareNoLimitsWords says what a share allows that has no limit and does not ask every time, in one wording for the dashboard, the app, the command line and the agent. Nothing that can be priced goes through unasked there (a tool that pays is shared with a limit or with asking every time, and a call the server cannot price waits); what does is a tool that works only on something an earlier call through the share made, such as checking or cancelling that payment, which pays nothing itself (skills.Tool.Weigh).

View Source
const SpeakFirstMarker = "[speaking first]"

SpeakFirstMarker begins the message a turn the agent starts on its own is given: an introduction, a memory check, an idea. Nobody wrote it; the agent is about to speak first.

View Source
const StorageDatabaseTotalKey = "total"

StorageDatabaseTotalKey is the key of the one database sample of a day.

View Source
const UnwantedCategories = "^(phishing|junk)$"

UnwantedCategories is the condition that rule matches on: the two categories an agent gives a message nobody wants.

View Source
const UnwantedRuleName = "Phishing and junk"

UnwantedRuleName is what the rule every mailbox starts with is called, and how a mailbox that already has one is recognised.

View Source
const VoiceMessageWaveformLevelCount = 48

VoiceMessageWaveformLevelCount is how many peak levels a voice message's waveform holds.

Variables

View Source
var (
	HourlyInterval uint64 = 3600 // every hour

	MaxHourlyUsages uint64 = 53 * 7 * 24 // save 53 weeks worth of hourly usage
)

AgentAudiences is every audience, for validation and the prompts.

View Source
var AgentCategories = []string{"personal", "work", "newsletter", "notification", "receipt", "promotion", "social", "invitation", "phishing", "junk", "other"}

AgentCategories is the fixed vocabulary every insight draws from, beside the person's own. Fixed so that chips translate and rules stay portable.

"phishing" and "junk" are here rather than left to each person to invent, because they are the categories somebody wants a standing rule about on the day they first need one, and a rule is only portable if the word is. Both are judgements about a message rather than verdicts from a check: the spam filter and DMARC catch what they can, and what reaches these is the mail that passed both. Phishing is a lie with a purpose -- a real domain nobody has ever written from, asking for a password. Junk is mail nobody asked for from somebody with no reason to write, which is a different thing from a promotion, and the difference is whether the person has a relationship with the sender at all.

AgentChannelKinds are the apps there are.

AgentEdgeRelations is every relation.

AgentFactKinds is every kind.

AgentFactKindsFiled is the kinds a conversation, a tool or a person files: every kind but a reflection.

AgentKnowledgeFormats is every format a source may be read in.

AgentKnowledgeKinds is every kind.

AgentNodeKinds is every kind, for validation and for the tool's schema.

View Source
var AgentPriorities = []string{"high", "normal", "low"}

AgentPriorities are the three levels an insight assigns.

AgentRecordKinds is every kind, for validation and for the tool's schema.

AgentRecordRelations is every relation.

View Source
var AgentRoots = []AgentRoot{
	{PathSelf, NodeSelf, "Who they are", ""},
	{PathPeople, NodeFolder, "People", "Everyone they have told you about."},
	{PathProjects, NodeFolder, "Projects", "What they are working on."},
	{PathPlaces, NodeFolder, "Places", "Where things are."},
	{PathThings, NodeFolder, "Things", "Objects, accounts, machines, possessions."},
	{PathTopics, NodeFolder, "Topics", "Subjects that are not a person or a project."},
	{PathNotes, NodeFolder, "Notes", "Anything that does not belong anywhere else yet."},
	{PathTime, NodeFolder, "Time", "A page per month and per year, of what happened then."},
}

AgentRoots is the shape every graph starts with. Notes is where anything that has no better home goes, and where the memories of the flat list that came before land.

View Source
var CalendarNamed = map[CalendarKind]string{
	CalendarEvents:    "Calendar",
	CalendarReminders: "Reminders",
}

CalendarNamed is the name a calendar of each kind is given when it is made for somebody.

View Source
var ChatAllMentionWords = []string{"all", "所有人", "全員"}

ChatAllMentionWords are what follows an @ to mention everybody in a chat, in each language the apps are shown in: the composer writes the one of its language. What a message mentions is stored with it, so these are read only from words that came without a composer (what an agent writes).

View Source
var DefaultFolders = []struct {
	Kind MailboxFolderKind
	Name string
}{
	{MailboxFolderKindInbox, "Inbox"},
	{MailboxFolderKindDrafts, "Drafts"},
	{MailboxFolderKindSent, "Sent"},
	{MailboxFolderKindArchive, "Archive"},
	{MailboxFolderKindJunk, "Junk"},
	{MailboxFolderKindTrash, "Trash"},
}

DefaultFolders are what a new mailbox starts with, in the order the tree shows them.

View Source
var ErrNoShareTarget = errors.New("neither a person nor a circle")

ErrNoShareTarget is what ResolveShareTarget answers when the words name nobody and no circle. The caller words the refusal for its own surface, because what to run next differs; a name that matches several things is worded here, once, so every surface says the same.

EvaluationQuestionKinds is every kind, in the order they are listed.

View Source
var GoalMailFields = []string{"from", "to", "subject", "header", "any"}

GoalMailFields are the tests a goal's mail conditions may make: those a message can be judged by as it arrives, before the agent has sorted it.

NotificationKinds is every kind, in the order a person chooses among them.

OwnTurnMarkers are the markers of every turn the agent takes on its own in a person's conversation: what anything looking for the person's own last word must pass over.

PhonePlatforms is every platform, the iPhone first.

PlaceLabels lists the labels in the order a picker offers them.

RecordingShareLevels is every level that can be given, least first.

ShareKinds is every kind, in the order the Sharing page lists them.

ShoppingItemStates is every state, in the order a list shows them.

SkillShareCallStates is every state.

StorageFileKinds is every kind of file, in the order they are listed.

View Source
var TaxFilingStatuses = []string{"single", "married_filing_jointly", "married_filing_separately", "head_of_household"}

TaxFilingStatuses are the ways a US tax return is filed.

TaxFormKinds are every kind of tax form TeaNode reads.

UnattendedRisks is every reason a person may allow, in the order the settings show them.

Functions

func AgentSpeakerLabel added in v0.170.0

func AgentSpeakerLabel(agentName, ownerName string) string

AgentSpeakerLabel is how an agent's chat message says whose it is. Most agents keep the name "Agent", so a chat with two people's agents in it needs the owner to be told apart: "<agent name> · <owner name>'s agent", and just "<owner name>'s agent" while the agent still has the default name, which would otherwise repeat the word. The clients word it in the person's language; this is the English of the command line and of a phone's notification to a person who reads English (internal/chat words it in the others).

func AlbumShareScopes added in v0.194.0

func AlbumShareScopes(isLocationIncluded, isFaceNamesIncluded bool) []string

AlbumShareScopes is what an album share gives beyond its level: where its photos were taken, when the share includes that.

func AmbiguousCircleNameError added in v0.170.0

func AmbiguousCircleNameError(typed string, circles []ShareableCircle) error

AmbiguousCircleNameError is the refusal for a circle name that more than one circle has.

func ChatAgentDetail added in v0.170.0

func ChatAgentDetail(agentName, ownerName string) string

ChatAgentDetail is the detail of a chat_agent_owner_only note.

func ChatCallWords added in v0.212.0

func ChatCallWords(call *ChatCall) string

ChatCallWords is what a model reads in place of a call's line in a chat: "[call, 4:12]", "[call, 4:12, transcribed]", "[call going]", "[missed call]" or "[declined call]". The transcript is read with the chat tool, not here.

func ChatDirectKey added in v0.170.0

func ChatDirectKey(userId, otherUserId string) string

ChatDirectKey is the same for the two people of a direct chat whichever way round they are given.

func ChatMentionsIn added in v0.196.0

func ChatMentionsIn(body string, members []*ChatMember) (mentionedUserIds []string, isAllMentioned bool)

ChatMentionsIn are the people words mention when no composer chose them: an @ that is not inside an address or a word, followed by the name of a member in the chat now, or by one of ChatAllMentionWords. The name ends where a letter, a digit or an underscore does not follow, so "@Ada" is not "@Adam"; of two names that both fit, the longer is the one meant.

func ChatReactorKey added in v0.170.0

func ChatReactorKey(reactorKind AgentReactorKind, id string) string

ChatReactorKey is how a reactor is told apart from every other in chat_reaction: the account for a person, the agent for an agent.

func CircleInvitedDetail added in v0.170.0

func CircleInvitedDetail(invitedByName, circleName string) string

CircleInvitedDetail is the detail of a circle_invited note.

func CircleMemberAddedDetail added in v0.194.0

func CircleMemberAddedDetail(addedName, circleName string) string

CircleMemberAddedDetail is the detail of a circle_member_added note.

func CurrencyExponent added in v0.170.0

func CurrencyExponent(currencyCode string) int

CurrencyExponent is how many digits a currency's major unit is divided into: 2 for most (cents), 0 for those with no minor unit (yen), 3 for those with thousandths (dinars). The limits of a share are stored in the minor unit and shown and typed in the major one.

func DashboardPath added in v0.84.0

func DashboardPath(scheme, target string) string

DashboardPath is the path in the dashboard a link of its own schemes opens, or "" when what follows the scheme is not one it could be. It is strict because the text is a model's: a memory: path is only a path the graph could hold, so no query, no "..", and nothing else rides along.

A fact's number is accepted and not carried: the Knowledge page opens a page, not a place in it.

A page another person shared with the person is cited as [name](memory:PATH#N@username), the username last, and opens in the Knowledge page's "Shared with you" with ?owner=username. Spoken, the citation is "people/a-grandparent#3 (shared by Ada)".

func DescribeCircle added in v0.170.0

func DescribeCircle(name string, memberCount int) string

DescribeCircle says which circle a result or a card means: the circle, with its name in quotes, so that a name typed by whoever made the circle cannot read as part of the sentence, and how many people it is.

func DescribeCircleByName added in v0.170.0

func DescribeCircleByName(name string) string

DescribeCircleByName is DescribeCircle for a line that does not know the circle's size, such as a share in a list.

func DescribeCircleChoices added in v0.170.0

func DescribeCircleChoices(circles []ShareableCircle) string

DescribeCircleChoices lists circles by id and size, which is what somebody needs to pick one of several that are called the same.

func DiscretizeTimestamp

func DiscretizeTimestamp(interval, timestamp uint64) uint64

func DomainKeyName

func DomainKeyName(selector, domain string) string

DomainKeyName is where a domain's key is published.

func EvaluationAnswerScore added in v0.61.0

func EvaluationAnswerScore(questionKind EvaluationQuestionKind, answerVerdict string) float64

EvaluationAnswerScore is what one graded answer counts for: a right answer, and a right "not known" to an abstain question, count one; a partial answer a half; anything else nothing.

func FahrenheitFromCelsius added in v0.202.0

func FahrenheitFromCelsius(celsius float64) float64

FahrenheitFromCelsius converts a temperature.

func FeedChoiceKeyOption added in v0.230.0

func FeedChoiceKeyOption(optionNumber int) string

FeedChoiceKeyOption is the key of a coding session's option, "option:3".

func FeedOptionNumber added in v0.230.0

func FeedOptionNumber(choiceKey string) (int, bool)

FeedOptionNumber is the number in an "option:N" key, and whether the key is one.

func FeedStackKeyCodingDay added in v0.230.0

func FeedStackKeyCodingDay(day time.Time) string

FeedStackKeyCodingDay is the stack of the coding sessions' questions of one day, the day as the person's clock tells it.

func FeedStackKeyOnDay added in v0.251.0

func FeedStackKeyOnDay(feedStackKey string, day time.Time) string

FeedStackKeyOnDay is a stack's key for the cards of one day, the day as the person's clock tells it, so that no stack holds two days' cards: a card posted to yesterday's stack starts today's. A key that names a day already has it replaced; a coding key is a day's already.

func FormatMinor added in v0.170.0

func FormatMinor(minor int64, currencyCode string) string

FormatMinor writes an amount in minor units as people write money: 14.00 USD. The code is upper case, the number has the currency's own digits.

func FormatRecordReference added in v0.154.0

func FormatRecordReference(recordKind AgentRecordKind, recordId string, startMS, endMS int64) string

FormatRecordReference is a record named in one word: kind, colon, identifier, and for a passage "@start-end" in milliseconds.

func GoalEmojiOrPicked added in v0.246.0

func GoalEmojiOrPicked(goalEmoji, goalTitle, goalDescription string) string

GoalEmojiOrPicked is the emoji a goal shows: the one it was given, or, for a goal with none, the one its words call for.

func IsAgentAudience

func IsAgentAudience(audience AgentAudience) bool

IsAgentAudience says whether a word names an audience.

func IsAgentEdgeRelation

func IsAgentEdgeRelation(relation AgentEdgeRelation) bool

IsAgentEdgeRelation says whether a word names a relation.

func IsAgentFactKind

func IsAgentFactKind(kind AgentFactKind) bool

IsAgentFactKind says whether a word names a kind.

func IsAgentGoalState added in v0.111.0

func IsAgentGoalState(goalState AgentGoalState) bool

IsAgentGoalState says whether a state is one of the five.

func IsAgentKnowledgeFormat

func IsAgentKnowledgeFormat(format string) bool

IsAgentKnowledgeFormat says whether a word names a format.

func IsAgentKnowledgeKind

func IsAgentKnowledgeKind(kind AgentKnowledgeKind) bool

IsAgentKnowledgeKind says whether a word names a kind.

func IsAgentNodeKind

func IsAgentNodeKind(kind AgentNodeKind) bool

IsAgentNodeKind says whether a word names a kind.

func IsAgentRecordKind added in v0.154.0

func IsAgentRecordKind(recordKind AgentRecordKind) bool

IsAgentRecordKind says whether a word names a kind.

func IsAgentRecordRelation added in v0.154.0

func IsAgentRecordRelation(recordRelation AgentRecordRelation) bool

IsAgentRecordRelation says whether a word names a relation.

func IsCurrencyCode added in v0.87.0

func IsCurrencyCode(currencyCode string) bool

IsCurrencyCode says a word is shaped like an ISO 4217 code: three capital letters. Whether anyone publishes a rate for it is another question, answered by the rates stored.

func IsEmailAddress

func IsEmailAddress(value string) bool

IsEmailAddress reports whether a value looks like one address.

func IsFeedCardLayout added in v0.230.0

func IsFeedCardLayout(value FeedCardLayout) bool

IsFeedCardLayout says whether a word is one of the layouts.

func IsFeedChoiceRole added in v0.230.0

func IsFeedChoiceRole(value FeedChoiceRole) bool

IsFeedChoiceRole says whether a word is one of the roles.

func IsFeedDestination added in v0.230.0

func IsFeedDestination(value string) bool

IsFeedDestination is one of the two, and an empty one is the feed.

func IsFeedItemKind added in v0.230.0

func IsFeedItemKind(value FeedItemKind) bool

IsFeedItemKind says whether a word is one of the kinds of card.

func IsFeedResolverKind added in v0.240.0

func IsFeedResolverKind(value FeedResolverKind) bool

IsFeedResolverKind says whether a word is one of the kinds of resolver.

func IsFeedSourceKind added in v0.230.0

func IsFeedSourceKind(value FeedSourceKind) bool

IsFeedSourceKind says whether a word is one of the kinds of source.

func IsFeedUrgency added in v0.230.0

func IsFeedUrgency(value FeedUrgency) bool

IsFeedUrgency says whether a word is one of the urgencies.

func IsFillerTranscriptText added in v0.157.0

func IsFillerTranscriptText(text string) bool

IsFillerTranscriptText says whether a passage holds only filler ("Mm-hmm. Okay. Okay."), which a reader skips and nobody needs to label. A passage with no words at all is not filler; it is empty. Nor is a question ("Right?"), however short: it asks something.

func IsHostLabel

func IsHostLabel(value string) bool

IsHostLabel reports whether a value is one label of a host name.

func IsHostname

func IsHostname(value string) bool

IsHostname reports whether a value is a fully qualified host name: the names this server publishes and obtains certificates for.

func IsMeasurementSystem added in v0.202.0

func IsMeasurementSystem(value string) bool

IsMeasurementSystem says whether a value is one the database accepts for an account's measurement system.

func IsOwnTurn added in v0.131.1

func IsOwnTurn(message string) bool

IsOwnTurn says whether a turn's opening message is one of the agent's own turns rather than something a person wrote.

func IsPort

func IsPort(value string) bool

IsPort reports whether a value is a port somebody can connect to.

func IsRelayHost

func IsRelayHost(value string) bool

IsRelayHost reports whether a value names something this server can open an SMTP connection to.

Looser than IsHostname on purpose. A relay target is reached over whatever network this server is on, not looked up in public DNS: an address, a single-label name from a container network or a search domain, or a fully qualified name are all ordinary.

func IsReservedUsername

func IsReservedUsername(username string) bool

IsReservedUsername says whether a name may not be given to an account, whatever its case. A person who could rename their account to the console's name would be the console from then on.

func IsTaxFilingStatus added in v0.155.0

func IsTaxFilingStatus(text string) bool

IsTaxFilingStatus says text is one of TaxFilingStatuses.

func IsThePerson

func IsThePerson(path string, owner *User, self *AgentNode) bool

IsThePerson says whether a path under people names the person whose agent this is: by their username, by any word of their name, by their name's slug, or by what their own page is called and also called. The account's name can be a first name alone -- "Ziyan" -- while a model files under the full one, so the self page's aliases, which carry every name the person has been found under, are part of the check. Such a page is a duplicate of "self", where what the agent knows about them lives, and everything that files or links routes it there.

func IsThemePath added in v0.79.0

func IsThemePath(path string) bool

IsThemePath says whether a path is a theme's page: anything under themes, not the folder itself.

func JoinPath

func JoinPath(parent, segment string) string

JoinPath is a parent path and a segment, with the segment slugged.

func JournalMonthPageSentence added in v0.202.0

func JournalMonthPageSentence(month string) string

JournalMonthPageSentence ends the memory page made from the journal's narrative of a month (month is YYYY-MM): it says where the month is in the journal, and tells the page apart from one the timeline wrote, so that the page goes when the narrative does.

func JournalWordsDigest added in v0.202.0

func JournalWordsDigest(original, how string) string

JournalWordsDigest is the digest a touched-up text records of the original and instruction it was made from: hex SHA-256 of the instruction, a zero byte and the original.

func KnownWeekStart

func KnownWeekStart(value string) string

KnownWeekStart is a week start this server writes down, or empty for anything else. Checked rather than stored as given: the dashboard draws its columns from this, and a word it does not know would silently become one of the two anyway.

func KnownWriter

func KnownWriter(value string) string

KnownWriter is one of those three, or empty for anything else.

func LastSegment

func LastSegment(path string) string

LastSegment is the last part of a path.

func LinkDashboardLinks(text, base string) string

LinkDashboardLinks makes each link in the dashboard's own schemes whole from base, the dashboard's address (config.DashboardBase), for somewhere that opens only addresses: a chat app. With no base, or a link that is not one, what is left is its words, which is what a chat app would otherwise show as a raw address that opens nothing.

func LocalPartOfPattern

func LocalPartOfPattern(pattern string) string

LocalPartOfPattern is the one local part a literal pattern names — "^alice$" is alice, and so is a bare "alice", which is what people type when the anchors mean nothing to them — or empty for a pattern that names several or none, which is what a mailbox address has to be exactly one of. It reads back what PatternForLocalPart writes: "^first\.last$" is first.last, while an unescaped "." stands for any character and names several.

func LocationShareBackWords added in v0.226.0

func LocationShareBackWords(name string, seen, granted, limit LocationShareLevel) string

LocationShareBackWords says why a person sees less of someone's location than that person shares, when what they share back is why: seen is what they see, granted what is shared with them, and limit their own limit. Empty when what they share back is not why.

func MilesFromMeters added in v0.202.0

func MilesFromMeters(meters float64) float64

MilesFromMeters converts a distance.

func NormalizeCurrencyCode added in v0.170.0

func NormalizeCurrencyCode(code string) (string, bool)

NormalizeCurrencyCode is a currency code as it is stored: three letters, lower case. The second answer is false for anything else.

func NormalizePath

func NormalizePath(path string) string

NormalizePath cleans a path the model or a person wrote: trims, drops leading and trailing slashes, slugs each segment, and drops empty ones. It does not report an error -- ValidPath does that -- so that a caller can normalize first and complain about what is left.

func NormalizePhotoAlbumTitle added in v0.171.0

func NormalizePhotoAlbumTitle(albumTitle string) (string, error)

NormalizePhotoAlbumTitle trims a title and refuses one that is empty or too long, saying what the limit is.

func NoteText added in v0.71.2

func NoteText(kind AgentNoteKind, detail string) string

NoteText is a note in English: the kind's words, then its detail. The compaction's detail is the whole note, which is not repeated here.

func PageShareScopes added in v0.194.0

func PageShareScopes(isQuoteShared bool) []string

PageShareScopes is what a page share gives beyond the page: the words each fact was read in, when the share includes them.

func ParentPath

func ParentPath(path string) string

ParentPath is everything above the last segment, and empty for a root.

func ParseMinor added in v0.170.0

func ParseMinor(text, currencyCode string) (int64, error)

ParseMinor reads an amount somebody typed in the currency's major unit ("100", "100.5", "100.50") into minor units. It refuses more digits than the currency has, a sign, a thousands separator, and anything that is not a number above zero, because a limit read wrongly is a limit that does not hold.

func PathIsWithin added in v0.170.0

func PathIsWithin(pagePath, root string) bool

PathIsWithin says whether a page path is the root or lies under it. The boundary is a slash: "people/a" contains "people/a" and "people/a/x" and never "people/ab", which is a different page whose name starts the same way.

func PatternForLocalPart

func PatternForLocalPart(localPart string) string

PatternForLocalPart is the pattern that names exactly one local part.

func PeopleCountWords added in v0.170.0

func PeopleCountWords(count int) string

PeopleCountWords says how many people a circle has: "1 person", "4 people".

func PhoneModelName added in v0.154.4

func PhoneModelName(identifier string) string

PhoneModelName is the name a person knows a device by, such as "iPhone 17 Pro Max", for the identifier it reported, such as "iPhone18,2". An identifier this table does not know is returned as it is: a newer device shows its identifier until the table learns it, never a guess.

func PhotoBlobFileID added in v0.171.0

func PhotoBlobFileID(blobSha256 string) string

PhotoBlobFileID is the name of a blob in the blob store.

func PhotoPreviewFileID added in v0.171.0

func PhotoPreviewFileID(photoId string, photoPreviewSize PhotoPreviewSize) string

PhotoPreviewFileID is the name of a preview in the blob store.

func PhotoUploadPartFileID added in v0.171.0

func PhotoUploadPartFileID(photoUploadId string, partIndex int) string

PhotoUploadPartFileID is the name of a stored part in the blob store.

func PickGoalEmoji added in v0.246.0

func PickGoalEmoji(goalTitle, goalDescription string) string

PickGoalEmoji chooses an emoji for a goal from its words, with no model involved: the first group of keywords, in the table's order, that the title has a word of, else the first that the description has, else the default. It is pure: the same words always give the same emoji.

func PlainCircleName added in v0.170.0

func PlainCircleName(name string) string

PlainCircleName is a circle's name as it is kept: on one line, with every control character and run of blanks made a single space. Whoever made the circle typed it, and it is shown to every member on cards and in the model's view, where a line break would pass for a line of its own.

func PlainText added in v0.138.2

func PlainText(text string) string

PlainText is an answer as a surface that draws no Markdown shows it: a notification, a title, a line in a list. What is hidden is gone and no Markdown mark is left: a heading, a list item, a table row, a quote, a rule, a fence line, emphasis, strikethrough, a code span, a link's target, an HTML tag or an escape. A picture reads as its alt text, a list item as its words, a table row as its cells joined by " · ". The code inside a fence stays as text. Lines are kept; a caller that wants one line joins them, and a caller that cuts does so after this, so a cut never lands inside syntax.

func RecordLinkKey added in v0.154.0

func RecordLinkKey(nodeId string, recordKind AgentRecordKind, recordId string, recordRelation AgentRecordRelation, startMS, endMS int64) string

RecordLinkKey is the unique key of a link as one string, for a set of links a pass has already seen or the person has dismissed.

func RegexpErrorMessage

func RegexpErrorMessage(err error) string

RegexpErrorMessage strips the "error parsing regexp: " prefix that regexp.Compile adds, because the surrounding message already says that.

func RelationshipDetail added in v0.178.0

func RelationshipDetail(personName string, relationshipKind RelationshipKind, termGender TermGender) string

RelationshipDetail is the detail of a relationship_set or relationship_removed note.

func ReplaceWholePhrase added in v0.153.0

func ReplaceWholePhrase(text, phrase, replacement string) (string, int)

ReplaceWholePhrase replaces every occurrence of phrase in text with replacement and says how many it replaced. An occurrence must start and end on a word boundary: a phrase edge that is a letter or a digit may not touch another letter or digit, so "node" is not found inside "nodes". Any run of white space in the text matches the single space between the words of the phrase, because the model that proposed the phrase read the text with its white space collapsed. The match is otherwise exact, including case.

func ShareReachedDetail added in v0.194.0

func ShareReachedDetail(note ShareReachedNote) string

ShareReachedDetail is the detail of a share_reached note.

func ShareReachedText added in v0.194.0

func ShareReachedText(note *ShareReachedNote) string

ShareReachedText is a share_reached note in English: "Sam joined Family and can now see your calendar and location".

func ShareReceivedDetail added in v0.194.0

func ShareReceivedDetail(note ShareReceivedNote) string

ShareReceivedDetail is the detail of a share_received note.

func ShareReceivedText added in v0.194.0

func ShareReceivedText(note *ShareReceivedNote) string

ShareReceivedText is a share_received note in English: "Alex shared their calendar with you (titles)".

func SharedReference added in v0.170.0

func SharedReference(pagePath string, number int, ownerName string) string

SharedReference is the citation of a shared fact: "people/a-grandparent#3 (shared by Ada)". The owner is named so that the person reading the answer knows whose memory it came from.

func ShoppingItemSimilarity added in v0.219.0

func ShoppingItemSimilarity(typed, description string) float64

ShoppingItemSimilarity says how alike what somebody is typing and an item's description read, from 0 when they share no word to 1 when they are the same words in any order. Case, punctuation, a plural, a word only begun and a small misspelling make no difference to whether they match; extra words on either side lower the score, so "milk" is nearer "Milk" than "Whole milk".

func ShoppingStoreKey added in v0.201.0

func ShoppingStoreKey(storeName string) string

ShoppingStoreKey is the form every store name is compared in: lower case, letters and digits only, so "Example Market", "EXAMPLE MARKET'S" and "example-market" are one store. A name with no letter or digit has the empty key, which is any store.

func SkillShareCallDetail added in v0.170.0

func SkillShareCallDetail(note SkillShareCallNote) string

SkillShareCallDetail is the detail of a skill_share_call_waiting note.

func Slug

func Slug(name string) string

Slug is a name as a path segment: lowercase, letters digits and dashes, runs of anything else collapsed to one dash. Non-ASCII letters are kept -- a person whose name is not written in ASCII still gets a page they can read -- because the path is an address for a model and a person, not a file name.

func SortAgentEdgesFrom added in v0.120.3

func SortAgentEdgesFrom(path string, edges []*AgentEdge)

SortAgentEdgesFrom puts a page's links in an order that holds from one read to the next, so that reading them a part at a time neither repeats a link nor skips one: the page's own links first, then those pointing at it, each by relation and then by the path at the other end.

func SortUsages

func SortUsages(usages []Usage)

func SplitHostPort

func SplitHostPort(value string) (string, string)

SplitHostPort separates a name from the port it may carry.

Not net.SplitHostPort, which fails outright on a value with no port at all, and a name without one is the ordinary case. A value whose last colon is not followed by digits is handed back whole: nothing this server accepts as a name carries a colon, so cutting at one would quietly change what somebody typed into something else.

func StripHiddenMarkers added in v0.138.2

func StripHiddenMarkers(text string) string

StripHiddenMarkers takes everything off an answer that only the dashboard and the app read: the suggested replies it ends with, and any other HTML comment, including one still being written. For a surface that draws Markdown but not these, such as a chat app, a mail or a terminal.

func StripSuggestedReplies added in v0.62.0

func StripSuggestedReplies(text string) string

StripSuggestedReplies takes the hidden suggested replies off an answer, for anywhere but the dashboard, which reads them: a chat app, a mail, a terminal. See web/src/suggestions.ts.

func UnlinkDashboardLinks(text string) string

UnlinkDashboardLinks leaves each link in the dashboard's own schemes as its words.

func UsesUSUnits added in v0.202.0

func UsesUSUnits(measurementSystem string, locale string) bool

UsesUSUnits says whether numbers are written in degrees Fahrenheit and miles for a person: as they chose, or when they did not, as the region of the locale says. A locale with no region ("en", "ja") says nothing about where the person is, so it reads as metric; only a locale that names a region ("en-US", "en_US.UTF-8") can read as US.

func ValidPath

func ValidPath(path string) error

ValidPath reports everything wrong with a path.

func ValidateChangedRulePatterns added in v0.249.0

func ValidateChangedRulePatterns(before, after []MailboxRule) error

ValidateChangedRulePatterns checks the patterns of the rules that are new or changed between two versions of a mailbox's rules. A rule kept as it was is not checked, so a mailbox holding an older rule that can never match can still be saved for anything else.

func ValidateChatMessageBody added in v0.170.0

func ValidateChatMessageBody(body string, hasAttachments bool) error

ValidateChatMessageBody says why a message cannot be sent, or nil. A message with nothing to say needs a file with it.

func ValidateChatTitle added in v0.170.0

func ValidateChatTitle(title string) error

ValidateChatTitle says why a title cannot be a group's, or nil.

func ValidateGoalEmoji added in v0.246.0

func ValidateGoalEmoji(goalEmoji string) error

ValidateGoalEmoji says why a text cannot be a goal's emoji, or nil when it is exactly one emoji. An empty one is refused here: it means "choose one for me", which the caller decides before asking.

func ValidateGoalMailConditions added in v0.232.0

func ValidateGoalMailConditions(conditions []MailboxRuleCondition) error

ValidateGoalMailConditions reports what is wrong with a goal's mail conditions.

func ValidateReactionEmoji added in v0.134.0

func ValidateReactionEmoji(reactionEmoji string) error

ValidateReactionEmoji says why an emoji cannot be a reaction, or nil when it can. An empty one is refused here: it means taking a reaction away, which the caller decides before asking.

func VoiceMessageClock added in v0.211.0

func VoiceMessageClock(durationMS int64) string

VoiceMessageClock is the length of a recording as a clock, "0:12".

func VoiceMessageSeconds added in v0.211.0

func VoiceMessageSeconds(durationMS int64) int64

VoiceMessageSeconds is the length of a recording in whole seconds, rounded to the nearest and never below one for a recording that has any length.

Types

type ARCResult

type ARCResult struct {
	// ARC result
	Result string `json:"result,omitempty"`

	// ARC instances
	Instances int `json:"instances,omitempty"`
}

ARCResult holds authentication results related to ARC.

type AccountInvestmentIncome added in v0.159.0

type AccountInvestmentIncome struct {
	FinanceAccountID string `json:"financeAccountId"`
	AccountName      string `json:"accountName"`
	// AccountSubtype is the provider's (savings, brokerage, ira, hsa).
	AccountSubtype string `json:"accountSubtype"`
	// IncomeKind is "interest" or "dividend".
	IncomeKind       string `json:"incomeKind"`
	Amount           string `json:"amount"`
	TransactionCount int    `json:"transactionCount"`
}

AccountInvestmentIncome is the interest or the dividends one finance account was paid within some days, as its transactions say.

type AddressBook

type AddressBook struct {
	ID         string    `json:"id"`
	UserID     string    `json:"userId"`
	CircleID   string    `json:"circleId,omitempty"`
	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`

	Name        string `json:"name"`
	Description string `json:"description,omitempty"`

	// AgentGranted says the person has given their agent this address book.
	// False until they do: nothing from a source the person has not granted
	// is ever sent to a model.
	AgentGranted bool `json:"agentGranted"`
}

AddressBook is a collection of contacts: a person's own, or a circle's.

A person's own belongs to the account rather than to a mailbox: somebody with two mailboxes has one address book, and reaches it through either of them. An account is given one named "Contacts" the first time it looks, so that nobody has to create one before they can keep a contact. It is never shared.

A circle's belongs to the circle (CircleID set, UserID empty): every member reads and edits it, and it goes when the circle goes. Exactly one of the two is set.

type AddressBookAccess added in v0.194.0

type AddressBookAccess struct {
	// CanEdit is that the person may read the book and add, change and remove
	// the contacts in it: the owner of a personal book, any member of the
	// circle whose book it is.
	CanEdit bool
	// CanManage is that the person may rename the book and delete it: its
	// owner, or an admin of its circle.
	CanManage bool
	// IsOwner is that the book is the person's own. Everything that is owner
	// only (the account link, the agent's grant, the ties from recordings and
	// photos) asks for this and never for CanEdit.
	IsOwner bool
}

AddressBookAccess is what a person may do with one address book, answered by the database's AddressBookAccess and asked by every door into a book.

type Agent

type Agent struct {
	ID         string    `json:"id"`
	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`
	UserID     string    `json:"userId"`

	// Name is what the person calls it. "Agent" until they say otherwise.
	Name string `json:"name"`

	// Enabled is the person's own switch. Off cancels queued work and held
	// replies and keeps what was learned.
	Enabled bool `json:"enabled"`

	// Instructions are the person's standing words: who they are, how they
	// write, what matters to them. Appended to every prompt as their own
	// block, never interpolated into the conduct.
	Instructions string `json:"instructions,omitempty" graphapi:"nullable"`

	// Language is what the agent writes in; empty resolves to the account's
	// locale, chosen or learned.
	Language string `json:"language,omitempty" graphapi:"nullable"`

	// KnowledgeLanguage is what the agent's notes are written in: pages,
	// openings, facts. Kept apart from Language so that notes stay in one
	// language while the person reads the dashboard or answers mail in
	// another; empty follows Language.
	KnowledgeLanguage string `json:"knowledgeLanguage,omitempty" graphapi:"nullable"`

	// Voice is structured style, for models that follow fields better than
	// prose. Nil means neutral, medium, no greeting or sign-off.
	Voice *AgentVoice `json:"voice,omitempty" graphapi:"nullable"`

	// Categories are the person's own, beside the fixed vocabulary in
	// AgentCategories, across every source.
	Categories []AgentCategory `json:"categories"`

	// Notifications say how the person learns what the agent did.
	Notifications *AgentNotifications `json:"notifications,omitempty" graphapi:"nullable"`

	// Confirm names tools the person wants asked about before they run,
	// beyond the risk classes. Add-only: nobody can subtract from the floor.
	Confirm []string `json:"confirm"`

	// UnattendedAllowedRisks are the kinds of action that would need the
	// person's word which the agent may take when they are not there to
	// give it: in a schedule, a goal, a night, a message by mail. Empty
	// allows none; with nobody present such a call is refused.
	UnattendedAllowedRisks []UnattendedRisk `json:"unattendedAllowedRisks"`

	// AskModel is the person's choice for their conversations, one of the
	// operator's choices, or empty for the operator's ask model.
	AskModel string `json:"askModel,omitempty" graphapi:"nullable"`

	// SpeechVoice is the voice the person's answers are read aloud in on a
	// voice call, one of the provider's; empty is the server's.
	SpeechVoice string `json:"speechVoice,omitempty" graphapi:"nullable"`

	// DailyTokens is this person's budget, set only by an operator; zero is
	// the server's default.
	DailyTokens int64 `json:"dailyTokens"`

	// DailyCost is the same budget said in money — what the day's calls
	// cost at the provider's prices — for an operator who would rather
	// cap the bill than the tokens. Zero is no limit of its own. Where
	// both are set, whichever runs out first stops the day.
	DailyCost float64 `json:"dailyCost"`

	// OperatorDisabledAt is set by an operator and cannot be cleared by the
	// person; while set the agent does nothing and the page says why.
	OperatorDisabledAt *time.Time `json:"operatorDisabledAt,omitempty" graphapi:"nullable"`

	// DreamFrom and DreamUntil are the hours of the person's night, as
	// "01:00" in their own zone, within which the nightly run works
	// through what arrived and tidies what it knows. Empty means the
	// default window; "00:00" to "00:00" means any time.
	DreamFrom  string `json:"dreamFrom,omitempty" graphapi:"nullable"`
	DreamUntil string `json:"dreamUntil,omitempty" graphapi:"nullable"`

	// DreamedAt is when the nightly run last finished.
	DreamedAt *time.Time `json:"dreamedAt,omitempty" graphapi:"nullable"`

	// DecayedAt is when the arithmetic half of a night last faded this
	// agent's links, and so what the next fade is accounting for. A link
	// loses weight by elapsed time, not by how often the night ran:
	// bootstrapping dreams every few minutes, and a fade per pass put
	// every untouched link on the floor within a day. Empty until the
	// first pass, which fades nothing and only writes this down.
	DecayedAt *time.Time `json:"decayedAt,omitempty" graphapi:"nullable"`

	// FollowUpBackfilledAt is when the one look back over the last 45 days
	// of mail for bills, parcels and notices ran, empty until it has. See
	// internal/agent/follow_up_backfill.go.
	FollowUpBackfilledAt *time.Time `json:"followUpBackfilledAt,omitempty" graphapi:"nullable"`

	// DreamBootstrap says the night runs again as soon as it can, with
	// wider limits, until nothing waits to be read: what a first ingest
	// needs. The night clears it itself.
	DreamBootstrap bool `json:"dreamBootstrap"`

	// SpokeFirstAt is when the agent last started a conversation on its
	// own, and OnboardedAt when its introduction ended, answered or not.
	// IsSuggestionsEnabled is the person's switch for what it suggests on
	// its own (ideas to try, checks of what it remembers), and
	// SpeakFirstSnoozedUntil is how long they asked it to keep quiet. See
	// internal/agent/speak_first.go.
	SpokeFirstAt           *time.Time `json:"spokeFirstAt,omitempty" graphapi:"nullable"`
	OnboardedAt            *time.Time `json:"onboardedAt,omitempty" graphapi:"nullable"`
	IsSuggestionsEnabled   bool       `json:"isSuggestionsEnabled"`
	SpeakFirstSnoozedUntil *time.Time `json:"speakFirstSnoozedUntil,omitempty" graphapi:"nullable"`

	// IsAlertsEnabled is the person's switch for alerts: the agent telling
	// them, unasked, what their mail says they should know now. On for a
	// new agent. See internal/agent/alert.go.
	//
	// AlertQuietStart, AlertQuietEnd and AlertDailyMost are no longer used:
	// a card lands in the feed at any hour and every alert is delivered.
	// They are still answered, read-only, so an older app's settings page
	// loads; the columns go in a later migration.
	IsAlertsEnabled bool   `json:"isAlertsEnabled"`
	AlertQuietStart string `json:"alertQuietStart,omitempty" graphapi:"nullable"`
	AlertQuietEnd   string `json:"alertQuietEnd,omitempty" graphapi:"nullable"`
	AlertDailyMost  int    `json:"alertDailyMost"`

	// FeedDestination is where what the agent says unasked goes: feed, the
	// default, or main, the main conversation as before the feed. See
	// docs/subsystems/feed.md.
	FeedDestination string `json:"feedDestination"`

	// LookAroundWeekday and LookAroundTime are no longer used: the look
	// around is an ordinary goal (migration 0285 made one from each
	// person's setting). They are still answered, read-only, so an older
	// app's settings page loads; the columns go in a later migration.
	LookAroundWeekday string `json:"lookAroundWeekday,omitempty" graphapi:"nullable"`
	LookAroundTime    string `json:"lookAroundTime,omitempty" graphapi:"nullable"`

	// ReportingCurrencyCode is the one currency the person wants totals
	// shown in, an ISO 4217 code. Empty means the currency of their first
	// finance account.
	ReportingCurrencyCode string `json:"reportingCurrencyCode,omitempty" graphapi:"nullable"`

	// TaxFilingStatus is how the person files their tax return, one of
	// TaxFilingStatuses. Empty means they have not said, and the tax
	// year's estimate assumes one from the number of people.
	TaxFilingStatus string `json:"taxFilingStatus,omitempty" graphapi:"nullable"`

	// TaxDocumentToken is the token of the person's tax document address,
	// sealed with the server's secret; empty until the address is first
	// asked for. Never shown: the address is the way in.
	TaxDocumentToken string `json:"-" graphapi:"ignore"`
}

Agent is a person's agent: one per account, made when they turn it on, holding what is about them. What it may reach — a mailbox, later a calendar or an address book — is a source the person grants, and each source carries its own processing policy (see AgentMailbox).

docs/decisions/20260910-agents-belong-to-people.md says why the agent is the person's and not the mailbox's.

func (*Agent) Active

func (self *Agent) Active() bool

Active says whether the agent does anything at all: on, and not switched off by an operator.

func (*Agent) CategoryNames

func (self *Agent) CategoryNames() []string

CategoryNames is the fixed vocabulary followed by the person's own.

func (*Agent) DisplayName

func (self *Agent) DisplayName() string

DisplayName is what to call the agent.

func (*Agent) DreamWindow

func (self *Agent) DreamWindow() (string, string)

DreamWindow is the hours of this person's night, filled in.

func (*Agent) IsAllowedUnattended added in v0.113.0

func (self *Agent) IsAllowedUnattended(unattendedRisks []UnattendedRisk) bool

IsAllowedUnattended says every reason given is one the person allows the agent to act on when they are not there. No reasons is allowed.

func (*Agent) IsFeedFor added in v0.230.0

func (self *Agent) IsFeedFor() bool

IsFeedFor says whether what the agent says unasked goes to its feed, which is the default.

func (*Agent) IsPlaceholder added in v0.170.0

func (self *Agent) IsPlaceholder() bool

IsPlaceholder says the row was made for a person who chats and has never touched their agent: switched off, and not changed since it was made. Everybody who can chat has an agent row, because their conversations and phones hang from it (db.EnsureAgent), and such a row is to everything that asks whether the person uses an agent -- their settings page, the operator's list, a grant of a mailbox -- as if there were none. The first time the person saves anything about their agent the row is changed, and is theirs.

func (*Agent) Validate

func (self *Agent) Validate() error

Validate reports everything wrong with the agent.

type AgentAlert added in v0.82.0

type AgentAlert struct {
	ID      string `json:"id"`
	AgentID string `json:"agentId"`

	// SubjectKey is the sender and what it is about, in the same words
	// each time the same thing comes up, which is how nothing is said
	// twice.
	SubjectKey string `json:"subjectKey"`
	AlertText  string `json:"alertText"`

	// IsUrgent says it could not wait for the morning, and was said at
	// night if that is when it came.
	IsUrgent bool `json:"isUrgent"`

	CandidateIDs   []string  `json:"candidateIds"`
	ConversationID string    `json:"conversationId"`
	MessageID      string    `json:"messageId"`
	SentAt         time.Time `json:"sentAt"`

	// What the alert was about in terms the model's wording does not
	// change, which a mute taken from it names: the burst keys of the
	// bursts it covered, the addresses and domains of the senders, and
	// what the sorting called the messages. Empty for an alert recorded
	// before they were kept.
	CoveredBurstKeys       []string `json:"coveredBurstKeys"`
	CoveredSenderAddresses []string `json:"coveredSenderAddresses"`
	CoveredSenderDomains   []string `json:"coveredSenderDomains"`
	CoveredMailCategories  []string `json:"coveredMailCategories"`
}

AgentAlert is what the agent told the person unasked, as it was said in the main conversation.

type AgentAlertCandidate added in v0.82.0

type AgentAlertCandidate struct {
	ID        string `json:"id"`
	AgentID   string `json:"agentId"`
	MailboxID string `json:"mailboxId"`

	// MailID is the message it is about: the one the sorting judged, or
	// the latest of a burst.
	MailID string `json:"mailId"`

	CandidateKind AlertCandidateKind `json:"candidateKind"`

	// AlertSignal is the sorting's signal for a message, and
	// CandidateReason its line, or what the count saw of a burst.
	AlertSignal     string `json:"alertSignal"`
	CandidateReason string `json:"candidateReason"`

	// BurstKey is a burst's sender address and its subject with the
	// digits taken out; BurstCount how many messages it counted.
	BurstKey   string `json:"burstKey,omitempty"`
	BurstCount int    `json:"burstCount,omitempty"`

	// BudgetKey names a budget crossing, such as
	// "spending-category:<id>:2026-09:at_risk", and becomes the subject
	// key of the alert that tells it, so the same crossing is told once.
	BudgetKey string `json:"budgetKey,omitempty"`

	// What a watched candidate is about, since its item is not stored
	// here: the skill and its watch that found it, the item's id there,
	// who it is from, its title and when it happened, what the judgement
	// called it, the item as the judgement saw it, and where it is.
	WatchedSkillName string     `json:"watchedSkillName,omitempty"`
	WatchedWatchName string     `json:"watchedWatchName,omitempty"`
	WatchedItemID    string     `json:"watchedItemId,omitempty"`
	WatchedSender    string     `json:"watchedSender,omitempty"`
	WatchedTitle     string     `json:"watchedTitle,omitempty"`
	WatchedCategory  string     `json:"watchedCategory,omitempty"`
	WatchedItemAt    *time.Time `json:"watchedItemAt,omitempty"`
	WatchedItemText  string     `json:"watchedItemText,omitempty"`
	WatchedItemURL   string     `json:"watchedItemUrl,omitempty"`

	// What a follow_up candidate is about: the follow-ups (one, or several
	// for the Sunday roundup), what is being told about them, and the
	// subject key of the alert that tells it, which is the follow-up's key
	// and the told state (for a roundup "follow-up-roundup:" and the
	// Sunday's date). The subject key is written once per agent, so the
	// same thing is never made a candidate twice.
	FollowUpIDs        []string               `json:"followUpIds,omitempty"`
	FollowUpToldState  AgentFollowUpToldState `json:"followUpToldState,omitempty"`
	FollowUpSubjectKey string                 `json:"followUpSubjectKey,omitempty"`

	CreatedAt time.Time `json:"createdAt"`

	// AlertID is the alert that told the person about it. DroppedAt and
	// DropReason say when and why it was not told instead.
	AlertID    string     `json:"alertId,omitempty"`
	DroppedAt  *time.Time `json:"droppedAt,omitempty"`
	DropReason string     `json:"dropReason,omitempty"`
}

AgentAlertCandidate is something that might be worth telling the person about, waiting for the alert job to decide.

func (*AgentAlertCandidate) IsWaiting added in v0.82.0

func (self *AgentAlertCandidate) IsWaiting() bool

IsWaiting says the candidate has been neither told nor dropped.

type AgentAlertMute added in v0.82.0

type AgentAlertMute struct {
	ID      string `json:"id"`
	AgentID string `json:"agentId"`

	// MuteScope is what MuteTarget is: an address, a domain, a subject
	// key or a kind, in lower case.
	MuteScope  AlertMuteScope `json:"muteScope"`
	MuteTarget string         `json:"muteTarget"`

	// AlertID is the alert the person muted from, when they did; empty
	// when they named the target themselves.
	AlertID string `json:"alertId"`

	CreatedAt time.Time `json:"createdAt"`
}

AgentAlertMute is the person's "don't tell me about these": a candidate or an alert that matches it is dropped, saying it was muted.

type AgentAlerts added in v0.82.0

type AgentAlerts struct {
	Enabled bool `json:"enabled"`
}

AgentAlerts is the alerting policy for one source.

type AgentAttachment

type AgentAttachment struct {
	ID             string    `json:"id"`
	CreatedAt      time.Time `json:"createdAt"`
	AgentID        string    `json:"agentId"`
	ConversationID string    `json:"conversationId,omitempty"`
	MessageID      string    `json:"messageId,omitempty"`
	Name           string    `json:"name"`
	ContentType    string    `json:"contentType"`
	Size           int64     `json:"size"`
	Text           string    `json:"-"`

	// FinanceTransactionID is the finance transaction the file was
	// uploaded to as its receipt, empty for any other file.
	FinanceTransactionID string `json:"financeTransactionId,omitempty" graphapi:"nullable"`

	// IsTaxDocument says the file was handed in as a paystub or a tax
	// form: it is kept while it waits to be read, and its text, which
	// holds the person's taxpayer number, is never kept in Text.
	IsTaxDocument bool `json:"isTaxDocument,omitempty"`

	// PhotoID is the photo of the person's library the file was copied from
	// to be read as a document, empty for any other file.
	PhotoID string `json:"photoId,omitempty"`

	// Caption is the line sent with a file sent to the person's main chat,
	// and SentBy who sent it there: a program over MCP by the name it was
	// approved under, another conversation, a reminder. Both empty for any
	// other file.
	Caption string `json:"caption,omitempty"`
	SentBy  string `json:"sentBy,omitempty"`

	// MainChatQueuedAt is when a file sent to the main chat was sent, while
	// it waits for a turn running there to end; nil once it is posted, and
	// for any other file.
	MainChatQueuedAt *time.Time `json:"-"`

	// IsRemoved says the file went with the account that held it: the chat
	// message it came with is kept, the file is not, and a screen says so
	// where the file was.
	IsRemoved bool `json:"isRemoved,omitempty"`

	// AudioDurationMS and AudioWaveform are the facts of a voice message's
	// recording, zero and empty on any other file. The waveform is
	// VoiceMessageWaveformLevelCount peak levels, 0 to 255 each, in base64,
	// for drawing the bubble without fetching the sound.
	AudioDurationMS int64  `json:"audioDurationMS,omitempty"`
	AudioWaveform   string `json:"audioWaveform,omitempty"`
}

AgentAttachment is a file a person handed their agent: the row, with the bytes in the spool under the same id. Text is what could be read out of it as text, for the model; empty for a picture or a video.

type AgentAudience

type AgentAudience string

AgentAudience names the kinds of run a memory is addressed to.

const (
	AudienceAsk       AgentAudience = "ask"
	AudienceTriage    AgentAudience = "triage"
	AudienceResearch  AgentAudience = "research"
	AudienceReply     AgentAudience = "reply"
	AudienceSummaries AgentAudience = "summaries"
)

The audiences: the conversation, and each kind of run that reads memories.

type AgentAutoReply

type AgentAutoReply struct {
	Enabled bool `json:"enabled"`

	// Guidance is when and how to answer, in the person's words.
	Guidance string `json:"guidance,omitempty" graphapi:"nullable"`

	// Scope is known (contacts only), everyone, or list (Allow only).
	Scope string `json:"scope,omitempty" graphapi:"nullable"`

	// Allow and Never are addresses or domains: the list for scope list,
	// and the ones never answered whatever the scope.
	Allow []string `json:"allow,omitempty" graphapi:"nullable"`
	Never []string `json:"never,omitempty" graphapi:"nullable"`

	// Categories restricts answering to these; empty means any.
	Categories []string `json:"categories,omitempty" graphapi:"nullable"`

	// When is always, outsideHours (see Hours), or whenAway (only while the
	// mailbox's out-of-office reply is on).
	When  string      `json:"when,omitempty" graphapi:"nullable"`
	Hours *AgentHours `json:"hours,omitempty" graphapi:"nullable"`

	// HoldMinutes is how long a reply waits in Drafts before it is sent,
	// during which the person can cancel or take it over. Zero means ten.
	HoldMinutes int `json:"holdMinutes,omitempty" graphapi:"nullable"`

	// DailyLimit is the most replies sent from this source in a day. Zero
	// means twenty.
	DailyLimit int `json:"dailyLimit,omitempty" graphapi:"nullable"`
}

AgentAutoReply is the policy under which the agent answers mail in this source on the person's behalf. Whether a given message is answered is the refusal ladder's decision, in the reply run; this is what the person set.

func (*AgentAutoReply) EffectiveDailyLimit

func (self *AgentAutoReply) EffectiveDailyLimit() int

EffectiveDailyLimit resolves the zero value.

func (*AgentAutoReply) EffectiveHoldMinutes

func (self *AgentAutoReply) EffectiveHoldMinutes() int

EffectiveHoldMinutes resolves the zero value.

type AgentBackgroundWork added in v0.81.0

type AgentBackgroundWork struct {
	ID      string `json:"id"`
	AgentID string `json:"agentId"`

	// ConversationID is the conversation to wake when it finishes; empty
	// when it was started from the API, which wakes nothing.
	ConversationID string                     `json:"conversationId"`
	WorkKind       AgentBackgroundWorkKind    `json:"workKind"`
	Title          string                     `json:"title"`
	WorkRequest    AgentBackgroundWorkRequest `json:"workRequest"`

	// IsPersonPresent says the turn that started it had the person
	// present. Kept for the record: work started by any turn wakes its
	// conversation, with the person there or not.
	IsPersonPresent bool                      `json:"isPersonPresent"`
	WorkStatus      AgentBackgroundWorkStatus `json:"workStatus"`

	// ResultText is the survey's report or the subagent's answer, RunIDs
	// every run it made, and ErrorMessage why it failed.
	ResultText   string   `json:"resultText"`
	RunIDs       []string `json:"runIds"`
	ErrorMessage string   `json:"errorMessage"`

	CreatedAt  time.Time  `json:"createdAt"`
	StartedAt  *time.Time `json:"startedAt,omitempty"`
	FinishedAt *time.Time `json:"finishedAt,omitempty"`
	WokenAt    *time.Time `json:"wokenAt,omitempty"`

	// WakeClaimedAt is when an instance took the waking of the
	// conversation for it, so that no other does too.
	WakeClaimedAt *time.Time `json:"wakeClaimedAt,omitempty"`
}

AgentBackgroundWork is one piece of background work.

type AgentBackgroundWorkKind added in v0.81.0

type AgentBackgroundWorkKind string

AgentBackgroundWorkKind is what a piece of background work is.

const (
	// BackgroundWorkSurvey is a survey of an area of the graph.
	BackgroundWorkSurvey AgentBackgroundWorkKind = "survey"
	// BackgroundWorkSubagent is a piece of work handed to a run of its own.
	BackgroundWorkSubagent AgentBackgroundWorkKind = "subagent"
)

type AgentBackgroundWorkRequest added in v0.81.0

type AgentBackgroundWorkRequest struct {
	Question  string `json:"question,omitempty"`
	ScopePath string `json:"scopePath,omitempty"`

	Prompt            string   `json:"prompt,omitempty"`
	AllowedToolNames  []string `json:"allowedToolNames,omitempty"`
	ReadOnlyToolNames []string `json:"readOnlyToolNames,omitempty"`
	IsReadOnly        bool     `json:"isReadOnly,omitempty"`

	// StartingTurnPermissions is what the turn that started a subagent
	// could do. It runs held to them, so that it never does more than
	// that turn could, whatever the person may do by the time it runs.
	StartingTurnPermissions *EffectivePermissions `json:"startingTurnPermissions,omitempty"`
}

AgentBackgroundWorkRequest is what was asked: a survey's question and scope, or a subagent's prompt and what it may use, which is fixed when it is started so that a run after a restart has the same tools.

type AgentBackgroundWorkStatus added in v0.81.0

type AgentBackgroundWorkStatus string

AgentBackgroundWorkStatus is where a piece of background work is.

const (
	BackgroundWorkQueued  AgentBackgroundWorkStatus = "queued"
	BackgroundWorkRunning AgentBackgroundWorkStatus = "running"
	BackgroundWorkDone    AgentBackgroundWorkStatus = "done"
	BackgroundWorkFailed  AgentBackgroundWorkStatus = "failed"
	// BackgroundWorkStopped was stopped by the person or the agent before
	// it finished. It wakes nothing: whoever stopped it knows.
	BackgroundWorkStopped AgentBackgroundWorkStatus = "stopped"
)

func (AgentBackgroundWorkStatus) IsFinished added in v0.81.0

func (self AgentBackgroundWorkStatus) IsFinished() bool

IsFinished says whether the work will not run again.

type AgentBilledDay added in v0.165.0

type AgentBilledDay struct {
	ProviderName string    `json:"providerName"`
	BilledOn     time.Time `json:"billedOn"`
	Model        string    `json:"model"`

	// BilledAmount is in CurrencyCode and is not rounded to cents.
	BilledAmount float64 `json:"billedAmount"`
	CurrencyCode string  `json:"currencyCode"`
}

AgentBilledDay is what a provider billed for one model on one day (UTC). Model is TeaNode's name for it, without a snapshot date.

type AgentBilledPrice added in v0.165.0

type AgentBilledPrice struct {
	Model     string `json:"model"`
	TokenKind string `json:"tokenKind"`

	// ConfiguredPerMillion and BilledPerMillion are in the configured
	// currency per million tokens.
	ConfiguredPerMillion float64 `json:"configuredPerMillion"`
	BilledPerMillion     float64 `json:"billedPerMillion"`

	// DayCount is how many days of the bill the billed price rests on.
	DayCount int `json:"dayCount"`

	// IsPattern says the configured price comes from an entry whose model
	// is a pattern covering other models too. Such an entry is reported
	// and never changed.
	IsPattern bool `json:"isPattern"`
}

AgentBilledPrice is one price the daily check set beside the provider's bill: what the configuration says for a model and kind of token, and what the bill implies.

type AgentBillingCheck added in v0.165.0

type AgentBillingCheck struct {
	ProviderName string    `json:"providerName"`
	CheckedAt    time.Time `json:"checkedAt"`

	// ErrorMessage is why the bill could not be read, such as a refused
	// key. Empty when it was read.
	ErrorMessage string `json:"errorMessage"`

	Compared []AgentBilledPrice `json:"compared"`
	Changed  []AgentPriceChange `json:"changed"`
}

AgentBillingCheck is what the last check of one provider's prices against its bill did.

type AgentCategory

type AgentCategory struct {
	Name        string `json:"name"`
	Description string `json:"description" graphapi:"nullable"`
}

AgentCategory is a category the person declared, with the one-line description the sorting prompt is given.

type AgentChannel

type AgentChannel struct {
	ID         string           `json:"id"`
	CreatedAt  time.Time        `json:"createdAt"`
	ModifiedAt time.Time        `json:"modifiedAt"`
	AgentID    string           `json:"agentId"`
	Kind       AgentChannelKind `json:"kind"`

	// Token is the bot's, sealed with the server secret; never shown.
	Token string `json:"-"`

	// BotName is what the app calls the bot, once the bot has been seen.
	BotName string `json:"botName,omitempty"`

	// LinkedID is the chat (Telegram) or the user (Discord) linked to the
	// bot; LinkedName what it was called when it linked. Empty until the
	// code has been sent from a chat.
	LinkedID   string `json:"linkedId,omitempty"`
	LinkedName string `json:"linkedName,omitempty"`

	// LinkedSenderID is who sent the code, and LinkedSenderName what the
	// app calls them. The bot answers that person and nobody else: a chat
	// is a room, and in a group every member of it -- and everybody they
	// invite -- would otherwise be speaking with the owner's voice and
	// answering the agent's confirmations.
	//
	// Empty for a bot linked before this was kept, which is refused rather
	// than trusted.
	LinkedSenderID   string `json:"linkedSenderId,omitempty"`
	LinkedSenderName string `json:"linkedSenderName,omitempty"`

	// LinkCode is what a chat sends the bot to become the linked one; a
	// new one is drawn whenever the link is dropped.
	LinkCode string `json:"linkCode,omitempty"`

	Enabled    bool       `json:"enabled"`
	LastError  string     `json:"lastError,omitempty"`
	LastSeenAt *time.Time `json:"lastSeenAt,omitempty"`

	// ClaimedBy is the server instance running the bot, and ClaimedUntil
	// when its claim lapses unless renewed: one instance runs a bot.
	ClaimedBy    string     `json:"claimedBy,omitempty"`
	ClaimedUntil *time.Time `json:"claimedUntil,omitempty"`

	// RelayedThrough is the last message of the main conversation the bot
	// has looked at for the agent's own turns to send on to the chat.
	RelayedThrough string `json:"-"`
}

AgentChannel is a person's bot in a chat app, through which they talk to their agent's primary conversation: the bot's token, sealed, and the one chat linked to it with a code.

func (*AgentChannel) Linked

func (self *AgentChannel) Linked() bool

Linked says whether a chat has linked itself to the bot.

type AgentChannelKind

type AgentChannelKind string

AgentChannelKind is a chat app a person may talk to their agent from.

const (
	AgentChannelTelegram AgentChannelKind = "telegram"
	AgentChannelDiscord  AgentChannelKind = "discord"
)

type AgentChunk

type AgentChunk struct {
	ID         string    `json:"id"`
	AgentID    string    `json:"agentId"`
	DocumentID string    `json:"documentId"`
	SourceID   string    `json:"sourceId"`
	Number     int       `json:"number"`
	Text       string    `json:"text"`
	Segmented  bool      `json:"segmented"`
	CreatedAt  time.Time `json:"createdAt"`
}

AgentChunk is a slice of a document, small enough to rank.

type AgentChunkPost added in v0.202.0

type AgentChunkPost struct {
	DocumentID string

	// ClockMinutes is the post's clock as minutes after midnight, in
	// whatever zone the unit writes its clocks in.
	ClockMinutes int
	Author       string
}

AgentChunkPost is one post in a chat unit's text, a line that begins "15:04 author: ": the clock it was written at and who wrote it.

type AgentConnection

type AgentConnection struct {
	ID         string    `json:"id"`
	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`
	AgentID    string    `json:"agentId"`
	ServerName string    `json:"serverName"`

	Status AgentConnectionStatus `json:"status"`

	// Credential is the person's own credential for a user-authenticated
	// server; Tokens the JSON of an OAuth authorization; Pending the state
	// and verifier of a flow under way. All sealed.
	Credential string `json:"-"`
	Tokens     string `json:"-"`
	Pending    string `json:"-"`

	LastError       string     `json:"lastError,omitempty"`
	LastConnectedAt *time.Time `json:"lastConnectedAt,omitempty"`
}

AgentConnection is a person's own way into a connected server the operator declared. The sealed fields hold the credential or the tokens and are never returned to anybody.

type AgentConnectionStatus

type AgentConnectionStatus string

AgentConnectionStatus is where a person's connection to a server stands.

const (
	ConnectionPending      AgentConnectionStatus = "pending"
	ConnectionConnected    AgentConnectionStatus = "connected"
	ConnectionError        AgentConnectionStatus = "error"
	ConnectionDisconnected AgentConnectionStatus = "disconnected"
)

The statuses: pending while an authorization is under way; connected; error with the reason; disconnected by the person.

type AgentConversation

type AgentConversation struct {
	ID         string                `json:"id"`
	CreatedAt  time.Time             `json:"createdAt"`
	ModifiedAt time.Time             `json:"modifiedAt"`
	AgentID    string                `json:"agentId"`
	MailboxID  string                `json:"mailboxId,omitempty"`
	Kind       AgentConversationKind `json:"kind"`
	Title      string                `json:"title"`

	// Summary is a line on what the conversation is about, rewritten by
	// the model as it goes; TitledBy is "person" once they named it
	// themselves, after which the model leaves the title alone.
	Summary  string `json:"summary,omitempty"`
	TitledBy string `json:"titledBy,omitempty"`

	// DescribedAt is when the title and summary were last written; a
	// conversation with something said since, once it has gone quiet, is
	// described again.
	DescribedAt *time.Time `json:"describedAt,omitempty"`

	// RememberedThrough is the last message a run that files what the
	// conversation taught has read, and RememberedAt when it last ran.
	// The identifier rather than the time, so a run that dies re-reads
	// from where it was rather than skipping what arrived meanwhile.
	RememberedThrough string     `json:"-"`
	RememberedAt      *time.Time `json:"rememberedAt,omitempty"`

	// JobID, JobKind and SubjectID say which run this is the record of.
	JobID     string `json:"jobId,omitempty"`
	JobKind   string `json:"jobKind,omitempty"`
	SubjectID string `json:"subjectId,omitempty"`

	// Surface is where a conversation is held: drawer, page, cli, api, mail.
	Surface string `json:"surface,omitempty"`

	ArchivedAt *time.Time `json:"archivedAt,omitempty"`
	LastAt     time.Time  `json:"lastAt"`

	// CompactedThrough is the last message the latest compaction note
	// stands in for; the verbatim transcript resumes after it. The note
	// itself is a later message with the compaction role.
	CompactedThrough string `json:"compactedThrough,omitempty"`

	// Goal is the standing instruction on this conversation, in the
	// person's words: what the agent keeps working toward across turns of
	// its own until it is met or they clear it. Empty means there is
	// none, and GoalState is empty with it.
	//
	// GoalNote is the agent's last word on where it is -- a sentence or
	// two, shown beside the conversation and, while it waits, above the
	// composer. GoalNextAt is when the agent takes its next turn on its
	// own; nothing is scheduled while it waits for the person or once the
	// goal is met.
	Goal       string         `json:"goal,omitempty"`
	GoalTitle  string         `json:"goalTitle,omitempty"`
	GoalState  AgentGoalState `json:"goalState,omitempty"`
	GoalNote   string         `json:"goalNote,omitempty"`
	GoalNextAt *time.Time     `json:"goalNextAt,omitempty"`
	// GoalTitle is what a goal is called in a list: a few words. Goal is
	// then the description, what it is for and what done looks like.
	//
	// GoalSetAt is when the goal was set, for the panel that says since
	// when the agent has been at it.
	GoalSetAt *time.Time `json:"goalSetAt,omitempty"`

	// GoalSurfacedAt is when a goal that came to need the person was said
	// in the main conversation; nil while it waits to be, and for a goal
	// that never needed them.
	GoalSurfacedAt *time.Time `json:"goalSurfacedAt,omitempty"`

	// GoalOriginConversationID is the conversation the goal was asked for
	// in, when it was asked for in one.
	GoalOriginConversationID string `json:"goalOriginConversationId,omitempty"`

	// GoalTimes are the times the goal takes its turns at, chosen by the
	// person or for them: each a cron line in their zone ("30 7 * * 1-5"),
	// or "@at" and a moment, which is dropped once it has passed. A goal
	// with times, or with mail it waits for, takes its turns then and not
	// at a cadence of its own.
	GoalTimes []string `json:"goalTimes"`

	// GoalMailConditions make the goal take a turn when a message arrives
	// that passes every one of them, in a mailbox the agent was given. They
	// are the tests a mailbox rule makes.
	GoalMailConditions []MailboxRuleCondition `json:"goalMailConditions"`

	// GoalMailArrivals are the messages that passed since the goal's last
	// turn, for the next one to be told about. Kept off the API: they are
	// the turn's to read, by the id each carries.
	GoalMailArrivals []AgentGoalArrival `json:"-"`

	// GoalWrittenBy is who wrote the goal's description: the person, the
	// agent through a tool, or TeaNode for the goals a switch starts (the
	// daily brief, the asset estimates). A goal's turn runs with nobody
	// watching and its description arrives in the turn's own message, the
	// most trusted thing in a conversation: right for the person's standing
	// instruction, and wrong for one the agent wrote on the strength of
	// something it read. Empty is taken to be the agent.
	GoalWrittenBy string `json:"goalWrittenBy,omitempty"`

	// GoalEmoji is the one emoji shown before the goal's title, chosen by
	// the agent that started it or by the person. Empty for a goal that
	// has none, which is shown with one chosen from its words. See
	// migration 0286.
	GoalEmoji string `json:"goalEmoji,omitempty"`

	// IsGoalNotifiedWhenPosted makes the first card each turn of the goal
	// posts send one quiet notification, "<title> is ready", though its
	// cards are not urgent.
	IsGoalNotifiedWhenPosted bool `json:"isGoalNotifiedWhenPosted"`

	// ChatID is the chat a conversation of the kind chat is the member's
	// own for; empty for every other.
	ChatID string `json:"-"`

	// Chat is the chat as this member sees it, filled in by the operations
	// that list and read conversations; null unless the kind is chat.
	Chat *ChatView `json:"chat,omitempty"`
}

AgentConversation is a conversation or a run transcript.

func (*AgentConversation) HasChatWords added in v0.170.0

func (self *AgentConversation) HasChatWords(words string) bool

HasChatWords says whether a chat's title or one of its members' names or usernames holds the words, in any case: how a chat is found by a search, since what was said in it is not searched. It is false for anything that is not a chat, or a chat whose title and members have not been described.

func (*AgentConversation) IsChat added in v0.170.0

func (self *AgentConversation) IsChat() bool

IsChat says whether a conversation is a member's own for a chat.

func (*AgentConversation) IsGoal added in v0.111.0

func (self *AgentConversation) IsGoal() bool

IsGoal says whether a conversation is a goal's own.

func (*AgentConversation) IsGoalOnSetTimes added in v0.232.0

func (self *AgentConversation) IsGoalOnSetTimes() bool

IsGoalOnSetTimes is whether the goal takes its turns at times somebody chose, or when mail it waits for arrives, rather than at a cadence the agent keeps for itself.

type AgentConversationKind

type AgentConversationKind string

AgentConversationKind tells a person's conversations from a run's record.

const (
	AgentConversationMain  AgentConversationKind = "main"
	AgentConversationNamed AgentConversationKind = "named"
	AgentConversationRun   AgentConversationKind = "run"
	AgentConversationGoal  AgentConversationKind = "goal"
	AgentConversationChat  AgentConversationKind = "chat"
)

The kinds: the one continuous conversation, a named one kept apart, the transcript of a run with nobody present, a goal's own conversation, where the turns the agent takes toward it run out of the person's sight, and a chat: a member's own conversation for a chat with people in it, which shows what they said and holds only what the member's own agent did there.

type AgentDocument

type AgentDocument struct {
	ID         string `json:"id"`
	AgentID    string `json:"agentId"`
	SourceID   string `json:"sourceId"`
	ExternalID string `json:"externalId"`

	Kind  AgentDocumentKind `json:"kind"`
	Title string            `json:"title"`
	URL   string            `json:"url,omitempty"`

	HappenedAt *time.Time `json:"happenedAt,omitempty"`
	ModifiedAt *time.Time `json:"modifiedAt,omitempty"`

	Hash       string `json:"-"`
	Bytes      int64  `json:"bytes"`
	StorageKey string `json:"-"`

	Metadata map[string]any `json:"metadata,omitempty"`
	Private  bool           `json:"private"`

	// SeenAt is when the source last said it still had this. A pass that
	// walks the whole tree deletes what it did not see, so this is what
	// tells a thing that is gone from one that has merely not changed.
	SeenAt *time.Time `json:"-"`

	CreatedAt time.Time `json:"createdAt"`
}

AgentDocument is one thing read from a source.

func (*AgentDocument) Author

func (self *AgentDocument) Author() string

Author is who wrote it, where the document says.

func (*AgentDocument) Channel

func (self *AgentDocument) Channel() string

Channel is where the record this file came with was posted, and Thread is which conversation in it, where the source said.

The two things that tell one screenshot from the fifty thousand beside it, so they are asked for in three places -- the night deciding what to open, the page showing a fact's evidence, and the agent looking at a picture again -- and are read off the document here rather than spelled out at each of them.

func (*AgentDocument) Checkout added in v0.58.9

func (self *AgentDocument) Checkout() string

Checkout is the checkout a commit was read from, as a directory relative to its source, where the document says.

func (*AgentDocument) Cite

func (self *AgentDocument) Cite() string

Cite is how a document is named in an answer, with the warning that it came from somewhere only the person can see.

func (*AgentDocument) ContentType

func (self *AgentDocument) ContentType() string

ContentType is what kind of file this is, where the source said: the media type without whatever parameters came with it, lowered, because what asks is code deciding whether anything here can open it.

func (*AgentDocument) Declined

func (self *AgentDocument) Declined() string

Declined is why the night decided against opening this, and "" where it has not decided or decided to.

Kept rather than acted on, so that a person who disagrees with what the agent passed over can read the reason and put the file back. Declined is not read: nothing has read it, and the two are separate marks so that clearing one leaves the other alone.

func (*AgentDocument) Thread

func (self *AgentDocument) Thread() string

Thread is which conversation in the channel this came from.

type AgentDocumentKind

type AgentDocumentKind string

AgentDocumentKind is what one thing from a source is.

const (
	DocumentFile AgentDocumentKind = "file"

	// DocumentAttachment is a picture or a file a record came with: a
	// document whose meaning is in its bytes rather than in its text,
	// kept in object storage under its hash and read, if anything here
	// can read it, later.
	DocumentAttachment AgentDocumentKind = "attachment"
	DocumentPage       AgentDocumentKind = "page"
	DocumentPost       AgentDocumentKind = "post"
	DocumentMessage    AgentDocumentKind = "message"
	DocumentCommit     AgentDocumentKind = "commit"
	DocumentChat       AgentDocumentKind = "chat"
	DocumentRequest    AgentDocumentKind = "request"
	DocumentJournal    AgentDocumentKind = "journal"
)

The kinds of document.

type AgentDraft

type AgentDraft struct {
	Text  string `json:"text"`
	Model string `json:"model"`
	RunID string `json:"runId"`
}

AgentDraft is what the agent wrote: the body of a reply, and the run that wrote it.

type AgentDraftRequest

type AgentDraftRequest struct {
	Agent        *Agent
	Owner        *User
	Mailbox      *Mailbox
	Mail         *Mail
	Instructions string
}

AgentDraftRequest asks the agent to write a reply the person will read before sending: to this message, in this mailbox, doing what the instructions say.

type AgentDream

type AgentDream struct {
	ID         string     `json:"id"`
	AgentID    string     `json:"agentId"`
	StartedAt  time.Time  `json:"startedAt"`
	FinishedAt *time.Time `json:"finishedAt,omitempty"`

	// JobID is the job that ran it. Every model call a dream makes is a
	// run tagged with that job, so a dream's runs can be listed and each
	// opened, as a sorting run can.
	JobID string `json:"jobId,omitempty"`

	Digested  int `json:"digested"`
	Filed     int `json:"filed"`
	Merged    int `json:"merged"`
	Rewritten int `json:"rewritten"`
	Moved     int `json:"moved"`
	Dormant   int `json:"dormant"`
	Embedded  int `json:"embedded"`

	// What the two halves of the night did. Strengthened is links
	// reweighted by what was used together, which is arithmetic and
	// happens every night; Associated is links the night found by
	// walking the graph and asking, which is the only phase that adds a
	// relation nobody typed.
	Strengthened int `json:"strengthened"`
	Associated   int `json:"associated"`

	// Rehearsed is how many questions it asked itself, Gaps how many of
	// those memory could not answer, and Unknown how many it could not
	// try -- no embedding model, no budget left, or a model that did not
	// answer. The gaps are in Proposals, as questions, because filling
	// one means deciding what the answer is and a run with nobody present
	// must not do that.
	//
	// Three numbers rather than two because every failure used to count
	// as answered, so a night whose model was unreachable read as a night
	// with nothing missing.
	Rehearsed int `json:"rehearsed"`
	Gaps      int `json:"gaps"`
	Unknown   int `json:"unknown"`

	// Revised is what an older build of this program wrote that this one
	// went back over and struck. A graph outlives its code, and this is
	// the number that says a newer build is cleaning up after an older
	// one rather than the person having to.
	Revised int `json:"revised"`

	// OverviewsWritten is how many pages had their overview written, or
	// written again because what it was written from had changed.
	OverviewsWritten int `json:"overviewsWritten"`

	// ThemesMade is how many theme pages the night made for groups it
	// found, ThemesUpdated how many it kept whose members changed or that
	// it moved, and ReflectionsWritten how many observations it wrote over
	// its themes.
	ThemesMade         int `json:"themesMade"`
	ThemesUpdated      int `json:"themesUpdated"`
	ReflectionsWritten int `json:"reflectionsWritten"`

	// JournalDaysWritten and JournalPeriodsWritten are the narratives of
	// journal days, and of weeks, months and years, the night wrote.
	// JournalNarrativesRefused is the answers it threw away because they
	// named a record that was not in what it was given, or were not an
	// answer at all.
	JournalDaysWritten       int `json:"journalDaysWritten"`
	JournalPeriodsWritten    int `json:"journalPeriodsWritten"`
	JournalNarrativesRefused int `json:"journalNarrativesRefused"`

	// Backlog is how much was still waiting when it stopped. A cap here
	// is pacing, never truncation: what is not read tonight is read
	// tomorrow, and this is the number that says how many nights that is.
	Backlog int `json:"backlog"`

	// Coarse says this night worked a stretch at a time rather than an
	// item at a time, because the backlog was larger than anybody would
	// wait for. Coverage is still total; only the detail is less, and a
	// later night can redo the stretch finely.
	Coarse bool `json:"coarse"`

	Proposals []DreamProposal `json:"proposals"`

	Tokens    int64  `json:"tokens"`
	Notes     string `json:"notes,omitempty"`
	LastError string `json:"lastError,omitempty"`

	// Cost is what the dream's model calls cost, at the prices the
	// providers are configured with, and Currency what it is said in.
	// Worked out from its runs when the dreams are listed, never stored.
	Cost     float64 `json:"cost"`
	Currency string  `json:"currency,omitempty"`
}

AgentDream is what the nightly run did, one row a night.

Kept and shown because a run that works while nobody is watching has to be able to say what it did, and because the backlog below is how the person decides whether to give it more of the day or let it work coarsely.

func (*AgentDream) Describe

func (self *AgentDream) Describe() string

Describe is a night in a sentence, for the page and the command line.

type AgentEdge

type AgentEdge struct {
	AgentID  string            `json:"agentId"`
	FromID   string            `json:"fromId"`
	ToID     string            `json:"toId"`
	Relation AgentEdgeRelation `json:"relation"`
	Weight   float32           `json:"weight"`

	// Status separates what the agent may assert from what it may only
	// wonder about. The nightly walk guesses a link from two pages being
	// two steps apart, which is a hypothesis; the person drawing one in
	// the dashboard is not. Without the distinction the agent said both
	// in the same voice.
	Status AgentEdgeStatus `json:"status"`

	Evidence  []Evidence `json:"evidence"`
	CreatedAt time.Time  `json:"createdAt"`

	// Note is what this particular link is about, in the person's own
	// terms: "wrote the payload angle check", "since 2019", "her
	// daughter". The relation says what sort of link it is and this says
	// which one.
	//
	// Without it an edge is a word. A model shown "people/alice-chen
	// works_on projects/portal" knows there is a link and nothing about
	// it; shown "Alice Chen works on Portal — led the API rewrite" it
	// knows something worth having.
	Note string `json:"note,omitempty"`

	// HappenedAt is when the link was true and UsedAt when it was last
	// wanted. A join that has gone stale sinks rather than being
	// forgotten: somebody who left a project two years ago did work on
	// it, and that is no longer the first thing to say about them.
	HappenedAt *time.Time `json:"happenedAt,omitempty"`
	UsedAt     *time.Time `json:"usedAt,omitempty"`

	// FromPath and ToPath are filled when an edge is read for display or
	// for a prompt, where a path means something and an identifier does
	// not. Not stored. FromName and ToName likewise, so that an edge can
	// be read as a sentence about two things rather than two paths.
	FromPath string        `json:"fromPath,omitempty"`
	ToPath   string        `json:"toPath,omitempty"`
	FromName string        `json:"fromName,omitempty"`
	ToName   string        `json:"toName,omitempty"`
	FromKind AgentNodeKind `json:"fromKind,omitempty"`
	ToKind   AgentNodeKind `json:"toKind,omitempty"`
}

AgentEdge joins two pages.

func (*AgentEdge) Phrase

func (self *AgentEdge) Phrase(outward, stale bool) string

Phrase is how this relation reads from one end, in the tense the link deserves.

func (*AgentEdge) Proposed

func (self *AgentEdge) Proposed() bool

Proposed says whether this link is the agent's own guess rather than something somebody stated.

func (*AgentEdge) Sentence

func (self *AgentEdge) Sentence(fromPath string, stale bool) string

Sentence is the edge as something to read, from the end given.

"Alice Chen works on Portal — led the API rewrite". The names rather than the paths, because the sentence is for a reader; the path is carried beside it for whoever wants to follow the link.

A proposed link is hedged in both directions: "perhaps" in front so the claim is never made flat, and who guessed it at the end so a reader knows whom to disagree with.

type AgentEdgeRelation

type AgentEdgeRelation string

AgentEdgeRelation is what one page is to another.

const (
	EdgePartOf     AgentEdgeRelation = "part_of"
	EdgeWorksOn    AgentEdgeRelation = "works_on"
	EdgeMemberOf   AgentEdgeRelation = "member_of"
	EdgeKnows      AgentEdgeRelation = "knows"
	EdgeOwns       AgentEdgeRelation = "owns"
	EdgeUses       AgentEdgeRelation = "uses"
	EdgeLocatedIn  AgentEdgeRelation = "located_in"
	EdgeRelatedTo  AgentEdgeRelation = "related_to"
	EdgeDecidedIn  AgentEdgeRelation = "decided_in"
	EdgeAboutPlace AgentEdgeRelation = "about"

	// EdgeDependsOn is a build-time dependency of one checkout on another,
	// read from its build files by a program. Not uses: that one is the
	// model's word for people and their tools, and a map of what builds on
	// what has to be told apart from it.
	EdgeDependsOn AgentEdgeRelation = "depends_on"
)

The relations. PartOf duplicates what the path already says, so that a query can walk the hierarchy without parsing strings.

type AgentEdgeStatus

type AgentEdgeStatus string

AgentEdgeStatus is how far a link may be asserted: something somebody stated, or something the agent worked out for itself.

const (
	EdgeStated   AgentEdgeStatus = "stated"
	EdgeProposed AgentEdgeStatus = "proposed"
)

The statuses. Stated is the default and what every writer but the nightly walk produces, so an empty status read out of an older row means stated.

type AgentEvaluationAnswer added in v0.61.0

type AgentEvaluationAnswer struct {
	ID            string    `json:"id"`
	RunID         string    `json:"runId"`
	QuestionID    string    `json:"questionId"`
	CreatedAt     time.Time `json:"createdAt"`
	AnswerFrom    string    `json:"answerFrom"`
	AnswerVerdict string    `json:"answerVerdict"`
	VerdictReason string    `json:"verdictReason"`
	AnswerText    string    `json:"answerText"`
	Cost          float64   `json:"cost"`
}

AgentEvaluationAnswer is one question answered from one source.

type AgentEvaluationQuestion added in v0.61.0

type AgentEvaluationQuestion struct {
	ID         string    `json:"id"`
	AgentID    string    `json:"agentId"`
	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`

	QuestionKind   EvaluationQuestionKind `json:"questionKind"`
	QuestionText   string                 `json:"questionText"`
	ExpectedAnswer string                 `json:"expectedAnswer"`

	// OutdatedAnswer is what was true once, for a question about
	// something that changed; an answer giving it is stale.
	OutdatedAnswer string `json:"outdatedAnswer,omitempty" graphapi:"nullable"`

	QuestionState EvaluationQuestionState `json:"questionState"`

	// SourceFactIDs are the facts a drafted question came from; empty for
	// one the person supplied.
	SourceFactIDs []string `json:"sourceFactIds"`

	// IsAnswerFiledAfter says the answer was filed into memory after the
	// question was written: the question is easy now, and its score is
	// reported apart.
	IsAnswerFiledAfter bool `json:"isAnswerFiledAfter"`

	ConversationID string     `json:"conversationId,omitempty" graphapi:"nullable"`
	AnsweredAt     *time.Time `json:"answeredAt,omitempty" graphapi:"nullable"`
}

AgentEvaluationQuestion is one question of the person's memory check: what was asked, the answer the person stands behind, and how it was settled. See docs/planning/agent-speaks-first-execplan.md.

type AgentEvaluationRun added in v0.61.0

type AgentEvaluationRun struct {
	ID         string     `json:"id"`
	AgentID    string     `json:"agentId"`
	StartedAt  time.Time  `json:"startedAt"`
	FinishedAt *time.Time `json:"finishedAt,omitempty" graphapi:"nullable"`

	// QuestionCount is how many questions the run answered.
	QuestionCount int     `json:"questionCount"`
	Cost          float64 `json:"cost"`

	// SourceScores is the score from each source, in the order memory,
	// sources, both.
	SourceScores []*EvaluationSourceScore `json:"sourceScores"`
}

AgentEvaluationRun is one grading of the agent against the person's memory check questions.

type AgentFact

type AgentFact struct {
	ID         string    `json:"id"`
	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`
	AgentID    string    `json:"agentId"`
	NodeID     string    `json:"nodeId"`

	// Version is the build that last wrote this. What an old build filed
	// under rules that have since changed is found by asking for it. See
	// migration 0073.
	Version string `json:"version,omitempty"`

	// Number is stable within the node: "people/alice-chen#3".
	Number int `json:"number"`

	Kind AgentFactKind `json:"kind"`
	Text string        `json:"text"`

	// HappenedAt is when it was true, which is not when it was learned, and
	// HappenedPrecision how precisely: HappenedDay, HappenedMonth or
	// HappenedYear, as the date was given; empty where it was not recorded.
	HappenedAt        *time.Time `json:"happenedAt,omitempty"`
	HappenedPrecision string     `json:"happenedPrecision,omitempty"`

	// Confidence is below one for anything assembled rather than said, and
	// Inferred marks it as such on the page and in the prompt. A "who did
	// that feature" put together from a chat thread and a commit is an
	// inference; filing it as a plain fact would make a guess permanent.
	Confidence float32 `json:"confidence"`
	Inferred   bool    `json:"inferred"`

	Evidence []Evidence `json:"evidence"`

	// Audiences is which unattended runs read it, as a memory's AppliesTo
	// was. The conversation always reads a fact on a page it is shown.
	Audiences []AgentAudience `json:"audiences"`

	// SupersededBy names the newer statement of the same thing. A
	// superseded fact leaves the page and stays readable.
	SupersededBy string `json:"supersededBy,omitempty"`

	Dormant bool       `json:"dormant"`
	UsedAt  *time.Time `json:"usedAt,omitempty"`
}

AgentFact is one sentence kept on a page.

func (*AgentFact) Addressed

func (self *AgentFact) Addressed(audience AgentAudience) bool

Addressed says whether a fact is read by an unattended run of a kind.

func (*AgentFact) Citations added in v0.79.0

func (self *AgentFact) Citations() []string

Citations is the pages and facts a reflection cites, as a reader names them: "projects/example-app", "projects/example-lib#2".

func (*AgentFact) HappenedText added in v0.97.1

func (self *AgentFact) HappenedText() string

HappenedText is when the fact happened, as precisely as it is known: "14 Jan 2023", "Jan 2023" or "2023". A date recorded before the precision was is shown to the day unless it falls on the first of a month, which is how a month given alone was stored.

func (*AgentFact) Line

func (self *AgentFact) Line() string

Line is the fact as a page or a prompt shows it: the sentence, then what a reader needs to judge it -- that it was inferred, and when it was true.

func (*AgentFact) Live

func (self *AgentFact) Live() bool

Live says whether a fact is one the page still states: not superseded, not dormant.

func (*AgentFact) Reference

func (self *AgentFact) Reference(path string) string

Reference is how a fact is cited in a prompt and on a page.

func (*AgentFact) ReflectionKind added in v0.79.0

func (self *AgentFact) ReflectionKind() string

ReflectionKind is what kind of observation a reflection is -- a pattern, a tension, a trend, a risk, a question -- from the night's own line in its evidence; empty for any other fact.

func (*AgentFact) SaidAt added in v0.97.1

func (self *AgentFact) SaidAt() *time.Time

SaidAt is when the fact was first learned: the earliest time its evidence records, which is when its source was written or said. Nil where no evidence says.

func (*AgentFact) Validate

func (self *AgentFact) Validate() error

Validate reports everything wrong with a fact.

type AgentFactKind

type AgentFactKind string

AgentFactKind is what sort of statement a fact is.

const (
	FactPlain      AgentFactKind = "fact"
	FactPreference AgentFactKind = "preference"
	FactDecision   AgentFactKind = "decision"
	FactEvent      AgentFactKind = "event"
	FactHowTo      AgentFactKind = "howto"

	// FactReflection is an observation the night made over a theme --
	// a pattern, a tension, a trend, a risk, a question -- citing the
	// pages and facts it rests on. Nobody said it; the night worked it out
	// from what the notes say, so only the night writes one.
	FactReflection AgentFactKind = "reflection"

	// FactLesson is what worked, or what to avoid, when doing a piece of
	// work, read from a conversation in which a command showed it worked:
	// when it applies, the approach, what failed, how it was verified. Only
	// the pass that reads conversations for lessons writes one, and only
	// with that command's result as its evidence.
	FactLesson AgentFactKind = "lesson"
)

The kinds. A preference or a decision may only come from the person's own words; the rest may be learned from what the agent read.

func (AgentFactKind) FromItsOwnReasoning added in v0.89.0

func (self AgentFactKind) FromItsOwnReasoning() bool

FromItsOwnReasoning says whether a kind is only ever written by the agent's own passes over what it knows: the dreams' reflections, and the lessons read from verified work. A model filing a conversation that calls its sentence a reflection or a lesson is filing a fact, and it is filed as one.

func (AgentFactKind) FromThePerson

func (self AgentFactKind) FromThePerson() bool

FromThePerson says whether a kind may only be written from what the person themselves said. An instruction inside a page, a mail or a tool's answer is not theirs, and a preference taken from one would have the agent following a stranger.

type AgentFeedItem added in v0.230.0

type AgentFeedItem struct {
	ID      string `json:"id"`
	AgentID string `json:"agentId"`
	UserID  string `json:"userId"`

	FeedItemKind   FeedItemKind   `json:"feedItemKind"`
	FeedSourceKind FeedSourceKind `json:"feedSourceKind"`

	// FeedSourceID is the goal, schedule or alert the card came from, the
	// computer and pane joined by a slash for a coding session, and empty for
	// a turn's own post.
	FeedSourceID string `json:"feedSourceId"`

	// RunConversationID is the run that posted it, to read the agent's work.
	RunConversationID string `json:"runConversationId"`

	Title string `json:"title"`

	// Body is Markdown: a few lines, links allowed.
	Body          string `json:"body"`
	PictureSymbol string `json:"pictureSymbol"`

	FactRows         []FeedFactRow    `json:"factRows"`
	SourceLinks      []FeedSourceLink `json:"sourceLinks"`
	RecordReferences []AgentReference `json:"recordReferences"`

	// FeedMedia are the card's pictures and videos, and the thumbnails of a
	// list card's rows.
	FeedMedia []FeedMedia `json:"feedMedia"`

	// ChartBlocks are the card's charts, at most FeedChartsMost.
	ChartBlocks []FeedChartBlock `json:"chartBlocks"`

	// CoalesceKey makes a later post with the same key from the same agent
	// replace this card. Empty for a card that is never replaced.
	CoalesceKey string `json:"coalesceKey"`

	Choices []FeedChoice `json:"choices"`

	// InteractionID is the durable question behind a decision.
	InteractionID string `json:"interactionId"`

	ChosenChoiceKey string     `json:"chosenChoiceKey"`
	ChosenAt        *time.Time `json:"chosenAt"`

	// ChosenConversationID is the main conversation a chosen action carried
	// on in.
	ChosenConversationID string `json:"chosenConversationId"`

	// OutcomeText is the agent's one line after a choice, and
	// IsOutcomePending says the turn that will write it has not ended.
	OutcomeText      string `json:"outcomeText"`
	IsOutcomePending bool   `json:"isOutcomePending"`

	FeedUrgency FeedUrgency `json:"feedUrgency"`

	// FeedStackKey names the stack the card is in: cards of one source pile
	// up and are shown as one entry. Empty for a card that stands alone.
	FeedStackKey string `json:"feedStackKey"`

	// FeedCardLayout is how the card is drawn, and LayoutContent the layout's
	// content as a JSON object, empty for text. The body is filled in plain
	// Markdown whatever the layout.
	FeedCardLayout FeedCardLayout `json:"feedCardLayout"`
	LayoutContent  string         `json:"layoutContent"`

	// StackPosition orders the cards of a stack that has an order, the
	// lowest first and a summary at 0; nil for a card that is placed by
	// when it was posted. FeedStackTitle names the stack, in the first card
	// that gives one.
	StackPosition  *int   `json:"stackPosition"`
	FeedStackTitle string `json:"feedStackTitle"`
	IsLiked        bool   `json:"isLiked"`

	// ResolvedAt is when the card was marked resolved, nil while it is not:
	// its problem cleared. ResolutionNote is the one line saying what
	// cleared, ResolvedByKind who marked it, and ResolvedByID the goal's
	// conversation or the person's user.
	ResolvedAt     *time.Time       `json:"resolvedAt"`
	ResolutionNote string           `json:"resolutionNote"`
	ResolvedByKind FeedResolverKind `json:"resolvedByKind"`
	ResolvedByID   string           `json:"resolvedById"`

	// PostNotes say what a post changed for the poster, such as a title that
	// was cut. They are answered with the post and never stored.
	PostNotes []string `json:"-"`

	ReadAt      *time.Time `json:"readAt"`
	DismissedAt *time.Time `json:"dismissedAt"`
	CreatedAt   time.Time  `json:"createdAt"`
	UpdatedAt   time.Time  `json:"updatedAt"`
	ExpiresAt   *time.Time `json:"expiresAt"`
}

AgentFeedItem is one card of the agent's feed. See docs/planning/agent-feed-execplan.md.

func (*AgentFeedItem) CanStack added in v0.230.0

func (self *AgentFeedItem) CanStack() bool

CanStack says whether the card may be in a stack. A card that needs the person on its own never stacks: one with a button that acts, dismisses or opens, and an alert. A coding session's questions do stack, a day of them in one stack, since a busy day of sessions asks many, and each card still answers its own session once the stack is open. So do ideas, a day of them in one stack: each still has its own buttons once the stack is open, and an idea is only ever in a stack after the person has read it.

func (*AgentFeedItem) DefaultFeedStackKey added in v0.230.0

func (self *AgentFeedItem) DefaultFeedStackKey() string

DefaultFeedStackKey is the stack a card goes in when its poster named none: the ideas' stack for an idea, its source for a goal, the reason for the agent speaking first, and for a schedule the run, so that each morning's brief is a stack of its own.

func (*AgentFeedItem) FileAttachmentIDs added in v0.250.0

func (self *AgentFeedItem) FileAttachmentIDs() []string

FileAttachmentIDs are the agent's files a card's file entries show.

func (*AgentFeedItem) FindChoice added in v0.230.0

func (self *AgentFeedItem) FindChoice(choiceKey string) *FeedChoice

FindChoice is the card's button with the key, or nil.

func (*AgentFeedItem) HasChoiceRole added in v0.230.0

func (self *AgentFeedItem) HasChoiceRole(choiceRole FeedChoiceRole) bool

HasChoiceRole says whether any button of the card has the role.

func (*AgentFeedItem) IsChosen added in v0.230.0

func (self *AgentFeedItem) IsChosen() bool

IsChosen says whether a choice was made on the card.

func (*AgentFeedItem) IsResolved added in v0.240.0

func (self *AgentFeedItem) IsResolved() bool

IsResolved says whether the card is marked resolved.

type AgentFeedback

type AgentFeedback struct {
	ID        string            `json:"id"`
	CreatedAt time.Time         `json:"createdAt"`
	AgentID   string            `json:"agentId"`
	MailboxID string            `json:"mailboxId,omitempty"`
	Kind      AgentFeedbackKind `json:"kind"`
	MailID    string            `json:"mailId,omitempty"`

	// Said is the correction in words, ready for a prompt.
	Said string `json:"said"`
}

AgentFeedback is a correction recorded from the person's own action, shown to the next run of the kind it corrects as an example.

type AgentFeedbackKind

type AgentFeedbackKind string

AgentFeedbackKind is what kind of thing the person did.

const (
	FeedbackFiled         AgentFeedbackKind = "filed"
	FeedbackReplyDeclined AgentFeedbackKind = "reply_declined"
	FeedbackSorted        AgentFeedbackKind = "sorted"

	// FeedbackUnlearned is a fact the person struck from a page. Shown to
	// the next filing run as an example of what not to keep, which is the
	// only way that run learns anything: it sees no other correction.
	FeedbackUnlearned AgentFeedbackKind = "unlearned"
)

The kinds of correction: the person filed a message somewhere other than the agent sorted it, or would not let a reply the agent wrote go.

type AgentFollowUp added in v0.169.0

type AgentFollowUp struct {
	ID      string `json:"id"`
	AgentID string `json:"agentId"`

	FollowUpKind AgentFollowUpKind `json:"followUpKind"`

	// FollowUpKey is what the same situation always produces, so a later
	// message about it finds this follow-up: the tracking number of a
	// parcel, the payee and due date of a bill.
	FollowUpKey   string `json:"followUpKey"`
	FollowUpTitle string `json:"followUpTitle"`

	Payee   string `json:"payee,omitempty" graphapi:"nullable"`
	Carrier string `json:"carrier,omitempty" graphapi:"nullable"`

	// Amount is a decimal number as a string, such as "1234.00", in
	// CurrencyCode, as FinanceTransaction.Amount is.
	Amount         string `json:"amount,omitempty" graphapi:"nullable"`
	CurrencyCode   string `json:"currencyCode,omitempty" graphapi:"nullable"`
	TrackingNumber string `json:"trackingNumber,omitempty" graphapi:"nullable"`

	// DueOn is a day written 2006-01-02, empty when the message gave none.
	DueOn string `json:"dueOn,omitempty" graphapi:"nullable"`
	Place string `json:"place,omitempty" graphapi:"nullable"`

	// SourceURL is the web page an event or deadline was found on by the
	// weekly look around, so every surface can link to it. Empty for what
	// mail said.
	SourceURL string `json:"sourceUrl,omitempty" graphapi:"nullable"`

	FollowUpState AgentFollowUpState `json:"followUpState"`
	ClosedReason  string             `json:"closedReason,omitempty" graphapi:"nullable"`

	// SourceItemIDs are the messages it came from, newest last.
	SourceItemIDs []string `json:"sourceItemIds"`

	// ToldState is what the person was last told about it, empty when
	// never, and ToldAt when.
	ToldState AgentFollowUpToldState `json:"toldState,omitempty" graphapi:"nullable"`
	ToldAt    *time.Time             `json:"toldAt,omitempty" graphapi:"nullable"`

	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

AgentFollowUp is a thing mail said is due, on its way or coming up, kept until something closes it.

type AgentFollowUpKind added in v0.169.0

type AgentFollowUpKind string

AgentFollowUpKind is what sort of situation a follow-up keeps track of.

const (
	AgentFollowUpBill     AgentFollowUpKind = "bill"
	AgentFollowUpParcel   AgentFollowUpKind = "parcel"
	AgentFollowUpDeadline AgentFollowUpKind = "deadline"
	AgentFollowUpEvent    AgentFollowUpKind = "event"
)

The kinds: a bill with a payee, an amount and a due date; a parcel with a carrier and a tracking number; something the person must do or return by a date, such as a form or an RSVP; and a dated happening they may want to go to. They differ in what closes them and when to speak.

func (AgentFollowUpKind) IsValid added in v0.169.0

func (self AgentFollowUpKind) IsValid() bool

IsValid says the kind is one of the four.

type AgentFollowUpState added in v0.169.0

type AgentFollowUpState string

AgentFollowUpState is where a follow-up stands.

const (
	AgentFollowUpOpen    AgentFollowUpState = "open"
	AgentFollowUpClosed  AgentFollowUpState = "closed"
	AgentFollowUpOverdue AgentFollowUpState = "overdue"
	AgentFollowUpStalled AgentFollowUpState = "stalled"
	AgentFollowUpExpired AgentFollowUpState = "expired"
	AgentFollowUpStopped AgentFollowUpState = "stopped"
)

The states: open, until something closes it; closed, by later mail or a payment that shows it happened; overdue, a bill past its date with no payment seen; stalled, a parcel well past its expected date; expired, a deadline or event whose day has gone; and stopped, which the person said not to follow any more.

func (AgentFollowUpState) IsOpen added in v0.169.0

func (self AgentFollowUpState) IsOpen() bool

IsOpen says the follow-up is still being watched: open, overdue or stalled. The others are over.

func (AgentFollowUpState) IsValid added in v0.169.0

func (self AgentFollowUpState) IsValid() bool

IsValid says the state is one of the six.

type AgentFollowUpToldState added in v0.169.0

type AgentFollowUpToldState string

AgentFollowUpToldState is what the person was last told about a follow-up, kept apart from the follow-up's own state: a bill is reminded while it is still open, and a delivered parcel is told about as it closes.

const (
	AgentFollowUpToldReminded  AgentFollowUpToldState = "reminded"
	AgentFollowUpToldOverdue   AgentFollowUpToldState = "overdue"
	AgentFollowUpToldStalled   AgentFollowUpToldState = "stalled"
	AgentFollowUpToldDelivered AgentFollowUpToldState = "delivered"
	AgentFollowUpToldRoundup   AgentFollowUpToldState = "roundup"
)

The things told: a bill or deadline reminded before its day, a bill overdue, a parcel stalled, a parcel delivered, and an event or deadline that went out in the Sunday roundup. A follow-up is told about each of them once.

func (AgentFollowUpToldState) IsValid added in v0.169.0

func (self AgentFollowUpToldState) IsValid() bool

IsValid says the told state is one of the five.

type AgentGoalActivity added in v0.111.0

type AgentGoalActivity struct {
	ID               string                `json:"id"`
	AgentID          string                `json:"agentId"`
	ConversationID   string                `json:"conversationId"`
	CreatedAt        time.Time             `json:"createdAt"`
	GoalActivityKind AgentGoalActivityKind `json:"goalActivityKind"`
	ActivityHeadline string                `json:"activityHeadline"`
	ActivityDetail   string                `json:"activityDetail,omitempty"`
}

AgentGoalActivity is one thing that happened on a goal, as the person reads it in the goal's log.

type AgentGoalActivityKind added in v0.111.0

type AgentGoalActivityKind string

AgentGoalActivityKind is what happened on a goal.

const (
	GoalActivityStarted  AgentGoalActivityKind = "started"
	GoalActivityProgress AgentGoalActivityKind = "progress"
	GoalActivityWaiting  AgentGoalActivityKind = "waiting"
	GoalActivityResumed  AgentGoalActivityKind = "resumed"
	GoalActivityMet      AgentGoalActivityKind = "met"
	GoalActivityDropped  AgentGoalActivityKind = "dropped"
	GoalActivityStalled  AgentGoalActivityKind = "stalled" // no longer written; goals do not stall, old logs keep it
	GoalActivityFailed   AgentGoalActivityKind = "failed"
)

What an activity row says happened: the goal was started; a turn of its own did something worth reading; it came to need the person; the person answered and it went back to work; it was met or dropped; it stopped after too many turns alone; or a turn failed.

type AgentGoalArrival added in v0.232.0

type AgentGoalArrival struct {
	MailboxItemID string    `json:"mailboxItemId"`
	MailboxName   string    `json:"mailboxName,omitempty"`
	From          string    `json:"from"`
	Subject       string    `json:"subject"`
	ReceivedAt    time.Time `json:"receivedAt"`
	// IsSenderVerified is whether the sender's domain vouched for the
	// message (DMARC passed), so that a From line anybody can write is not
	// taken for the sender it names.
	IsSenderVerified bool `json:"isSenderVerified"`
}

AgentGoalArrival is one message that set a goal off: enough for its turn to say what came and to read it, not what it says.

type AgentGoalArtifact added in v0.111.0

type AgentGoalArtifact struct {
	ID                string                `json:"id"`
	AgentID           string                `json:"agentId"`
	ConversationID    string                `json:"conversationId"`
	CreatedAt         time.Time             `json:"createdAt"`
	GoalArtifactKind  AgentGoalArtifactKind `json:"goalArtifactKind"`
	ArtifactReference string                `json:"artifactReference"`
	ArtifactTitle     string                `json:"artifactTitle"`
}

AgentGoalArtifact is one thing a goal made, by its own reference: a mail rule's name, a reminder's id, an alert mute's id.

type AgentGoalArtifactKind added in v0.111.0

type AgentGoalArtifactKind string

AgentGoalArtifactKind is what sort of thing a goal made.

const (
	GoalArtifactMailRule  AgentGoalArtifactKind = "mail_rule"
	GoalArtifactReminder  AgentGoalArtifactKind = "reminder"
	GoalArtifactAlertMute AgentGoalArtifactKind = "alert_mute"
)

The things a goal made that carry no conversation of their own; its schedules and background work are found by the conversation instead.

type AgentGoalState

type AgentGoalState string

AgentGoalState is where a conversation's goal stands.

const (
	GoalWorking AgentGoalState = "working"
	GoalWaiting AgentGoalState = "waiting"
	GoalPaused  AgentGoalState = "paused"
	GoalMet     AgentGoalState = "met"
	GoalDropped AgentGoalState = "dropped"
)

The states a goal is in. A goal that is working takes turns of the agent's own; one that is waiting takes none until the person writes again, and their next turn puts it back to working; one that is paused is one the person switched off for now, which takes no turns and hears no mail until they switch it on; one that is met is done, and its text stays on the conversation until they clear it; one that is dropped is one the person stopped.

type AgentHours

type AgentHours struct {
	From  string `json:"from"`  // "09:00"
	Until string `json:"until"` // "17:30"
	Days  []int  `json:"days"`  // 0 = Sunday … 6 = Saturday
}

AgentHours are the person's working hours in their own zone, for a policy that answers outside them.

type AgentIdea added in v0.76.0

type AgentIdea struct {
	ID      string `json:"id"`
	AgentID string `json:"agentId"`

	// IdeaKey names the idea for the agent: the catalog's key, or one made
	// for a personal idea.
	IdeaKey      string            `json:"ideaKey"`
	IdeaKind     AgentIdeaKind     `json:"ideaKind"`
	IdeaCategory AgentIdeaCategory `json:"ideaCategory"`
	Emoji        string            `json:"emoji"`

	// Headline is the offer in a line; Body what happens and where the
	// agent stops to ask.
	Headline string `json:"headline"`
	Body     string `json:"body"`

	// OpeningRequest is what the person would say to start it, put in the
	// reply box of the conversation that starting it opens.
	OpeningRequest string `json:"openingRequest"`

	// NeededToolNames are the tools it needs; a trailing * is any tool
	// whose name begins so.
	NeededToolNames []string `json:"neededToolNames"`

	// Evidence and SuggestionReason say why this person, for a personal
	// idea.
	Evidence         []AgentIdeaEvidence `json:"evidence"`
	SuggestionReason string              `json:"suggestionReason"`

	IdeaStatus AgentIdeaStatus `json:"ideaStatus"`

	// ExpiredReason is why an expired idea is not on offer, and empty for
	// an idea in any other status. An expired catalog idea keeps the reason
	// it is not offered now, which may have changed since it expired; one
	// that expired before reasons were kept, or whose key the catalog no
	// longer has, may have none.
	ExpiredReason AgentIdeaExpiredReason `json:"expiredReason"`

	// IsRestoredByPerson is a catalog idea the person opened again after it
	// expired because they already do what it offers. The check that found
	// that no longer expires it: they said they want it anyway, and it stays
	// until they dismiss it or finish it. A missing tool still expires it.
	IsRestoredByPerson bool `json:"isRestoredByPerson"`

	// RankScore orders open ideas, highest first.
	RankScore float64 `json:"rankScore"`

	// StartedConversationID is the conversation that carries it out.
	StartedConversationID string `json:"startedConversationId"`

	CreatedAt  time.Time  `json:"createdAt"`
	ModifiedAt time.Time  `json:"modifiedAt"`
	ShownAt    *time.Time `json:"shownAt" graphapi:"nullable"`
	StartedAt  *time.Time `json:"startedAt" graphapi:"nullable"`
	ClosedAt   *time.Time `json:"closedAt" graphapi:"nullable"`
	ExpiresAt  *time.Time `json:"expiresAt" graphapi:"nullable"`
}

AgentIdea is one idea of one person's agent.

type AgentIdeaCategory added in v0.76.0

type AgentIdeaCategory string

AgentIdeaCategory is the area of life an idea is about.

type AgentIdeaEvidence added in v0.76.0

type AgentIdeaEvidence struct {
	// EvidenceKind is message (a mailbox item), page (a memory page, by
	// its path) or conversation.
	EvidenceKind string `json:"evidenceKind"`
	// EvidenceID is the item's id, the page's path, or the conversation's
	// id.
	EvidenceID string `json:"evidenceId"`
	// EvidenceSummary says in a few words what it is.
	EvidenceSummary string `json:"evidenceSummary"`
}

AgentIdeaEvidence is one thing in the person's data that prompted a personal idea.

type AgentIdeaExpiredReason added in v0.83.3

type AgentIdeaExpiredReason string

AgentIdeaExpiredReason is why an idea expired: what stopped it being on offer.

const (
	// IdeaPastDate is a personal idea whose date passed.
	IdeaPastDate AgentIdeaExpiredReason = "past_date"
	// IdeaMissingTool is a catalog idea needing a tool the person does not
	// have. It cannot be opened again until the tool is back, when it comes
	// back on its own.
	IdeaMissingTool AgentIdeaExpiredReason = "missing_tool"
	// IdeaAlreadyUsed is a catalog idea about something the person already
	// does. They may still open it again.
	IdeaAlreadyUsed AgentIdeaExpiredReason = "already_used"
)

func (AgentIdeaExpiredReason) IsValid added in v0.83.3

func (self AgentIdeaExpiredReason) IsValid() bool

IsValid says whether a reason is one of the three, or none.

type AgentIdeaKind added in v0.76.0

type AgentIdeaKind string

AgentIdeaKind is where an idea came from.

const (
	IdeaCatalog  AgentIdeaKind = "catalog"
	IdeaPersonal AgentIdeaKind = "personal"
)

type AgentIdeaStatus added in v0.76.0

type AgentIdeaStatus string

AgentIdeaStatus is what became of an idea.

const (
	// IdeaOpen is on offer, shown or not.
	IdeaOpen AgentIdeaStatus = "open"
	// IdeaStarted has a conversation carrying it out.
	IdeaStarted AgentIdeaStatus = "started"
	// IdeaDone was carried out.
	IdeaDone AgentIdeaStatus = "done"
	// IdeaDismissed is one the person does not want.
	IdeaDismissed AgentIdeaStatus = "dismissed"
	// IdeaExpired stopped mattering, or stopped being something the agent
	// can do, before anybody took it up.
	IdeaExpired AgentIdeaStatus = "expired"
)

func (AgentIdeaStatus) IsValid added in v0.76.0

func (self AgentIdeaStatus) IsValid() bool

IsValid says whether a status is one of the five.

type AgentInteraction added in v0.61.4

type AgentInteraction struct {
	ID              string          `json:"id"`
	AgentID         string          `json:"agentId"`
	ConversationID  string          `json:"conversationId"`
	RunID           string          `json:"runId"`
	CallID          string          `json:"callId"`
	InteractionKind InteractionKind `json:"interactionKind"`
	ToolName        string          `json:"toolName"`
	ToolArguments   string          `json:"toolArguments"`

	// InteractionText is the question, or the approval card's line.
	InteractionText    string   `json:"interactionText"`
	InteractionChoices []string `json:"interactionChoices"`
	ToolRisk           string   `json:"toolRisk"`

	CreatedAt         time.Time  `json:"createdAt"`
	ResolvedAt        *time.Time `json:"resolvedAt,omitempty" graphapi:"nullable"`
	InteractionAnswer string     `json:"interactionAnswer"`

	// IsStartedByPerson says the turn that raised the card was one the person
	// started. The turn that carries on a late answer is the person's only
	// when this is true. Not sent to a client.
	IsStartedByPerson bool `json:"-"`
}

AgentInteraction is a question or an approval card, kept until the person answers it. See docs/planning/durable-interactions-execplan.md.

type AgentJob

type AgentJob struct {
	ID           string         `json:"id"`
	CreatedAt    time.Time      `json:"createdAt"`
	AgentID      string         `json:"agentId"`
	MailboxID    string         `json:"mailboxId,omitempty"`
	Kind         AgentJobKind   `json:"kind"`
	SubjectID    string         `json:"subjectId,omitempty"`
	Status       AgentJobStatus `json:"status"`
	Attempts     int            `json:"attempts"`
	FailureCount int            `json:"failureCount"`
	ClaimID      string         `json:"-" graphapi:"ignore"`
	NotBefore    *time.Time     `json:"notBefore,omitempty"`
	ClaimedAt    *time.Time     `json:"claimedAt,omitempty"`
	ClaimedBy    string         `json:"claimedBy,omitempty"`
	Error        string         `json:"error,omitempty"`
	FinishedAt   *time.Time     `json:"finishedAt,omitempty"`
}

AgentJob is one unit of work for the worker.

type AgentJobKind

type AgentJobKind string

AgentJobKind is what a job does.

const (
	AgentJobTriage    AgentJobKind = "triage"
	AgentJobResearch  AgentJobKind = "research"
	AgentJobSummarize AgentJobKind = "summarize"
	AgentJobEmbed     AgentJobKind = "embed"
	// AgentJobRecording prepares and transcribes passive media without a user turn.
	AgentJobRecording AgentJobKind = "recording"
	// AgentJobRecordingSummary names a recording and summarizes it from its
	// transcript. Its subject is the recording.
	AgentJobRecordingSummary AgentJobKind = "recording_brief"

	// AgentJobRecordingTerms corrects misheard names and terms in a finished
	// transcript from the person's own glossary, and then queues the summary
	// job. Its subject is the recording.
	AgentJobRecordingTerms AgentJobKind = "recording_terms"

	// AgentJobRecordingKnowledge publishes a recording's passages to the
	// person's knowledge: the documents, and the facts and overviews that cite
	// documents whose words changed. Its subject is the recording, so a run
	// of namings queues one. It makes no model call.
	AgentJobRecordingKnowledge AgentJobKind = "recording_sync"
	AgentJobReply              AgentJobKind = "reply"
	AgentJobSend               AgentJobKind = "send"

	// AgentJobExtract reads a message triage thought carries an appointment
	// or somebody's details in its words, and offers what it found. It
	// writes nothing but the offer.
	AgentJobExtract AgentJobKind = "extract"

	// AgentJobRemember reads what a conversation taught and files it onto
	// the graph. Its subject is the conversation.
	//
	// A run of its own rather than something asked of the model mid-turn:
	// a model doing the person's actual work does not stop to keep house,
	// and the measured result of asking it to was almost nothing kept.
	AgentJobRemember AgentJobKind = "remember"

	// AgentJobIngest reads one knowledge source. Its subject is the
	// source, and a pass that leaves work behind queues itself again at
	// once rather than waiting for the next tick: a first pass over a
	// checkout is a night's work, not a fortnight's.
	AgentJobIngest AgentJobKind = "ingest"

	// AgentJobDream is the nightly run: working through what arrived,
	// writing up the month, rewriting the pages it touched and tidying.
	// Its subject is the day, so a night runs once.
	AgentJobDream AgentJobKind = "dream"

	// AgentJobGoal is one turn of the agent's own toward the goal on a
	// conversation. Its subject is the conversation, so the queue's rule
	// of one open job per agent, kind and subject is also the rule that a
	// conversation takes one goal turn at a time.
	AgentJobGoal AgentJobKind = "goal"

	// AgentJobJournal makes the touch-ups and the narratives of a person's
	// journal that they asked for. Its subject is the person's user
	// identifier, so the queue's rule of one open job per agent, kind and
	// subject gathers requests that arrive together into one run.
	AgentJobJournal AgentJobKind = "journal"

	// AgentJobBackfill queues triage for what was already in a mailbox when
	// it was granted.
	AgentJobBackfill AgentJobKind = "backfill"

	// AgentJobNoop does nothing and records that it ran; it proves the
	// queue end to end before any kind that costs tokens exists.
	AgentJobNoop AgentJobKind = "noop"

	// Three kinds that are never queued but name a run: every model call
	// is a run of the loop, and these are made in the request or inside
	// a turn rather than from the queue. Draft writes an answer for the
	// composer, describe titles a conversation, compact writes the note
	// that stands in for a conversation's earlier part.
	AgentJobDraft    AgentJobKind = "draft"
	AgentJobDescribe AgentJobKind = "describe"
	AgentJobCompact  AgentJobKind = "compact"

	// AgentJobReact picks the emoji the agent puts on the person's
	// message the moment it arrives. Never queued; it runs beside the
	// turn that message began.
	AgentJobReact AgentJobKind = "react"

	// AgentJobEvaluate grades the agent against the person's memory check
	// questions; its subject is the run it fills. The calls it makes, and
	// the ones `teanode agent memory answers` makes, are runs of this kind,
	// so what an evaluation cost is apart from everything else.
	AgentJobEvaluate AgentJobKind = "evaluate"

	// AgentJobSpeakFirst is a turn the agent takes in the main conversation
	// with nobody having asked: to introduce itself, to check what it
	// remembers, or to offer an idea. Its subject is the reason.
	AgentJobSpeakFirst AgentJobKind = "speak_first"

	// AgentJobSurvey names the runs of a survey: one for each page it
	// asks for its part of an answer, and one that combines the parts.
	// Never queued; a survey runs in the request or the turn that asked
	// for it, and its runs are priced apart so that what one cost can be
	// read on its own.
	AgentJobSurvey AgentJobKind = "survey"

	// AgentJobSubagent names the run of a subagent: a piece of work a turn
	// handed to a run of its own. Never queued itself: a subagent runs
	// inside the turn that started it, or in a background job.
	AgentJobSubagent AgentJobKind = "subagent"

	// AgentJobBackground runs one piece of background work, a survey or a
	// subagent the agent did not wait for. Its subject is the
	// agent_background_work row, which says what to run and keeps what
	// came of it.
	AgentJobBackground AgentJobKind = "background"

	// AgentJobAlert decides which of the waiting alert candidates the
	// person is told about, and tells them. Its subject is the agent, so
	// the queue's rule of one open job per agent, kind and subject is what
	// gathers candidates arriving together into one decision.
	AgentJobAlert AgentJobKind = "alert"

	// AgentJobCategorize gives spending categories, with the categorize
	// model, to the finance transactions a sync left uncategorized. Its
	// subject is the agent, so syncs of several finance sources close
	// together queue one.
	AgentJobCategorize AgentJobKind = "categorize"

	// AgentJobStatementImport imports the OFX statements attached to a
	// message that arrived at the person's statement import address, and
	// tells them what came of it. Its subject is the message.
	AgentJobStatementImport AgentJobKind = "statement_import"

	// AgentJobReadReceipt reads a receipt out of a message sorting called
	// one, or out of a photo or a text file uploaded to a finance
	// transaction, records it and matches it to the charge it explains.
	// Its subject is the stored message (with its mailbox) or the
	// uploaded file, which names the finance transaction it was uploaded
	// to, when there is one.
	AgentJobReadReceipt AgentJobKind = "read_receipt"

	// AgentJobMatchShopping ties the lines of a receipt to the items of the
	// shopping lists its owner reaches: sure matches check items off and keep
	// their price, unsure ones wait for the person. Its subject is the
	// receipt. Every receipt, from any source, queues it while the owner
	// has items a receipt could have bought.
	AgentJobMatchShopping AgentJobKind = "match_shopping"

	// AgentJobShoppingPicture finds a picture for an item on a shopping list:
	// a web search, the page the model picks, and that page's own picture,
	// kept scaled down in the file store. Its subject is the item.
	AgentJobShoppingPicture AgentJobKind = "shopping_picture"

	// AgentJobShoppingImport names the run that reads a pasted list or a
	// screenshot of one into shopping items, which is made in the request
	// rather than queued.
	AgentJobShoppingImport AgentJobKind = "shopping_import"

	// AgentJobDescribePhoto writes what is in a photo, with the words that
	// can be read in it, and keeps it on the photo and searchable. Its
	// subject is the photo.
	AgentJobDescribePhoto AgentJobKind = "describe_photo"

	// AgentJobTranscribePhotoDocument reads the whole of a photo the
	// description said is a whiteboard, notes or a paper document, keeps its
	// title and transcription on the photo and as a document of the person's
	// knowledge, and tells the person in the feed. Its subject is the photo.
	// The columns that hold a job's kind take 40 characters, which is as
	// long as a kind may be.
	AgentJobTranscribePhotoDocument AgentJobKind = "transcribe_photo_document"

	// AgentJobTaxDocument reads a paystub or a tax form (a W-2) out of
	// a file handed in as one and records it. Its subject is the uploaded
	// file.
	AgentJobTaxDocument AgentJobKind = "tax_document"

	// AgentJobStatementPhoto reads the transactions of one account out of a
	// photo the description said is a statement, and imports them into the
	// account of imported statements they are of. Its subject is the copy
	// of the photo made to be read.
	AgentJobStatementPhoto AgentJobKind = "statement_photo"

	// AgentJobTaxMail copies the PDFs and pictures of a message that
	// arrived at the person's tax document address into tax document
	// uploads, queues the reading of each, and tells the person. Its
	// subject is the message.
	AgentJobTaxMail AgentJobKind = "tax_mail"

	// AgentJobWatch is one look by one watch of an installed skill: it
	// lists what arrived since the last look through the skill's own
	// tools, judges each new item and makes alert candidates of what
	// deserves one. Its subject is "skill/watch".
	AgentJobWatch AgentJobKind = "watch"

	// AgentJobFollowUpSweep reads the agent's open follow-ups against the
	// day and writes the alert candidates for the bills, parcels, deadlines
	// and coming events that are due to be told. Its subject is the day and
	// the hour it belongs to, so a sweep is queued once; it makes no model
	// call.
	AgentJobFollowUpSweep AgentJobKind = "follow_up_sweep"
)

The kinds of job the worker runs.

type AgentJobStatus

type AgentJobStatus string

AgentJobStatus is where a job is.

const (
	AgentJobQueued    AgentJobStatus = "queued"
	AgentJobRunning   AgentJobStatus = "running"
	AgentJobDone      AgentJobStatus = "done"
	AgentJobDead      AgentJobStatus = "dead"
	AgentJobCancelled AgentJobStatus = "cancelled"
)

A job's lifetime: queued, running, and then one of done, failed (to be retried), dead (given up), deferred (waiting for a budget) or cancelled.

type AgentKnowledgeKind

type AgentKnowledgeKind string

AgentKnowledgeKind is what sort of place a source is.

const (
	// SourceComputer is a directory on a machine the person runs
	// `teanode computer` on. Inside a repository the manifest is what git
	// tracks, which is how a checkout is read without its build output.
	SourceComputer AgentKnowledgeKind = "computer"

	// SourceArchive is an export of something, on the same machine, in a
	// shape the scan understands: a chat export, a folder of dated
	// notes.
	SourceArchive AgentKnowledgeKind = "archive"

	// SourceSkill pages an installed skill's tool -- a wiki, a forge, a
	// chat service -- with the person's own credentials.
	SourceSkill AgentKnowledgeKind = "skill"

	// SourceWeb crawls within an address prefix.
	SourceWeb AgentKnowledgeKind = "web"

	// SourceSent is the person's own sent mail, which is what makes the
	// agent able to write as they do.
	SourceSent AgentKnowledgeKind = "sent"

	// SourceFinance is one login at one financial institution, reached
	// through a provider. It files rows of finance accounts and finance
	// transactions rather than documents, so nothing in the memory graph
	// reads it; Specification.Type is the provider kind and
	// Specification.Settings holds FinanceSourceSettings.
	SourceFinance AgentKnowledgeKind = "finance"

	// SourceRecording is retained passive meeting evidence, created when a transcript completes.
	SourceRecording AgentKnowledgeKind = "recording"

	// SourceChat is a chat with other people that a member has let their
	// agent remember, read from the time they did. It is made only by the
	// member's switch on that chat (SetChatAgentReading); Specification.ChatID
	// names the chat.
	SourceChat AgentKnowledgeKind = "chat"

	// SourceLocation is where a person went, one document for each finished
	// day, written by the server from their recorded visits. It is made
	// once for each agent by EnsureLocationSource and is never read from
	// anywhere, so it has no schedule and no specification.
	SourceLocation AgentKnowledgeKind = "location"

	// SourcePhoto is the photos kept as documents (a whiteboard, notes, a
	// paper document), one document for each photo, written by the server
	// from the photo's transcription. It is made once for each agent by
	// EnsurePhotoSource and is never read from anywhere, so it has no
	// schedule and no specification.
	SourcePhoto AgentKnowledgeKind = "photo"
)

The kinds.

func (AgentKnowledgeKind) IsDocumentKind added in v0.87.0

func (self AgentKnowledgeKind) IsDocumentKind() bool

IsDocumentKind says a source of this kind files documents into the memory graph, which is every kind but finance.

func (AgentKnowledgeKind) IsMadeByLinking added in v0.87.0

func (self AgentKnowledgeKind) IsMadeByLinking() bool

IsMadeByLinking says a source of this kind is made only by the operations that link it, never by the generic source creation: a finance source needs a credential the provider hands over at the end of a link, and a row without one would be a source that can never sync.

type AgentKnowledgeSource

type AgentKnowledgeSource struct {
	ID         string    `json:"id"`
	AgentID    string    `json:"agentId"`
	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`

	Kind          AgentKnowledgeKind          `json:"kind"`
	Name          string                      `json:"name"`
	Specification AgentKnowledgeSpecification `json:"specification"`

	// RootPath is where in the graph what it finds is filed.
	RootPath string `json:"rootPath"`

	Enabled bool   `json:"enabled"`
	Cron    string `json:"cron,omitempty"`

	// Generation changes when a source is saved, invalidating older ingestion work.
	Generation int64 `json:"-"`

	// Cursor is where the last pass stopped. Opaque above the reader that
	// wrote it.
	Cursor map[string]any `json:"-"`

	// Instance is which server holds the socket to the device.
	Instance string `json:"-"`

	LastRunAt *time.Time `json:"lastRunAt,omitempty"`
	NextRunAt *time.Time `json:"nextRunAt,omitempty"`

	// RunRequestedAt is when somebody last asked for it to be read now and
	// no pass has started since: a pass ending with it set runs again at
	// once, since it may have read the files before what was asked for
	// was written. See db.RequestAgentSourceRun.
	RunRequestedAt *time.Time `json:"-"`
	LastError      string     `json:"lastError,omitempty"`

	DocumentCount int `json:"documentCount"`
	ChunkCount    int `json:"chunkCount"`
	RefusedCount  int `json:"refusedCount"`

	// CheckoutsKeptToProfile is how many checkouts under this source's
	// path were kept to what git says about them, their files left
	// unread, and FilesKeptToProfile how many files that was. Both are
	// what the last pass found over the whole tree, not a running total.
	//
	// Shown wherever the source is shown. A program that quietly reads
	// less than it was pointed at is one nobody can argue with, and the
	// argument -- specification.readEveryCheckout -- is only worth having
	// if the person can see there is something to argue about.
	CheckoutsKeptToProfile int `json:"checkoutsKeptToProfile"`
	FilesKeptToProfile     int `json:"filesKeptToProfile"`

	// More says the last pass left work behind and wants another.
	More bool `json:"more"`

	// UnknownAuthors are the commit addresses this source found that are
	// not on the card the person marked as themselves. Whether a checkout
	// is their own work is decided by that match, and when nothing
	// matches every answer built on it is empty -- so the addresses are
	// kept and shown rather than the silence.
	UnknownAuthors []string `json:"unknownAuthors"`
}

AgentKnowledgeSource is one standing grant of reach.

func (*AgentKnowledgeSource) Describe

func (self *AgentKnowledgeSource) Describe() string

Describe is what a source is, in a line, for a card and for a list.

func (*AgentKnowledgeSource) FinanceSourceSettings added in v0.87.0

func (self *AgentKnowledgeSource) FinanceSourceSettings() (FinanceSourceSettings, error)

FinanceSourceSettings reads a finance source's settings. Empty settings read as empty values, not as an error.

func (*AgentKnowledgeSource) IsFinanceCredentialRefused added in v0.87.0

func (self *AgentKnowledgeSource) IsFinanceCredentialRefused() bool

IsFinanceCredentialRefused says the provider refused the finance source's credential, so it is not synced again.

func (*AgentKnowledgeSource) IsFinanceSignInRequired added in v0.87.0

func (self *AgentKnowledgeSource) IsFinanceSignInRequired() bool

IsFinanceSignInRequired says the finance source is waiting for the person to sign in to the institution again.

func (*AgentKnowledgeSource) Validate

func (self *AgentKnowledgeSource) Validate() error

Validate reports everything wrong with a source.

type AgentKnowledgeSpecification

type AgentKnowledgeSpecification struct {
	// Type is the installed source type this source is one of, and
	// Settings what the person filled in for it, as a JSON object. A
	// type that names a reader built into TeaNode is read by that reader,
	// with its settings copied into the fields below; any other is read
	// with the typed format.
	Type     string          `json:"type,omitempty"`
	Settings json.RawMessage `json:"settings,omitempty"`

	// Computer and Path: the device the person attached and where on it.
	Computer string `json:"computer,omitempty"`
	Path     string `json:"path,omitempty"`

	// Format is how to read what is there: files, journal, records.
	Format string `json:"format,omitempty"`

	// Include and Exclude are globs, for a files source.
	Include []string `json:"include,omitempty"`
	Exclude []string `json:"exclude,omitempty"`

	// Tool is the skill tool to call, Arguments what to call it with, and
	// the rest say how to read what comes back.
	Tool        string         `json:"tool,omitempty"`
	Arguments   map[string]any `json:"arguments,omitempty"`
	ItemPath    string         `json:"itemPath,omitempty"`
	IDField     string         `json:"idField,omitempty"`
	TextField   string         `json:"textField,omitempty"`
	TitleField  string         `json:"titleField,omitempty"`
	URLField    string         `json:"urlField,omitempty"`
	DateField   string         `json:"dateField,omitempty"`
	CursorField string         `json:"cursorField,omitempty"`

	// Start, Allow and Depth are a web crawl.
	Start string   `json:"start,omitempty"`
	Allow []string `json:"allow,omitempty"`
	Depth int      `json:"depth,omitempty"`

	// MailboxID is which mailbox a sent source reads.
	MailboxID string `json:"mailboxId,omitempty"`

	// ChatID is which chat a chat source reads.
	ChatID string `json:"chatId,omitempty"`

	// ReadEveryCheckout reads the files of every checkout under this
	// source's path, including the ones barely any of whose history is
	// the person's own work.
	//
	// Off by default, which is what stops a folder of clones being read
	// as though it were the person's own work: a checkout too little of
	// whose history is theirs -- OwnCommitsAtLeast below says how little
	// that is -- is kept to its profile, what it is, where it lives and
	// what git says about it, and its files are left where they are. On
	// for somebody who does want a dependency's source read.
	ReadEveryCheckout bool `json:"readEveryCheckout,omitempty"`

	// CommitsPerPass is how many commits one pass over this source's
	// tree carries, over all the checkouts in it. Zero is the daemon's
	// own pace, which is two thousand.
	//
	//	The history is what says who wrote a piece of code, and it is
	// deep: a tree of a hundred or more checkouts can hold hundreds of
	// thousands of commits, which filed in one night would bury the
	// graph and the person's embedding budget. So a pass takes the
	// newest of them, at a pace
	// somebody chose, and the graph fills at that pace. Raise it for a
	// tree whose history matters more than its files.
	CommitsPerPass int `json:"commitsPerPass,omitempty"`

	// OwnCommitsAtLeast is how many commits of the person's own a
	// checkout under this source must hold before its files are read,
	// whatever the length of its history. Zero is the bar the program on
	// the machine works out for itself, which is two for a short history
	// and climbs with a long one -- a fiftieth of the log, up to
	// twenty-five commits.
	//
	// That climb is why the setting is here. One commit is a visit and
	// not authorship: on the tree this was written for, 59 checkouts
	// holding a single commit of the person's were admitting 129,306
	// files, 39% of everything read, and the largest of them was a fork
	// of linux-stable admitting 70,766 files on the strength of one.
	// Raise it for a tree where a handful of commits still is not yours;
	// set it to one for a tree where every visit is worth reading, which
	// is the rule this replaced; and readEveryCheckout for a tree where
	// even the checkouts you have never touched are.
	OwnCommitsAtLeast int `json:"ownCommitsAtLeast,omitempty"`

	// MaxAttachmentBytes is the largest file this source carries off the
	// person's machine, in bytes. Zero means the default,
	// computer.DefaultMaxAttachmentBytes, which is what nearly every
	// source wants; it is here for the one archive whose pictures are
	// bigger than everybody else's.
	MaxAttachmentBytes int64 `json:"maxAttachmentBytes,omitempty"`
}

AgentKnowledgeSpecification is what to read. Which fields mean anything depends on the kind; the rest are empty.

type AgentMailbox

type AgentMailbox struct {
	// Granted says the agent may read this mailbox and act in it.
	Granted bool `json:"granted"`

	Triage       *AgentTriage    `json:"triage,omitempty" graphapi:"nullable"`
	Summaries    *AgentSummaries `json:"summaries,omitempty" graphapi:"nullable"`
	DraftReplies bool            `json:"draftReplies"`
	Search       bool            `json:"search"`
	Research     bool            `json:"research"`
	AutoReply    *AgentAutoReply `json:"autoReply,omitempty" graphapi:"nullable"`

	// Alerts is whether what arrives here may be told to the person
	// unasked. Nil means on: a mailbox granted before alerts existed, or
	// granted without saying, alerts wherever it is sorted.
	Alerts *AgentAlerts `json:"alerts,omitempty" graphapi:"nullable"`
}

AgentMailbox is a mailbox as a source: whether the agent may reach it and what it does there. A JSON column on the mailbox; nil means never granted.

func (*AgentMailbox) IsAlertsEnabled added in v0.82.0

func (self *AgentMailbox) IsAlertsEnabled() bool

IsAlertsEnabled says whether the source alerts, reading an absent policy as on.

func (*AgentMailbox) Validate

func (self *AgentMailbox) Validate() error

Validate reports everything wrong with the source's policy.

type AgentMemory

type AgentMemory struct {
	ID         string    `json:"id"`
	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`
	AgentID    string    `json:"agentId"`

	Title   string   `json:"title"`
	Content string   `json:"content"`
	Tags    []string `json:"tags"`

	// AppliesTo is which runs read it; empty means the conversation only.
	AppliesTo []AgentAudience `json:"appliesTo"`

	// Pinned memories come first in every prompt.
	Pinned bool `json:"pinned"`

	// UsedAt is when a prompt last carried it or a search last found it,
	// which is what orders the rest.
	UsedAt *time.Time `json:"usedAt,omitempty"`

	// Vector is what the memory means, for finding it by meaning rather
	// than by the words it happens to use, and VectorModel is what said
	// so: two vectors are comparable only when one model made them both.
	Vector      []float32 `json:"-"`
	VectorModel string    `json:"-"`
}

AgentMemory is a durable fact about the person that outlives a conversation — "signs as Z.", "the accountant is Maria", "never answer the landlord automatically" — addressed to the runs that should read it. Per person, per server; never shared.

func (*AgentMemory) Addressed

func (self *AgentMemory) Addressed(audience AgentAudience) bool

Addressed says whether a memory is for an audience.

func (*AgentMemory) Line

func (self *AgentMemory) Line() string

Line is the memory as a prompt carries it.

func (*AgentMemory) Validate

func (self *AgentMemory) Validate() error

Validate reports everything wrong with a memory.

type AgentMessage

type AgentMessage struct {
	ID             string    `json:"id"`
	CreatedAt      time.Time `json:"createdAt"`
	ConversationID string    `json:"conversationId"`

	Role       string          `json:"role"` // system | user | assistant | tool | note
	Content    string          `json:"content"`
	ToolCalls  []AgentToolCall `json:"toolCalls,omitempty"`
	ToolCallID string          `json:"toolCallId,omitempty"`
	Name       string          `json:"name,omitempty"`
	Usage      *AgentUsageNote `json:"usage,omitempty"`

	// Attachments are the files that came with a person's turn, and
	// References the threads they pointed at when they wrote it.
	Attachments []AgentAttachment `json:"attachments,omitempty"`
	References  []AgentReference  `json:"references,omitempty"`

	// Reactions are the emoji the person and the agent put on the
	// message, at most one each, read with the page the message is on. In a
	// chat, one for each person who reacted.
	Reactions []AgentMessageReaction `json:"reactions,omitempty"`

	// The author, so that a client draws a message from the owner, their
	// agent or another person on one path. AuthorKind is person or agent.
	// For a conversation with an agent the person is the owner and the agent
	// theirs; in a chat they are whoever wrote it. An agent has no picture:
	// its AuthorAvatarURL is null and the color is its owner's.
	AuthorKind   ChatAuthorKind `json:"authorKind,omitempty"`
	AuthorUserID string         `json:"authorUserId,omitempty"`
	AuthorName   string         `json:"authorName,omitempty"`
	// AuthorOwnerName is, on an agent's message in a chat, its owner's
	// name; see ChatMessage.AuthorOwnerName and AgentSpeakerLabel.
	AuthorOwnerName        string  `json:"authorOwnerName,omitempty"`
	AuthorAvatarURL        *string `json:"authorAvatarUrl,omitempty"`
	AuthorAvatarColorIndex int     `json:"authorAvatarColorIndex,omitempty"`
	AuthorAgentID          string  `json:"authorAgentId,omitempty"`

	// AgentRunID is, on a chat message an agent wrote, the run of the turn
	// that wrote it, so that a client replaces the text it drew while that
	// turn was still being written with this message.
	AgentRunID string `json:"agentRunId,omitempty"`

	// IsMine says the message was written by the person reading it or by
	// their agent.
	IsMine bool `json:"isMine,omitempty"`

	// MentionedUserIDs and IsAllMentioned are, on a chat's message, who it
	// mentions: see ChatMessage.MentionedUserIDs. A client marks the
	// mentions in the words with them.
	MentionedUserIDs []string `json:"mentionedUserIds,omitempty"`
	IsAllMentioned   bool     `json:"isAllMentioned,omitempty"`

	// IsAgentWork says that, in a chat, the row is what the reader's own
	// agent did to answer (a call, its result, a note, a card) and not
	// something said in the chat. Only they read it; the chat's messages are
	// the rows without it.
	IsAgentWork bool `json:"isAgentWork,omitempty"`

	// IsVoiceMessage, TranscriptText and TranscriptState are, on a chat's
	// message, what ChatMessage says of them.
	IsVoiceMessage  bool   `json:"isVoiceMessage,omitempty"`
	TranscriptText  string `json:"transcriptText,omitempty"`
	TranscriptState string `json:"transcriptState,omitempty"`

	// CallID and Call are, on a chat's message that is the line of a call,
	// what ChatMessage says of them.
	CallID string    `json:"callId,omitempty"`
	Call   *ChatCall `json:"call,omitempty"`

	// EditedAt is when its author last changed what it says, and IsDeleted
	// says they took it back: its content is then empty.
	EditedAt  *time.Time `json:"editedAt,omitempty"`
	IsDeleted bool       `json:"isDeleted,omitempty"`
}

AgentMessage is one turn, tool call or result in a conversation.

func NewAgentNote added in v0.71.2

func NewAgentNote(conversationId string, kind AgentNoteKind, detail string) *AgentMessage

NewAgentNote is a note of a kind for a conversation.

func (*AgentMessage) CanBeReactedToBy added in v0.136.1

func (self *AgentMessage) CanBeReactedToBy(reactorKind AgentReactorKind) bool

CanBeReactedToBy says whether a reactor may put a reaction on the message: each side reacts to what the other said, as in a chat app, so the person to the agent's messages and the agent to the person's. Nobody reacts to their own words, nor to a tool's result or a note.

func (*AgentMessage) VoiceMessageDurationMS added in v0.211.0

func (self *AgentMessage) VoiceMessageDurationMS() int64

VoiceMessageDurationMS is the length of the recording the message carries, zero when it is not a voice message.

func (*AgentMessage) WordsForReading added in v0.211.0

func (self *AgentMessage) WordsForReading() string

WordsForReading is what a model reads for the message: its content, or for a voice message the same words ChatMessage.WordsForReading gives.

type AgentMessageReaction added in v0.134.0

type AgentMessageReaction struct {
	Emoji       string           `json:"emoji"`
	ReactorKind AgentReactorKind `json:"reactorKind"`
	ReactedAt   time.Time        `json:"reactedAt"`

	// ReactorUserID and ReactorName say who, in a chat where there are
	// several people to tell apart. ReactorUserID is empty once the account
	// is gone, and for a conversation with an agent, where it is always the
	// owner.
	ReactorUserID string `json:"reactorUserId,omitempty"`
	ReactorName   string `json:"reactorName,omitempty"`
}

AgentMessageReaction is an emoji put on a message, as in a chat app: one per reactor per message, replaced by reacting again.

type AgentNode

type AgentNode struct {
	ID         string    `json:"id"`
	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`
	AgentID    string    `json:"agentId"`

	// Version is the build that last wrote this, so a later one can find
	// what an earlier one filed under rules that have since changed. See
	// migration 0073.
	Version string `json:"version,omitempty"`

	// Path is the address, and the hierarchy: "work/northwind/dev/portal" is
	// under "work/northwind/dev". ParentID is the same thing as a link, so a
	// query can walk what a string can only spell.
	Path     string `json:"path"`
	ParentID string `json:"parentId,omitempty"`

	Kind AgentNodeKind `json:"kind"`
	Name string        `json:"name"`

	// Aliases are what else the person calls it: "alice", "the fleet
	// team". Searched along with the name.
	Aliases []string `json:"aliases"`

	// Summary is the page: written by the person, or by the dream from
	// the facts below it.
	Summary string `json:"summary"`

	// ContactID is the address book entry this page is about, for a
	// person. The card that is the person themselves is on their account,
	// not here; the self page reads it live.
	ContactID string `json:"contactId,omitempty"`

	Pinned bool `json:"pinned"`

	// Importance orders the index every prompt carries. Recomputed by the
	// nightly run and by nothing else, so a prompt's cacheable part does
	// not move during the day.
	Importance float32 `json:"importance"`

	// Dormant is out of the index and still searchable.
	Dormant bool `json:"dormant"`

	UsedAt *time.Time `json:"usedAt,omitempty"`

	// Overview is how the thing works, in several short markdown sections,
	// written by the night from the page's facts, the overviews of the
	// pages under it and the openings of the pages it is linked to. The
	// opening says what a page is and every prompt's index carries it; the
	// overview is longer and is read only when the page itself is.
	//
	// Written only by the night's overview phase, and never by writing the
	// page, so a page saved from a copy read before an overview was written
	// does not put the old one back.
	Overview          string     `json:"overview,omitempty"`
	OverviewWrittenAt *time.Time `json:"overviewWrittenAt,omitempty"`

	// OverviewInputs is a hash of what the overview was written from. The
	// night writes it again when the hash of the page's inputs as they are
	// now is different; empty means it is due.
	OverviewInputs string `json:"-"`

	// OverviewEvidence is the pages (kind memory, the path as the quote)
	// and the files (kind document) the overview cites.
	OverviewEvidence []Evidence `json:"overviewEvidence,omitempty"`
}

AgentNode is a page about one thing.

func (*AgentNode) IndexLine

func (self *AgentNode) IndexLine(width int) string

IndexLine is a page as the index in a prompt carries it: the path, the name, and the first sentence of the summary if there is room.

func (*AgentNode) Validate

func (self *AgentNode) Validate() error

Validate reports everything wrong with a page.

type AgentNodeKind

type AgentNodeKind string

AgentNodeKind is what a page is about.

const (
	NodeSelf         AgentNodeKind = "self"
	NodePerson       AgentNodeKind = "person"
	NodeOrganization AgentNodeKind = "organization"
	NodeProject      AgentNodeKind = "project"
	NodeTopic        AgentNodeKind = "topic"
	NodePlace        AgentNodeKind = "place"
	NodeThing        AgentNodeKind = "thing"
	NodeFolder       AgentNodeKind = "folder"
	NodePeriod       AgentNodeKind = "period"
)

The kinds. A folder holds other pages and says nothing itself; a period is a month or a year, which is how time becomes a place in the graph.

type AgentNoteKind added in v0.71.2

type AgentNoteKind string

AgentNoteKind names a note, so that a client words it in the person's language. A note of a kind keeps the kind in the message's Name and only its detail in Content: the goal, the reason, the count. A note without one is prose, shown as written.

const (
	NoteQueued                AgentNoteKind = "queued"                   // the turn waits behind the one before it
	NoteStopped               AgentNoteKind = "stopped"                  // stopped, by the person or for the detail's reason
	NoteFailed                AgentNoteKind = "failed"                   // the turn failed: the error
	NoteCallUnreadable        AgentNoteKind = "call_unreadable"          // a tool call the server could not read
	NoteRepeatedFailure       AgentNoteKind = "repeated_failure"         // the same call failed three times
	NoteRoundLimit            AgentNoteKind = "round_limit"              // the most rounds a turn may take
	NoteCompacting            AgentNoteKind = "compacting"               // the earlier conversation is being folded into a note
	NoteCompacted             AgentNoteKind = "compacted"                // it was: the detail is the note
	NoteDepth                 AgentNoteKind = "depth"                    // looked into carefully: the detail is why
	NoteHerdrAsked            AgentNoteKind = "herdr_asked"              // a coding session's question, for the drawer to draw: JSON; only in older conversations
	NoteHerdrAnswered         AgentNoteKind = "herdr_answered"           // it went, and what it was answered with: JSON; only in older conversations
	NoteCircleInvited         AgentNoteKind = "circle_invited"           // somebody invited the person to a circle: JSON of the inviter's name and the circle's
	NoteCircleMemberAdded     AgentNoteKind = "circle_member_added"      // an operator put an account in a circle the person administers: JSON of the account's name and the circle's
	NoteSkillShareCallWaiting AgentNoteKind = "skill_share_call_waiting" // a call of a shared skill waits for the person's approval: JSON naming the call
	NoteRelationshipSet       AgentNoteKind = "relationship_set"         // somebody said what they are to the person: JSON (RelationshipNote)
	NoteRelationshipRemoved   AgentNoteKind = "relationship_removed"     // somebody took that away: JSON (RelationshipNote)
	NoteShareReceived         AgentNoteKind = "share_received"           // somebody shared something with the person: JSON (ShareReceivedNote)
	NoteShareReached          AgentNoteKind = "share_reached"            // somebody joined a circle the person shares things with: JSON (ShareReachedNote)

	// What only the person who addressed an agent in a chat is told, when
	// no turn of it started: the detail is the agent's name, and for the
	// first the names of the agent and its owner as JSON (ChatAgentNote),
	// since an agent is called "Agent" until its owner names it and only the
	// owner tells two of them apart.
	NoteChatAgentOwnerOnly AgentNoteKind = "chat_agent_owner_only" // only its owner can ask that agent in this chat
	NoteChatAgentOff       AgentNoteKind = "chat_agent_off"        // its owner has switched it off
	NoteChatAgentAbsent    AgentNoteKind = "chat_agent_absent"     // its owner is not in this chat
	// The goal notes below are written no longer, since goals have their
	// own conversations and activity; they are kept so that transcripts
	// written before still read.
	NoteGoalSet      AgentNoteKind = "goal_set" // the detail is the goal
	NoteGoalSetAgain AgentNoteKind = "goal_set_again"
	NoteGoalChanged  AgentNoteKind = "goal_changed"
	NoteGoalCleared  AgentNoteKind = "goal_cleared"
	NoteGoalMet      AgentNoteKind = "goal_met"     // the detail is what was said of it, or the goal
	NoteGoalStalled  AgentNoteKind = "goal_stalled" // no longer written; old transcripts keep it, and the detail is how many turns went by alone
)

The kinds of note a conversation carries.

type AgentNotifications

type AgentNotifications struct {
	HeldReply    string `json:"heldReply,omitempty" graphapi:"nullable"`
	HighPriority string `json:"highPriority,omitempty" graphapi:"nullable"`
	RunFailed    string `json:"runFailed,omitempty" graphapi:"nullable"`
}

AgentNotifications say, per event, whether the person is told and how: "off", "dashboard", or "mail" to the account's notification address.

type AgentPageShare added in v0.170.0

type AgentPageShare struct {
	ID string `json:"id"`

	// AgentID is the owner's agent, whose pages are shared.
	AgentID string `json:"agentId"`

	// Path is the root of the shared subtree: the page at that path and every
	// page under it.
	Path string `json:"path"`

	GranteeUserID   string `json:"granteeUserId,omitempty"`
	GranteeCircleID string `json:"granteeCircleId,omitempty"`

	// IsQuoteShared says the words each fact was read in are shown too. Left
	// off, a reader sees what a fact says and where it was read, and not the
	// owner's own mail, chat or documents quoted back.
	IsQuoteShared bool `json:"isQuoteShared"`

	CreatedAt       time.Time `json:"createdAt"`
	CreatedByUserID string    `json:"createdByUserId,omitempty"`

	// The rest is read along with the row. The owner is the account the
	// agent belongs to; the grantee is a person or a circle, named for a
	// screen.
	OwnerUserID       string `json:"ownerUserId,omitempty"`
	OwnerUsername     string `json:"ownerUsername,omitempty"`
	OwnerName         string `json:"ownerName,omitempty"`
	OwnerUser         *User  `json:"-"`
	GranteeUsername   string `json:"granteeUsername,omitempty"`
	GranteeName       string `json:"granteeName,omitempty"`
	GranteeUser       *User  `json:"-"`
	GranteeCircleName string `json:"granteeCircleName,omitempty"`
}

AgentPageShare gives one person, or every member of one circle, a read-only view of a page and everything under it. Exactly one of GranteeUserID and GranteeCircleID is set.

func (*AgentPageShare) Covers added in v0.170.0

func (self *AgentPageShare) Covers(pagePath string) bool

Covers says whether the share reaches the page at this path: the shared path itself and every path under it.

type AgentPhone added in v0.128.0

type AgentPhone struct {
	ID         string    `json:"id"`
	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`

	AgentID  string `json:"agentId"`
	ClientID string `json:"clientId"`

	PhoneName  string `json:"phoneName"`
	PhoneModel string `json:"phoneModel"`

	// PhonePlatform is PhonePlatformIOS or PhonePlatformAndroid: which app
	// the phone runs, and so which push service the relay reaches it by.
	PhonePlatform string `json:"phonePlatform"`

	// PushRegistration is the relay's sealed registration, empty once Apple
	// said the phone is gone. Never shown to anybody.
	PushRegistration string `json:"-"`

	// VoIPPushRegistration is the relay's sealed registration for the token
	// PushKit gave the app, which is how a phone is rung for a call. Empty
	// while the app has not registered one, or once Apple said it is gone.
	// Never shown to anybody.
	VoIPPushRegistration string `json:"-"`

	// PayloadKey is the phone's notification key, sealed. Never shown.
	PayloadKey string `json:"-"`

	// NotificationKinds are the kinds the phone wants; empty is all.
	NotificationKinds []string `json:"notificationKinds"`

	// PushedThrough is how far the agent's own turns have been sent.
	PushedThrough string `json:"-"`

	LastSeenAt        *time.Time `json:"lastSeenAt,omitempty"`
	LastDeliveredAt   *time.Time `json:"lastDeliveredAt,omitempty"`
	LastDeliveryError string     `json:"lastDeliveryError,omitempty"`

	// TouredAt is when the agent showed the person around the phone, once,
	// after it connected.
	TouredAt *time.Time `json:"touredAt,omitempty"`
}

AgentPhone is a phone a person talks to their agent from, in the TeaNode app: one per install, tied to the OAuth client the app registered as.

func (*AgentPhone) CanBeNotified added in v0.128.0

func (self *AgentPhone) CanBeNotified() bool

CanBeNotified reports whether the phone has a registration to send to.

func (*AgentPhone) CanRing added in v0.212.0

func (self *AgentPhone) CanRing() bool

CanRing reports whether the phone can be rung for a call: it has a VoIP registration and a key to seal the call's content with.

func (*AgentPhone) Wants added in v0.128.0

func (self *AgentPhone) Wants(notificationKind string) bool

Wants reports whether the phone takes a kind of notification.

type AgentPriceChange added in v0.165.0

type AgentPriceChange struct {
	Model     string `json:"model"`
	TokenKind string `json:"tokenKind"`

	BeforePerMillion float64 `json:"beforePerMillion"`
	AfterPerMillion  float64 `json:"afterPerMillion"`
}

AgentPriceChange is one price the check set from the bill.

type AgentReach added in v0.50.0

type AgentReach struct {
	AgentID string `json:"agentId"`

	// Kind is AgentReachSkill or AgentReachServer.
	Kind string `json:"kind"`

	// Name is the skill's or the server's.
	Name string `json:"name"`

	// ComputerName is the attached computer the requests go through.
	ComputerName string `json:"computerName"`

	ModifiedAt time.Time `json:"modifiedAt"`
}

AgentReach is a reach: the computer one of a person's skills or connected servers makes its requests through, rather than through this server, named as it attaches.

type AgentReactorKind added in v0.134.0

type AgentReactorKind string

AgentReactorKind is who put a reaction on a message of a conversation.

const (
	ReactorPerson AgentReactorKind = "person"
	ReactorAgent  AgentReactorKind = "agent"
)

The two who react: the person whose conversation it is, and their agent.

type AgentRecordDetail added in v0.154.0

type AgentRecordDetail struct {
	// TranscriptRunID is the transcript a recording passage's range is
	// counted in; a recording can be transcribed again.
	TranscriptRunID string `json:"transcriptRunId,omitempty"`

	// MailboxID is the mailbox a mail message is in.
	MailboxID string `json:"mailboxId,omitempty"`
}

AgentRecordDetail is where inside a record a link points, for the kinds that need more than an identifier.

type AgentRecordKind added in v0.154.0

type AgentRecordKind string

AgentRecordKind is which of the person's own records a link points at.

const (
	RecordContact             AgentRecordKind = "contact"
	RecordMail                AgentRecordKind = "mail"
	RecordCalendarEvent       AgentRecordKind = "calendar_event"
	RecordReminder            AgentRecordKind = "reminder"
	RecordConversationMessage AgentRecordKind = "conversation_message"
	RecordFinanceTransaction  AgentRecordKind = "finance_transaction"
	RecordFinanceReceipt      AgentRecordKind = "finance_receipt"
	RecordRecordingPassage    AgentRecordKind = "recording_passage"

	// The kinds a journal day links to besides the ones above. A calendar
	// occurrence is the event's identifier, "@" and the occurrence's start
	// (RFC 3339), so that one occurrence of a repeating event can be named; a
	// Health day is the Health type, "@" and the day (stepCount@2026-10-22).
	RecordPhoto              AgentRecordKind = "photo"
	RecordPlaceVisit         AgentRecordKind = "place_visit"
	RecordAgentDocument      AgentRecordKind = "agent_document"
	RecordChatMessage        AgentRecordKind = "chat_message"
	RecordRecording          AgentRecordKind = "recording"
	RecordCalendarOccurrence AgentRecordKind = "calendar_occurrence"
	RecordHealthDay          AgentRecordKind = "health_day"
	RecordShoppingTrip       AgentRecordKind = "shopping_trip"
	RecordNote               AgentRecordKind = "note"
	RecordIdea               AgentRecordKind = "idea"
	RecordGoal               AgentRecordKind = "goal"
)

The kinds. A passage of a recording is the recording's identifier plus a range of milliseconds (AgentRecordLink.PassageStartMS and PassageEndMS).

func ParseRecordReference added in v0.154.0

func ParseRecordReference(reference string) (recordKind AgentRecordKind, recordId string, startMS, endMS int64, err error)

ParseRecordReference is the inverse of FormatRecordReference. A passage without a range is the whole recording, 0 to 0.

type AgentRecordLink struct {
	ID      string `json:"id"`
	AgentID string `json:"agentId"`
	NodeID  string `json:"nodeId"`

	// NodePath, NodeName and NodeKind are filled when the link is read for
	// a record's backlinks, where the page is the other end. Not stored.
	NodePath string        `json:"nodePath,omitempty"`
	NodeName string        `json:"nodeName,omitempty"`
	NodeKind AgentNodeKind `json:"nodeKind,omitempty"`

	RecordKind   AgentRecordKind   `json:"recordKind"`
	RecordID     string            `json:"recordId"`
	RecordDetail AgentRecordDetail `json:"recordDetail"`

	// PassageStartMS and PassageEndMS are the range of a recording passage
	// in milliseconds on the recording's timeline; zero for any other kind.
	PassageStartMS int64 `json:"passageStartMS"`
	PassageEndMS   int64 `json:"passageEndMS"`

	RecordRelation AgentRecordRelation `json:"recordRelation"`

	// LinkStatus is the same vocabulary as a link between two pages:
	// stated, or proposed where the agent only guessed.
	LinkStatus AgentEdgeStatus `json:"linkStatus"`

	Evidence   []Evidence `json:"evidence"`
	Note       string     `json:"note,omitempty"`
	HappenedAt *time.Time `json:"happenedAt,omitempty"`
	CreatedAt  time.Time  `json:"createdAt"`
	ModifiedAt time.Time  `json:"modifiedAt"`
}

AgentRecordLink joins a page to one of the person's own records.

func (*AgentRecordLink) Proposed added in v0.154.0

func (self *AgentRecordLink) Proposed() bool

Proposed says whether this link is the agent's own guess.

func (*AgentRecordLink) Reference added in v0.154.0

func (self *AgentRecordLink) Reference() string

Reference is the link's record as a person or a command line names it: "contact:ID", or "recording_passage:ID@START-END" for a range of a recording, in milliseconds.

func (*AgentRecordLink) Validate added in v0.154.0

func (self *AgentRecordLink) Validate() error

Validate says whether a link could be stored: a known kind, a relation that fits it, a record named, and a range only where it means something.

type AgentRecordRelation added in v0.154.0

type AgentRecordRelation string

AgentRecordRelation is what a page is to a record.

const (
	RecordRelationIsContact   AgentRecordRelation = "is_contact"
	RecordRelationWrote       AgentRecordRelation = "wrote"
	RecordRelationReceived    AgentRecordRelation = "received"
	RecordRelationAttended    AgentRecordRelation = "attended"
	RecordRelationOrganized   AgentRecordRelation = "organized"
	RecordRelationSpokeIn     AgentRecordRelation = "spoke_in"
	RecordRelationMentionedIn AgentRecordRelation = "mentioned_in"
	RecordRelationPaid        AgentRecordRelation = "paid"
	RecordRelationPaidBy      AgentRecordRelation = "paid_by"
	RecordRelationReceiptFor  AgentRecordRelation = "receipt_for"
	RecordRelationAbout       AgentRecordRelation = "about"
)

The relations. IsContact is the page's person being that card; Wrote and Received are mail; Attended and Organized are events; SpokeIn is a passage of a recording; Paid and PaidBy are a transaction, Paid being the page the money went to (a merchant) and PaidBy the page it came from; ReceiptFor is a receipt standing behind a transaction; MentionedIn and About are the loose ones.

func RecordRelationsOf added in v0.154.0

func RecordRelationsOf(recordKind AgentRecordKind) []AgentRecordRelation

RecordRelationsOf is the relations that fit a kind of record.

type AgentReference

type AgentReference struct {
	ItemID   string `json:"itemId,omitempty" graphapi:"nullable"`
	ThreadID string `json:"threadId,omitempty" graphapi:"nullable"`
	Subject  string `json:"subject,omitempty" graphapi:"nullable"`
	From     string `json:"from,omitempty" graphapi:"nullable"`

	// Path and Name point at a page of the agent's own memory instead of
	// a message: the person pressed Ask on a page of the graph, and wants
	// the agent to dig into it, or to change what it says and links to.
	Path string `json:"path,omitempty" graphapi:"nullable"`
	Name string `json:"name,omitempty" graphapi:"nullable"`

	// FinanceTransactionID points at one of the agent's finance
	// transactions instead: the person pressed Ask in its details. The
	// fields after it are what the chip shows, named as on the finance
	// transaction; the server fills them in from the stored row whatever
	// the dashboard sent, and drops the reference when the finance
	// transaction is not the agent's.
	FinanceTransactionID string `json:"financeTransactionId,omitempty" graphapi:"nullable"`
	PostedOn             string `json:"postedOn,omitempty" graphapi:"nullable"`
	Amount               string `json:"amount,omitempty" graphapi:"nullable"`
	CurrencyCode         string `json:"currencyCode,omitempty" graphapi:"nullable"`
	MerchantName         string `json:"merchantName,omitempty" graphapi:"nullable"`
	Description          string `json:"description,omitempty" graphapi:"nullable"`

	// RecordingID points at one of the person's recordings instead: the
	// person pressed Ask on its page. RecordingTitle is what the chip
	// shows, its typed or generated title or "Untitled recording"; the
	// server fills it in from the stored row whatever the dashboard sent,
	// and drops the reference when the recording is not the person's or
	// has been deleted.
	RecordingID    string `json:"recordingId,omitempty" graphapi:"nullable"`
	RecordingTitle string `json:"recordingTitle,omitempty" graphapi:"nullable"`

	// PhotoID points at one of the person's photos instead: the person
	// pressed Ask on it in the library. PhotoTitle is what the chip shows,
	// the place and the date where it was taken, or its file name; the
	// server fills it in from the stored row whatever the dashboard sent,
	// and drops the reference when the photo is not the person's or has
	// been deleted.
	PhotoID    string `json:"photoId,omitempty" graphapi:"nullable"`
	PhotoTitle string `json:"photoTitle,omitempty" graphapi:"nullable"`

	// AgentMessageID points at a message earlier in the same conversation
	// instead: the person swiped it, or picked Reply on it, to say what
	// they are answering. QuotedRole is whose it was, "user" or
	// "assistant", and QuotedText what it said, whole; the server
	// fills both in from the stored message whatever the dashboard sent,
	// and drops the reference when the message is not in the
	// conversation. A line the dashboard has no id for yet, an answer
	// still arriving, is quoted by its words alone.
	AgentMessageID string `json:"agentMessageId,omitempty" graphapi:"nullable"`
	QuotedRole     string `json:"quotedRole,omitempty" graphapi:"nullable"`
	QuotedText     string `json:"quotedText,omitempty" graphapi:"nullable"`

	// FeedItemID points at a card of the agent's feed instead: the person
	// pressed Discuss on it, or chose an action on it. FeedItemTitle is what
	// the chip shows; the server fills it in from the stored card whatever
	// the client sent, and drops the reference when the card is not the
	// person's.
	FeedItemID    string `json:"feedItemId,omitempty" graphapi:"nullable"`
	FeedItemTitle string `json:"feedItemTitle,omitempty" graphapi:"nullable"`

	// FeedItemContext is what the model is told about the card in the turn
	// it was pointed at: read from the database when the turn is kept, and
	// never stored.
	FeedItemContext string `json:"-"`

	// FinanceTransactionContext is what the model is told about the
	// finance transaction in the turn it was pointed at: read from the
	// database when the turn is kept, and never stored, so an earlier
	// turn names it by its id alone and the finance tool reads it again.
	FinanceTransactionContext string `json:"-"`

	// RecordingContext is the same for a recording: what the model is told
	// about it in the turn it was pointed at, read when the turn is kept
	// and never stored, so an earlier turn names it by its id alone and the
	// recording tool reads it again.
	RecordingContext string `json:"-"`

	// PhotoContext is the same for a photo: what the model is told about it
	// in the turn it was pointed at, read when the turn is kept and never
	// stored, so an earlier turn names it by its id alone and the photo tool
	// reads it again.
	PhotoContext string `json:"-"`
}

AgentReference is a thread or message the person pointed the agent at with a turn: what the dashboard had open, named so that "this" keeps meaning it after the page moves on.

type AgentReply

type AgentReply struct {
	ID         string    `json:"id"`
	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`

	AgentID   string `json:"agentId"`
	MailboxID string `json:"mailboxId"`

	// MailID is the message answered; ThreadID its conversation.
	MailID   string `json:"mailId"`
	ThreadID string `json:"threadId,omitempty"`

	// DraftItemID is the draft in Drafts while the reply is held.
	DraftItemID string `json:"draftItemId,omitempty"`
	RunID       string `json:"runId,omitempty"`

	Status AgentReplyStatus `json:"status"`
	Reason string           `json:"reason,omitempty"`

	// What is sent: the subject, the address it goes from — the one the
	// message was written to — the address it goes to, and the text.
	Subject string `json:"subject"`
	From    string `json:"from"`
	To      string `json:"to"`
	Text    string `json:"text"`

	// SendAfter is when the hold ends; SentMailID and SentAt what was sent
	// and when.
	SendAfter  *time.Time `json:"sendAfter,omitempty"`
	SentMailID string     `json:"sentMailId,omitempty"`
	SentAt     *time.Time `json:"sentAt,omitempty"`
}

AgentReply is a reply the agent wrote on the person's behalf: to which message, held as which draft, and what became of it.

type AgentReplyStatus

type AgentReplyStatus string

AgentReplyStatus is where a reply the agent wrote stands.

const (
	AgentReplyHeld      AgentReplyStatus = "held"
	AgentReplySending   AgentReplyStatus = "sending"
	AgentReplySent      AgentReplyStatus = "sent"
	AgentReplyCancelled AgentReplyStatus = "cancelled"
	AgentReplyRefused   AgentReplyStatus = "refused"
	AgentReplyFailed    AgentReplyStatus = "failed"
)

The statuses: held in Drafts until the hold passes; sent; cancelled by the person (or taken over by an edit); refused by the ladder before or at sending, with the reason; failed to send after the ladder let it go.

type AgentRevision

type AgentRevision struct {
	ID       string `json:"id"`
	AgentID  string `json:"agentId"`
	NodeID   string `json:"nodeId"`
	Revision int    `json:"revision"`

	Kind  RevisionKind  `json:"kind"`
	Actor RevisionActor `json:"actor"`

	// Before and After are what changed. Both, because a change that only
	// records the new value cannot be undone or explained.
	Before map[string]any `json:"before"`
	After  map[string]any `json:"after"`

	Reason    string    `json:"reason,omitempty"`
	Version   string    `json:"version,omitempty"`
	CreatedAt time.Time `json:"createdAt"`
}

AgentRevision is one change to a page, kept so the page can be accounted for.

Version is the build that made the change. A graph outlives the code that filled it, and "written before the rule existed" is a question only a version can answer.

func (*AgentRevision) Change

func (self *AgentRevision) Change() string

Change is what happened, without who did it.

func (*AgentRevision) Describe

func (self *AgentRevision) Describe() string

Describe is the change in a line, for a history somebody reads: who, then what they did.

Change is the same line without the who, for a reader that shows the actor beside it rather than in it -- the dashboard puts it in a badge, and saying it twice in one row reads as a stutter.

func (*AgentRevision) PathAfter

func (self *AgentRevision) PathAfter() string

PathAfter is the page a change points at: where a page was moved to, or the other end of a link. For an unlink, which has no "after" at all, it is the page that was unlinked.

func (*AgentRevision) TextAfter

func (self *AgentRevision) TextAfter() string

func (*AgentRevision) TextBefore

func (self *AgentRevision) TextBefore() string

TextBefore and TextAfter are the words a change moved, where it moved words at all. Empty for a change that moved something else.

type AgentRoot

type AgentRoot struct {
	Path    string
	Kind    AgentNodeKind
	Name    string
	Summary string
}

AgentRoot is one of the roots and what it is called.

type AgentSkill

type AgentSkill struct {
	Name       string    `json:"name"`
	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`

	Version     string `json:"version"`
	Publisher   string `json:"publisher"`
	URL         string `json:"url"`
	SHA256      string `json:"sha256"`
	Description string `json:"description"`

	// Content is the file as it was fetched and checked, kept so that a
	// server that can no longer reach the registry still has it and an
	// operator can read what is installed.
	Content string `json:"-"`

	Enabled bool `json:"enabled"`

	// Scope is who fills this skill's secrets in, when an operator has
	// settled it for the whole skill rather than leaving it to what the
	// skill's author declared per secret: "operator", "person", or empty
	// for the author's declaration.
	Scope string `json:"scope"`
}

AgentSkill is a skill installed from a registry: a file of declarations whose tools join everybody's catalog. Installed by an operator and belonging to the server, not to a person, which is why there is no agent here.

type AgentSkillSecret

type AgentSkillSecret struct {
	AgentID    string    `json:"agentId"`
	Skill      string    `json:"skill"`
	Key        string    `json:"key"`
	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`

	// Value is sealed with the server secret and never leaves the server.
	Value string `json:"-"`
}

AgentSkillSecret is one person's own value for a secret an installed skill declared as theirs to fill in. The operator's values live in the configuration; these belong to the person whose agent uses them.

type AgentSourceSecret added in v0.55.0

type AgentSourceSecret struct {
	SourceID   string    `json:"sourceId"`
	Key        string    `json:"key"`
	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`

	// Value is sealed with the server secret; it is opened only to be
	// sent to the computer that reads the source.
	Value string `json:"-"`
}

AgentSourceSecret is one secret a source's type declares, filled in by the person whose source it is.

type AgentSourceType added in v0.54.0

type AgentSourceType struct {
	Name       string    `json:"name"`
	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`

	Version     string `json:"version"`
	Publisher   string `json:"publisher"`
	URL         string `json:"url"`
	SHA256      string `json:"sha256"`
	Description string `json:"description"`

	// Content is the file as it was fetched and checked, or as the
	// operator gave it.
	Content string `json:"-"`

	// IsLocal says the type was added from a file rather than installed
	// from the registry, so nothing but the operator vouches for it.
	IsLocal bool `json:"isLocal"`
}

AgentSourceType is a source type installed on this server: the file that says how to read one kind of knowledge source, with what the registry said about it, or an operator's own file, marked local.

type AgentSummaries

type AgentSummaries struct {
	Enabled bool `json:"enabled"`

	// MinimumMessages is how long a conversation is before it gets a
	// summary without being opened. Zero means the default, three.
	MinimumMessages int `json:"minimumMessages,omitempty" graphapi:"nullable"`

	// Style is brief or detailed.
	Style string `json:"style,omitempty" graphapi:"nullable"`
}

AgentSummaries is the summarizing policy for one source.

type AgentSymbol

type AgentSymbol struct {
	AgentID    string `json:"agentId"`
	DocumentID string `json:"documentId"`
	Symbol     string `json:"symbol"`
	Kind       string `json:"kind"`
	Line       int    `json:"line"`
}

AgentSymbol is one definition a code file declares.

type AgentTodo

type AgentTodo struct {
	ID             string     `json:"id"`
	CreatedAt      time.Time  `json:"createdAt"`
	ConversationID string     `json:"conversationId"`
	Text           string     `json:"text"`
	DoneAt         *time.Time `json:"doneAt,omitempty"`
}

AgentTodo is one item of a conversation's task list.

type AgentToolCall

type AgentToolCall struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Arguments string `json:"arguments"`
	// Intention is the model's words for what the call does, as the apps
	// show it in place of the tool's name; "" when it gave none fit to
	// show. The arguments still carry it, as the model wrote them.
	Intention string `json:"intention,omitempty"`
}

AgentToolCall is a tool the model asked for, as recorded.

type AgentTriage

type AgentTriage struct {
	Enabled bool `json:"enabled"`

	// Backfill is what to do with the mail already there when the mailbox
	// is granted: none, recent (the newest 200), or all (under the budget,
	// over days).
	Backfill string `json:"backfill,omitempty" graphapi:"nullable"`

	// ReplyExpectation is what counts as needing a reply: direct (the
	// person is addressed) or any (including copies).
	ReplyExpectation string `json:"replyExpectation,omitempty" graphapi:"nullable"`
}

AgentTriage is the sorting policy for one source.

type AgentTurn added in v0.206.2

type AgentTurn struct {
	RunID          string `json:"runId"`
	ConversationID string `json:"conversationId"`

	// Instance is the name of the instance running it.
	Instance string `json:"instance"`

	StartedAt time.Time `json:"startedAt"`

	// HeartbeatAt is when its instance last said it was still running it. A
	// turn whose instance has not said so for a while is one that instance
	// lost when it stopped without saying so.
	HeartbeatAt time.Time `json:"heartbeatAt"`

	// CutAt is when its instance stopped with the turn still in flight, nil
	// while it runs: the turn waits for whichever instance carries it on.
	CutAt *time.Time `json:"cutAt,omitempty"`
}

AgentTurn is a turn of the agent running on some instance of the server: what lets every instance tell whether a conversation has a turn in flight, reach it with a word (stop, an answer, a card), and carry it on when the instance running it went away.

type AgentUsageModelRow

type AgentUsageModelRow struct {
	Key    string           `json:"key"`
	Model  string           `json:"model"`
	Totals AgentUsageTotals `json:"totals"`
}

AgentUsageModelRow is totals under one key for one model, which is what pricing a period needs: models are not priced alike.

type AgentUsageNote

type AgentUsageNote struct {
	Model            string `json:"model"`
	Kind             string `json:"kind"`
	PromptTokens     int    `json:"promptTokens"`
	CompletionTokens int    `json:"completionTokens"`
	CacheReadTokens  int    `json:"cacheReadTokens"`
	CacheWriteTokens int    `json:"cacheWriteTokens"`

	// Cost is what the call cost by the provider's pricing, in the
	// operator's currency; zero when there is no pricing.
	Cost float64 `json:"cost,omitempty"`
}

AgentUsageNote is what one model call cost, on the message it produced.

type AgentUsageRow

type AgentUsageRow struct {
	Key    string           `json:"key"`
	Totals AgentUsageTotals `json:"totals"`

	// Cost is what those tokens came to at the prices the models are
	// configured with, and Currency what that is written in. The store
	// leaves both alone: only what knows the prices fills them in.
	Cost     float64 `json:"cost"`
	Currency string  `json:"currency,omitempty"`

	// BilledAmount is what the provider billed for the same period, in
	// BilledCurrencyCode, when the daily check has read its bill for it.
	// Nil when it has not, or when the grouping is not one a bill is kept
	// for (only none, day and model are).
	BilledAmount       *float64 `json:"billedAmount,omitempty"`
	BilledCurrencyCode string   `json:"billedCurrencyCode,omitempty"`
}

AgentUsageRow is totals under one key: a day, a run kind, a source or a model, depending on what was asked.

type AgentUsageTotals

type AgentUsageTotals struct {
	PromptTokens     int64 `json:"promptTokens"`
	CompletionTokens int64 `json:"completionTokens"`
	CacheReadTokens  int64 `json:"cacheReadTokens"`
	CacheWriteTokens int64 `json:"cacheWriteTokens"`
	AudioInputTokens int64 `json:"audioInputTokens"`
	Calls            int64 `json:"calls"`
}

AgentUsageTotals are token counts summed over some rows.

func (AgentUsageTotals) Total

func (self AgentUsageTotals) Total() int64

Total is every token.

type AgentVoice

type AgentVoice struct {
	Tone     string `json:"tone,omitempty" graphapi:"nullable"`   // formal | neutral | casual
	Length   string `json:"length,omitempty" graphapi:"nullable"` // short | medium | long
	Greeting string `json:"greeting,omitempty" graphapi:"nullable"`
	Signoff  string `json:"signoff,omitempty" graphapi:"nullable"`
}

AgentVoice is how the agent sounds, as fields.

type AgentWatchedItem added in v0.114.0

type AgentWatchedItem struct {
	AgentID            string    `json:"agentId"`
	SkillName          string    `json:"skillName"`
	WatchName          string    `json:"watchName"`
	WatchedItemID      string    `json:"watchedItemId"`
	WatchedItemVersion string    `json:"watchedItemVersion"`
	WatchedItemAt      time.Time `json:"watchedItemAt"`
	AlertSignal        string    `json:"alertSignal"`
	LookedAt           time.Time `json:"lookedAt"`
}

AgentWatchedItem is an item a skill's watch has looked at, in the version it was looked at, so that it is judged once and again only when it changes.

type AlertCandidateKind added in v0.82.0

type AlertCandidateKind string

AlertCandidateKind is what made something a candidate for an alert.

const (
	AlertCandidateMessage AlertCandidateKind = "message"
	AlertCandidateBurst   AlertCandidateKind = "burst"
	AlertCandidateBudget  AlertCandidateKind = "budget"
	AlertCandidateWatched AlertCandidateKind = "watched"

	AlertCandidateFollowUp AlertCandidateKind = "follow_up"
)

The kinds: one message the sorting judged worth telling, a burst of messages alike that a count noticed, which no single message's sorting can see, a budget or savings target crossing that code computed after a sync, an item a skill's watch found and judged worth telling: mail in a mailbox this server does not host, a transaction, a mention, and a follow-up (a bill, a parcel, a deadline, coming events) that the daily sweep or a closing parcel found due to be told.

type AlertMuteScope added in v0.82.0

type AlertMuteScope string

AlertMuteScope is what a mute is matched against.

const (
	AlertMuteSender           AlertMuteScope = "sender"
	AlertMuteDomain           AlertMuteScope = "domain"
	AlertMuteSubjectKey       AlertMuteScope = "subjectKey"
	AlertMuteKind             AlertMuteScope = "kind"
	AlertMuteSpendingCategory AlertMuteScope = "spendingCategory"
)

The things the person can say not to be told about: one sender's address, everybody at a domain, one subject (an alert's subject key, or a burst's), a kind of alert (a burst, a budget, or a category of the sorting, such as notification or receipt), or the budget alerts of one spending category, by its id.

func (AlertMuteScope) IsValid added in v0.82.0

func (self AlertMuteScope) IsValid() bool

IsValid says the scope is one of the five.

type Alias

type Alias struct {
	// ID is generated once and never changes; stored deliveries reference it.
	ID string `json:"id"`

	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`

	DomainID string `json:"domainId"`

	// Position is the alias's place among the domain's aliases, which is the
	// order the operator arranged and the order they are matched in.
	Position int `json:"position"`

	// Pattern is a Go regular expression matched against the local part of
	// the recipient address, the part before the "@", without regard to
	// case. Anchor it: "^hello$" matches only hello@, while "hello" also
	// matches say-hello-now@. An empty pattern makes this a catch-all.
	Pattern string `json:"pattern"`

	// Comment is a note for the operator.
	Comment string `json:"comment,omitempty"`

	// Kind is one of null, email, webhook, mailServer or mailbox.
	Kind AliasKind `json:"kind"`

	// Email is the destination address when kind is email.
	Email string `json:"email,omitempty"`

	// Webhook is the destination URL when kind is webhook.
	Webhook string `json:"webhook,omitempty"`

	// MailServer is the destination server when kind is mailServer.
	MailServer *MailServer `json:"mailServer,omitempty"`

	// MailboxID is the mailbox delivered into when kind is mailbox.
	MailboxID string `json:"mailboxId,omitempty"`

	// Disabled stops the alias from matching without deleting it.
	Disabled bool `json:"disabled,omitempty"`
}

Alias decides where mail for a domain goes. Every alias whose pattern matches produces a delivery, so one address can forward to several places; an alias with an empty pattern is a catch-all and receives only what nothing else matched.

func (*Alias) IsCatchAll

func (self *Alias) IsCatchAll() bool

IsCatchAll reports whether this alias receives everything nothing else matched.

func (*Alias) Validate

func (self *Alias) Validate() error

Validate reports everything wrong with the alias.

type AliasKind

type AliasKind string

AliasKind selects what an alias does with matching mail.

const (
	// AliasKindNull accepts the mail and discards it.
	AliasKindNull AliasKind = "null"

	// AliasKindEmail forwards the mail to another email address.
	AliasKindEmail AliasKind = "email"

	// AliasKindWebhook posts the mail to an HTTP endpoint.
	AliasKindWebhook AliasKind = "webhook"

	// AliasKindMailServer relays the mail to a specific mail server.
	AliasKindMailServer AliasKind = "mailServer"

	// AliasKindMailbox delivers the mail into a mailbox on this server: an
	// item in the mailbox's Inbox, referencing the one stored message.
	AliasKindMailbox AliasKind = "mailbox"
)

type AllFinanceShare added in v0.210.0

type AllFinanceShare struct {
	ID          string `json:"id"`
	OwnerUserID string `json:"ownerUserId"`

	GranteeUserID   string `json:"granteeUserId,omitempty"`
	GranteeCircleID string `json:"granteeCircleId,omitempty"`

	// FinanceShareLevel is spending or transactions.
	FinanceShareLevel FinanceShareLevel `json:"financeShareLevel"`

	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`

	// CreatedByUserID is empty once that person is gone.
	CreatedByUserID string `json:"createdByUserId,omitempty"`

	// The rest is filled in by the listings.
	OwnerUsername     string `json:"ownerUsername,omitempty"`
	OwnerName         string `json:"ownerName,omitempty"`
	OwnerUser         *User  `json:"-"`
	GranteeUsername   string `json:"granteeUsername,omitempty"`
	GranteeName       string `json:"granteeName,omitempty"`
	GranteeCircleName string `json:"granteeCircleName,omitempty"`
}

AllFinanceShare gives one person, or every member of one circle, a level of access to all of the owner's finance: every finance account they hold now and every one they link later. Exactly one of GranteeUserID and GranteeCircleID is set. It is the whole-finance counterpart of FinanceShare, which is of one account.

type AnnotatedBy added in v0.118.0

type AnnotatedBy string

AnnotatedBy is who wrote a finance transaction's annotation.

const (
	AnnotatedByPerson AnnotatedBy = "person"
	AnnotatedByAgent  AnnotatedBy = "agent"
)

The person, or their agent acting for them.

func (AnnotatedBy) IsValid added in v0.118.0

func (self AnnotatedBy) IsValid() bool

IsValid says the author is one of the two.

type AntivirusResult

type AntivirusResult struct {
	// Found viruses
	Viruses []string `json:"viruses,omitempty"`
}

AntivirusResult holds authentication results related to antivirus scanning.

type Asset added in v0.87.0

type Asset struct {
	ID        string    `json:"id"`
	AgentID   string    `json:"agentId"`
	AssetName string    `json:"assetName"`
	AssetKind AssetKind `json:"assetKind"`

	// IsLiability is set from the kind: a liability's values subtract.
	IsLiability  bool   `json:"isLiability"`
	CurrencyCode string `json:"currencyCode"`

	// FinanceAccountID is the finance account whose balance values it,
	// empty for anything else.
	FinanceAccountID string `json:"financeAccountId,omitempty" graphapi:"nullable"`

	// FinanceSecurityID is the security a holding holds: an asset valued
	// by a finance account for one security, rather than the account's own
	// asset, which then holds only its cash. FinanceSecurity is the
	// security itself when the asset was read with it.
	FinanceSecurityID string           `json:"financeSecurityId,omitempty" graphapi:"nullable"`
	FinanceSecurity   *FinanceSecurity `json:"financeSecurity,omitempty" graphapi:"nullable"`

	ValuationSource ValuationSource `json:"valuationSource"`

	// EstimateDescription is what the person allowed the agent to search
	// the web with, and IsEstimateAllowed whether they allowed it.
	EstimateDescription string `json:"estimateDescription,omitempty" graphapi:"nullable"`
	IsEstimateAllowed   bool   `json:"isEstimateAllowed"`

	// ClosedOn is the day it was sold or paid off, "2006-01-02": it counts
	// until that day and not after. Empty while open.
	ClosedOn string `json:"closedOn,omitempty" graphapi:"nullable"`

	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`

	// LatestValuation is the valuation that counts today, when the asset
	// was read with it; nil otherwise and when it has none.
	LatestValuation *AssetValuation `json:"latestValuation,omitempty" graphapi:"nullable"`
}

Asset is anything that counts toward net worth, what is owed included.

type AssetKind added in v0.87.0

type AssetKind string

AssetKind is what sort of thing an asset is. The last four are owed rather than owned, and an asset of one of them subtracts from net worth.

const (
	AssetKindCash           AssetKind = "cash"
	AssetKindInvestment     AssetKind = "investment"
	AssetKindRetirement     AssetKind = "retirement"
	AssetKindProperty       AssetKind = "property"
	AssetKindVehicle        AssetKind = "vehicle"
	AssetKindOtherAsset     AssetKind = "other_asset"
	AssetKindCreditCard     AssetKind = "credit_card"
	AssetKindLoan           AssetKind = "loan"
	AssetKindMortgage       AssetKind = "mortgage"
	AssetKindOtherLiability AssetKind = "other_liability"
)

The kinds of asset.

func (AssetKind) IsLiability added in v0.87.0

func (self AssetKind) IsLiability() bool

IsLiability says an asset of this kind is owed, and subtracts.

func (AssetKind) IsValid added in v0.87.0

func (self AssetKind) IsValid() bool

IsValid says the kind is one of the ten.

type AssetValuation added in v0.87.0

type AssetValuation struct {
	ID      string `json:"id"`
	AgentID string `json:"agentId"`
	AssetID string `json:"assetId"`

	// ValuedOn is the day, "2006-01-02".
	ValuedOn string `json:"valuedOn"`

	// Value is a decimal, the size of the thing; the asset's IsLiability
	// gives the sign. Negative only for an account that is overdrawn.
	Value           string          `json:"value"`
	CurrencyCode    string          `json:"currencyCode"`
	ValuationSource ValuationSource `json:"valuationSource"`

	// An estimate's range, what it rests on, and the pages it read.
	EstimateLow   string   `json:"estimateLow,omitempty" graphapi:"nullable"`
	EstimateHigh  string   `json:"estimateHigh,omitempty" graphapi:"nullable"`
	ValuationNote string   `json:"valuationNote,omitempty" graphapi:"nullable"`
	EvidenceURLs  []string `json:"evidenceUrls"`

	// A holding's size on the day, the price of one unit, and what was
	// paid for it, as decimals; empty for anything else.
	HeldQuantity string `json:"heldQuantity,omitempty" graphapi:"nullable"`
	UnitPrice    string `json:"unitPrice,omitempty" graphapi:"nullable"`
	CostBasis    string `json:"costBasis,omitempty" graphapi:"nullable"`

	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`
}

AssetValuation is one value of one asset on one day.

type AuditAction

type AuditAction string

AuditAction is what happened to the row.

const (
	AuditActionCreate AuditAction = "create"
	AuditActionUpdate AuditAction = "update"
	AuditActionDelete AuditAction = "delete"

	// AuditActionObserveConversation is an operator reading another person's
	// agent conversation: nothing changed, and the row says who looked.
	AuditActionObserveConversation AuditAction = "agent.conversation.observe"
)

type AuditActorKind

type AuditActorKind string

AuditActorKind says what kind of principal made a change.

const (
	// AuditActorUser is a signed-in person, through the web UI or the API.
	AuditActorUser AuditActorKind = "user"

	// AuditActorSystem is the server itself: a sweep, a certificate renewal,
	// single sign-on reconciling a group's users.
	AuditActorSystem AuditActorKind = "system"

	// AuditActorRescue is teanode-server run on the host against the
	// database, the one path that bypasses permissions.
	AuditActorRescue AuditActorKind = "rescue"

	// AuditActorAgent is a person's agent acting for them: the row names
	// the person, and the kind says it was the agent's doing.
	AuditActorAgent AuditActorKind = "agent"
)

type AuditEvent

type AuditEvent struct {
	ID        string    `json:"id"`
	CreatedAt time.Time `json:"createdAt"`

	ActorKind   AuditActorKind `json:"actorKind"`
	ActorUserID string         `json:"actorUserId,omitempty"`

	// ActorLabel is the actor's username, or "system" or "rescue": resolved
	// when read, never stored, so a renamed user reads by their current name.
	ActorLabel string `json:"actorLabel,omitempty"`

	// ImpersonatorUserID is the operator who was signed in as the actor
	// when the change was made, and ImpersonatorLabel their username,
	// resolved when read. Empty for a change the actor made themselves.
	ImpersonatorUserID string `json:"impersonatorUserId,omitempty"`
	ImpersonatorLabel  string `json:"impersonatorLabel,omitempty"`

	// TokenID is the session or API token that authorized the request; never
	// its secret.
	TokenID  string `json:"tokenId,omitempty"`
	SourceIP string `json:"sourceIp,omitempty"`

	// Instance is which server instance served the request.
	Instance string `json:"instance,omitempty"`

	ResourceType AuditResourceType `json:"resourceType"`
	ResourceID   string            `json:"resourceId"`
	Action       AuditAction       `json:"action"`

	// ResourceLabel is what the thing is called, resolved when the event is
	// read rather than stored: a renamed group reads by the name it has now,
	// and a row that only carried an id said nothing to anybody.
	ResourceLabel string `json:"resourceLabel,omitempty"`

	// ResourceLink is where the thing is in the dashboard, when it is still
	// there and the reader may see it. Empty for something that has been
	// deleted, or that has no page of its own.
	ResourceLink string `json:"resourceLink,omitempty"`

	// Before is the row before the change, redacted; nil on create.
	Before json.RawMessage `json:"before,omitempty"`

	// After is the row after the change, redacted; nil on delete.
	After json.RawMessage `json:"after,omitempty"`
}

AuditEvent is one administrative change: who made it, from where, what row it touched, and the row before and after with secrets removed. Written in the same transaction as the change.

Per-user private things — folders, items, contacts, flags — are never audited. "Who gave this group that role" must be answerable a year later; "who read this message" must not be recorded.

type AuditRedactor

type AuditRedactor interface {
	RedactForAudit() any
}

AuditRedactor is implemented by a model that carries a secret, so the secret never reaches the audit row.

type AuditResourceType

type AuditResourceType string

AuditResourceType names what was changed. Adding one here is what makes a table audited.

const (
	AuditResourceSyncCredential     AuditResourceType = "sync_credential"
	AuditResourceUser               AuditResourceType = "user"
	AuditResourceGroup              AuditResourceType = "group" // and its users, roles, domains
	AuditResourceRole               AuditResourceType = "role"  // and its permissions
	AuditResourceDomain             AuditResourceType = "domain"
	AuditResourceAlias              AuditResourceType = "alias"
	AuditResourceCredential         AuditResourceType = "credential"
	AuditResourceMailbox            AuditResourceType = "mailbox" // and its rules, signature, out-of-office
	AuditResourceMailboxAddress     AuditResourceType = "mailbox_address"
	AuditResourceMailboxAppPassword AuditResourceType = "mailbox_app_password"
	AuditResourceToken              AuditResourceType = "token"
	AuditResourcePasskey            AuditResourceType = "passkey"
	AuditResourceConfiguration      AuditResourceType = "configuration"
	AuditResourceAgent              AuditResourceType = "agent"       // a person's agent, and its sources
	AuditResourceAddressBook        AuditResourceType = "addressbook" // the book, not the contacts in it
	AuditResourceCalendar           AuditResourceType = "calendar"    // the calendar, not the events in it
	AuditResourceAsset              AuditResourceType = "asset"
	AuditResourceAssetValuation     AuditResourceType = "asset_valuation" // manual valuations only
	AuditResourceSpendingCategory   AuditResourceType = "spending_category"
	AuditResourceSpendingRule       AuditResourceType = "spending_rule"
	AuditResourceBudget             AuditResourceType = "budget"
	AuditResourceSavingsTarget      AuditResourceType = "savings_target"      // and the assets and finance accounts it measures
	AuditResourceFinanceAccount     AuditResourceType = "finance_account"     // renamed or deleted by the person; a sync's writes are not audited
	AuditResourceFinanceTransaction AuditResourceType = "finance_transaction" // annotated by the person or their agent
	AuditResourceFinanceReceipt     AuditResourceType = "finance_receipt"     // and its lines and matches
	AuditResourceFinancePaystub     AuditResourceType = "finance_paystub"     // and its lines
	AuditResourceFinanceTaxForm     AuditResourceType = "finance_tax_form"    // and its boxes
	AuditResourceTaxYearSetting     AuditResourceType = "tax_year_setting"    // a year's estimate inputs
	AuditResourcePasswords          AuditResourceType = "passwords"           // a person's setup, never a key or a hash
	AuditResourcePasswordItem       AuditResourceType = "password_item"       // what happened to an item and who it is shared with, never a sealed value
	AuditResourceAgentConversation  AuditResourceType = "agent_conversation"  // read by an operator with agent:observe or agent:act; nothing in it is recorded
	AuditResourceCircleMember       AuditResourceType = "circle_member"       // an account an operator put in a circle, with no invitation to answer
)

type AuthenticationResults

type AuthenticationResults struct {
	// Authentication results related to sender mail servers
	SenderMX *MXResult `json:"senderMx,omitempty"`

	// Authentication results related to from mail servers
	FromMX *MXResult `json:"fromMx,omitempty"`

	// Authentication results related to DMARC
	DMARC *DMARCResult `json:"dmarc,omitempty"`

	// Authentication results related to SPF
	SPF *SPFResult `json:"spf,omitempty"`

	// Authentication results related to DKIM
	DKIMs []*DKIMResult `json:"dkims,omitempty"`

	// Authentication results related to ARC
	ARC *ARCResult `json:"arc,omitempty"`

	// Authentication results related antivirus scanning
	Antivirus *AntivirusResult `json:"antivirus,omitempty"`

	// Authentication results related to spam filter
	SpamFilter *SpamFilterResult `json:"spamFilter,omitempty"`

	// Authentication results related to content filter
	ContentFilter *ContentFilterResult `json:"contentFilter,omitempty"`

	// Error messages
	Errors []string `json:"errors,omitempty"`
}

AuthenticationResults holds authentication results of a Mail.

type Budget added in v0.87.0

type Budget struct {
	ID                 string `json:"id"`
	AgentID            string `json:"agentId"`
	SpendingCategoryID string `json:"spendingCategoryId"`

	// MonthlyAmount is a decimal; zero ends the budget.
	MonthlyAmount string `json:"monthlyAmount"`
	CurrencyCode  string `json:"currencyCode"`

	// EffectiveFrom is the first day of the month it starts, "2006-01-02".
	EffectiveFrom string `json:"effectiveFrom"`

	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`
}

Budget is an amount for one spending category for each month from a given month on, until a later row for the same spending category. On a spending category that is income it is the income expected each month rather than a limit on spending.

type BudgetPace added in v0.87.0

type BudgetPace string

BudgetPace is how a spending category's month is going against its budget.

const (
	BudgetPaceUnder   BudgetPace = "under"
	BudgetPaceOnTrack BudgetPace = "on_track"
	BudgetPaceAtRisk  BudgetPace = "at_risk"
	BudgetPaceOver    BudgetPace = "over"
)

The four paces: the month will end well under the budget, near it, well over it (projected, after the first week), or spending is past it already.

func (BudgetPace) IsValid added in v0.87.0

func (self BudgetPace) IsValid() bool

IsValid says the pace is one of the four.

type BudgetStatus added in v0.87.0

type BudgetStatus struct {
	// Month is "2006-01"; AsOf the day it is computed for, "2006-01-02",
	// which is the last day of a past month. For a year, Month is empty and
	// DayOfMonth and DaysInMonth are of AsOf's month.
	Month       string `json:"month"`
	AsOf        string `json:"asOf"`
	DayOfMonth  int    `json:"dayOfMonth"`
	DaysInMonth int    `json:"daysInMonth"`

	// Year is "2006" for the status of a year, empty for a month's. Of a
	// year, MonthsElapsedCount is how many of its months have begun by
	// AsOf (twelve once it is over, none before it begins), and DayOfYear
	// and DaysInYear say how far through it AsOf is (DayOfYear none
	// before it begins). All three are zero for a month.
	Year               string `json:"year"`
	MonthsElapsedCount int    `json:"monthsElapsedCount"`
	DayOfYear          int    `json:"dayOfYear"`
	DaysInYear         int    `json:"daysInYear"`

	// SpendingCategories are the budgets on spending, and
	// IncomeCategories the budgets on income spending categories: the
	// income expected each month.
	SpendingCategories []*SpendingCategoryBudgetStatus `json:"spendingCategories"`
	IncomeCategories   []*IncomeCategoryBudgetStatus   `json:"incomeCategories"`
}

BudgetStatus is every spending category with a budget in one month, or in any month of one year, against that budget, as of one day.

type Calendar

type Calendar struct {
	ID         string    `json:"id"`
	UserID     string    `json:"userId,omitempty"`
	CircleID   string    `json:"circleId,omitempty"`
	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`

	Name        string `json:"name"`
	Description string `json:"description,omitempty"`

	// Colour is what a client paints this calendar's events, as "#rrggbb".
	// Timezone is the zone a new event is written in when nothing says
	// otherwise, as an IANA name such as "Europe/London".
	Colour   string `json:"colour,omitempty"`
	Timezone string `json:"timezone,omitempty"`

	// WeekStart is the day a week is drawn from: "sunday" or "monday".
	// Where the columns of a month or a week begin is a local convention
	// rather than a fact, so it is written down rather than assumed.
	WeekStart string `json:"weekStart,omitempty"`

	// AgentGranted says the person has given their agent this calendar.
	// False until they do, including for calendars that existed before
	// there was a switch: nothing from a source the person has not granted
	// is ever sent to a model.
	AgentGranted bool `json:"agentGranted"`

	// CalendarKind is what it holds: events, or reminders. A person has one
	// of each.
	CalendarKind CalendarKind `json:"calendarKind"`
}

Calendar is a person's own. It belongs to the account rather than to a mailbox: somebody with two mailboxes has one calendar, and reaches it through either of them.

An account is given one named "Calendar" the first time it looks, so that nobody has to create one before they can keep an appointment.

A circle may have one of its own, which every member reads and writes: then CircleID is set and UserID is empty. Exactly one of the two is set. Whose a calendar is must never be decided by comparing UserID alone; ask CalendarAccess, which knows about shares and circles.

type CalendarInvitation

type CalendarInvitation struct {
	ID        string `json:"id"`
	UserID    string `json:"userId"`
	MailboxID string `json:"mailboxId"`
	ItemID    string `json:"itemId"`
	MailID    string `json:"mailId"`

	// Recipient is the address this was delivered to, which is the one the
	// sender wrote to and so the one an invitation has to name. A mailbox's
	// advertised addresses are not the same thing: one reached by a
	// catch-all advertises none.
	Recipient  string    `json:"recipient,omitempty"`
	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`

	Status    CalendarInvitationStatus `json:"status"`
	Attempts  int                      `json:"attempts"`
	NotBefore *time.Time               `json:"notBefore,omitempty"`
	ClaimedAt *time.Time               `json:"claimedAt,omitempty"`
	ClaimedBy string                   `json:"claimedBy,omitempty"`
	Error     string                   `json:"error,omitempty"`

	Method     string `json:"method,omitempty"`
	UID        string `json:"uid,omitempty"`
	Sequence   int    `json:"sequence,omitempty"`
	Organizer  string `json:"organizer,omitempty"`
	CalendarID string `json:"calendarId,omitempty"`
	ObjectID   string `json:"objectId,omitempty"`
}

CalendarInvitation is a message that carried a calendar part.

It exists because reading one means fetching the message from storage and decoding it, and that must not happen in the SMTP transaction: a slow read or a failure there would bounce mail. Delivery writes the row; a worker reads the message afterwards.

type CalendarInvitationStatus

type CalendarInvitationStatus string

CalendarInvitationStatus is how far an invitation that arrived as mail has got.

const (
	// Waiting: not read yet. Delivery writes this and does no more.
	CalendarInvitationWaiting CalendarInvitationStatus = "waiting"
	// Read: it was an invitation, and the calendar knows about it.
	CalendarInvitationRead CalendarInvitationStatus = "read"
	// Ignored: it carried nothing this server acts on, or it was refused.
	// Error says which, and it is kept rather than deleted so that the
	// same message is not picked up and refused again every time it is
	// looked at.
	CalendarInvitationIgnored CalendarInvitationStatus = "ignored"
)

type CalendarKind added in v0.77.0

type CalendarKind string

CalendarKind is what a calendar holds.

const (
	// CalendarEvents holds events: the calendar.
	CalendarEvents CalendarKind = "events"
	// CalendarReminders holds reminders, which iCalendar calls to-dos: the
	// list a phone's Reminders app syncs.
	CalendarReminders CalendarKind = "reminders"
)

type CalendarObject

type CalendarObject struct {
	ID         string    `json:"id"`
	CalendarID string    `json:"calendarId"`
	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`

	// UID is the file's own UID property, which is how the same event is
	// recognized across devices and how a reply is matched to what it
	// answers; ETag names a version, and is what a conditional write is
	// checked against.
	UID  string `json:"uid"`
	ETag string `json:"etag"`
	Data string `json:"data"`

	Summary  string `json:"summary,omitempty"`
	Location string `json:"location,omitempty"`

	// StartsAt and EndsAt are the first occurrence. A recurring event has
	// more, which are in the occurrence index rather than here.
	StartsAt  time.Time `json:"startsAt,omitempty"`
	EndsAt    time.Time `json:"endsAt,omitempty"`
	AllDay    bool      `json:"allDay,omitempty"`
	Recurring bool      `json:"recurring,omitempty"`

	// Status is the event's own STATUS: CONFIRMED, TENTATIVE or CANCELLED.
	Status string `json:"status,omitempty"`

	// IndexedUntil is how far ahead the times this event happens have been
	// worked out. A repeat with no end cannot be worked out for ever, so
	// the index reaches a horizon and something extends it as that horizon
	// approaches; this is what says which events still need it.
	IndexedUntil *time.Time `json:"indexedUntil,omitempty"`

	// IndexedAt is when that work was last done. An event whose repeat is
	// too fine to reach the horizon is worked out only as far as its last
	// written occurrence, so it is always running out; this is what keeps
	// it from being done again on every tick, ahead of everybody else's.
	IndexedAt *time.Time `json:"indexedAt,omitempty"`
}

CalendarObject is one iCalendar file: usually one event, sometimes an event together with the occurrences of it that were changed one at a time.

Data is the whole of it, and is what a phone sends and is given back. The fields beside it are pulled out of the text when it is written, so that listing and searching never parse iCalendar; where the two disagree the text is right.

type CalendarRequestReceipt added in v0.48.0

type CalendarRequestReceipt struct {
	UserID              string
	RequestID           string
	Operation           string
	CalendarID          string
	ObjectID            string
	RequestDigest       string
	CompletedAt         time.Time
	IsMailSendRequired  bool
	IsMailWriteRequired bool
}

CalendarRequestReceipt records a completed command without retaining event content. It survives event deletion so a late retry cannot recreate the event.

type CalendarShare added in v0.170.0

type CalendarShare struct {
	ID         string `json:"id"`
	CalendarID string `json:"calendarId"`

	GranteeUserID   string `json:"granteeUserId,omitempty"`
	GranteeCircleID string `json:"granteeCircleId,omitempty"`

	ShareLevel ShareLevel `json:"shareLevel"`

	CreatedAt time.Time `json:"createdAt"`

	// CreatedByUserID is empty once that account is gone.
	CreatedByUserID string `json:"createdByUserId,omitempty"`

	// GranteeUsername, GranteeName and GranteeCircleName are filled in by the
	// listing, for a screen that says who a calendar is shared with.
	GranteeUsername   string `json:"granteeUsername,omitempty"`
	GranteeName       string `json:"granteeName,omitempty"`
	GranteeCircleName string `json:"granteeCircleName,omitempty"`
}

CalendarShare gives one person, or every member of one circle, a level of access to one calendar. Exactly one of GranteeUserID and GranteeCircleID is set.

type CashFlowDay added in v0.91.1

type CashFlowDay struct {
	// CashFlowOn is the day, "2006-01-02".
	CashFlowOn     string `json:"cashFlowOn"`
	CurrencyCode   string `json:"currencyCode"`
	IncomeAmount   string `json:"incomeAmount"`
	SpendingAmount string `json:"spendingAmount"`
}

CashFlowDay is one day's income and spending in one currency, as the Spending section and cash flow count them: spending is money out less refunds in spending categories that are not income, and money out in the other category or with no spending category; income is what income categories took in, and money in in the other category or with no spending category. Transfers are left out of both.

type CategorizedBy added in v0.87.0

type CategorizedBy string

CategorizedBy is what gave a finance transaction its spending category.

const (
	CategorizedByPerson                  CategorizedBy = "person"
	CategorizedBySpendingRule            CategorizedBy = "spending_rule"
	CategorizedByProviderCategoryMapping CategorizedBy = "provider_category_mapping"
	CategorizedByCategorizeModel         CategorizedBy = "categorize_model"
	CategorizedByTransferDetection       CategorizedBy = "transfer_detection"
)

Who may categorize, in the order they are asked: the person, then their spending rules, then the fixed mapping from provider categories, then the categorize model. What the person chose nothing else overwrites. Transfer detection, pairing money out of one account with the same amount into another, gives only the transfer category, and a transfer it or the mapping gave is not taken over by a spending rule.

func (CategorizedBy) IsValid added in v0.87.0

func (self CategorizedBy) IsValid() bool

IsValid says it is one of the five.

type Chat added in v0.170.0

type Chat struct {
	ID         string    `json:"id"`
	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`
	ChatKind   ChatKind  `json:"chatKind"`

	// Title is a group's name; empty for a direct chat, and for a group
	// nobody named.
	Title string `json:"title"`

	// CircleID is the circle this is the circle chat of, empty for any other.
	CircleID string `json:"circleId,omitempty"`

	// CreatedByUserID is empty once that account is gone.
	CreatedByUserID string `json:"createdByUserId,omitempty"`

	LastMessageAt *time.Time `json:"lastMessageAt,omitempty"`

	// Members are everybody who is or was in it, those still in it first,
	// then in the order they joined.
	Members []*ChatMember `json:"members"`
}

Chat is a conversation with people in it. What a person sees of it is their own conversation of the kind chat, which points here with ChatID.

func (*Chat) ActiveMembers added in v0.170.0

func (self *Chat) ActiveMembers() []*ChatMember

ActiveMembers are the people in it now.

func (*Chat) IsCircleChat added in v0.170.0

func (self *Chat) IsCircleChat() bool

IsCircleChat says whether this is the chat every circle has.

func (*Chat) Member added in v0.170.0

func (self *Chat) Member(userId string) *ChatMember

Member is the row of one account in the chat, taken out or not, or nil.

type ChatAgentNote added in v0.170.0

type ChatAgentNote struct {
	AgentName string `json:"agentName"`
	OwnerName string `json:"ownerName"`
}

ChatAgentNote is the detail of a chat_agent_owner_only note: which agent was addressed and whose it is.

func ParseChatAgentNote added in v0.170.0

func ParseChatAgentNote(detail string) *ChatAgentNote

ParseChatAgentNote reads the detail of a chat_agent_owner_only note, or returns nil when it is one written before the owner was named in it: the agent's name alone.

type ChatAuthorKind added in v0.170.0

type ChatAuthorKind string

ChatAuthorKind says whether a chat message was written by a person or by somebody's agent.

const (
	ChatAuthorPerson ChatAuthorKind = "person"
	ChatAuthorAgent  ChatAuthorKind = "agent"
)

The two who write.

type ChatCall added in v0.212.0

type ChatCall struct {
	ID              string            `json:"id"`
	ChatID          string            `json:"chatId"`
	StartedByUserID string            `json:"startedByUserId,omitempty"`
	StartedAt       time.Time         `json:"startedAt"`
	AnsweredAt      *time.Time        `json:"answeredAt,omitempty"`
	EndedAt         *time.Time        `json:"endedAt,omitempty"`
	EndReason       ChatCallEndReason `json:"endReason,omitempty"`

	// Instance is the server instance whose media server holds the call.
	Instance string `json:"-"`

	// TranscriptionAskedByUserID is who asked for the call to be
	// transcribed; empty when nobody did. Their agent pays for it.
	TranscriptionAskedByUserID string     `json:"transcriptionAskedByUserId,omitempty"`
	TranscriptState            string     `json:"transcriptState,omitempty"`
	TranscriptTriedAt          *time.Time `json:"-"`
	SummaryMessageID           string     `json:"summaryMessageId,omitempty"`
	// RecordingID is the recording the call became once it was
	// transcribed: owned by whoever turned transcription on.
	RecordingID string `json:"recordingId,omitempty"`

	Members []ChatCallMember `json:"members"`
}

ChatCall is a call in a chat, with each member's part in it.

func (*ChatCall) DurationMS added in v0.212.0

func (self *ChatCall) DurationMS(now time.Time) int64

DurationMS is how long the call went from its first answer to its end, or to now while it goes; zero for a call nobody answered.

func (*ChatCall) IsGoing added in v0.212.0

func (self *ChatCall) IsGoing() bool

IsGoing says the call has not ended.

func (*ChatCall) Member added in v0.212.0

func (self *ChatCall) Member(userId string) *ChatCallMember

Member is the person's part in the call; nil when they have none.

func (*ChatCall) OnCount added in v0.212.0

func (self *ChatCall) OnCount() int

OnCount is how many people are on the call now.

type ChatCallEndReason added in v0.212.0

type ChatCallEndReason string

ChatCallEndReason says how a call ended; empty while it goes.

const (
	// ChatCallEnded: the last person on it left.
	ChatCallEnded ChatCallEndReason = "ended"
	// ChatCallMissed: nobody answered before the ringing stopped.
	ChatCallMissed ChatCallEndReason = "missed"
	// ChatCallDeclined: everybody rung said no.
	ChatCallDeclined ChatCallEndReason = "declined"
	// ChatCallFailed: the server stopped under it.
	ChatCallFailed ChatCallEndReason = "failed"
)

type ChatCallMember added in v0.212.0

type ChatCallMember struct {
	UserID    string            `json:"userId"`
	RingState ChatCallRingState `json:"ringState"`
	JoinedAt  *time.Time        `json:"joinedAt,omitempty"`
	LeftAt    *time.Time        `json:"leftAt,omitempty"`
	IsVideoOn bool              `json:"isVideoOn,omitempty"`
	IsMuted   bool              `json:"isMuted,omitempty"`
}

ChatCallMember is one person's part in a call.

func (*ChatCallMember) IsOn added in v0.212.0

func (self *ChatCallMember) IsOn() bool

IsOn says the member is on the call now: joined, and not left since.

type ChatCallRingState added in v0.212.0

type ChatCallRingState string

ChatCallRingState is what came of ringing one member.

const (
	// ChatCallRingNone: the one who started the call.
	ChatCallRingNone ChatCallRingState = "none"
	// ChatCallRinging: rung, and not answered yet.
	ChatCallRinging ChatCallRingState = "ringing"
	// ChatCallRingAnswered: they joined the call.
	ChatCallRingAnswered ChatCallRingState = "answered"
	// ChatCallRingDeclined: they said no.
	ChatCallRingDeclined ChatCallRingState = "declined"
	// ChatCallRingMissed: the ringing stopped before they answered.
	ChatCallRingMissed ChatCallRingState = "missed"
)

type ChatKind added in v0.170.0

type ChatKind string

ChatKind says who a chat is between: two people, or any number.

const (
	ChatKindDirect ChatKind = "direct"
	ChatKindGroup  ChatKind = "group"
)

The kinds of chat. A circle's circle chat is a group.

func (ChatKind) IsValid added in v0.170.0

func (self ChatKind) IsValid() bool

IsValid reports whether this is one of the kinds.

type ChatMember added in v0.170.0

type ChatMember struct {
	// UserID is empty once the account is deleted.
	UserID   string `json:"userId"`
	Username string `json:"username"`

	// Name is what they were called when last seen, which a deleted account
	// keeps.
	Name string `json:"name"`

	// AvatarURL is the address of their picture, null when they have none.
	AvatarURL *string `json:"avatarUrl"`

	// AvatarColorIndex is which of the twelve avatar colors their initial is
	// drawn on when they have no picture.
	AvatarColorIndex int `json:"avatarColorIndex"`

	// MemberRole is admin or member. In a circle's circle chat it is the
	// role they have in the circle.
	MemberRole MemberRole `json:"memberRole"`

	// IsDeletedAccount says the account is gone and Name is all that is left.
	IsDeletedAccount bool `json:"isDeletedAccount"`

	// IsRemoved says they are not in the chat any more; they read it up to
	// the time they left.
	IsRemoved bool `json:"isRemoved"`

	// ReadThroughMessageID is the newest message they have read, empty when
	// they have read none.
	ReadThroughMessageID string `json:"readThroughMessageId"`

	// IsAgentReading says their agent remembers this chat.
	IsAgentReading bool `json:"isAgentReading"`

	// IsAgentAskableByOthers says the others in this chat may address their
	// agent: each of their questions starts a turn of it held to what
	// everybody in the chat may see. Off, only the person can.
	IsAgentAskableByOthers bool `json:"isAgentAskableByOthers"`

	// AgentID and AgentName say which agent is theirs and what it is called,
	// for an @ to address it by; the agent is shown by its name. IsAgentActive
	// says it is switched on, so addressing it starts a turn; a switched-off
	// agent is in the list but starts nothing.
	AgentID       string `json:"agentId"`
	AgentName     string `json:"agentName"`
	IsAgentActive bool   `json:"isAgentActive"`

	// The rest is read from the row for the code that decides, and not
	// shown.
	JoinedAt          time.Time             `json:"-"`
	RemovedAt         *time.Time            `json:"-"`
	NotificationLevel ChatNotificationLevel `json:"-"`
	User              *User                 `json:"-"`

	// ConversationID is the member's own conversation for the chat, when the
	// query that returned the member looked it up.
	ConversationID string `json:"-"`

	// IsConversationArchived says the member put that conversation away, which
	// quiets the chat for them the way a mute does.
	IsConversationArchived bool `json:"-"`
}

ChatMember is one person in one chat, as a screen draws them.

type ChatMessage added in v0.170.0

type ChatMessage struct {
	ID        string    `json:"id"`
	ChatID    string    `json:"chatId"`
	CreatedAt time.Time `json:"createdAt"`

	// AuthorUserID is empty once the account is gone. For an agent's
	// message it is the agent's owner.
	AuthorUserID string `json:"authorUserId,omitempty"`

	// AuthorName is what the author was called when they wrote it.
	AuthorName string `json:"authorName"`

	// AuthorOwnerName is, on an agent's message, the name of the agent's
	// owner as the chat knew them, kept like AuthorName after the account
	// is gone. Most agents keep the name "Agent", so the owner's name is what
	// tells two of them apart. Empty on a person's message.
	AuthorOwnerName string `json:"authorOwnerName,omitempty"`

	// AuthorKind says whether a person or an agent wrote it. It outlives
	// AuthorAgentID, which is cleared when the agent is deleted.
	AuthorKind ChatAuthorKind `json:"authorKind,omitempty"`

	// AuthorAgentID is set when the message is an agent's.
	AuthorAgentID string `json:"authorAgentId,omitempty"`

	AgentRunID string `json:"agentRunId,omitempty"`

	Body        string            `json:"body"`
	Attachments []AgentAttachment `json:"attachments,omitempty"`

	ReplyToMessageID string     `json:"replyToMessageId,omitempty"`
	EditedAt         *time.Time `json:"editedAt,omitempty"`
	DeletedAt        *time.Time `json:"deletedAt,omitempty"`

	// MentionedUserIDs are the members the message mentions by name, and
	// IsAllMentioned says it mentions everybody in the chat. A member told
	// only of mentions is told of a message that does either. Mentioning a
	// person is not addressing their agent: that is AddressedAgentIDs on the
	// ask, and starts a turn.
	MentionedUserIDs []string `json:"mentionedUserIds,omitempty"`
	IsAllMentioned   bool     `json:"isAllMentioned,omitempty"`

	// Reactions are one per reactor, in the order they were made.
	Reactions []AgentMessageReaction `json:"reactions,omitempty"`

	// IsVoiceMessage says the message is one recording, in Attachments, with
	// an empty Body. TranscriptText is the words said in it, written by the
	// server after the message is posted, and TranscriptState says how that
	// stands: see VoiceTranscriptState. All three are empty on any other
	// message.
	IsVoiceMessage  bool   `json:"isVoiceMessage,omitempty"`
	TranscriptText  string `json:"transcriptText,omitempty"`
	TranscriptState string `json:"transcriptState,omitempty"`

	// CallID names the call this message is the line of in the chat: such a
	// message has no words, and Call is the call as it now stands, read with
	// the message.
	CallID string    `json:"callId,omitempty"`
	Call   *ChatCall `json:"call,omitempty"`
}

ChatMessage is a row of what was said: by a person, or by an agent speaking for its owner.

func (*ChatMessage) IsByAgent added in v0.170.0

func (self *ChatMessage) IsByAgent() bool

IsByAgent says an agent wrote it.

func (*ChatMessage) MentionsUser added in v0.196.0

func (self *ChatMessage) MentionsUser(userId string) bool

MentionsUser says the message mentions the person, by name or by mentioning everybody.

func (*ChatMessage) VoiceMessageDurationMS added in v0.211.0

func (self *ChatMessage) VoiceMessageDurationMS() int64

VoiceMessageDurationMS is the length of the recording the message carries, zero when it is not a voice message.

func (*ChatMessage) WordsForReading added in v0.211.0

func (self *ChatMessage) WordsForReading() string

WordsForReading is what a model or a quote shows for the message: its body, or for a voice message "[voice message, 0:12] words" or "[voice message, 0:12, no transcript]".

type ChatNotificationLevel added in v0.196.0

type ChatNotificationLevel string

ChatNotificationLevel is what a member of a chat is told of on their phone: every message, only one that mentions them (by name, or everybody), or nothing. It is theirs alone and stays until they change it.

const (
	ChatNotificationAll      ChatNotificationLevel = "all"
	ChatNotificationMentions ChatNotificationLevel = "mentions"
	ChatNotificationOff      ChatNotificationLevel = "off"
)

func (ChatNotificationLevel) IsValid added in v0.196.0

func (self ChatNotificationLevel) IsValid() bool

IsValid says the level is one of the three.

type ChatView added in v0.170.0

type ChatView struct {
	ChatID   string   `json:"chatId"`
	ChatKind ChatKind `json:"chatKind"`

	// CircleID is the circle this is the circle chat of, null for any other.
	CircleID *string `json:"circleId"`

	// Title is the group's name, or for a direct chat the other person's.
	Title string `json:"title"`

	IsCircleChat bool `json:"isCircleChat"`

	// Members are the people in it, then those who left.
	Members []*ChatMember `json:"members"`

	// UnreadCount is how many messages by others are newer than this
	// member's read mark.
	UnreadCount int `json:"unreadCount"`

	// NotificationLevel is what this member's phone is told of in the chat.
	NotificationLevel ChatNotificationLevel `json:"notificationLevel"`

	// IsMuted and MutedUntil are what app builds made before the level read
	// instead: a chat turned off is muted, and no level has an end. Without
	// them those builds could not list a chat at all. Drop them once the
	// builds people have installed read NotificationLevel.
	IsMuted    bool       `json:"isMuted"`
	MutedUntil *time.Time `json:"mutedUntil"`

	// IsRemoved says this member is no longer in the chat; it reads up to
	// the time they left and takes no more.
	IsRemoved bool `json:"isRemoved"`
}

ChatView is a chat as one member sees it: what a screen needs beside the conversation, and what is theirs alone, their unread count and what they are told of.

type Circle added in v0.170.0

type Circle struct {
	ID         string     `json:"id"`
	CreatedAt  time.Time  `json:"createdAt"`
	ModifiedAt time.Time  `json:"modifiedAt"`
	Name       string     `json:"name"`
	CircleKind CircleKind `json:"circleKind"`

	// CreatedByUserID is empty once that account is gone.
	CreatedByUserID string `json:"createdByUserId,omitempty"`

	// Members is filled in by the queries that return a whole circle, the
	// admins first and then in the order they joined.
	Members []*CircleMember `json:"members,omitempty"`
}

Circle is a named set of accounts on one server that know each other. Everything this server shares between people is shared with a circle or with a person in one.

func (*Circle) AdminCount added in v0.170.0

func (self *Circle) AdminCount() int

AdminCount is how many of its members are admins.

func (*Circle) Member added in v0.170.0

func (self *Circle) Member(userId string) *CircleMember

Member is the row of one person in the circle, or nil.

func (*Circle) Validate added in v0.170.0

func (self *Circle) Validate() error

Validate reports everything wrong with the circle.

type CircleInvitation added in v0.170.0

type CircleInvitation struct {
	ID              string     `json:"id"`
	CircleID        string     `json:"circleId"`
	InvitedUserID   string     `json:"invitedUserId"`
	InvitedByUserID string     `json:"invitedByUserId,omitempty"`
	MemberRole      MemberRole `json:"memberRole"`
	CreatedAt       time.Time  `json:"createdAt"`
	ExpiresAt       time.Time  `json:"expiresAt"`

	// AnsweredAt and InvitationAnswer are empty while it waits.
	AnsweredAt       *time.Time       `json:"answeredAt,omitempty"`
	InvitationAnswer InvitationAnswer `json:"invitationAnswer,omitempty"`

	// The rest is read along with the row, for the screens that list
	// invitations: the circle it is to, who asked and who was asked.
	CircleName        string     `json:"circleName,omitempty"`
	CircleKind        CircleKind `json:"circleKind,omitempty"`
	InvitedByUsername string     `json:"invitedByUsername,omitempty"`
	InvitedByName     string     `json:"invitedByName,omitempty"`
	InvitedUsername   string     `json:"invitedUsername,omitempty"`
}

CircleInvitation asks one person to join one circle.

func (*CircleInvitation) IsOpen added in v0.170.0

func (self *CircleInvitation) IsOpen(now time.Time) bool

IsOpen says whether it can still be answered at this moment.

type CircleInvitedNote added in v0.170.0

type CircleInvitedNote struct {
	InvitedByName string `json:"invitedByName"`
	CircleName    string `json:"circleName"`
}

CircleInvitedNote is the detail of a circle_invited note: who asked and to what. Two names cannot share one plain string without a separator that a name may contain, so the detail is this as JSON and each client words it.

func ParseCircleInvitedNote added in v0.170.0

func ParseCircleInvitedNote(detail string) *CircleInvitedNote

ParseCircleInvitedNote reads the detail of a circle_invited note, or returns nil when it is not one.

type CircleKind added in v0.170.0

type CircleKind string

CircleKind is what a circle is for. It is how screens describe the circle ("your family", "your colleagues") where the generic word would read oddly, and it decides nothing else.

const (
	CircleKindFamily     CircleKind = "family"
	CircleKindFriends    CircleKind = "friends"
	CircleKindColleagues CircleKind = "colleagues"
)

The kinds of circle.

func (CircleKind) IsValid added in v0.170.0

func (self CircleKind) IsValid() bool

IsValid reports whether this is one of the kinds.

type CircleMember added in v0.170.0

type CircleMember struct {
	CircleID        string     `json:"circleId"`
	UserID          string     `json:"userId"`
	MemberRole      MemberRole `json:"memberRole"`
	JoinedAt        time.Time  `json:"joinedAt"`
	InvitedByUserID string     `json:"invitedByUserId,omitempty"`

	// User is the account, filled in by the queries that return a whole
	// circle so that a screen can name and draw the person.
	User *User `json:"-"`
}

CircleMember is one person in one circle.

type CircleMemberAddedNote added in v0.194.0

type CircleMemberAddedNote struct {
	AddedName  string `json:"addedName"`
	CircleName string `json:"circleName"`
}

CircleMemberAddedNote is the detail of a circle_member_added note: whose account an operator put in, and in which circle. As for CircleInvitedNote, two names travel as JSON and each client words them.

func ParseCircleMemberAddedNote added in v0.194.0

func ParseCircleMemberAddedNote(detail string) *CircleMemberAddedNote

ParseCircleMemberAddedNote reads the detail of a circle_member_added note, or returns nil when it is not one.

type CircleShareOwner added in v0.194.0

type CircleShareOwner struct {
	OwnerUserID string
	ShareKinds  []ShareKind
}

CircleShareOwner is a member of a circle and the kinds of thing they have shared with that circle, so that a person who joins it can be told to the owner.

type Contact

type Contact struct {
	ID            string    `json:"id"`
	AddressBookID string    `json:"addressBookId"`
	CreatedAt     time.Time `json:"createdAt"`
	ModifiedAt    time.Time `json:"modifiedAt"`

	// UID is the card's own UID property, which is how the same person is
	// recognized across devices; ETag names a version of the card, and is
	// what a conditional write is checked against.
	UID  string `json:"uid"`
	ETag string `json:"etag"`
	Card string `json:"card"`

	Name         string   `json:"name,omitempty"`
	Organization string   `json:"organization,omitempty"`
	Emails       []string `json:"emails,omitempty"`
	Phones       []string `json:"phones,omitempty"`

	// AccountUserID is the account on this server that the owner says this
	// contact is, or empty. Only the owner sees the link: read only while the
	// owner still shares a circle with that account, never carried in the
	// card, and never seen by the account. It is written only by
	// SetContactAccount, so saving a card does not touch it.
	AccountUserID string `json:"accountUserId,omitempty"`
}

Contact is one person in an address book.

Card is the whole of it: the vCard text, which is what a phone sends and what it is given back. The fields beside it are pulled out of the card when it is written, so that listing and searching never parse a vCard; where the two disagree the card is right.

This is the only list of people the server keeps. A mailbox does not learn the addresses it sees go past: "is this sender known" means "is this sender in the address book", here, and address completion comes from here too.

type ContactAccountSuggestion added in v0.184.0

type ContactAccountSuggestion struct {
	Contact       *Contact `json:"contact"`
	AccountUserID string   `json:"accountUserId"`
}

ContactAccountSuggestion is a contact the owner has not linked whose email addresses include a mailbox address of an account they share a circle with. It says which account, never which address matched.

type ContentFilterResult

type ContentFilterResult struct {
	// Found unsafe extensions
	UnsafeExtensions []string `json:"unsafeExtensions,omitempty"`
}

ContentFilterResult holds authentication results related to content filtering.

type Credential

type Credential struct {
	// ID is what the SMTP username encodes; stored mail references it.
	ID string `json:"id"`

	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`

	DomainID string `json:"domainId"`
	Position int    `json:"position"`

	// Key is the secret half of the credential. Never shown after creation.
	Key string `json:"-"`

	// Alias, when set, restricts this credential to sending as exactly that
	// local part of the domain.
	Alias string `json:"alias,omitempty"`

	// Comment names the device or service that holds this credential.
	Comment string `json:"comment,omitempty"`

	// Disabled refuses authentication without deleting the credential.
	Disabled bool `json:"disabled,omitempty"`
}

Credential may authenticate to the submission port and send mail as its domain.

func (*Credential) Validate

func (self *Credential) Validate() error

Validate reports everything wrong with the credential.

type CredentialKind added in v0.170.0

type CredentialKind string

CredentialKind is what a request signed in with, as far as telling a person's tap from a program's call goes.

const (
	// CredentialSession is the dashboard's cookie session, which also had to
	// pass the cross-site check for a request that changes something.
	CredentialSession CredentialKind = "session"

	// CredentialApp is a token of the phone app's own sign-in.
	CredentialApp CredentialKind = "app"

	// CredentialToken is any other token: one minted for the command line
	// or an API client, or one a program was authorized for.
	CredentialToken CredentialKind = "token"
)

func (CredentialKind) IsInteractive added in v0.170.0

func (self CredentialKind) IsInteractive() bool

IsInteractive says whether the credential is one a person's own tap on a screen arrives with: the dashboard in a browser, or the phone app. A command line or an agent running on the person's computer holds a token of the other kind, so it never arrives as a tap.

type CreditLimitSource added in v0.101.0

type CreditLimitSource string

CreditLimitSource is where the credit limit a card's usage is measured against comes from.

const (
	// CreditLimitSourceProvider is the limit the provider gave.
	CreditLimitSourceProvider CreditLimitSource = "provider"
	// CreditLimitSourceDerived is what is owed plus the credit still
	// available, for a card whose provider gave no limit.
	CreditLimitSourceDerived CreditLimitSource = "derived"
	// CreditLimitSourceUnknown is a card with neither, whose usage cannot
	// be measured.
	CreditLimitSourceUnknown CreditLimitSource = "unknown"
)

func (CreditLimitSource) IsValid added in v0.101.0

func (self CreditLimitSource) IsValid() bool

IsValid says the source is one of the three.

type CurrencyAmount added in v0.87.0

type CurrencyAmount struct {
	CurrencyCode string `json:"currencyCode"`
	Amount       string `json:"amount"`
}

CurrencyAmount is an amount in one currency, a decimal.

type CurrencyPairRate added in v0.87.0

type CurrencyPairRate struct {
	FromCurrencyCode string `json:"fromCurrencyCode"`
	ToCurrencyCode   string `json:"toCurrencyCode"`

	// Rate is a decimal: how many of ToCurrencyCode one FromCurrencyCode
	// bought.
	Rate string `json:"rate"`

	// RateOn is the published day the rate is from, "2006-01-02".
	RateOn     string     `json:"rateOn"`
	RateSource RateSource `json:"rateSource"`
}

CurrencyPairRate is what one unit of one currency bought in another on one day, and which published day that came from: the day asked, or the latest earlier one when nothing was published that day.

type DKIMResult

type DKIMResult struct {
	// DKIM result
	Result string `json:"result,omitempty"`

	// Domain name
	Domain string `json:"domain,omitempty"`

	// DKIM selector
	Selector string `json:"selector,omitempty"`

	// DKIM identifier
	Identifier string `json:"identifier,omitempty"`
}

DKIMResult holds authentication results related to DKIM.

type DMARCResult

type DMARCResult struct {
	// From domain name
	Domain string `json:"domain,omitempty"`

	// DMARC policy
	Policy string `json:"policy,omitempty"`

	// Subdomain DMARC policy
	SubdomainPolicy string `json:"subdomainPolicy,omitempty"`

	// PolicyDomain is the domain the policy was found at, set only when that
	// is not the From domain itself — a sender on a subdomain is governed by
	// the organizational domain above it, and saying which one answers "where
	// did this policy come from" without a second lookup.
	PolicyDomain string `json:"policyDomain,omitempty"`

	// DKIM alignment mode
	DKIMAlignment string `json:"dkimAlignment,omitempty"`

	// SPF alignment mode
	SPFAlignment string `json:"spfAlignment,omitempty"`

	// DMARC result
	Result string `json:"result,omitempty"`

	// PassedAtForwarderDomain is the domain of a mail service that forwarded the
	// message and recorded, under a valid ARC seal, that it passed DMARC when
	// it arrived there. Set only when it failed here: forwarding rewrites the
	// envelope sender and can break a signature, so a failure here says what
	// the forwarding did, and the forwarder's word says what the sender did.
	// Mail with it set is held to a pass, the "trusted_forwarder" override
	// of RFC 7489 section 7.2.1.
	PassedAtForwarderDomain string `json:"passedAtForwarderDomain,omitempty"`
}

DMARCResult holds authentication results related to DMARC.

func (*DMARCResult) IsPassed added in v0.226.1

func (self *DMARCResult) IsPassed() bool

IsPassed is whether the message satisfies its sender's DMARC policy: it passed here, or failed here only because a trusted forwarder changed it.

type DeletedHealthSample added in v0.183.0

type DeletedHealthSample struct {
	HealthType string    `json:"healthType"`
	StartedAt  time.Time `json:"startedAt"`
	EndedAt    time.Time `json:"endedAt"`
}

DeletedHealthSample is what is left to say about a reading that was deleted: which kind it was and when, so that the phone can work out the days it touched again. It is kept for HealthDeletedSampleDays.

type Delivery

type Delivery struct {
	// ID of the Delivery
	ID string `json:"id,omitempty"`

	// Timestamp when the Delivery was created
	CreatedAt time.Time `json:"createdAt,omitempty"`

	// Timestamp when the Delivery was last modified
	ModifiedAt time.Time `json:"modifiedAt,omitempty"`

	// The Delivery was made for which Mail
	MailID string `json:"mailId,omitempty"`
	Mail   *Mail  `json:"-"`

	// Domain the Mail being delivered arrived for. Not a column of its own —
	// the delivery reaches its domain through the mail — so it is only filled
	// in by the queries that scope to a domain and can therefore state it.
	DomainID string `json:"domainId,omitempty"`

	// Alias that was matched to this delivery. The identifier is stored; the
	// pointer is resolved from the configuration and is nil once the alias has
	// been removed, which historical deliveries have to tolerate.
	AliasID string `json:"aliasId,omitempty"`
	Alias   *Alias `json:"-"`

	// MailboxID and MailboxItemID name the mailbox and the item a delivery
	// of kind mailbox produced.
	MailboxID     string `json:"mailboxId,omitempty"`
	MailboxItemID string `json:"mailboxItemId,omitempty"`

	// Recipient address, indicating the recipient in the Mail being delivered to
	Recipient string `json:"recipient,omitempty"`

	// Delivery kind, one of: forward, internal, external
	Kind DeliveryKind `json:"kind,omitempty"`

	// Delivery status, one of: queued, dropped, delivered, failed, delayed, relayed, expanded
	Status DeliveryStatus `json:"status,omitempty"`

	// Size of the Delivery
	Size uint64 `json:"size,omitempty"`

	// Timestamp when the Delivery was attempted
	AttemptedAt *time.Time `json:"attemptedAt,omitempty"`

	// Timestamp when the Delivery was delivered successfully
	DeliveredAt *time.Time `json:"deliveredAt,omitempty"`

	// Timestamp when the Delivery was dropped
	DroppedAt *time.Time `json:"droppedAt,omitempty"`

	// Timestamp when the Delivery was notified by delivery status
	NotifiedAt *time.Time `json:"notifiedAt,omitempty"`

	// Timestamp when the Delivery will be retried
	RetryAt *time.Time `json:"retryAt,omitempty"`

	// How many attempts has been made
	Attempts uint64 `json:"attempts,omitempty"`

	// Method is how the message is handed on — "email" for a forward to an
	// address by looking up its mail servers, "mailServer" for a relay to a
	// configured host, "webhook" for a POST, "smtp" for a message this
	// server sends out itself. Derived from the alias when the delivery is
	// read; not stored.
	Method string `json:"method,omitempty"`

	// Destination is where that goes: the address, the host and port, or
	// the URL. Derived alongside Method.
	Destination string `json:"destination,omitempty"`

	// Last error reported
	Error string `json:"error,omitempty"`

	// Last known delivery statuses
	DeliveryStatuses []*dsn.DeliveryStatus `json:"deliveryStatuses,omitempty"`
}

Delivery is a record of what happened when mail is being delivered to the next server.

func (*Delivery) Describe

func (self *Delivery) Describe(alias *Alias)

Describe fills Method and Destination from the alias the delivery was made for, which is configuration rather than a stored column. An external delivery has no alias: it is this server sending to the recipient directly.

type DeliveryKind

type DeliveryKind string
const (
	DeliveryKindUnknown  DeliveryKind = ""
	DeliveryKindInternal DeliveryKind = "internal"
	DeliveryKindExternal DeliveryKind = "external"
	DeliveryKindForward  DeliveryKind = "forward"

	// DeliveryKindMailbox is the message placed in a folder of a mailbox on
	// this server: one per mailbox the message reached, created in the
	// receipt transaction, already delivered, like the internal kind.
	DeliveryKindMailbox DeliveryKind = "mailbox"
)

func GetDeliveryKind

func GetDeliveryKind(value string) DeliveryKind

func (DeliveryKind) String

func (self DeliveryKind) String() string

type DeliveryStatus

type DeliveryStatus string
const (
	DeliveryStatusUnknown   DeliveryStatus = ""
	DeliveryStatusQueued    DeliveryStatus = "queued"
	DeliveryStatusDropped   DeliveryStatus = "dropped"
	DeliveryStatusDelivered DeliveryStatus = "delivered"
	DeliveryStatusAttempted DeliveryStatus = "attempted"
	DeliveryStatusFailed    DeliveryStatus = "failed"
	DeliveryStatusDelayed   DeliveryStatus = "delayed"
)

func GetDeliveryStatus

func GetDeliveryStatus(value string) DeliveryStatus

func (DeliveryStatus) String

func (self DeliveryStatus) String() string

type Domain

type Domain struct {
	ID string `json:"id"`

	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`

	// Domain is the mail domain itself, for example "example.com".
	Domain string `json:"domain"`

	// Subdomain is the label whose CNAME points at this server, so that
	// bounces and DMARC reports have somewhere to arrive. Usually "mail",
	// making mail.example.com a CNAME to the server's name.
	Subdomain string `json:"subdomain,omitempty"`

	// MailServers are the names this domain's MX records point at, and so
	// the names a sender connects to and is handed a certificate for. Empty
	// means one name derived from the domain itself, "mx." in front of it.
	MailServers []string `json:"mailServers,omitempty"`

	// LinkHost is the name in the addresses this server writes into mail it
	// sends. Empty means the domain's first mail server name.
	//
	// It may carry a port -- "mail.example.com:10443" -- for a deployment
	// reached on one of its own. The port belongs to the name rather than
	// to what this server binds: the same server may be reached under one
	// name directly and under another through something that forwards the
	// usual port, and only the name knows which.
	LinkHost string `json:"linkHost,omitempty"`

	// Comment is a note for the operator; it is never used in mail handling.
	Comment string `json:"comment,omitempty"`

	// DKIM is the key that signs mail sent from this domain.
	DKIM DomainKey `json:"-"`

	// TLS is the certificate served to a sender connecting to this domain's
	// own mail server name, obtained automatically when tls.acme.perDomain is
	// on.
	TLS DomainCertificate `json:"-"`

	// SpamFilterScoreThreshold is the spam score above which mail for this
	// domain is rejected. Read it with SpamThreshold(), which supplies the
	// default for a domain that has never been given one.
	SpamFilterScoreThreshold float64 `json:"spamFilterScoreThreshold"`

	// Aliases decide where mail for this domain goes, in the order the
	// operator arranged them. Loaded with the domain.
	Aliases []*Alias `json:"aliases,omitempty"`

	// Credentials may authenticate to the submission port and send mail as
	// this domain. Loaded with the domain.
	Credentials []*Credential `json:"credentials,omitempty"`
}

Domain is a mail domain this server accepts mail for, with the aliases that decide where its mail goes and the credentials that may send as it.

A row in the domain table. Its identifier is what stored mail, deliveries and usage rows name it by, and is stable for as long as it exists.

func (*Domain) FindAlias

func (self *Domain) FindAlias(aliasId string) *Alias

FindAlias returns the alias with this identifier, or nil.

func (*Domain) FindCredential

func (self *Domain) FindCredential(credentialId string) *Credential

FindCredential returns the credential with this identifier, or nil.

func (*Domain) Hostname

func (self *Domain) Hostname() string

Hostname returns the fully qualified name that mail for this domain arrives at, for example "mail.example.com", used as the bounce and DMARC report domain. It falls back to the bare domain when no subdomain is configured.

func (*Domain) InThisDomain

func (self *Domain) InThisDomain(host string) bool

InThisDomain reports whether a name belongs to this domain's own zone, and so whether its address record is this operator's to publish and its certificate this server's to obtain.

func (*Domain) SpamThreshold

func (self *Domain) SpamThreshold() float64

SpamThreshold is the score above which mail for this domain is refused.

func (*Domain) Validate

func (self *Domain) Validate() error

Validate reports everything wrong with the domain itself. Its aliases and credentials are validated by their own writers.

type DomainCertificate

type DomainCertificate struct {
	// Certificate is the issued chain, in PEM.
	Certificate string `json:"-"`

	// PrivateKey is its private half, in PEM. Encrypted at rest the same way
	// the signing key is.
	PrivateKey string `json:"-"`
}

DomainCertificate is a certificate obtained for a domain's own mail server name.

type DomainKey

type DomainKey struct {
	// Selector this key is published under.
	Selector string `json:"selector,omitempty"`

	// PrivateKey is a PKCS#8 RSA key in PEM form. Encrypted at rest, and
	// never shown.
	PrivateKey string `json:"-"`
}

DomainKey is the key a domain signs its outgoing mail with.

func GenerateDomainKey

func GenerateDomainKey(selector string) (DomainKey, error)

GenerateDomainKey creates a signing key for a domain.

func (*DomainKey) PublicKeyRecord

func (self *DomainKey) PublicKeyRecord() (string, error)

PublicKeyRecord returns the TXT value to publish at <selector>._domainkey.<domain>, which is what makes the signature checkable.

func (*DomainKey) Signer

func (self *DomainKey) Signer() (crypto.Signer, error)

Signer parses the private key so it can sign a message.

type DomainPermissions

type DomainPermissions struct {
	DomainID    string       `json:"domainId"`
	Permissions []Permission `json:"permissions"`
}

DomainPermissions is what the caller may do over one domain.

type DomainSubmission added in v0.48.0

type DomainSubmission struct {
	PrincipalID   string
	SubmissionID  string
	DomainID      string
	RequestDigest string
	MailID        string
	AcceptedAt    time.Time
}

DomainSubmission is acceptance by a domain operator or the host console. PrincipalID separates account identifiers from the console's identity.

type DreamProposal

type DreamProposal struct {
	Kind   string `json:"kind"`
	Path   string `json:"path"`
	To     string `json:"to,omitempty"`
	Reason string `json:"reason,omitempty"`
}

DreamProposal is something the night wants the person to decide: where a page belongs, what a folder should be called. Applied by a press, never by the run.

type DuplicateDecidedBy added in v0.102.1

type DuplicateDecidedBy string

DuplicateDecidedBy is what decided whether a finance transaction is a mirrored copy of another.

const (
	DuplicateDecidedByMirrorDetection DuplicateDecidedBy = "mirror_detection"
	DuplicateDecidedByPerson          DuplicateDecidedBy = "person"
)

What may decide it: mirror detection, which finds the same day, amount, currency and description on two or more investment accounts of one Plaid finance source and keeps one of them counted; or the person, who says a copy is real and counts, after which detection leaves it alone.

type EffectivePermissions

type EffectivePermissions struct {
	// Everywhere holds the server and all-domains permissions the caller's
	// groups carry.
	Everywhere []Permission `json:"everywhere"`

	// ByDomain holds the domain-kind permissions, from each group's roles
	// crossed with that group's domains. Additive: two groups that each reach
	// a domain contribute both their roles.
	ByDomain []DomainPermissions `json:"byDomain"`
}

EffectivePermissions is what one request may do, resolved once from the caller's groups: user_group × group_role × role_permission, scoped by group_domain. Carried on the request; never cached across requests on an instance, so a role change made through one instance applies to another's next request.

func NewEffectivePermissions

func NewEffectivePermissions(grants []Grant) *EffectivePermissions

NewEffectivePermissions folds grants into the shape a request carries.

func (*EffectivePermissions) Covers

func (self *EffectivePermissions) Covers(other *EffectivePermissions) bool

Covers reports whether these permissions include everything another set holds -- server-wide permissions and domain ones alike.

It is the question "may this person hand that out": somebody who may change who is in a group, or what a role carries, is deciding what other people may do, and nobody should be able to give away more than they have. Without it, the permission to manage accounts was the permission to become an administrator -- add yourself to the group that already holds everything, and the next request is answered with every permission on the server.

func (*EffectivePermissions) DomainsWith

func (self *EffectivePermissions) DomainsWith(permission Permission) (domainIds []string, all bool)

DomainsWith lists the domains a domain permission is held over, and whether it is held over all of them.

func (*EffectivePermissions) Has

func (self *EffectivePermissions) Has(permission Permission) bool

Has reports whether a server or all-domains permission is held.

func (*EffectivePermissions) HasAnywhere

func (self *EffectivePermissions) HasAnywhere(permission Permission) bool

HasAnywhere reports whether a domain permission is held over at least one domain, or everywhere.

func (*EffectivePermissions) HasOverDomain

func (self *EffectivePermissions) HasOverDomain(permission Permission, domainId string) bool

HasOverDomain reports whether a domain permission is held over this domain: either granted over it through a group, or granted everywhere through the all-domains permission that widens it.

func (*EffectivePermissions) Manages

func (self *EffectivePermissions) Manages() bool

Manages reports whether the caller holds at least one permission that opens the management side of the web UI.

func (*EffectivePermissions) Within added in v0.81.0

Within is what these permissions and the limit both allow: a server-wide permission held in both, and a domain permission held over a domain in both, whether through that domain or through the all-domains permission that widens it. For work that must never do more than the turn that started it, whatever the person may do by the time it runs.

type EvaluationQuestionKind added in v0.61.0

type EvaluationQuestionKind string

EvaluationQuestionKind is what a memory check question tests, the same kinds a question file uses.

const (
	EvaluationQuestionDirect     EvaluationQuestionKind = "direct"
	EvaluationQuestionParaphrase EvaluationQuestionKind = "paraphrase"
	EvaluationQuestionChanged    EvaluationQuestionKind = "changed"
	EvaluationQuestionMultihop   EvaluationQuestionKind = "multihop"
	EvaluationQuestionAbstain    EvaluationQuestionKind = "abstain"
)

The kinds. Direct asks what a fact says; paraphrase asks it in other words; changed asks about something that is no longer so; multihop needs two facts together; abstain asks what memory should not know.

type EvaluationQuestionState added in v0.61.0

type EvaluationQuestionState string

EvaluationQuestionState is where a question stands with the person.

const (
	EvaluationQuestionAsked     EvaluationQuestionState = "asked"
	EvaluationQuestionConfirmed EvaluationQuestionState = "confirmed"
	EvaluationQuestionCorrected EvaluationQuestionState = "corrected"
	EvaluationQuestionDropped   EvaluationQuestionState = "dropped"
	EvaluationQuestionUnsure    EvaluationQuestionState = "unsure"
)

The states. Asked is put to the person and not yet answered. Confirmed is the answer the agent gave, which the person said was right; corrected carries the answer the person gave instead. Both take part in an evaluation. Dropped is a question the person did not want kept, and unsure one they could not answer; neither takes part.

func (EvaluationQuestionState) IsEvaluated added in v0.61.0

func (self EvaluationQuestionState) IsEvaluated() bool

IsEvaluated says whether a question in this state takes part in an evaluation: its answer is one the person stands behind.

type EvaluationSourceScore added in v0.61.0

type EvaluationSourceScore struct {
	// AnswerFrom is memory, sources or both.
	AnswerFrom string `json:"answerFrom"`

	// AnsweredCount is how many questions were answered from it.
	AnsweredCount int `json:"answeredCount"`

	// ScorePercent counts a right answer, and a right "not known" to an
	// abstain question, as one, and a partial answer as a half.
	ScorePercent float64 `json:"scorePercent"`

	// ScorePercentWithoutFiledAfter leaves out the questions whose answers
	// were filed into memory after they were written, which are easy.
	ScorePercentWithoutFiledAfter float64 `json:"scorePercentWithoutFiledAfter"`
	FiledAfterCount               int     `json:"filedAfterCount"`

	// VerdictCounts is how many answers had each verdict.
	VerdictCounts map[string]int `json:"verdictCounts"`
}

EvaluationSourceScore is how the answers from one source scored.

type Evidence

type Evidence struct {
	Kind EvidenceKind `json:"kind"`
	ID   string       `json:"id,omitempty"`

	// Quote is the line it was read in, so a person looking at a page can
	// see why the agent believes it.
	Quote string `json:"quote,omitempty"`

	// At is when the evidence was written, where that is known and
	// different from when the fact was filed.
	At *time.Time `json:"at,omitempty"`

	// For a recording passage, ID is the recording and these are the
	// transcript it was read in and the range, in milliseconds, so that the
	// dashboard opens the recording at the passage. Zero for any other kind.
	TranscriptRunID string `json:"transcriptRunId,omitempty"`
	StartMS         int64  `json:"startMS,omitempty"`
	EndMS           int64  `json:"endMS,omitempty"`
}

Evidence is one place a fact came from, with the words it was read in.

func MergeEvidence added in v0.110.2

func MergeEvidence(standing, added []Evidence) []Evidence

MergeEvidence is a fact's evidence with another saying's added, each place (kind, id and quote) once and within EvidenceCount.

A place said again moves to where the newest are, keeping the earlier of its two times, since SaidAt is the earliest; only the first entry, where the fact came from, stays where it is. Past EvidenceCount the middle goes: the first entry and the newest, which hold everything the merge just added and so whatever a rise in confidence rests on, are kept. Cutting the end instead dropped everything a full fact was told later, while its confidence rose on the strength of it.

type EvidenceKind

type EvidenceKind string

EvidenceKind is where a fact came from.

const (
	EvidenceConversation EvidenceKind = "conversation"
	EvidenceMail         EvidenceKind = "mail"
	EvidenceDocument     EvidenceKind = "document"
	EvidenceCommit       EvidenceKind = "commit"
	EvidenceChat         EvidenceKind = "chat"
	EvidenceContact      EvidenceKind = "contact"
	EvidenceRepository   EvidenceKind = "repository"
	EvidenceMemory       EvidenceKind = "memory"
	EvidencePerson       EvidenceKind = "person"

	// The records of the person's own that evidence can name, besides mail
	// and contact above: the same words as the kinds of record a page can
	// be linked to (AgentRecordKind), so that a fact's source opens the
	// record. A recording passage carries its range, see Evidence.
	EvidenceCalendarEvent       EvidenceKind = "calendar_event"
	EvidenceReminder            EvidenceKind = "reminder"
	EvidenceConversationMessage EvidenceKind = "conversation_message"
	EvidenceFinanceTransaction  EvidenceKind = "finance_transaction"
	EvidenceFinanceReceipt      EvidenceKind = "finance_receipt"
	EvidenceRecordingPassage    EvidenceKind = "recording_passage"

	// EvidenceDream is the agent's own reasoning rather than anything it
	// read: the path a nightly walk took to reach a page. It has its own
	// kind so that no reader mistakes the walk for a document.
	EvidenceDream EvidenceKind = "dream"
)

The kinds of evidence.

type ExchangeRate added in v0.87.0

type ExchangeRate struct {
	// RateOn is the day it was published for, "2006-01-02".
	RateOn       string `json:"rateOn"`
	CurrencyCode string `json:"currencyCode"`

	// EuroRate is a decimal: how many of CurrencyCode one euro bought.
	EuroRate   string     `json:"euroRate"`
	RateSource RateSource `json:"rateSource"`

	CreatedAt time.Time `json:"createdAt"`
}

ExchangeRate is what one euro bought in one currency on one day, as a rate source published it. Rates between two other currencies are the ratio of their euro rates.

type ExpectedRepeatCharge added in v0.98.1

type ExpectedRepeatCharge struct {
	MerchantName   string `json:"merchantName"`
	ExpectedAmount string `json:"expectedAmount"`
	CurrencyCode   string `json:"currencyCode"`
}

ExpectedRepeatCharge is a merchant that charged a spending category in each of the last three full months and has not yet this month: what it is expected to charge, its median over those months.

type FeedCardLayout added in v0.230.0

type FeedCardLayout string

FeedCardLayout is how a card is drawn: text, the default, or a layout with structured content that every app draws natively.

const (
	FeedLayoutText    FeedCardLayout = "text"
	FeedLayoutList    FeedCardLayout = "list"
	FeedLayoutWeather FeedCardLayout = "weather"
	FeedLayoutAgenda  FeedCardLayout = "agenda"
)

The layouts.

type FeedChange added in v0.230.0

type FeedChange string

FeedChange is what happened to a card, for a screen that has it open.

const (
	FeedChangePosted    FeedChange = "posted"
	FeedChangeReplaced  FeedChange = "replaced"
	FeedChangeSettled   FeedChange = "settled"
	FeedChangeDismissed FeedChange = "dismissed"
	FeedChangeRestored  FeedChange = "restored"

	// FeedChangeResolved and FeedChangeUnresolved say a card was marked
	// resolved, or the mark was taken off. Neither moves the card.
	FeedChangeResolved   FeedChange = "resolved"
	FeedChangeUnresolved FeedChange = "unresolved"
)

The changes.

type FeedChartBar added in v0.240.0

type FeedChartBar struct {
	BarLabel string  `json:"barLabel"`
	BarValue float64 `json:"barValue"`
}

FeedChartBar is one bar of a bar chart, never negative.

type FeedChartBlock added in v0.240.0

type FeedChartBlock struct {
	ChartKind  FeedChartKind `json:"chartKind"`
	ChartTitle string        `json:"chartTitle"`

	// Unit is what the numbers count, such as "USD" or "steps".
	Unit       string `json:"unit"`
	Provenance string `json:"provenance"`

	// XLabels, Series and Markers are for a series chart.
	XLabels []string          `json:"xLabels"`
	Series  []FeedChartSeries `json:"series"`
	Markers []FeedChartMarker `json:"markers"`

	// Bars are for a bar chart, largest first.
	Bars []FeedChartBar `json:"bars"`
}

FeedChartBlock is a chart on a card. Provenance says where and when the numbers were read.

type FeedChartKind added in v0.240.0

type FeedChartKind string

FeedChartKind is how a chart is drawn: a series over time, or bars.

const (
	FeedChartKindSeries FeedChartKind = "series"
	FeedChartKindBars   FeedChartKind = "bars"
)

The kinds of chart.

type FeedChartMarker added in v0.240.0

type FeedChartMarker struct {
	MarkerAt    string `json:"markerAt"`
	MarkerLabel string `json:"markerLabel"`
}

FeedChartMarker is a labeled vertical rule at one of the axis labels.

type FeedChartSeries added in v0.240.0

type FeedChartSeries struct {
	SeriesName string         `json:"seriesName"`
	SeriesRole FeedSeriesRole `json:"seriesRole"`
	Values     []*float64     `json:"values"`
}

FeedChartSeries is one line of a series chart: a number for each label of the axis, or nil where there is none.

type FeedChoice added in v0.230.0

type FeedChoice struct {
	ChoiceKey   string         `json:"choiceKey"`
	ChoiceLabel string         `json:"choiceLabel"`
	ChoiceRole  FeedChoiceRole `json:"choiceRole"`
}

FeedChoice is a button on a card.

type FeedChoiceRole added in v0.230.0

type FeedChoiceRole string

FeedChoiceRole is what choosing a button does: action carries it out, dismiss closes the card, discuss opens a conversation about it, open opens the thing it is about (a coding session).

const (
	FeedChoiceAction  FeedChoiceRole = "action"
	FeedChoiceDismiss FeedChoiceRole = "dismiss"
	FeedChoiceDiscuss FeedChoiceRole = "discuss"
	FeedChoiceOpen    FeedChoiceRole = "open"
)

The roles of a choice.

type FeedCursor added in v0.230.0

type FeedCursor struct {
	OrderedAt time.Time
	ID        string
}

FeedCursor is how far a page of the feed got: the time the page is ordered by (when the card was posted, or for the dismissed cards when it was dismissed) and the id of its last card.

type FeedEvent added in v0.230.0

type FeedEvent struct {
	UserID      string     `json:"userId"`
	FeedItemID  string     `json:"feedItemId"`
	FeedChange  FeedChange `json:"feedChange"`
	UnreadCount int        `json:"unreadCount"`
}

FeedEvent is what a screen with the feed open is told.

type FeedFactRow added in v0.230.0

type FeedFactRow struct {
	FactLabel string `json:"factLabel"`
	FactValue string `json:"factValue"`
}

FeedFactRow is one line of a card's short table.

type FeedItemKind added in v0.230.0

type FeedItemKind string

FeedItemKind is what a card is: an update, a decision the person is asked to make, an alert, a report a schedule or goal made, an idea, or news.

const (
	FeedItemUpdate   FeedItemKind = "update"
	FeedItemDecision FeedItemKind = "decision"
	FeedItemAlert    FeedItemKind = "alert"
	FeedItemReport   FeedItemKind = "report"
	FeedItemIdea     FeedItemKind = "idea"
	FeedItemNews     FeedItemKind = "news"
)

The kinds of card.

type FeedMedia added in v0.230.0

type FeedMedia struct {
	// MediaKey names the entry on its card, for the address its picture is
	// served from.
	MediaKey      string        `json:"mediaKey"`
	FeedMediaKind FeedMediaKind `json:"feedMediaKind"`

	// PhotoID is the person's photo or video, for those kinds.
	PhotoID string `json:"photoId,omitempty"`

	// PageURL is the page whose picture this is, for a picture. ImageFileID
	// is the picture as the server keeps it, empty until it is fetched, and
	// IsPictureMissing says the page had none or could not be read, so it
	// is not shown or tried again.
	PageURL          string `json:"pageUrl,omitempty"`
	ImageFileID      string `json:"imageFileId,omitempty"`
	IsPictureMissing bool   `json:"isPictureMissing,omitempty"`

	// SiteName is what the page calls its site.
	SiteName     string `json:"siteName,omitempty"`
	MediaCaption string `json:"mediaCaption,omitempty"`
	WidthPixels  int    `json:"widthPixels,omitempty"`
	HeightPixels int    `json:"heightPixels,omitempty"`

	// ListRowIndex makes the entry the thumbnail of that row of a list card;
	// nil for a picture of the whole card.
	ListRowIndex *int `json:"listRowIndex,omitempty"`

	// CameraName is the camera a still is from, and CapturedAt when, in RFC
	// 3339 on the camera's own clock with its offset, never converted to
	// UTC. StillReason says why this camera. PlaybackURL opens the
	// recording and LiveURL the live view, each https or the app's own
	// scheme. All for a camera still.
	CameraName  string `json:"cameraName,omitempty"`
	CapturedAt  string `json:"capturedAt,omitempty"`
	StillReason string `json:"stillReason,omitempty"`
	PlaybackURL string `json:"playbackUrl,omitempty"`
	LiveURL     string `json:"liveUrl,omitempty"`

	// AttachmentID is the file of the posting run that a camera still is
	// made from. It is read as the card is posted and never stored.
	AttachmentID string `json:"-"`

	// FileAttachmentID is the agent's file a file entry shows, kept while
	// the card holds it, with its name, type and size as they were when it
	// was sent.
	FileAttachmentID string `json:"fileAttachmentId,omitempty"`
	FileName         string `json:"fileName,omitempty"`
	FileContentType  string `json:"fileContentType,omitempty"`
	FileSize         int64  `json:"fileSize,omitempty"`
}

FeedMedia is a picture or video on a card.

func (*FeedMedia) IsPictureWaiting added in v0.230.0

func (self *FeedMedia) IsPictureWaiting() bool

IsPictureWaiting says the entry is a page's picture not fetched yet.

func (*FeedMedia) IsShown added in v0.230.0

func (self *FeedMedia) IsShown() bool

IsShown says the entry has something to show: a photo or video, a page's picture that was fetched, or a camera still that was kept or is one of the person's photos.

type FeedMediaKind added in v0.230.0

type FeedMediaKind string

FeedMediaKind is what a picture or video on a card is.

const (
	// FeedMediaPhoto is one of the person's own photos.
	FeedMediaPhoto FeedMediaKind = "photo"

	// FeedMediaVideo is one of the person's own videos.
	FeedMediaVideo FeedMediaKind = "video"

	// FeedMediaPicture is the picture of a web page, which the server
	// fetches and keeps so that the person's device never asks the page's
	// site for it.
	FeedMediaPicture FeedMediaKind = "picture"

	// FeedMediaCameraStill is a still from one of the person's cameras, kept
	// by the server as a page's picture is, or one of the person's photos of
	// that moment, with why this camera was chosen.
	FeedMediaCameraStill FeedMediaKind = "camera_still"

	// FeedMediaFile is a file sent to the person's feed: one of the agent's
	// files, a picture drawn in place and anything else opened as the main
	// chat opens a file.
	FeedMediaFile FeedMediaKind = "file"
)

type FeedResolution added in v0.240.0

type FeedResolution struct {
	ResolutionNote string
	ResolvedByKind FeedResolverKind
	ResolvedByID   string
}

FeedResolution is what marks a card resolved: who, and the one line saying what cleared.

type FeedResolverKind added in v0.240.0

type FeedResolverKind string

FeedResolverKind is who marked a card resolved: a goal in its own turn, the person, or the agent outside a goal's turn.

const (
	FeedResolverGoal   FeedResolverKind = "goal"
	FeedResolverPerson FeedResolverKind = "person"
	FeedResolverAgent  FeedResolverKind = "agent"
)

The kinds of resolver.

type FeedSeriesRole added in v0.240.0

type FeedSeriesRole string

FeedSeriesRole is what a line of a series chart is: measured, the default, a reference to compare with (last month, the average), or a projection of what is expected ahead.

const (
	FeedSeriesMeasured   FeedSeriesRole = "measured"
	FeedSeriesReference  FeedSeriesRole = "reference"
	FeedSeriesProjection FeedSeriesRole = "projection"
)

The roles of a line.

type FeedSettlement added in v0.230.0

type FeedSettlement struct {
	ChoiceKey      string
	OutcomeText    string
	ConversationID string

	// IsOutcomePending says a turn is running whose last words will be the
	// outcome.
	IsOutcomePending bool
}

FeedSettlement is what settles a card: the choice, what came of it, and where it carried on.

type FeedSourceKind added in v0.230.0

type FeedSourceKind string

FeedSourceKind is what made a card: a goal, an alert, the agent speaking first, a coding session, or a turn's own post.

const (
	FeedSourceGoal          FeedSourceKind = "goal"
	FeedSourceAlert         FeedSourceKind = "alert"
	FeedSourceSpeakFirst    FeedSourceKind = "speak_first"
	FeedSourceCodingSession FeedSourceKind = "coding_session"
	FeedSourceAgent         FeedSourceKind = "agent"
)

The kinds of source.

type FeedSourceLink struct {
	SourceTitle string `json:"sourceTitle"`
	SourceURL   string `json:"sourceUrl"`
}

FeedSourceLink is a page a card is built from, listed on its info sheet.

type FeedStackCounts added in v0.230.0

type FeedStackCounts struct {
	ItemCount   int
	UnreadCount int

	// StackTitle is the first title any card of the stack gave.
	StackTitle string
}

FeedStackCounts is what a stack holds: how many cards, and how many of them are unread, which is none now that a stack holds only read cards; it is kept for the apps that read it.

type FeedUrgency added in v0.230.0

type FeedUrgency string

FeedUrgency is how soon the person should see a card. Only now sends a phone notification; the others raise the unread count.

const (
	FeedUrgencyNow      FeedUrgency = "now"
	FeedUrgencyToday    FeedUrgency = "today"
	FeedUrgencyWhenever FeedUrgency = "whenever"
)

The urgencies.

type FinanceAccount added in v0.87.0

type FinanceAccount struct {
	ID       string `json:"id"`
	AgentID  string `json:"agentId"`
	SourceID string `json:"sourceId"`

	// ProviderAccountID is the provider's id for it, unique within its
	// finance source.
	ProviderAccountID string `json:"providerAccountId"`

	AccountName  string             `json:"accountName"`
	AccountMask  string             `json:"accountMask,omitempty" graphapi:"nullable"`
	AccountKind  FinanceAccountKind `json:"accountKind"`
	CurrencyCode string             `json:"currencyCode"`

	// CurrentBalance and AvailableBalance are decimals as the provider
	// reports them, empty when it does not say. For a card or a loan the
	// sign is the provider's: Plaid reports what is owed as positive,
	// most institutions behind SimpleFIN as negative.
	CurrentBalance   string     `json:"currentBalance,omitempty" graphapi:"nullable"`
	AvailableBalance string     `json:"availableBalance,omitempty" graphapi:"nullable"`
	BalanceAt        *time.Time `json:"balanceAt,omitempty" graphapi:"nullable"`

	// CreditLimitAmount is a card's credit limit as the provider gives it,
	// a positive decimal, empty when it gives none.
	CreditLimitAmount string `json:"creditLimitAmount,omitempty" graphapi:"nullable"`

	// ProviderMetadata is the provider's whole object for the account, as
	// it arrived.
	ProviderMetadata json.RawMessage `json:"providerMetadata,omitempty" graphapi:"nullable"`

	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`
}

FinanceAccount is one account a finance source reports: checking, savings, a card, a brokerage account, a loan.

func (*FinanceAccount) InstitutionName added in v0.105.0

func (self *FinanceAccount) InstitutionName(source *AgentKnowledgeSource) string

InstitutionName is the institution the finance account is at: the one its finance source names, else the one its provider metadata names. SimpleFIN gives each account its institution ("org"), since one of its finance sources can reach several, and the finance source itself keeps none; an imported statement names the institution that wrote it ("institutionOrganization"). The source may be nil.

type FinanceAccountKind added in v0.87.0

type FinanceAccountKind string

FinanceAccountKind is what sort of account a finance account is, in the providers' shared vocabulary.

const (
	FinanceAccountKindDepository FinanceAccountKind = "depository"
	FinanceAccountKindCredit     FinanceAccountKind = "credit"
	FinanceAccountKindLoan       FinanceAccountKind = "loan"
	FinanceAccountKindInvestment FinanceAccountKind = "investment"
	FinanceAccountKindOther      FinanceAccountKind = "other"
)

The five kinds. Plaid's vocabulary, the richer of the two providers'; SimpleFIN has none and its accounts are mostly "other".

func (FinanceAccountKind) IsValid added in v0.87.0

func (self FinanceAccountKind) IsValid() bool

IsValid says the kind is one of the five.

type FinancePaystub added in v0.155.0

type FinancePaystub struct {
	ID                string `json:"id"`
	AgentID           string `json:"agentId"`
	AgentAttachmentID string `json:"agentAttachmentId"`

	EmployerName string `json:"employerName"`
	// EmployerTaxID is the employer's identification number as printed.
	EmployerTaxID string `json:"employerTaxId,omitempty" graphapi:"nullable"`
	EmployeeName  string `json:"employeeName"`
	// EmployeeTaxIDMask is the last four digits of the person's taxpayer
	// number, empty when the paystub prints none.
	EmployeeTaxIDMask string `json:"employeeTaxIdMask,omitempty" graphapi:"nullable"`

	// PayDate is the day paid, and PeriodStartOn and PeriodEndOn the days
	// the pay is for, "2006-01-02".
	PayDate       string `json:"payDate"`
	PeriodStartOn string `json:"periodStartOn,omitempty" graphapi:"nullable"`
	PeriodEndOn   string `json:"periodEndOn,omitempty" graphapi:"nullable"`
	CurrencyCode  string `json:"currencyCode"`

	// The totals as printed; empty when the paystub prints none.
	GrossAmount           string `json:"grossAmount"`
	YearToDateGrossAmount string `json:"yearToDateGrossAmount,omitempty" graphapi:"nullable"`
	TotalTaxAmount        string `json:"totalTaxAmount,omitempty" graphapi:"nullable"`
	TotalDeductionAmount  string `json:"totalDeductionAmount,omitempty" graphapi:"nullable"`
	NetAmount             string `json:"netAmount"`

	// PaystubCheckState says whether the lines add up, and
	// CheckDifferenceAmount by how much take-home pay misses: gross less
	// the taxes and deductions less the printed net, zero when balanced.
	PaystubCheckState     PaystubCheckState `json:"paystubCheckState"`
	CheckDifferenceAmount string            `json:"checkDifferenceAmount"`

	PaystubLines []*FinancePaystubLine `json:"paystubLines"`

	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`
}

FinancePaystub is one paycheck's pay statement, stored line by line as printed and checked against its own totals. Amounts are decimals, positive as printed. Only the last four digits of the person's taxpayer number are ever kept.

type FinancePaystubLine added in v0.155.0

type FinancePaystubLine struct {
	ID string `json:"id"`

	// LineNumber is its place on the paystub, from 1.
	LineNumber      int             `json:"lineNumber"`
	PaystubLineKind PaystubLineKind `json:"paystubLineKind"`
	Description     string          `json:"description"`

	// Hours and RateAmount are an earning's, when printed.
	Hours      string `json:"hours,omitempty" graphapi:"nullable"`
	RateAmount string `json:"rateAmount,omitempty" graphapi:"nullable"`

	// CurrentAmount is an earning or a tax this period, or a deduction's
	// employee part; YearToDateAmount the same for the year so far.
	CurrentAmount    string `json:"currentAmount,omitempty" graphapi:"nullable"`
	YearToDateAmount string `json:"yearToDateAmount,omitempty" graphapi:"nullable"`

	// PaystubTaxKind and TaxJurisdictionCode (a state's code or a
	// locality) are a tax's, and CurrentWagesAmount and
	// YearToDateWagesAmount the wages it was figured on, when printed.
	PaystubTaxKind        PaystubTaxKind `json:"paystubTaxKind,omitempty" graphapi:"nullable"`
	TaxJurisdictionCode   string         `json:"taxJurisdictionCode,omitempty" graphapi:"nullable"`
	CurrentWagesAmount    string         `json:"currentWagesAmount,omitempty" graphapi:"nullable"`
	YearToDateWagesAmount string         `json:"yearToDateWagesAmount,omitempty" graphapi:"nullable"`

	// PaystubDeductionKind is a deduction's, and EmployerCurrentAmount and
	// EmployerYearToDateAmount the employer's part of it, when printed.
	PaystubDeductionKind     PaystubDeductionKind `json:"paystubDeductionKind,omitempty" graphapi:"nullable"`
	EmployerCurrentAmount    string               `json:"employerCurrentAmount,omitempty" graphapi:"nullable"`
	EmployerYearToDateAmount string               `json:"employerYearToDateAmount,omitempty" graphapi:"nullable"`
}

FinancePaystubLine is one printed line of a paystub that has an amount.

type FinanceReceipt added in v0.118.0

type FinanceReceipt struct {
	ID      string `json:"id"`
	AgentID string `json:"agentId"`

	// ReceiptSourceKind says where it was read from, and exactly one of
	// MailID, GmailMessageID and AgentAttachmentID is set, the one it
	// names.
	ReceiptSourceKind ReceiptSourceKind `json:"receiptSourceKind"`
	MailID            string            `json:"mailId,omitempty" graphapi:"nullable"`
	GmailMessageID    string            `json:"gmailMessageId,omitempty" graphapi:"nullable"`
	AgentAttachmentID string            `json:"agentAttachmentId,omitempty" graphapi:"nullable"`

	// AgentJobID is the import job that made or last read it, empty for a
	// receipt written by a person or by the tool, or from before the job
	// was remembered. Not shown: the list of imports reads it.
	AgentJobID string `json:"-"`

	// MailboxItemID is where the message is in the person's mailboxes now,
	// for opening it; filled when the receipt is read for the person, not
	// stored, and empty when the message is gone.
	MailboxItemID string `json:"mailboxItemId,omitempty" graphapi:"nullable"`

	// MerchantName and MerchantReceiptNumber (an order or receipt number)
	// are as the merchant wrote them.
	MerchantName          string `json:"merchantName"`
	MerchantReceiptNumber string `json:"merchantReceiptNumber,omitempty" graphapi:"nullable"`

	// PurchasedOn is the day, "2006-01-02", and PurchasedAt the moment
	// when the receipt prints a time.
	PurchasedOn string     `json:"purchasedOn,omitempty" graphapi:"nullable"`
	PurchasedAt *time.Time `json:"purchasedAt,omitempty" graphapi:"nullable"`

	CurrencyCode string `json:"currencyCode"`

	// SubtotalAmount is empty when the receipt prints none.
	SubtotalAmount string `json:"subtotalAmount,omitempty" graphapi:"nullable"`
	TotalAmount    string `json:"totalAmount"`

	// PaymentAccountMask is the last digits of the card or account the
	// receipt says paid, empty when it does not say.
	PaymentAccountMask string `json:"paymentAccountMask,omitempty" graphapi:"nullable"`

	// ReceiptCheckState says whether the lines add up, and
	// CheckDifferenceAmount by how much they miss: what the lines come to
	// less what is printed, zero when balanced.
	ReceiptCheckState     ReceiptCheckState `json:"receiptCheckState"`
	CheckDifferenceAmount string            `json:"checkDifferenceAmount"`

	// IsFeeAfterSubtotal says the receipt prints its fees after the
	// subtotal, with the taxes and tips, rather than among the items the
	// subtotal adds up; worked out from the lines each time the receipt
	// is read (finance.IsReceiptFeeAfterSubtotal), not stored.
	IsFeeAfterSubtotal bool `json:"isFeeAfterSubtotal"`

	ReceiptLines   []*FinanceReceiptLine  `json:"receiptLines"`
	ReceiptMatches []*FinanceReceiptMatch `json:"receiptMatches"`

	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`
}

FinanceReceipt is one merchant's printed or emailed record of one purchase or order, stored line by line exactly as printed, checked against its own totals, and matched to the charges it explains. Amounts are decimals, positive for what was paid. The finance transaction, not the receipt, is what totals count.

type FinanceReceiptLine added in v0.118.0

type FinanceReceiptLine struct {
	ID string `json:"id"`

	// LineNumber is its place on the receipt, from 1.
	LineNumber      int             `json:"lineNumber"`
	ReceiptLineKind ReceiptLineKind `json:"receiptLineKind"`
	Description     string          `json:"description"`

	// Quantity, QuantityUnit ("lb", "kg") and UnitPriceAmount are what the
	// line prints of them, empty when it prints none.
	Quantity        string `json:"quantity,omitempty" graphapi:"nullable"`
	QuantityUnit    string `json:"quantityUnit,omitempty" graphapi:"nullable"`
	UnitPriceAmount string `json:"unitPriceAmount,omitempty" graphapi:"nullable"`

	// LineAmount is signed as printed: a discount is negative.
	LineAmount string `json:"lineAmount"`

	// TaxClassCode is the receipt's own mark: on an item or a discount the
	// tax it falls under, on a tax line the mark it covers. Empty when the
	// receipt does not say.
	TaxClassCode string `json:"taxClassCode,omitempty" graphapi:"nullable"`

	// DiscountedLineNumber and DiscountedLineID are a discount's item:
	// written by its number, kept by its id.
	DiscountedLineNumber int    `json:"discountedLineNumber,omitempty" graphapi:"nullable"`
	DiscountedLineID     string `json:"discountedLineId,omitempty" graphapi:"nullable"`

	// SpendingCategoryID is reserved for splitting a charge across
	// spending categories by its receipt; nothing writes it yet.
	SpendingCategoryID string `json:"spendingCategoryId,omitempty" graphapi:"nullable"`
}

FinanceReceiptLine is one printed line of a finance receipt.

type FinanceReceiptMatch added in v0.118.0

type FinanceReceiptMatch struct {
	ReceiptID            string             `json:"receiptId"`
	FinanceTransactionID string             `json:"financeTransactionId"`
	MatchedAmount        string             `json:"matchedAmount"`
	ReceiptMatchSource   ReceiptMatchSource `json:"receiptMatchSource"`

	// MatchConfidence is the matcher's confidence, a decimal between 0
	// and 1; empty for the person's.
	MatchConfidence string    `json:"matchConfidence,omitempty" graphapi:"nullable"`
	CreatedAt       time.Time `json:"createdAt"`
}

FinanceReceiptMatch is a link between one finance receipt and one finance transaction: how much of the transaction the receipt explains, a positive decimal, and what made the link.

type FinanceSecurity added in v0.88.0

type FinanceSecurity struct {
	ID      string `json:"id"`
	AgentID string `json:"agentId"`

	// ProviderKind is the provider that reported it, and
	// ProviderSecurityID the provider's id for it.
	ProviderKind       string `json:"providerKind"`
	ProviderSecurityID string `json:"providerSecurityId"`

	TickerSymbol string       `json:"tickerSymbol,omitempty" graphapi:"nullable"`
	SecurityName string       `json:"securityName"`
	SecurityKind SecurityKind `json:"securityKind"`
	CurrencyCode string       `json:"currencyCode,omitempty" graphapi:"nullable"`

	// ClosePrice is the last close the provider reported, a decimal, and
	// ClosePriceOn its day, "2006-01-02"; both empty when it gave none.
	ClosePrice   string `json:"closePrice,omitempty" graphapi:"nullable"`
	ClosePriceOn string `json:"closePriceOn,omitempty" graphapi:"nullable"`

	// ProviderMetadata is the provider's whole object for the security, as
	// it last arrived.
	ProviderMetadata json.RawMessage `json:"providerMetadata,omitempty" graphapi:"nullable"`

	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`
}

FinanceSecurity is something an investment account can hold, as the provider that reported it describes it. One per agent per provider's security; it outlives the finance source that brought it.

type FinanceShare added in v0.194.0

type FinanceShare struct {
	ID               string `json:"id"`
	FinanceAccountID string `json:"financeAccountId"`

	GranteeUserID   string `json:"granteeUserId,omitempty"`
	GranteeCircleID string `json:"granteeCircleId,omitempty"`

	FinanceShareLevel FinanceShareLevel `json:"financeShareLevel"`

	CreatedAt time.Time `json:"createdAt"`

	// CreatedByUserID is empty once that account is gone.
	CreatedByUserID string `json:"createdByUserId,omitempty"`

	// The rest is filled in by the listings, for a screen that says which
	// account it is, whose it is and who it is shared with.
	OwnerUserID       string `json:"ownerUserId,omitempty"`
	OwnerUsername     string `json:"ownerUsername,omitempty"`
	OwnerName         string `json:"ownerName,omitempty"`
	OwnerUser         *User  `json:"-"`
	AccountName       string `json:"accountName,omitempty"`
	AccountMask       string `json:"accountMask,omitempty"`
	GranteeUsername   string `json:"granteeUsername,omitempty"`
	GranteeName       string `json:"granteeName,omitempty"`
	GranteeCircleName string `json:"granteeCircleName,omitempty"`
}

FinanceShare gives one person, or every member of one circle, a level of access to one finance account. Exactly one of GranteeUserID and GranteeCircleID is set.

type FinanceShareLevel added in v0.194.0

type FinanceShareLevel string

FinanceShareLevel is how much of a finance account somebody may see. A person shares a finance account with a circle or with one person in a circle they share, at one of these three. Each level adds to the one before.

Never at any level: the account's receipts and their images, what the person or their agent wrote on a transaction, the provider's own data, paystubs, tax forms, finance sources and their credentials, spending rules, budgets, and whether the institution waits for the person to sign in.

const (
	// FinanceShareLevelBalance is the account's name, mask, kind and currency,
	// its current balance and the day of it, and for a credit card what is
	// owed against its limit. No transaction.
	FinanceShareLevelBalance FinanceShareLevel = "balance"
	// FinanceShareLevelSpending adds the account's money out and money in by
	// month and spending category, with no merchant and no description.
	FinanceShareLevelSpending FinanceShareLevel = "spending"
	// FinanceShareLevelTransactions adds each transaction's day, amount,
	// merchant name and spending category.
	FinanceShareLevelTransactions FinanceShareLevel = "transactions"
)

The levels, from least to most.

func HighestFinanceShareLevel added in v0.194.0

func HighestFinanceShareLevel(first, second FinanceShareLevel) FinanceShareLevel

HighestFinanceShareLevel is the greater of two levels, so that a person reached by both a direct share and a circle's takes the better of them.

func (FinanceShareLevel) AtLeast added in v0.194.0

func (self FinanceShareLevel) AtLeast(other FinanceShareLevel) bool

AtLeast reports whether this level reaches the other.

func (FinanceShareLevel) IsGrantable added in v0.194.0

func (self FinanceShareLevel) IsGrantable() bool

IsGrantable reports whether a share may be made at this level.

func (FinanceShareLevel) IsGrantableForAllAccounts added in v0.210.0

func (self FinanceShareLevel) IsGrantableForAllAccounts() bool

IsGrantableForAllAccounts reports whether all of a person's finance may be shared at this level. A balance belongs to one account, and a share of all finance shows no account, so it has no balance level.

func (FinanceShareLevel) Rank added in v0.194.0

func (self FinanceShareLevel) Rank() int

Rank orders the levels; zero is no access at all.

type FinanceSourceSettings added in v0.87.0

type FinanceSourceSettings struct {
	InstitutionID     string `json:"institutionId,omitempty"`
	InstitutionName   string `json:"institutionName,omitempty"`
	ProviderReference string `json:"providerReference,omitempty"`
}

FinanceSourceSettings is what a finance source's Specification.Settings holds: the institution it reaches and the provider's reference for the link (Plaid's item id; empty for SimpleFIN).

type FinanceSpendingSummaryGroupBy added in v0.87.0

type FinanceSpendingSummaryGroupBy string

FinanceSpendingSummaryGroupBy is what a spending summary groups by.

const (
	FinanceSpendingSummaryGroupByProviderCategory FinanceSpendingSummaryGroupBy = "providerCategory"
	FinanceSpendingSummaryGroupBySpendingCategory FinanceSpendingSummaryGroupBy = "spendingCategory"
	FinanceSpendingSummaryGroupByMerchant         FinanceSpendingSummaryGroupBy = "merchant"
	FinanceSpendingSummaryGroupByMonth            FinanceSpendingSummaryGroupBy = "month"
	FinanceSpendingSummaryGroupByFinanceAccount   FinanceSpendingSummaryGroupBy = "financeAccount"
)

The ways a spending summary groups: by the provider's category, by the person's spending category, by merchant (the description when there is no merchant), by month, or by finance account.

func (FinanceSpendingSummaryGroupBy) IsValid added in v0.87.0

func (self FinanceSpendingSummaryGroupBy) IsValid() bool

IsValid says the grouping is one of the five.

type FinanceSpendingSummaryRow added in v0.87.0

type FinanceSpendingSummaryRow struct {
	// GroupKey is what the rows were grouped by: the provider category,
	// the spending category's id, the merchant, the month as "2006-01" or
	// the finance account's id. Empty for transactions with none.
	// GroupLabel is the name to show for an id: the spending category's or
	// the finance account's name; for the others it is the key.
	GroupKey   string `json:"groupKey"`
	GroupLabel string `json:"groupLabel"`

	CurrencyCode            string `json:"currencyCode"`
	MoneyOut                string `json:"moneyOut"`
	MoneyIn                 string `json:"moneyIn"`
	FinanceTransactionCount int    `json:"financeTransactionCount"`
}

FinanceSpendingSummaryRow is one group's money out and money in, in one currency, transfers left out. Both are positive decimals.

type FinanceStatementImport added in v0.100.0

type FinanceStatementImport struct {
	ImportedAt            time.Time             `json:"importedAt"`
	StatementImportOrigin StatementImportOrigin `json:"statementImportOrigin"`

	// StatementFileNames are the files read, as they were named.
	StatementFileNames []string `json:"statementFileNames"`

	// The transactions: new ones added, stored ones whose fields changed,
	// stored ones the file repeated unchanged, and ones not written
	// because their account could not be found.
	AddedTransactionCount     int `json:"addedTransactionCount"`
	UpdatedTransactionCount   int `json:"updatedTransactionCount"`
	UnchangedTransactionCount int `json:"unchangedTransactionCount"`
	SkippedTransactionCount   int `json:"skippedTransactionCount"`

	// TransactionWithoutFITIDCount is how many had no FITID, the
	// institution's identifier, and were known by their day, amount and
	// name instead.
	TransactionWithoutFITIDCount int `json:"transactionWithoutFitIdCount"`

	// FinanceAccountIDs and FinanceAccountNames are the accounts the
	// statements went into, the names with the end of the account's
	// identifier.
	FinanceAccountIDs   []string `json:"financeAccountIds"`
	FinanceAccountNames []string `json:"financeAccountNames"`

	// ImportErrorMessage says why nothing was imported; empty when the
	// import worked.
	ImportErrorMessage string `json:"importErrorMessage,omitempty" graphapi:"nullable"`
}

FinanceStatementImport is what one import of statement files did: kept on the statement finance source as its last import, and answered to whoever imported.

type FinanceTaxForm added in v0.155.0

type FinanceTaxForm struct {
	ID                string `json:"id"`
	AgentID           string `json:"agentId"`
	AgentAttachmentID string `json:"agentAttachmentId"`

	// AgentJobID is the import job that made or last read it, empty for a
	// form from before the job was remembered. Not shown: the list of
	// imports reads it.
	AgentJobID string `json:"-"`

	TaxFormKind TaxFormKind `json:"taxFormKind"`
	TaxYear     int         `json:"taxYear"`
	// IsCorrected says it is a corrected form (a W-2c).
	IsCorrected bool `json:"isCorrected"`

	// PayerName and PayerTaxID are the employer's on a W-2, the bank's or
	// the broker's on a 1099.
	PayerName  string `json:"payerName"`
	PayerTaxID string `json:"payerTaxId,omitempty" graphapi:"nullable"`
	// RecipientName and RecipientTaxIDMask (the last four digits) are the
	// employee's on a W-2.
	RecipientName      string `json:"recipientName"`
	RecipientTaxIDMask string `json:"recipientTaxIdMask,omitempty" graphapi:"nullable"`

	TaxFormEntries []*FinanceTaxFormEntry `json:"taxFormEntries"`

	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`
}

FinanceTaxForm is one tax form for one tax year, its boxes as entries. Only the last four digits of the recipient's taxpayer number are kept.

type FinanceTaxFormEntry added in v0.155.0

type FinanceTaxFormEntry struct {
	ID string `json:"id"`

	// EntryNumber is its place in the form as read, from 1.
	EntryNumber int `json:"entryNumber"`
	// BoxCode is the box's number as the form prints it ("1", "12").
	BoxCode string `json:"boxCode"`
	// BoxQualifier tells boxes of one number apart: box 12's letter code,
	// a state's code in boxes 15 to 17, a locality in boxes 18 to 20,
	// box 14's label, box 13's checkbox. Empty for a box that is one.
	BoxQualifier string `json:"boxQualifier,omitempty" graphapi:"nullable"`
	// Amount is the box's amount, TextValue its text (an employer's state
	// id), IsChecked its mark.
	Amount    string `json:"amount,omitempty" graphapi:"nullable"`
	TextValue string `json:"textValue,omitempty" graphapi:"nullable"`
	IsChecked bool   `json:"isChecked"`
}

FinanceTaxFormEntry is one box of a tax form.

type FinanceTrade added in v0.88.0

type FinanceTrade struct {
	ID               string `json:"id"`
	AgentID          string `json:"agentId"`
	FinanceAccountID string `json:"financeAccountId"`

	// FinanceSecurityID is the security traded, empty when the provider
	// named none, and FinanceSecurity the security itself when the trade
	// was read with it.
	FinanceSecurityID string           `json:"financeSecurityId,omitempty" graphapi:"nullable"`
	FinanceSecurity   *FinanceSecurity `json:"financeSecurity,omitempty" graphapi:"nullable"`

	// ProviderTradeID is the provider's id for it, unique within its
	// finance account.
	ProviderTradeID string `json:"providerTradeId"`

	// TradedOn is the day, "2006-01-02".
	TradedOn string `json:"tradedOn"`

	// TradeKind is what it was, and TradeSubkind the provider's finer word
	// for it, as the provider wrote it.
	TradeKind    TradeKind `json:"tradeKind"`
	TradeSubkind string    `json:"tradeSubkind,omitempty" graphapi:"nullable"`

	// TradedQuantity is how much of the security it moved, and UnitPrice
	// the price of one unit, decimals; empty when the provider gave none.
	TradedQuantity string `json:"tradedQuantity,omitempty" graphapi:"nullable"`
	UnitPrice      string `json:"unitPrice,omitempty" graphapi:"nullable"`

	// TradeAmount is the cash it moved in the account, a decimal, negative
	// when cash left it (a buy); FeeAmount what it cost in fees.
	TradeAmount  string `json:"tradeAmount"`
	FeeAmount    string `json:"feeAmount,omitempty" graphapi:"nullable"`
	CurrencyCode string `json:"currencyCode"`

	// Description is the institution's, as the provider passed it on.
	Description string `json:"description"`

	// ProviderMetadata is the provider's whole object for the trade, as it
	// arrived.
	ProviderMetadata json.RawMessage `json:"providerMetadata,omitempty" graphapi:"nullable"`

	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`
}

FinanceTrade is one trade in an investment account: cash swapped for a security or back inside the account. It is never spending or income, and it is not a finance transaction.

type FinanceTransaction added in v0.87.0

type FinanceTransaction struct {
	ID               string `json:"id"`
	AgentID          string `json:"agentId"`
	FinanceAccountID string `json:"financeAccountId"`

	// ProviderTransactionID is the provider's id for it, unique within its
	// finance account.
	ProviderTransactionID string `json:"providerTransactionId"`

	// PostedOn is the day it posted, "2006-01-02".
	PostedOn     string     `json:"postedOn"`
	TransactedAt *time.Time `json:"transactedAt,omitempty" graphapi:"nullable"`

	// Amount is a decimal; negative is money leaving the account.
	Amount       string `json:"amount"`
	CurrencyCode string `json:"currencyCode"`

	// Description and MerchantName are written by outsiders: whoever
	// charged the account, and the provider's cleaning of it.
	Description  string `json:"description"`
	MerchantName string `json:"merchantName,omitempty" graphapi:"nullable"`

	// The category the provider assigned: Plaid's primary and detailed
	// categories, or for SimpleFIN the merchant category code as
	// "mcc:5411" in the detailed one.
	ProviderCategoryPrimary  string `json:"providerCategoryPrimary,omitempty" graphapi:"nullable"`
	ProviderCategoryDetailed string `json:"providerCategoryDetailed,omitempty" graphapi:"nullable"`

	IsPending                    bool   `json:"isPending"`
	PendingProviderTransactionID string `json:"pendingProviderTransactionId,omitempty" graphapi:"nullable"`

	// ProviderMetadata is the provider's whole object for the transaction,
	// as it arrived.
	ProviderMetadata json.RawMessage `json:"providerMetadata,omitempty" graphapi:"nullable"`

	// SpendingCategoryID is the person's spending category for it, empty
	// while uncategorized, and CategorizedBy what gave it. It is a
	// transfer between the person's own accounts, neither spending nor
	// income, exactly when the spending category is the agent's transfer
	// category (SpendingCategory.IsTransfer); nothing else says so.
	// CategorizationConfidence is the decision model's confidence, a
	// decimal between 0 and 1, empty for anything else.
	SpendingCategoryID       string        `json:"spendingCategoryId,omitempty" graphapi:"nullable"`
	CategorizedBy            CategorizedBy `json:"categorizedBy,omitempty" graphapi:"nullable"`
	CategorizationConfidence string        `json:"categorizationConfidence,omitempty" graphapi:"nullable"`

	// DuplicateOfTransactionID is the counted copy this one mirrors: the
	// same charge reported again on another investment account of the
	// same Plaid finance source, left out of every total like a transfer.
	// Empty when it is counted. DuplicateDecidedBy says what decided:
	// mirror detection, which marks and clears copies after each sync, or
	// the person, whose "count this one" detection then leaves alone.
	// Empty when nothing did.
	DuplicateOfTransactionID string             `json:"duplicateOfTransactionId,omitempty" graphapi:"nullable"`
	DuplicateDecidedBy       DuplicateDecidedBy `json:"duplicateDecidedBy,omitempty" graphapi:"nullable"`

	// Annotation is what the person or their agent wrote on it, and
	// AnnotatedBy which of them; both empty when nobody has. The agent
	// never overwrites the person's.
	Annotation  string      `json:"annotation,omitempty" graphapi:"nullable"`
	AnnotatedBy AnnotatedBy `json:"annotatedBy,omitempty" graphapi:"nullable"`

	// ReceiptCount is how many receipts are matched to it.
	ReceiptCount int `json:"receiptCount"`

	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`
}

FinanceTransaction is one transaction on a finance account.

type GoalCardEngagement added in v0.249.0

type GoalCardEngagement struct {
	PostedCardCount    int `json:"postedCardCount"`
	UsefulCardCount    int `json:"usefulCardCount"`
	LikedCardCount     int `json:"likedCardCount"`
	DiscussedCardCount int `json:"discussedCardCount"`
	ActedOnCardCount   int `json:"actedOnCardCount"`
	ExpectedCardCount  int `json:"expectedCardCount"`
	DismissedCardCount int `json:"dismissedCardCount"`
	ReadOnlyCardCount  int `json:"readOnlyCardCount"`
	NotReadCardCount   int `json:"notReadCardCount"`
}

GoalCardEngagement counts how the person responded to the cards a goal posted. The buckets overlap (a liked card may also be dismissed), except that UsefulCardCount counts each card once, and ReadOnlyCardCount is the cards that were read and nothing else was done with.

func CountGoalCardEngagement added in v0.249.0

func CountGoalCardEngagement(reactions []*GoalCardReaction) *GoalCardEngagement

CountGoalCardEngagement counts the reactions to the cards of a goal.

func (*GoalCardEngagement) Words added in v0.249.0

func (self *GoalCardEngagement) Words() string

Words says how the cards landed in the plain sentence a goal's own turn is given, empty for a goal that has posted none.

type GoalCardReaction added in v0.249.0

type GoalCardReaction struct {
	FeedItemID string
	PostedAt   time.Time

	IsLiked     bool
	IsDiscussed bool
	IsActedOn   bool
	IsDismissed bool
	IsRead      bool

	// IsAnswerExpected is a card with buttons that nobody has pressed.
	IsAnswerExpected bool
}

GoalCardReaction is what the person did with one card a goal posted, as the database knows it. IsDiscussed says a message of theirs pointed the agent at the card, which is what pressing Discuss on it leads to.

func RecentGoalCardReactions added in v0.249.0

func RecentGoalCardReactions(reactions []*GoalCardReaction, since time.Time) []*GoalCardReaction

RecentGoalCardReactions are the reactions to the cards posted on or after the moment.

type Grant

type Grant struct {
	Permission Permission
	DomainID   string
}

Grant is one (permission, domain) pair a group's roles produce; the domain is empty for a server or all-domains permission.

type Group

type Group struct {
	ID          string    `json:"id"`
	CreatedAt   time.Time `json:"createdAt"`
	ModifiedAt  time.Time `json:"modifiedAt"`
	Name        string    `json:"name"`
	Description string    `json:"description,omitempty"`

	// IDPGroup is the group's name at the identity provider; single sign-on
	// adds and removes users of a group that has one and never touches one
	// that does not.
	IDPGroup string `json:"idpGroup,omitempty"`

	// UserIDs is the user_group table: who is in the group.
	UserIDs []string `json:"userIds"`

	// RoleIDs is the group_role table: what every user in the group may do.
	RoleIDs []string `json:"roleIds"`

	// DomainIDs is the group_domain table: where the domain-kind permissions
	// of those roles apply.
	DomainIDs []string `json:"domainIds"`
}

Group is a named set of users, and the only thing a role or a domain is attached to: everyone in the group holds the group's roles, over the group's domains for the domain-kind permissions and everywhere for the rest.

func (*Group) Validate

func (self *Group) Validate() error

Validate reports everything wrong with the group.

type HealthCharacteristic added in v0.183.0

type HealthCharacteristic struct {
	HealthType          string    `json:"healthType"`
	CharacteristicValue string    `json:"characteristicValue"`
	UpdatedAt           time.Time `json:"updatedAt"`
}

HealthCharacteristic is a fact about the person that HealthKit keeps once: date of birth, biological sex, blood type, skin type, wheelchair use.

type HealthChoices added in v0.183.0

type HealthChoices struct {
	// CanAgentReadHealth is the person's switch for the agent's health tool;
	// off until they turn it on.
	CanAgentReadHealth bool `json:"canAgentReadHealth"`

	// HealthErasedAt is when the person last erased all of their Health data,
	// nil if they never did.
	HealthErasedAt *time.Time `json:"healthErasedAt,omitempty"`
}

HealthChoices is what a person has decided about their Health, which lives on their account and is cheap to read: every report and every check of the agent's switch reads it.

type HealthDaySummary added in v0.183.0

type HealthDaySummary struct {
	UserID     string `json:"userId"`
	HealthType string `json:"healthType"`

	// SummaryDay is the phone's calendar day, written YYYY-MM-DD.
	SummaryDay string `json:"summaryDay"`

	QuantityUnit string `json:"quantityUnit"`

	SumValue     *float64 `json:"sumValue,omitempty"`
	AverageValue *float64 `json:"averageValue,omitempty"`
	MinimumValue *float64 `json:"minimumValue,omitempty"`
	MaximumValue *float64 `json:"maximumValue,omitempty"`

	SampleCount int `json:"sampleCount"`

	// DurationSeconds is the time a category or workout covered, with sources
	// that overlap counted once.
	DurationSeconds *float64 `json:"durationSeconds,omitempty"`

	// CategorySecondsJSON is a JSON object of seconds by the category's own
	// words, such as the stages of a night's sleep.
	CategorySecondsJSON string `json:"categorySecondsJson"`

	// WorkedOutAt is when the phone worked the day out, zero when it did not
	// say. A day sent again with an earlier time than the stored one is left
	// out.
	WorkedOutAt time.Time `json:"workedOutAt"`

	UpdatedAt time.Time `json:"updatedAt"`
}

HealthDaySummary is one kind of reading on one day, as the phone worked it out. A value that does not mean anything for the kind is nil.

type HealthPeriodSummary added in v0.183.0

type HealthPeriodSummary struct {
	// StartDay and EndDay are the first and last day of the period, written
	// YYYY-MM-DD, whether or not the days asked for cover all of it.
	StartDay string `json:"startDay"`
	EndDay   string `json:"endDay"`

	SumValue     *float64 `json:"sumValue,omitempty"`
	AverageValue *float64 `json:"averageValue,omitempty"`
	MinimumValue *float64 `json:"minimumValue,omitempty"`
	MaximumValue *float64 `json:"maximumValue,omitempty"`

	SampleCount     int      `json:"sampleCount"`
	DurationSeconds *float64 `json:"durationSeconds,omitempty"`

	// DayCount is how many days of the period have a summary, which is what
	// a per-day average of a sum or a duration divides by: a month the phone
	// sent twelve days of is twelve days, not thirty.
	DayCount int `json:"dayCount"`

	// CategorySeconds is the seconds of each of the category's words.
	CategorySeconds map[string]float64 `json:"categorySeconds"`
}

HealthPeriodSummary is the days of one period added up. A sum is the days' sums added, an average the days' averages weighted by how many readings each had (a day with none counts as one), a minimum the lowest of the days' minimums, a maximum the highest of the maximums, and the durations and the seconds of each category added.

type HealthRoute added in v0.183.0

type HealthRoute struct {
	UserID         string      `json:"userId"`
	HealthSampleID string      `json:"healthSampleId"`
	RoutePoints    [][]float64 `json:"routePoints"`
	ReceivedAt     time.Time   `json:"receivedAt"`
}

HealthRoute is the path of a workout, as rows of [secondsFromStart, latitudeDegrees, longitudeDegrees, altitudeMeters].

type HealthSample added in v0.183.0

type HealthSample struct {
	ID     string `json:"id"`
	UserID string `json:"userId"`

	// HealthSampleID is HealthKit's identifier for the reading. The phone
	// sends it again until the server has answered, and a deletion on the
	// phone names it, so it is what makes a batch sent twice one batch.
	HealthSampleID string `json:"healthSampleId"`

	// HealthType is HealthKit's identifier of the kind without its prefix:
	// stepCount, heartRate, sleepAnalysis, workout.
	HealthType string `json:"healthType"`

	StartedAt time.Time `json:"startedAt"`
	EndedAt   time.Time `json:"endedAt"`

	// QuantityValue is nil for a reading that is not a quantity.
	QuantityValue *float64 `json:"quantityValue,omitempty"`
	QuantityUnit  string   `json:"quantityUnit"`

	// CategoryValue is HealthKit's raw number for a category reading, nil for
	// any other.
	CategoryValue *int `json:"categoryValue,omitempty"`

	// WorkoutActivityType is running, cycling and so on for a workout, empty
	// for any other reading.
	WorkoutActivityType string `json:"workoutActivityType"`

	SourceName     string `json:"sourceName"`
	SourceBundleID string `json:"sourceBundleId"`
	DeviceName     string `json:"deviceName"`

	// SampleMetadataJSON is a JSON object: a workout's totals, an
	// electrocardiogram's classification, an audiogram's points, the labels of
	// a State of Mind entry, and the metadata keys HealthKit gave the reading.
	SampleMetadataJSON string `json:"sampleMetadataJson"`

	ReceivedAt time.Time `json:"receivedAt"`

	// HasRoute is filled in by the listing of readings: whether a route was
	// kept for the workout.
	HasRoute bool `json:"hasRoute"`
}

HealthSample is one reading from a person's Apple Health: a quantity over a time, a category over a time, or a workout, an electrocardiogram, an audiogram or a State of Mind entry. Only the fields of its own shape are filled. internal/health says which kinds there are.

type HealthSamplePage added in v0.183.0

type HealthSamplePage struct {
	Samples []*HealthSample `json:"samples"`

	// HasMore is whether a reading follows the page.
	HasMore bool `json:"hasMore"`

	// TotalCount is how many readings match, when it was asked for: exact
	// up to HealthSampleCountMost, and that number when there are more
	// (IsTotalCountCapped).
	TotalCount         int  `json:"totalCount"`
	IsTotalCountCapped bool `json:"isTotalCountCapped"`
}

HealthSamplePage is a page of readings, newest first.

type HealthShare added in v0.183.0

type HealthShare struct {
	ID string `json:"id"`

	// UserID is the person whose Health it is.
	UserID string `json:"userId"`

	GranteeUserID   string `json:"granteeUserId,omitempty"`
	GranteeCircleID string `json:"granteeCircleId,omitempty"`

	// HealthCategories are the categories shared, never empty for a share
	// that exists. internal/health lists them.
	HealthCategories []string `json:"healthCategories"`

	CreatedAt time.Time `json:"createdAt"`

	// CreatedByUserID is empty once that account is gone.
	CreatedByUserID string `json:"createdByUserId,omitempty"`

	// OwnerUsername and OwnerName, and GranteeUsername, GranteeName and
	// GranteeCircleName, are filled in by the listings, for a screen that says
	// whose Health it is and who it is shared with.
	OwnerUsername     string `json:"ownerUsername,omitempty"`
	OwnerName         string `json:"ownerName,omitempty"`
	GranteeUsername   string `json:"granteeUsername,omitempty"`
	GranteeName       string `json:"granteeName,omitempty"`
	GranteeCircleName string `json:"granteeCircleName,omitempty"`
}

HealthShare gives one person, or every member of one circle, the day summaries of the sharer's Health in some Health categories. Exactly one of GranteeUserID and GranteeCircleID is set.

type HealthStatus added in v0.183.0

type HealthStatus struct {
	HealthChoices

	SampleCount int `json:"sampleCount"`

	// LastReceivedAt is when the latest reading arrived, nil with none.
	LastReceivedAt *time.Time `json:"lastReceivedAt,omitempty"`

	Characteristics []*HealthCharacteristic `json:"characteristics"`
}

HealthStatus is what a person's Health holds, for their settings.

type HealthTypeSummary added in v0.183.0

type HealthTypeSummary struct {
	HealthType string `json:"healthType"`

	// SampleCount is how many readings of the kind are kept.
	SampleCount int `json:"sampleCount"`

	// QuantityUnit is the unit the latest day summary is in, empty when there
	// is none.
	QuantityUnit string `json:"quantityUnit"`

	// FirstDay and LastDay are empty for a kind with no day summaries yet.
	FirstDay string `json:"firstDay"`
	LastDay  string `json:"lastDay"`

	// LatestDaySummary is the summary of LastDay, nil when there is none.
	LatestDaySummary *HealthPeriodSummary `json:"latestDaySummary,omitempty"`
}

HealthTypeSummary is one kind of data a person has: how many readings are kept, the first and last day it has a summary for, and the latest day.

type IdeaCategory added in v0.76.0

type IdeaCategory struct {
	IdeaCategory AgentIdeaCategory `json:"ideaCategory"`
	Emojis       []string          `json:"emojis"`
}

IdeaCategory is an area, with the emoji an idea in it may carry: a fixed list, so that nothing reads as a joke beside a serious idea. The first is the area's own.

func IdeaCategories added in v0.76.0

func IdeaCategories() []IdeaCategory

IdeaCategories is every area, in the order they are shown.

func IdeaCategoryOf added in v0.76.0

func IdeaCategoryOf(name AgentIdeaCategory) (IdeaCategory, bool)

IdeaCategoryOf is the area with this name, and whether there is one.

type IncomeCategoryBudgetStatus added in v0.98.0

type IncomeCategoryBudgetStatus struct {
	SpendingCategoryID   string `json:"spendingCategoryId"`
	SpendingCategoryName string `json:"spendingCategoryName"`

	// BudgetAmount is the income expected in the whole month, or, for a
	// year, in each of its months that had this budget, added up.
	BudgetAmount string `json:"budgetAmount"`
	CurrencyCode string `json:"currencyCode"`

	// BudgetedMonthCount is how many months the budget was in force: one
	// for a month, and for a year the months of it BudgetAmount adds up.
	BudgetedMonthCount int `json:"budgetedMonthCount"`

	// FirstBudgetedMonth and LastBudgetedMonth are as a
	// SpendingCategoryBudgetStatus's: the first and last of those months.
	FirstBudgetedMonth string `json:"firstBudgetedMonth"`
	LastBudgetedMonth  string `json:"lastBudgetedMonth"`

	// IncomeAmount is what came in this month so far, and
	// IncomeBySameDayLastMonthAmount what came in last month by the same
	// day. For a year, IncomeAmount is what came in during the months that
	// had this budget, and nothing is compared with last month.
	IncomeAmount                   string `json:"incomeAmount"`
	IncomeBySameDayLastMonthAmount string `json:"incomeBySameDayLastMonthAmount"`

	// ExpectedByTodayAmount is the month's expected income spread evenly
	// over its days, up to and including today: what the pace compares
	// IncomeAmount with. For a year, the expected income of the months that
	// are over and the month in progress's spread over its days so far.
	ExpectedByTodayAmount string `json:"expectedByTodayAmount"`

	// ProjectedAmount is where the month is expected to end: for a month
	// in progress, the expected income, or what came in when that is more
	// already, since income comes in a few large amounts that a straight
	// line cannot project; for a month that is over, what came in. For a
	// year (ProjectIncomeCategoryYear), the months added up that way, each
	// month still to come at its expected income.
	ProjectedAmount string     `json:"projectedAmount"`
	IncomePace      IncomePace `json:"incomePace"`

	// UnconvertedIncome is income left out because its currency has no
	// exchange rate into the budget's, and
	// UnconvertedIncomeBySameDayLastMonth the same for last month's.
	UnconvertedIncome                   []*CurrencyAmount `json:"unconvertedIncome"`
	UnconvertedIncomeBySameDayLastMonth []*CurrencyAmount `json:"unconvertedIncomeBySameDayLastMonth"`
}

IncomeCategoryBudgetStatus is one income spending category against the income expected of it. Every amount is a decimal in CurrencyCode, the budget's: income in another currency is converted at the rate of the day it came in.

type IncomeCategoryDay added in v0.98.0

type IncomeCategoryDay struct {
	SpendingCategoryID string `json:"spendingCategoryId"`
	CurrencyCode       string `json:"currencyCode"`

	// ReceivedOn is the day, "2006-01-02".
	ReceivedOn   string `json:"receivedOn"`
	IncomeAmount string `json:"incomeAmount"`
}

IncomeCategoryDay is one day's income in one income spending category and one currency: money in less money taken back, transfers left out.

type IncomePace added in v0.98.0

type IncomePace string

IncomePace is how an income spending category's month is going against the income expected of it. Falling short is the bad direction, so it is not a BudgetPace.

const (
	IncomePaceBehind  IncomePace = "behind"
	IncomePaceOnTrack IncomePace = "on_track"
	IncomePaceAhead   IncomePace = "ahead"
)

The three paces: less has come in than was expected by this day of the month (after the first week), about what was expected, or more than the whole month was expected to bring already.

func (IncomePace) IsValid added in v0.98.0

func (self IncomePace) IsValid() bool

IsValid says the pace is one of the three.

type InteractionKind added in v0.61.4

type InteractionKind string

InteractionKind is what the agent stopped to ask the person for.

const (
	InteractionQuestion InteractionKind = "question"
	InteractionApproval InteractionKind = "approval"
	// InteractionTakeOver asks the person to take their browser tab over
	// from the dashboard, do what only they can, and hand it back.
	InteractionTakeOver InteractionKind = "take_over"
)

The kinds: an answer to a question, or the word to go ahead with a call that needs it.

type InvitationAnswer added in v0.170.0

type InvitationAnswer string

InvitationAnswer is how an invitation ended; empty while it waits.

const (
	InvitationAnswerAccepted  InvitationAnswer = "accepted"
	InvitationAnswerDeclined  InvitationAnswer = "declined"
	InvitationAnswerWithdrawn InvitationAnswer = "withdrawn"
)

The answers. Withdrawn is the inviting circle's own, before the invited person said anything.

type JournalChapter added in v0.202.0

type JournalChapter struct {
	FromDay  string `json:"fromDay"`
	UntilDay string `json:"untilDay"`
	Title    string `json:"title"`
	Detail   string `json:"detail"`
}

JournalChapter is a stretch of a year that belongs together.

type JournalCorrection added in v0.202.0

type JournalCorrection struct {
	CorrectionText string    `json:"correctionText"`
	CreatedAt      time.Time `json:"createdAt"`
}

JournalCorrection is something the person said a narrative got wrong.

type JournalDay added in v0.202.0

type JournalDay struct {
	ID     string `json:"id"`
	UserID string `json:"userId"`

	// Day is the person's calendar date, written YYYY-MM-DD.
	Day string `json:"day"`

	// TimeZone is the IANA zone the day's edges were cut in when the row was
	// made; later changes of the person's zone do not move it.
	TimeZone string `json:"timeZone"`

	// Words is what the person wrote, the original. Only the person changes
	// it, or the agent adding to it when the person asked in a turn they
	// started.
	Words           string     `json:"words"`
	WordsModifiedAt *time.Time `json:"wordsModifiedAt,omitempty"`

	// TouchedUpWords is the version the agent made from Words when the person
	// asked, nil when touching up is off for the day. TouchUpHow is what the
	// person asked for ("shorter", "fix the grammar"). TouchedUpFromDigest is
	// the digest of the Words it was made from (JournalWordsDigest), so a
	// touched-up text made from older words is known to be stale.
	// TouchUpRequestedAt is set while a touch-up is waiting to be made.
	TouchedUpWords      *string    `json:"touchedUpWords,omitempty"`
	TouchUpHow          string     `json:"touchUpHow"`
	TouchedUpFromDigest string     `json:"touchedUpFromDigest"`
	TouchUpRequestedAt  *time.Time `json:"touchUpRequestedAt,omitempty"`

	// MoodLevel is 1 (awful) to 5 (great), nil when there is none.
	MoodLevel  *int              `json:"moodLevel,omitempty"`
	MoodWords  string            `json:"moodWords"`
	MoodSource JournalMoodSource `json:"moodSource"`

	// Weather is nil until it was fetched, and stays nil for a day with no
	// place or with weather turned off.
	Weather *JournalWeather `json:"weather,omitempty"`

	Facts           JournalFacts `json:"facts"`
	FactsComputedAt *time.Time   `json:"factsComputedAt,omitempty"`

	// Headline is the agent's one line for the day and Narrative its few
	// paragraphs, in which a record is written [[kind:id]]. Both are empty
	// until a dream wrote them.
	Headline           string     `json:"headline"`
	Narrative          string     `json:"narrative"`
	NarrativeWrittenAt *time.Time `json:"narrativeWrittenAt,omitempty"`

	// NarrativeInputDigest is the digest of what the narrative was written
	// from; when what the day would be written from now differs, the day is
	// stale and a dream writes it again.
	NarrativeInputDigest string `json:"narrativeInputDigest"`

	// NarrativeFailure says why the last attempt was refused, empty when it
	// was not.
	NarrativeFailure string `json:"narrativeFailure"`

	// NarrativeCorrections are the person's corrections, given to every later
	// writing as facts to keep.
	NarrativeCorrections []JournalCorrection `json:"narrativeCorrections"`

	// NarrativeRequestedAt is set while the person is waiting for the
	// narrative to be written now (after a correction, or "write it again").
	NarrativeRequestedAt *time.Time `json:"narrativeRequestedAt,omitempty"`

	// IsNarrativeRequested marks a day older than JournalNarrativeDepthDays
	// whose narrative the person asked for; dreams write it like a recent one.
	IsNarrativeRequested bool `json:"isNarrativeRequested"`

	// CoverPhotoID is the photo the agent chose to stand for the day, empty
	// for none.
	CoverPhotoID string `json:"coverPhotoId"`

	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`
}

JournalDay is one day of a person's journal.

type JournalFacts added in v0.202.0

type JournalFacts struct {
	PhotoCount         int      `json:"photoCount"`
	PhotoCandidateIDs  []string `json:"photoCandidateIds,omitempty"`
	PlaceCount         int      `json:"placeCount"`
	VisitedPlaceIDs    []string `json:"visitedPlaceIds,omitempty"`
	WalkedMeters       float64  `json:"walkedMeters"`
	StepCount          int      `json:"stepCount"`
	SleepMinutes       int      `json:"sleepMinutes"`
	WorkoutMinutes     int      `json:"workoutMinutes"`
	CodingSessionCount int      `json:"codingSessionCount"`
	WorkProjectCount   int      `json:"workProjectCount"`
	CodingMinutes      int      `json:"codingMinutes"`
	MeetingCount       int      `json:"meetingCount"`
	MeetingMinutes     int      `json:"meetingMinutes"`
	RecordingCount     int      `json:"recordingCount"`
	ConversationCount  int      `json:"conversationCount"`
	ChatMessageCount   int      `json:"chatMessageCount"`
	MailReceivedCount  int      `json:"mailReceivedCount"`
	MailSentCount      int      `json:"mailSentCount"`
	DocumentCount      int      `json:"documentCount"`
	TransactionCount   int      `json:"transactionCount"`
	SpentMinorUnits    int64    `json:"spentMinorUnits"`
	SpentCurrency      string   `json:"spentCurrency,omitempty"`
	ShoppingTripCount  int      `json:"shoppingTripCount"`
	MemoryPageCount    int      `json:"memoryPageCount"`
	HasActivity        bool     `json:"hasActivity"`
	MainPlaceID        string   `json:"mainPlaceId,omitempty"`
	MainPlaceName      string   `json:"mainPlaceName,omitempty"`
	MainPlaceLatitude  float64  `json:"mainPlaceLatitude,omitempty"`
	MainPlaceLongitude float64  `json:"mainPlaceLongitude,omitempty"`
	HealthMoodLevel    int      `json:"healthMoodLevel,omitempty"`

	// FactsVersion is the way the numbers were worked out
	// (JournalFactsVersion then); a day worked out an older way is worked out
	// again.
	FactsVersion int `json:"factsVersion,omitempty"`
}

JournalFacts are a day's numbers, worked out without a model from the sources the person keeps. They hold counts, sums and ids, never content, and a source the person does not have is left at zero.

type JournalLink struct {
	ID              string `json:"id"`
	UserID          string `json:"userId"`
	JournalDayID    string `json:"journalDayId,omitempty"`
	JournalPeriodID string `json:"journalPeriodId,omitempty"`

	RecordKind AgentRecordKind `json:"recordKind"`
	RecordID   string          `json:"recordId"`

	LinkSource JournalLinkSource `json:"linkSource"`
	LinkReason string            `json:"linkReason"`
	LinkRank   int               `json:"linkRank"`

	// IsHidden is a dream's choice the person took off the page, kept so that
	// the next dream does not choose it again.
	IsHidden bool `json:"isHidden"`

	CreatedAt time.Time `json:"createdAt"`
}

JournalLink is a record a day or a period links to: chosen by a dream with why it mattered, or pinned by the person. Exactly one of JournalDayID and JournalPeriodID is set.

type JournalLinkSource added in v0.202.0

type JournalLinkSource string

JournalLinkSource says who put a record on a day or a period.

const (
	// JournalLinkFromAgent is a record a dream chose as mattering, with why.
	JournalLinkFromAgent JournalLinkSource = "agent"
	// JournalLinkFromPerson is a record the person pinned.
	JournalLinkFromPerson JournalLinkSource = "person"
)

type JournalMoodSource added in v0.202.0

type JournalMoodSource string

JournalMoodSource says where a day's mood came from.

const (
	// JournalMoodFromPerson is a mood the person chose.
	JournalMoodFromPerson JournalMoodSource = "person"
	// JournalMoodFromHealth is Apple Health's State of Mind for the day, shown
	// until the person chooses.
	JournalMoodFromHealth JournalMoodSource = "health"
)

type JournalNarrativeWriting added in v0.202.0

type JournalNarrativeWriting struct {
	Headline    string
	Narrative   string
	InputDigest string

	// CoverPhotoID is a day's chosen photo, empty for none or for a period.
	CoverPhotoID string

	// Chapters are a year's, nil for a day, a week or a month.
	Chapters []JournalChapter

	// Choices are the records chosen as mattering, in order, each with its
	// kind, id and reason; their other fields are ignored.
	Choices []*JournalLink
}

JournalNarrativeWriting is what one writing of a day or a period made.

type JournalPeriod added in v0.202.0

type JournalPeriod struct {
	ID         string            `json:"id"`
	UserID     string            `json:"userId"`
	PeriodKind JournalPeriodKind `json:"periodKind"`

	// PeriodStart is its first day, YYYY-MM-DD.
	PeriodStart string `json:"periodStart"`

	// LookingBack is the person's own text about the period, with the same
	// touching up as a day's words.
	LookingBack           string     `json:"lookingBack"`
	LookingBackModifiedAt *time.Time `json:"lookingBackModifiedAt,omitempty"`
	TouchedUpLookingBack  *string    `json:"touchedUpLookingBack,omitempty"`
	TouchUpHow            string     `json:"touchUpHow"`
	TouchedUpFromDigest   string     `json:"touchedUpFromDigest"`
	TouchUpRequestedAt    *time.Time `json:"touchUpRequestedAt,omitempty"`

	Headline             string              `json:"headline"`
	Narrative            string              `json:"narrative"`
	NarrativeWrittenAt   *time.Time          `json:"narrativeWrittenAt,omitempty"`
	NarrativeInputDigest string              `json:"narrativeInputDigest"`
	NarrativeFailure     string              `json:"narrativeFailure"`
	NarrativeCorrections []JournalCorrection `json:"narrativeCorrections"`
	NarrativeRequestedAt *time.Time          `json:"narrativeRequestedAt,omitempty"`

	// Chapters are a year's stretches that belong together; empty for a week
	// or a month.
	Chapters []JournalChapter `json:"chapters"`

	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`
}

JournalPeriod is a week, a month or a year of a person's journal.

type JournalPeriodKind added in v0.202.0

type JournalPeriodKind string

JournalPeriodKind is the length of a JournalPeriod.

const (
	// JournalPeriodWeek starts on the first day of the person's week.
	JournalPeriodWeek JournalPeriodKind = "week"
	// JournalPeriodMonth starts on the first of the month.
	JournalPeriodMonth JournalPeriodKind = "month"
	// JournalPeriodYear starts on January 1.
	JournalPeriodYear JournalPeriodKind = "year"
)

func (JournalPeriodKind) IsValid added in v0.202.0

func (self JournalPeriodKind) IsValid() bool

IsValid says whether the kind is one of the three.

type JournalSearchHit added in v0.202.0

type JournalSearchHit struct {
	Target   JournalTarget `json:"target"`
	Headline string        `json:"headline"`
	Snippet  string        `json:"snippet"`
}

JournalSearchHit is a day or a period whose text matched a search.

type JournalSettings added in v0.202.0

type JournalSettings struct {
	// IsWeatherOn fetches each day's weather; the coordinates of the day's
	// main place, rounded to about 11 km, go to the weather service.
	IsWeatherOn bool `json:"isWeatherOn"`

	// IsEveningQuestionOn asks "How was today?" each evening at
	// EveningQuestionTime, a local time written HH:MM.
	IsEveningQuestionOn bool   `json:"isEveningQuestionOn"`
	EveningQuestionTime string `json:"eveningQuestionTime"`
}

JournalSettings is what a person decided about their journal.

type JournalTarget added in v0.202.0

type JournalTarget struct {
	Day         string            `json:"day,omitempty"`
	PeriodKind  JournalPeriodKind `json:"periodKind,omitempty"`
	PeriodStart string            `json:"periodStart,omitempty"`
}

JournalTarget names a day (PeriodKind empty, Day set) or a period (PeriodKind and PeriodStart set).

func (JournalTarget) IsPeriod added in v0.202.0

func (self JournalTarget) IsPeriod() bool

IsPeriod says the target is a period.

type JournalWeather added in v0.202.0

type JournalWeather struct {
	// WeatherCode is the WMO weather interpretation code the weather service
	// answers (0 clear, 1 to 3 partly cloudy to overcast, 45 and 48 fog, 51
	// to 67 drizzle and rain, 71 to 77 snow, 80 to 82 showers, 95 to 99
	// thunderstorms).
	WeatherCode int `json:"weatherCode"`

	HighCelsius     float64 `json:"highCelsius"`
	LowCelsius      float64 `json:"lowCelsius"`
	PrecipitationMM float64 `json:"precipitationMM"`

	// PlaceName is the place the weather is for, as the person named it.
	PlaceName string `json:"placeName"`

	FetchedAt time.Time `json:"fetchedAt"`
}

JournalWeather is a day's weather where the person spent most of it.

type Layout

type Layout struct {
	// ID of the Layout
	ID string `json:"id,omitempty"`

	// Timestamp when the Layout was created
	CreatedAt time.Time `json:"createdAt,omitempty"`

	// Timestamp when the Layout was last modified
	ModifiedAt time.Time `json:"modifiedAt,omitempty"`

	// Domain that the Layout belongs to
	DomainID string  `json:"domainId,omitempty"`
	Domain   *Domain `json:"-"`

	// Comment about this Layout
	Comment string `json:"comment,omitempty"`

	// Locale of the default HTMLContent and TextContent, such as "en" or "zh-CN"; optional
	Locale string `json:"locale,omitempty"`

	// HTML content
	HTMLContent string `json:"htmlContent,omitempty"`

	// Text content
	TextContent string `json:"textContent,omitempty"`

	// Translations of the content into other locales
	Translations []*LayoutTranslation `json:"translations,omitempty"`
}

Layout is a base layout for Template.

type LayoutTranslation

type LayoutTranslation struct {
	// Locale this translation is in, such as "zh-CN"
	Locale string `json:"locale"`

	// HTML content
	HTMLContent string `json:"htmlContent,omitempty"`

	// Text content
	TextContent string `json:"textContent,omitempty"`
}

LayoutTranslation is a Layout's content in one locale.

type LocationNotificationMute added in v0.198.0

type LocationNotificationMute struct {
	UserID      string     `json:"userId"`
	MutedUserID string     `json:"mutedUserId"`
	MutedUntil  *time.Time `json:"mutedUntil,omitempty"`

	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

LocationNotificationMute is a person's mute of the notices that somebody sharing their location with them arrived at or left a place. UserID is the person who muted, MutedUserID the person they no longer hear about. It is in effect at an instant when MutedUntil is nil, a mute that lasts until the person unmutes, or after the instant.

func (*LocationNotificationMute) IsInEffectAt added in v0.198.0

func (self *LocationNotificationMute) IsInEffectAt(instant time.Time) bool

IsInEffectAt reports whether the mute covers the instant.

type LocationPause added in v0.195.0

type LocationPause struct {
	ID     string `json:"id"`
	UserID string `json:"userId"`

	StartedAt time.Time  `json:"startedAt"`
	EndedAt   *time.Time `json:"endedAt,omitempty"`

	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

LocationPause is a time during which a person's location is not recorded. It is in effect at an instant when StartedAt is at or before it and EndedAt is nil or after it; EndedAt is nil for a pause that lasts until the person resumes. Resuming sets it to that moment.

func (*LocationPause) IsInEffectAt added in v0.195.0

func (self *LocationPause) IsInEffectAt(instant time.Time) bool

IsInEffectAt reports whether the pause covers the instant.

type LocationPermission added in v0.226.0

type LocationPermission struct {
	UserID          string                  `json:"userId"`
	PhonePermission LocationPhonePermission `json:"phonePermission"`
	IsRecordingOn   bool                    `json:"isRecordingOn"`
	ReportedAt      time.Time               `json:"reportedAt"`
}

LocationPermission is what a person's app last said about their phone: its permission, and whether the app's own switch for recording is on.

type LocationPhonePermission added in v0.226.0

type LocationPhonePermission string

LocationPhonePermission is what a person's phone lets TeaNode record of where they are.

const (
	// LocationPhonePermissionAlways records visits in the background.
	LocationPhonePermissionAlways LocationPhonePermission = "always"
	// LocationPhonePermissionWhileUsing records only where they are while
	// the app is open, so no visits.
	LocationPhonePermissionWhileUsing LocationPhonePermission = "while_using"
	// LocationPhonePermissionOff records nothing: Location is off for the
	// app, or the person has not answered the phone's question yet.
	LocationPhonePermissionOff LocationPhonePermission = "off"
)

func (LocationPhonePermission) IsKnown added in v0.226.0

func (self LocationPhonePermission) IsKnown() bool

IsKnown reports whether the permission is one of the three.

type LocationPoint added in v0.175.0

type LocationPoint struct {
	ID     string `json:"id"`
	UserID string `json:"userId"`

	LatitudeDegrees  float64 `json:"latitudeDegrees"`
	LongitudeDegrees float64 `json:"longitudeDegrees"`
	AccuracyMeters   float64 `json:"accuracyMeters"`

	AltitudeMeters       *float64 `json:"altitudeMeters,omitempty"`
	SpeedMetersPerSecond *float64 `json:"speedMetersPerSecond,omitempty"`
	CourseDegrees        *float64 `json:"courseDegrees,omitempty"`

	// MeasuredAt is when the device took the position and ReceivedAt when the
	// server got it; a phone that was offline reports late.
	MeasuredAt time.Time `json:"measuredAt"`
	ReceivedAt time.Time `json:"receivedAt"`

	LocationSource LocationSource `json:"locationSource"`

	// AgentPhoneID is the install that reported it, empty for a browser or
	// once that phone was removed.
	AgentPhoneID string `json:"agentPhoneId,omitempty"`
}

LocationPoint is one position a phone or browser reported. The optional measurements are nil when the device did not give them.

type LocationShare added in v0.175.0

type LocationShare struct {
	ID string `json:"id"`

	// UserID is the person whose location it is.
	UserID string `json:"userId"`

	GranteeUserID   string `json:"granteeUserId,omitempty"`
	GranteeCircleID string `json:"granteeCircleId,omitempty"`

	ShareLevel LocationShareLevel `json:"shareLevel"`

	CreatedAt time.Time `json:"createdAt"`

	// CreatedByUserID is empty once that account is gone.
	CreatedByUserID string `json:"createdByUserId,omitempty"`

	// GranteeUsername, GranteeName and GranteeCircleName are filled in by the
	// listing, for a screen that says who a location is shared with.
	GranteeUsername   string `json:"granteeUsername,omitempty"`
	GranteeName       string `json:"granteeName,omitempty"`
	GranteeCircleName string `json:"granteeCircleName,omitempty"`
}

LocationShare gives one person, or every member of one circle, a level of access to the sharer's location. Exactly one of GranteeUserID and GranteeCircleID is set.

type LocationShareLevel added in v0.175.0

type LocationShareLevel string

LocationShareLevel is how much of a person's location somebody may see. A person shares their location with a circle or with one person in a circle they share, at one of these two.

const (
	// LocationShareLevelCurrent is where the person is now, and the place.
	LocationShareLevelCurrent LocationShareLevel = "current"
	// LocationShareLevelHistory adds the person's visits.
	LocationShareLevelHistory LocationShareLevel = "history"
	// LocationShareLevelOwner is a person looking at their own location. It
	// is not a level anybody can be given: it lets "how much of this
	// person's location may this person see" have one answer for the owner
	// too.
	LocationShareLevelOwner LocationShareLevel = "owner"
)

The levels, from least to most.

func LessLocationShareLevel added in v0.226.0

func LessLocationShareLevel(first, second LocationShareLevel) LocationShareLevel

LessLocationShareLevel is the lower of two levels, the empty level when either is empty.

func (LocationShareLevel) AtLeast added in v0.175.0

func (self LocationShareLevel) AtLeast(other LocationShareLevel) bool

AtLeast reports whether this level reaches the other.

func (LocationShareLevel) IsGrantable added in v0.175.0

func (self LocationShareLevel) IsGrantable() bool

IsGrantable reports whether a share may be made at this level.

func (LocationShareLevel) Rank added in v0.175.0

func (self LocationShareLevel) Rank() int

Rank orders the levels; zero is no access at all.

type LocationSharingLimit added in v0.226.0

type LocationSharingLimit struct {
	ShareLevelLimit    LocationShareLevel
	SharingLimitReason LocationSharingLimitReason
}

LocationSharingLimit is the most of a person's location their phone and their pause let anybody see, whatever their shares say, and why. Nobody sees more of another person's location than they share with them, so it is also the most they see of anybody else's.

func LocationSharingLimitOf added in v0.226.0

func LocationSharingLimitOf(permission *LocationPermission, pause *LocationPause) LocationSharingLimit

LocationSharingLimitOf is the limit for a person with this permission (nil for an app that never reported one, which is judged by its shares alone) and this pause in effect (nil for none).

type LocationSharingLimitReason added in v0.226.0

type LocationSharingLimitReason string

LocationSharingLimitReason is why a person's own location shares less than their shares say, and so why they see less of other people's.

const (
	// LocationSharingLimitReasonNone is no limit: the shares say it all.
	LocationSharingLimitReasonNone LocationSharingLimitReason = ""
	// LocationSharingLimitReasonPaused is a pause in effect.
	LocationSharingLimitReasonPaused LocationSharingLimitReason = "paused"
	// LocationSharingLimitReasonRecordingOff is the app's switch for
	// recording turned off.
	LocationSharingLimitReasonRecordingOff LocationSharingLimitReason = "recording_off"
	// LocationSharingLimitReasonPhoneLocationOff is Location off for the app
	// on the phone.
	LocationSharingLimitReasonPhoneLocationOff LocationSharingLimitReason = "phone_location_off"
	// LocationSharingLimitReasonPhoneWhileUsing is Location set to While
	// Using on the phone, which records no visits.
	LocationSharingLimitReasonPhoneWhileUsing LocationSharingLimitReason = "phone_while_using"
)

func (LocationSharingLimitReason) Words added in v0.226.0

func (self LocationSharingLimitReason) Words() string

Words returns what the limit means for what the person sees, and what to change, in a sentence; empty for no limit. The command line and the agent say it as the app's banner does.

type LocationSource added in v0.175.0

type LocationSource string

LocationSource is what reported a position: the iPhone app, or a browser answering the agent's location tool.

const (
	LocationSourcePhone   LocationSource = "phone"
	LocationSourceBrowser LocationSource = "browser"
)

The sources of a position.

func (LocationSource) IsValid added in v0.175.0

func (self LocationSource) IsValid() bool

IsValid reports whether this is one of the sources.

type MXResult

type MXResult struct {
	// Sender domain or from domain
	Domain string `json:"domain,omitempty"`

	// Discovered mail servers
	MailServers []string `json:"mailServers,omitempty"`
}

MXResult holds authentication results related to mail servers.

type Mail

type Mail struct {
	// ID of the Mail
	ID string `json:"id,omitempty"`

	// Timestamp when the Mail was created
	CreatedAt time.Time `json:"createdAt,omitempty"`

	// Timestamp when the Mail was last modified
	ModifiedAt time.Time `json:"modifiedAt,omitempty"`

	// Domain that the Mail belongs to. The identifier is stored; the pointer
	// is resolved from the configuration when the Mail is loaded, and is nil
	// when the domain has since been removed from the configuration.
	DomainID string  `json:"domainId,omitempty"`
	Domain   *Domain `json:"-"`

	// Credential that was used to send this Mail, if any. Resolved from the
	// configuration in the same way, and nil once it is deleted.
	CredentialID string      `json:"credentialId,omitempty"`
	Credential   *Credential `json:"-"`

	// For DSN mail, the Delivery that caused the bounce, if any
	DeliveryID string    `json:"deliveryId,omitempty"`
	Delivery   *Delivery `json:"-"`

	// For debugging, the envelope ID when the Mail was received
	EnvelopeID string `json:"envelopeId,omitempty"`

	// Hello string when the Mail was received
	Hello string `json:"hello,omitempty"`

	// IP address from where the Mail was received
	IP string `json:"ip,omitempty"`

	// Reverse DNS name of the IP address
	RDNS string `json:"rdns,omitempty"`

	// TLS version used when receiving the Mail
	TLSVersion string `json:"tlsVersion,omitempty"`

	// TLS cipher suite used when receiving the Mail
	TLSCipherSuite string `json:"tlsCipherSuite,omitempty"`

	// Location of the Mail sender
	Location *geoip.Location `json:"location,omitempty"`

	// Sender address, also known as return path or bounce address
	Sender string `json:"sender,omitempty"`

	// Recipient addresses
	Recipients []string `json:"recipients,omitempty"`

	// Message ID from the header of the Mail
	MessageID string `json:"messageId,omitempty"`

	// From field from the header of the Mail
	From string `json:"from,omitempty"`

	// Subject line from the header of the Mail
	Subject string `json:"subject,omitempty"`

	// Raw data, not saved in database
	Headers []string `json:"-"`
	Body    []byte   `json:"-"`

	// ThreadID is the conversation this message is part of, derived from
	// In-Reply-To and References: the root message's own id when it starts
	// one. What "show me the thread" reads.
	ThreadID string `json:"threadId,omitempty"`

	// UnreferencedAt is when the last mailbox item holding this message went
	// away — or its arrival, for a message no mailbox took. Nil while any
	// item references it. Retention prunes what has been unreferenced for
	// longer than the retention period, nothing else.
	UnreferencedAt *time.Time `json:"unreferencedAt,omitempty"`

	// AttachmentCount is how many attachments the message carries, counted
	// when it was indexed; nil for a message indexed before that was kept.
	AttachmentCount *int `json:"attachmentCount,omitempty"`

	// FromName is the display name beside the From address, when the header
	// carried one.
	FromName string `json:"fromName,omitempty"`

	// What the message said about the mailing list it came from, read out of
	// its headers when it was stored: the headers themselves live in object
	// storage, and a page listing subscriptions cannot open every message to
	// build itself. ListKey identifies the subscription — the list's own
	// identifier when it publishes one, the sending address otherwise — and
	// is empty for ordinary mail. ListChecked says the headers have been read,
	// whatever they turned out to say.
	ListKey         string `json:"listKey,omitempty"`
	ListName        string `json:"listName,omitempty"`
	ListUnsubscribe string `json:"listUnsubscribe,omitempty"`
	ListOneClick    bool   `json:"listOneClick,omitempty"`
	ListStripped    bool   `json:"listStripped,omitempty"`
	ListChecked     bool   `json:"listChecked,omitempty"`

	// LogoDomain is the sending domain whose published logo this server
	// holds, resolved when the message is read and empty unless there is one
	// to show. Set only for a message that passed DMARC: a mark is a claim
	// about who sent something, and one on unproven mail helps whoever is
	// pretending to be them.
	LogoDomain string `json:"logoDomain,omitempty" gorm:"-"`

	// NoteIdentifier is the X-Universally-Unique-Identifier of a note, which
	// every version of the note carries: what says two messages are the same
	// note written twice. Empty for anything that is not a note.
	NoteIdentifier string `json:"noteIdentifier,omitempty"`

	// Size of the received Mail
	Size uint64 `json:"size,omitempty"`

	// Status of the Mail, one of: received, accepted, rejected
	Status MailStatus `json:"status,omitempty"`

	// Authentication result of the Mail
	AuthenticationResults AuthenticationResults `json:"authenticationResults,omitempty"`

	// Timestamp when the Mail was received
	ReceivedAt time.Time `json:"receivedAt,omitempty"`

	// Kind of Mail, one of: incoming, outgoing, exchange, dsn, rua, ruf, draft, note
	Kind MailKind `json:"kind,omitempty"`

	// One or more Delivery created from this Mail
	Deliveries []*Delivery `json:"deliveries,omitempty"`
}

Mail is an inbound mail that is being processed; one or more Delivery will be created for it.

func (*Mail) DMARCPassed

func (self *Mail) DMARCPassed() bool

DMARCPassed says the message proved it came from the domain it claims. The condition on showing that domain's mark: a claim about who sent something, made on unproven mail, helps whoever is pretending to be them.

func (*Mail) LooksLikeSpam

func (self *Mail) LooksLikeSpam() bool

LooksLikeSpam is whether this message is one the server's own checks distrusted: the spam filter failed it, or it failed DMARC under a policy asking for it to be held.

Here rather than beside either caller because two of them ask the same question -- whether to answer a message automatically, and whether to write what it carries into a calendar -- and two answers that drifted apart would mean a message too suspicious to reply to was trusted to make appointments.

func (*Mail) SenderDomain

func (self *Mail) SenderDomain() string

SenderDomain is the domain of the From address, lowercased, or empty when there is not one. What a published logo is looked up by.

func (*Mail) SubmittedHere

func (self *Mail) SubmittedHere() bool

SubmittedHere says the message came from somebody who signed in to this server, rather than from a stranger on port 25.

It answers the same question DMARC answers, and answers it better: this server took the message from a session it authenticated and checked the address it was allowed to send as, which is the thing DMARC exists to prove about a message from somewhere else.

It is needed because a message between two mailboxes here never leaves: the submission is delivered into the recipient's mailbox in the same transaction, so nothing ever evaluated SPF, DKIM or DMARC over it, and anything asking only "did DMARC pass" treated a colleague's invitation as proving nothing. A person asked to a meeting by the person at the next desk still wants their meeting.

type MailInsight

type MailInsight struct {
	MailID    string `json:"mailId"`
	MailboxID string `json:"mailboxId"`
	AgentID   string `json:"agentId"`

	Category   string `json:"category"`
	Priority   string `json:"priority"` // high | normal | low
	NeedsReply bool   `json:"needsReply"`

	// ResearchAsked says triage thought a lookup would help; the research
	// run, when it exists, writes Notes.
	ResearchAsked bool `json:"researchAsked"`

	Summary     string   `json:"summary"`
	ActionItems []string `json:"actionItems"`

	// Notes are what research found, shown above the message and read by
	// the reply run. NotesRunID is the run that wrote them.
	Notes      string `json:"notes,omitempty"`
	NotesRunID string `json:"notesRunId,omitempty"`

	// ExtractAsked says triage thought the message carries an appointment or
	// somebody's details in its words; the extract run, when it exists,
	// writes Proposals.
	ExtractAsked bool `json:"extractAsked"`

	// Proposals are what was found in the words and is offered in the
	// reader. Nothing here has been written anywhere.
	Proposals []MailProposal `json:"proposals"`

	// AlertSignal is whether the sorting thought the person should hear
	// about this message without opening their mail: AlertSignalNone,
	// AlertSignalSoon or AlertSignalNow. AlertReason is its line on why.
	AlertSignal string `json:"alertSignal"`
	AlertReason string `json:"alertReason,omitempty"`

	Model     string    `json:"model"`
	RunID     string    `json:"runId"`
	CreatedAt time.Time `json:"createdAt"`
}

MailInsight is what the agent worked out about one message for one mailbox: its category and priority, whether it needs an answer, a line of summary, the things it asks for. Rules read it in their second phase and the list shows it as chips. Two people who received the same message each have their own, because their agents were told different things.

type MailKind

type MailKind string
const (
	MailKindUnknown  MailKind = ""
	MailKindIncoming MailKind = "incoming"
	MailKindOutgoing MailKind = "outgoing"
	MailKindExchange MailKind = "exchange"
	MailKindDSN      MailKind = "dsn"
	MailKindRUA      MailKind = "rua"
	MailKindRUF      MailKind = "ruf"
	MailKindDraft    MailKind = "draft"

	// MailKindNote is a note from a phone's Notes app, which keeps its notes
	// as messages in a folder of the mail account. Not mail: nothing that
	// sorts, summarizes or searches mail should treat it as such.
	MailKindNote MailKind = "note"
)

func GetMailKind

func GetMailKind(value string) MailKind

func (MailKind) String

func (self MailKind) String() string

type MailProposal

type MailProposal struct {
	// Kind is "event" or "contact".
	Kind string `json:"kind"`

	// Because is the line of the message it was read out of, quoted, so the
	// person can see what the agent thought it saw.
	Because string `json:"because,omitempty"`

	// Status is "" while it is still an offer, then "accepted" or
	// "dismissed". A dismissed proposal is not offered again.
	Status string `json:"status,omitempty"`

	// An event: what it is, when, and where.
	Summary  string `json:"summary,omitempty"`
	Starts   string `json:"starts,omitempty"`
	Ends     string `json:"ends,omitempty"`
	Location string `json:"location,omitempty"`
	AllDay   bool   `json:"allDay,omitempty"`

	// A person: what the signature said. ContactID names the contact this
	// would change rather than add, when the address book already holds
	// somebody with one of these addresses.
	Name         string   `json:"name,omitempty"`
	Organization string   `json:"organization,omitempty"`
	Title        string   `json:"title,omitempty"`
	Emails       []string `json:"emails,omitempty"`
	Phones       []string `json:"phones,omitempty"`
	Note         string   `json:"note,omitempty"`
	ContactID    string   `json:"contactId,omitempty"`
}

MailProposal is something a message carries that belongs somewhere else: an appointment in its words, or a person's details in a signature.

It is an offer and never a write. Putting an appointment in somebody's diary because a stranger's message mentioned a day is how a calendar stops being trusted, so this is what the reader draws a card from and nothing happens until the person presses something.

type MailServer

type MailServer struct {
	Host     string `json:"host"`
	Port     uint16 `json:"port"`
	Username string `json:"username,omitempty"`
	Password string `json:"-"`
}

MailServer is where an alias of kind mailServer relays to.

type MailStatus

type MailStatus string
const (
	MailStatusUnknown  MailStatus = ""
	MailStatusReceived MailStatus = "received"
	MailStatusAccepted MailStatus = "accepted"
	MailStatusRejected MailStatus = "rejected"
)

func GetMailStatus

func GetMailStatus(value string) MailStatus

func (MailStatus) String

func (self MailStatus) String() string

type Mailbox

type Mailbox struct {
	ID         string    `json:"id"`
	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`
	UserID     string    `json:"userId"`
	Name       string    `json:"name"`

	// The signature the compose page appends when sending from this
	// mailbox; a user with two mailboxes signs differently from each.
	SignatureHTML string `json:"signatureHtml,omitempty"`
	SignatureText string `json:"signatureText,omitempty"`

	// Rules run in order when a message reaches the Inbox.
	Rules []MailboxRule `json:"rules"`

	// AutoReply is the out-of-office setting; nil when never set.
	AutoReply *MailboxAutoReply `json:"autoReply,omitempty"`

	// Agent is this mailbox as a source of the owner's agent, with the
	// processing policy for it; nil when never granted.
	Agent *AgentMailbox `json:"agent,omitempty"`

	// Addresses are the aliases of kind mailbox that deliver here, resolved
	// when read: what "send as" is checked against.
	Addresses []*MailboxAddress `json:"addresses,omitempty"`
}

Mailbox is a container of folders belonging to one user. A person gets one when their account is made and may have more. Its small per-mailbox settings — rules, signature, out-of-office — are columns on it.

func (*Mailbox) Validate

func (self *Mailbox) Validate() error

Validate reports everything wrong with the mailbox.

type MailboxAddress

type MailboxAddress struct {
	AliasID   string `json:"aliasId"`
	DomainID  string `json:"domainId"`
	Domain    string `json:"domain"`
	LocalPart string `json:"localPart"`
	Address   string `json:"address"`
}

MailboxAddress is an address that delivers into a mailbox, and that the mailbox's owner may send as: an alias of kind mailbox, read with the mailbox.

type MailboxAppPassword

type MailboxAppPassword struct {
	ID        string    `json:"id"`
	CreatedAt time.Time `json:"createdAt"`
	MailboxID string    `json:"mailboxId"`
	Name      string    `json:"name"`

	// Selector is the tag the password itself carries, which says which of a
	// mailbox's passwords is being offered. Not a secret -- it names the row
	// rather than opening it -- and empty for one made before this was
	// written down.
	//
	// It exists because the username is the mailbox's address: twenty
	// devices are twenty passwords behind one name, and without a tag a
	// sign-in had to try every one of them.
	Selector     string     `json:"selector,omitempty"`
	PasswordHash string     `json:"-"`
	LastUsedAt   *time.Time `json:"lastUsedAt,omitempty"`
}

MailboxAppPassword is what a mail program signs in with. It belongs to a mailbox, not a user: a program's "account" is one mailbox, so the login name is one of the mailbox's addresses and the app password is what says which mailbox that is. One per device, revocable alone; the hash never leaves the server.

func (*MailboxAppPassword) RedactForAudit

func (self *MailboxAppPassword) RedactForAudit() any

RedactForAudit is the app password as an audit row records it: without the hash.

type MailboxAutoReply

type MailboxAutoReply struct {
	Enabled bool       `json:"enabled"`
	From    *time.Time `json:"from,omitempty"`              // in force from; nil is now
	Until   *time.Time `json:"until,omitempty"`             // in force until; nil is until turned off
	Subject string     `json:"subject" graphapi:"nullable"` // "" means "Auto: " + the original subject
	Text    string     `json:"text" graphapi:"nullable"`
	HTML    string     `json:"html,omitempty" graphapi:"nullable"`

	// SameDomainOnly answers only senders at one of the mailbox's own
	// domains. An away message is written for the people who work with you;
	// sent to everybody, it tells whoever writes in that the person is gone
	// until the 30th, which is more than most strangers need to know.
	SameDomainOnly bool `json:"sameDomainOnly,omitempty"`
}

MailboxAutoReply is the out-of-office setting: what to send, and when it is in force. Whether to send it to a given message is decided by the protections in the out-of-office path, not by anything here.

type MailboxFolder

type MailboxFolder struct {
	ID         string            `json:"id"`
	CreatedAt  time.Time         `json:"createdAt"`
	ModifiedAt time.Time         `json:"modifiedAt"`
	MailboxID  string            `json:"mailboxId"`
	ParentID   string            `json:"parentId,omitempty"`
	Name       string            `json:"name"`
	Kind       MailboxFolderKind `json:"kind,omitempty"`

	// PinnedAt is when the owner pinned the folder to the top of the rail,
	// beside the Inbox and Starred; nil for a folder that sits in the tree
	// only. The pins are shown in the order they were made.
	PinnedAt *time.Time `json:"pinnedAt,omitempty"`

	// IMAP's contract: UIDs in a folder only grow, and a folder that is
	// recreated announces itself with a new validity.
	UIDValidity uint64 `json:"uidValidity"`
	UIDNext     uint64 `json:"uidNext"`

	// ModSeq grows on every change to the folder's items; what IDLE watches
	// and what CONDSTORE compares.
	ModSeq uint64 `json:"modseq"`

	// Counted when the tree is listed, never stored.
	Unread int64 `json:"unread"`
	Total  int64 `json:"total"`

	// NoteCount is how many of the items are a phone's notes, counted only
	// for the dashboard, which shows a folder holding nothing else as notes.
	NoteCount int64 `json:"noteCount"`
}

MailboxFolder is a named place in a mailbox, nested as deep as its owner likes. Each folder is an IMAP mailbox; each item in it a message with a UID that never changes while it stays there.

func (*MailboxFolder) Validate

func (self *MailboxFolder) Validate() error

Validate reports everything wrong with the folder.

type MailboxFolderExpunge

type MailboxFolderExpunge struct {
	FolderID   string    `json:"folderId"`
	UID        uint64    `json:"uid"`
	ModSeq     uint64    `json:"modseq"`
	ExpungedAt time.Time `json:"expungedAt"`
}

MailboxFolderExpunge records a UID that left a folder and the modseq it left at, so a client can be told what vanished since its last sync.

type MailboxFolderKind

type MailboxFolderKind string

MailboxFolderKind marks the folders every mailbox has. Custom folders are the empty kind.

const (
	MailboxFolderKindCustom  MailboxFolderKind = ""
	MailboxFolderKindInbox   MailboxFolderKind = "inbox"
	MailboxFolderKindSent    MailboxFolderKind = "sent"
	MailboxFolderKindDrafts  MailboxFolderKind = "drafts"
	MailboxFolderKindArchive MailboxFolderKind = "archive"
	MailboxFolderKindJunk    MailboxFolderKind = "junk"
	MailboxFolderKindTrash   MailboxFolderKind = "trash"
)

type MailboxItem

type MailboxItem struct {
	ID       string `json:"id"`
	FolderID string `json:"folderId"`
	MailID   string `json:"mailId"`
	Mail     *Mail  `json:"mail,omitempty"` // resolved when listed

	// Insight is what the owner's agent worked out about the message, when
	// it has; resolved when listed for a mailbox.
	Insight   *MailInsight `json:"insight,omitempty"`
	UID       uint64       `json:"uid"`
	ModSeq    uint64       `json:"modseq"`
	Seen      bool         `json:"seen"`
	Flagged   bool         `json:"flagged"`
	Answered  bool         `json:"answered"`
	Forwarded bool         `json:"forwarded"`
	Draft     bool         `json:"draft"`
	Deleted   bool         `json:"deleted"` // IMAP's \Deleted, awaiting EXPUNGE
	AddedAt   time.Time    `json:"addedAt"`

	// ImagesAt is when the reader chose to load this message's remote
	// pictures. Set once and kept, so the choice is not asked for again every
	// time the message is opened.
	ImagesAt *time.Time `json:"imagesAt,omitempty"`

	// SubscriptionID is the list this arrived from, when it arrived from one.
	// Written at delivery, so asking what a list has sent is an index lookup
	// rather than a join through the message to group by its list key.
	SubscriptionID string `json:"subscriptionId,omitempty"`
}

MailboxItem is one message in one folder: the possession of it, with its flags. The message is the existing Mail; this only refers to it.

type MailboxItemFlags

type MailboxItemFlags struct {
	Seen      *bool
	Flagged   *bool
	Answered  *bool
	Forwarded *bool
	Draft     *bool
	Deleted   *bool
}

MailboxItemFlags is what STORE and the web UI change on an item. Nil leaves a flag alone.

type MailboxRule

type MailboxRule struct {
	Name       string                 `json:"name"`
	Enabled    bool                   `json:"enabled"`
	Conditions []MailboxRuleCondition `json:"conditions"` // all must match
	Actions    []MailboxRuleAction    `json:"actions"`    // in order
	Stop       bool                   `json:"stop"`       // no later rule runs after this one matches
}

MailboxRule is one entry of Mailbox.Rules, run in array order when a message reaches the Inbox. No id and no row of its own: rules are saved as a whole.

func DefaultRules

func DefaultRules(junkFolderID string) []MailboxRule

DefaultRules are what a new mailbox starts with, given the folder its Junk is kept in.

One rule, and it does nothing until an agent is sorting this mailbox's mail: the category it asks about is only ever set by one. That is what makes it safe to ship switched on -- a mailbox with no agent behaves exactly as it did -- and it means the person who turns an agent on gets the filing they would have asked for on their first bad morning rather than after it.

A rule rather than something built into delivery, for the reason every other kind of filing here is a rule: it is in the list, it says what it does, and it can be changed or switched off by whoever owns the mailbox.

func (*MailboxRule) NeedsInsight

func (self *MailboxRule) NeedsInsight() bool

NeedsInsight says whether a rule has a condition only the agent's insight can answer, which is why such a rule runs in the second phase.

func (*MailboxRule) Validate

func (self *MailboxRule) Validate() error

Validate reports everything wrong with the rule.

func (*MailboxRule) ValidatePatterns added in v0.249.0

func (self *MailboxRule) ValidatePatterns() error

ValidatePatterns reports a pattern of the rule that can never match: one over addresses that needs a backslash, which no address contains (it was probably escaped twice, and the rule would let every message through without a word).

type MailboxRuleAction

type MailboxRuleAction struct {
	Kind     string `json:"kind"` // move, markRead, flag, forward, delete
	FolderID string `json:"folderId,omitempty" graphapi:"nullable"`
	Address  string `json:"address,omitempty" graphapi:"nullable"`
}

MailboxRuleAction is one thing to do: move somewhere, mark, forward, delete.

type MailboxRuleCondition

type MailboxRuleCondition struct {
	Field    string `json:"field"` // from, to, subject, header, score, sender-known, any
	Header   string `json:"header,omitempty" graphapi:"nullable"`
	Operator string `json:"operator"` // contains, equals, matches, above, below
	Value    string `json:"value,omitempty" graphapi:"nullable"`
}

MailboxRuleCondition is one test: a field, how to compare, and against what.

func (*MailboxRuleCondition) NeedsInsight

func (self *MailboxRuleCondition) NeedsInsight() bool

NeedsInsight says whether a condition reads the agent's insight.

type MailboxSubscription

type MailboxSubscription struct {
	// ID is the row's own, made when the first message from this list is
	// delivered. It is what a link to a list names: the key is an identifier
	// the sender chose, often an address, and putting one of those in a URL
	// spells it out for anybody who sees the address bar.
	ID string `json:"id"`

	// Key identifies the list: the identifier the list publishes for itself,
	// or the address it sends from when it publishes none.
	Key string `json:"key"`

	// Name is what to call it, and From the address the newest message came
	// from, which is not always what the name says.
	Name string `json:"name"`
	From string `json:"from"`

	// Count is how much of it this mailbox holds, Unread how much of that has
	// not been read.
	Count  int `json:"count"`
	Unread int `json:"unread"`

	// LastAt is when the newest arrived and LastItemID which message it is,
	// so the row opens on something.
	LastAt     time.Time `json:"lastAt"`
	LastItemID string    `json:"lastItemId"`

	// LogoDomain is the sending domain whose published logo this server holds,
	// empty unless there is one to show. Set only when the newest message
	// proved it came from that domain: a mark shown for mail that failed its
	// checks is an aid to whoever is pretending to be the sender.
	LogoDomain string `json:"logoDomain,omitempty"`

	// OneClick is the newest message promising that one request is enough to
	// leave, and Unsubscribe the addresses it offered to leave by.
	OneClick    bool     `json:"oneClick"`
	Unsubscribe []string `json:"unsubscribe"`

	// Stripped says the sender did offer a way out and something between them
	// and here removed it — a relay that hides the reader's address. Worth
	// saying, because "no way to leave" otherwise reads as the sender's doing.
	Stripped bool `json:"stripped,omitempty"`

	// MutedAt is when the reader asked for this list to stop arriving in the
	// Inbox. It keeps coming and goes straight to the Archive.
	MutedAt *time.Time `json:"mutedAt,omitempty"`

	// ImagesAt is when the reader said this list's pictures may be loaded
	// without asking. The cost is the same as loading them once, repeated:
	// the sender learns each message was opened.
	ImagesAt *time.Time `json:"imagesAt,omitempty"`

	// What this person has already asked for. RequestedAt is when they asked
	// to leave, nil while they have not; Method is how it was asked —
	// oneClick, mail, or link for a page they were handed; Failed and Error
	// say what went wrong when something did.
	RequestedAt *time.Time `json:"requestedAt,omitempty"`
	Method      string     `json:"method,omitempty"`
	Failed      bool       `json:"failed,omitempty"`
	Error       string     `json:"error,omitempty"`
}

MailboxSubscription is one mailing list a mailbox receives: what it is, how much of it there is, and whether leaving it has been asked for.

It is not a stored thing but a grouping of stored things — every message that named the same list — so it exists for as long as there is mail from it. What is stored is the request to leave, which outlives the mail.

type MailboxThread

type MailboxThread struct {
	// ThreadID is the id of the message that began the conversation.
	ThreadID string `json:"threadId"`

	// Item is the newest message of the conversation in this folder, which is
	// what the row shows. Its Mail is resolved the way a listed item's is.
	Item *MailboxItem `json:"item"`

	// Count is how many of the conversation's messages are in this folder,
	// and Unread how many of those have not been read.
	Count  int `json:"count"`
	Unread int `json:"unread"`

	// Flagged is whether any of them is starred, so that a conversation
	// carries the star of any message in it.
	Flagged bool `json:"flagged"`

	// Participants are the people who have written, oldest first, by the name
	// they wrote under or their address when they gave none.
	Participants []string `json:"participants"`

	// ItemIDs is every message of the conversation in this folder, so that
	// starring, moving or deleting the row acts on the conversation rather
	// than on the one message the row happens to show.
	ItemIDs []string `json:"itemIds"`

	// HasDraft says the conversation has an unsent message in it, anywhere in
	// the mailbox — a reply begun and left. The draft is in the Drafts
	// folder while the conversation is being read from the Inbox, so this is
	// asked of the whole mailbox rather than of the folder listed.
	HasDraft bool `json:"hasDraft"`
}

MailboxThread is a conversation as a folder's list shows one: the newest of its messages that are in that folder, how many of them there are, how many are unread, and who has taken part.

A conversation is not a stored thing. It is every message sharing a ThreadID, which the server derives from the In-Reply-To and References headers when the message is stored. So a thread has no id of its own beyond the id of the message that started it, and no row anywhere: it is what a query groups.

type Media

type Media struct {
	// ID of the Media, stable for its lifetime, and the name the bytes are
	// stored under.
	ID string `json:"id,omitempty"`

	// Timestamp when the Media was uploaded
	CreatedAt time.Time `json:"createdAt,omitempty"`

	// Timestamp when the Media was last modified
	ModifiedAt time.Time `json:"modifiedAt,omitempty"`

	// The Domain this Media belongs to. A picture uploaded for one domain is
	// served from that domain's own name and may only be put in that domain's
	// templates.
	DomainID string `json:"domainId,omitempty"`

	// Filename is what it was uploaded as, kept so a list of them reads as the
	// operator's own files rather than as identifiers.
	Filename string `json:"filename,omitempty"`

	// ContentType is what to answer with, decided by reading the bytes rather
	// than by believing what the browser said they were.
	ContentType string `json:"contentType,omitempty"`

	// Size in bytes.
	Size int64 `json:"size,omitempty"`

	// Checksum of the bytes, as hex. It is what tells an operator two
	// uploads are the same file, and what a later deduplication would use.
	Checksum string `json:"checksum,omitempty"`
}

Media is a file an operator uploaded to put in a template: a logo, a header, a signature.

The bytes are not here. They go to the same storage the messages do, for the same reason — a database holding every picture is one nobody can restore quickly — and this row is what says which file that is, who it belongs to and what to answer with when it is asked for.

type MediaLink struct {
	// Token is the address, and the primary key. Sixteen random bytes in
	// base32, not a ULID: these are reachable by anybody with no session, and
	// one that can be guessed from another lets a stranger fetch somebody
	// else's picture and mark their message opened.
	Token string `json:"token,omitempty"`

	// Timestamp when the address was created, which is when the message was
	// sent.
	CreatedAt time.Time `json:"createdAt,omitempty"`

	// Timestamp when the row was last written, which is the last fetch.
	ModifiedAt time.Time `json:"modifiedAt,omitempty"`

	// The Media this address resolves to.
	MediaID string `json:"mediaId,omitempty"`

	// EnvelopeID is the message this address was put in, by the identifier it
	// is given as it is composed — the same one the stored mail records as
	// its envelope.
	//
	// One address per message, not per recipient. The rewrite happens once,
	// while the body is being built, and every recipient is handed the same
	// bytes. A message sent to three people that comes back opened says the
	// message was opened, not which of them opened it.
	EnvelopeID string `json:"envelopeId,omitempty"`

	// OpenedAt is the first fetch, LastOpenedAt the most recent, and
	// OpenCount how many there have been. Zero and empty until one happens.
	OpenedAt     *time.Time `json:"openedAt,omitempty"`
	LastOpenedAt *time.Time `json:"lastOpenedAt,omitempty"`
	OpenCount    int64      `json:"openCount,omitempty"`

	// IP and UserAgent are from the most recent fetch. For Gmail they are
	// Google's proxy rather than the reader's, which is worth remembering
	// before reading anything into them.
	IP        string `json:"ip,omitempty"`
	UserAgent string `json:"userAgent,omitempty"`
}

MediaLink is one picture's address in one sent message.

A template names a picture once; every message sent from it gets an address of its own for that picture. That is what makes an open detectable — a fetch of this address can only have come from this message — and it is why the token is random rather than an identifier that sorts.

What an open is worth is worth saying wherever this is read. A fetch means a mail program asked for the picture, which is weaker than a person reading the message in both directions: Apple's Mail Privacy Protection fetches every picture before anybody has seen anything, and most programs fetch none until the reader asks. It is a floor with false positives in it.

type MemberRole added in v0.170.0

type MemberRole string

MemberRole is what somebody may do in a circle: an admin manages who is in it and its name, a member takes part. A role never decides what anybody may see of anybody else's; that is always the owner's choice.

const (
	MemberRoleAdmin  MemberRole = "admin"
	MemberRoleMember MemberRole = "member"
)

The member roles.

func (MemberRole) IsValid added in v0.170.0

func (self MemberRole) IsValid() bool

IsValid reports whether this is one of the roles.

type MerchantMonthSpending added in v0.87.0

type MerchantMonthSpending struct {
	SpendingCategoryID string `json:"spendingCategoryId"`

	// MerchantName is the merchant, or the description when there is none.
	MerchantName string `json:"merchantName"`

	// SpendingMonth is the month, "2006-01".
	SpendingMonth           string `json:"spendingMonth"`
	CurrencyCode            string `json:"currencyCode"`
	SpendingAmount          string `json:"spendingAmount"`
	FinanceTransactionCount int    `json:"financeTransactionCount"`
}

MerchantMonthSpending is what one merchant charged one spending category in one month, in one currency: what the budget pace reads to expect a fixed monthly charge before it lands.

type MotionActivity added in v0.203.0

type MotionActivity struct {
	ID     string `json:"id"`
	UserID string `json:"userId"`

	StartedAt          time.Time `json:"startedAt"`
	ActivityKind       string    `json:"activityKind"`
	ActivityConfidence string    `json:"activityConfidence"`

	CreatedAt time.Time `json:"createdAt"`
}

MotionActivity is what the phone's motion sensor said the person was doing from StartedAt on, until the next activity starts. ActivityKind is one of stationary, walking, running, cycling, automotive and unknown; ActivityConfidence is low, medium or high.

type NetWorthPoint added in v0.87.0

type NetWorthPoint struct {
	// NetWorthOn is the day, "2006-01-02".
	NetWorthOn     string `json:"netWorthOn"`
	CurrencyCode   string `json:"currencyCode"`
	NetWorthAmount string `json:"netWorthAmount"`
}

NetWorthPoint is net worth in one currency on one day: the winning valuations of the assets open that day, liabilities subtracted. Currencies are never added together here; converting is the caller's.

type OAuthAuthorization added in v0.49.0

type OAuthAuthorization struct {
	ID        string    `json:"id,omitempty"`
	CreatedAt time.Time `json:"createdAt,omitempty"`

	ClientID string `json:"clientId,omitempty"`
	UserID   string `json:"userId,omitempty"`

	// RedirectURI is where this approval is to be sent, which has to match
	// again when it is collected.
	RedirectURI string `json:"redirectUri,omitempty"`

	// CodeChallenge is the hash the program sent when it asked. It collects
	// by presenting the original.
	CodeChallenge string `json:"codeChallenge,omitempty"`

	// Resource is what the token will be good for.
	Resource string `json:"resource,omitempty"`

	// ClientKind is the kind the token will have (ClientKindApp or empty):
	// the app's, when the approval was made on the dashboard or in the app
	// and the program is an app that asked for the API itself.
	ClientKind TokenClientKind `json:"clientKind,omitempty"`

	ExpiresAt time.Time `json:"expiresAt,omitempty"`
}

OAuthAuthorization is the few minutes between a person approving and the program collecting.

It is deleted the moment it is spent, in the same transaction that mints the token, so a replayed approval finds nothing and a crash between the two cannot leave an approval that was spent and issued nothing.

type OAuthClient added in v0.49.0

type OAuthClient struct {
	ID         string    `json:"id,omitempty"`
	CreatedAt  time.Time `json:"createdAt,omitempty"`
	ModifiedAt time.Time `json:"modifiedAt,omitempty"`

	Name string `json:"name,omitempty"`

	// RedirectURIs are the addresses an approval may be sent to. Checked when
	// the client registers and again when somebody approves it.
	RedirectURIs []string `json:"redirectUris,omitempty"`

	// ApprovedAt is when somebody last approved this client, so a
	// registration nobody used can be swept without touching one in service.
	ApprovedAt time.Time `json:"approvedAt,omitempty"`
}

OAuthClient is a program that introduced itself.

It holds no secret. A program running on somebody's own machine cannot keep one, so registering is open and proves nothing: a client can do nothing at all until a person approves it, and what protects the exchange is the PKCE challenge rather than anything the client knows.

Name is whatever the program called itself and is shown to the person approving. It is not to be trusted, and the page says so.

func (*OAuthClient) AllowsRedirect added in v0.49.0

func (self *OAuthClient) AllowsRedirect(address string) bool

AllowsRedirect says whether an address is one this client registered.

Compared whole rather than by prefix. A prefix match lets somebody who registered "https://example.com/cb" collect at "https://example.com/cb.evil.test", which is the shape of most of the redirect attacks this check exists to stop.

type OAuthConnectCode added in v0.127.0

type OAuthConnectCode struct {
	ID        string    `json:"id,omitempty"`
	CreatedAt time.Time `json:"createdAt,omitempty"`
	UserID    string    `json:"userId,omitempty"`

	// ClientKind is the kind the token will have: ClientKindApp when the
	// code was made on the dashboard or in the app, empty when a command line
	// token made it.
	ClientKind TokenClientKind `json:"clientKind,omitempty"`
	ExpiresAt  time.Time       `json:"expiresAt,omitempty"`
}

OAuthConnectCode is a one-time secret that signs a phone app in as a person: shown where they are signed in, as a QR code, and scanned by the phone. It is deleted when it is used.

type Occurrence

type Occurrence struct {
	CalendarID string    `json:"calendarId"`
	ObjectID   string    `json:"objectId"`
	StartsAt   time.Time `json:"startsAt"`
	EndsAt     time.Time `json:"endsAt"`
	AllDay     bool      `json:"allDay,omitempty"`
}

Occurrence is one time an event happens.

These are derived from the iCalendar text and rewritten whenever an object is, so nothing here is authoritative. They exist so that "what is on this week" and "when is this person busy" are answered by reading a window rather than by expanding every recurrence rule in the calendar.

type Passkey

type Passkey struct {
	// ID of the Passkey, stable for its lifetime
	ID string `json:"id,omitempty"`

	// Timestamp when the Passkey was registered
	CreatedAt time.Time `json:"createdAt,omitempty"`

	// Timestamp when the Passkey was last modified
	ModifiedAt time.Time `json:"modifiedAt,omitempty"`

	// The User this Passkey signs in as
	UserID string `json:"userId,omitempty"`

	// What the person calls this authenticator, for example "phone"
	Name string `json:"name,omitempty"`

	// CredentialID is what the authenticator returns to identify itself. Not
	// the primary key: it is chosen by the authenticator and is bytes rather
	// than a name, and it has to be looked up by on sign-in, which is what the
	// unique index is for.
	CredentialID []byte `json:"-"`

	// PublicKey verifies what the authenticator signs.
	PublicKey []byte `json:"-"`

	// AttestationType is how the authenticator vouched for itself, if at all.
	AttestationType string `json:"attestationType,omitempty"`

	// Transports are how the browser can reach this authenticator: usb, nfc,
	// ble, internal, hybrid. Passed back at sign-in so the browser can offer
	// the right thing.
	Transports []string `json:"transports,omitempty"`

	// AAGUID identifies the make and model of the authenticator. Zero for
	// most passkeys, which deliberately do not say.
	AAGUID []byte `json:"-"`

	// SignCount is the authenticator's own counter. A count that does not
	// advance means two authenticators are answering for one credential,
	// which means it has been cloned.
	SignCount int64 `json:"-"`

	// BackupEligible says the credential may be synced to other devices;
	// BackupState says it currently is. Together they are the difference
	// between a passkey on one security key and one in a password manager.
	BackupEligible bool `json:"backupEligible,omitempty"`
	BackupState    bool `json:"backupState,omitempty"`

	// When it was last used to sign in, and from where
	UsedAt    time.Time `json:"usedAt,omitempty"`
	IP        string    `json:"ip,omitempty"`
	UserAgent string    `json:"userAgent,omitempty"`
}

Passkey is a credential an authenticator holds on somebody's behalf.

The private half never leaves the authenticator — the phone, the laptop's secure enclave, the security key on a keyring — so there is no shared secret here to leak, phish or reuse. What is stored is the public half and enough to recognize it again.

type PasswordAgentKey added in v0.193.0

type PasswordAgentKey struct {
	PublicKey        string
	PrivateKeySealed string
	CreatedAt        time.Time
}

PasswordAgentKey is the server's key pair for the items a person let the agent use. PrivateKeySealed is the private scalar sealed by secretbox under PasswordAgentKeyLabel.

type PasswordItem added in v0.193.0

type PasswordItem struct {
	ID          string           `json:"id"`
	OwnerUserID string           `json:"ownerUserId"`
	ItemKind    PasswordItemKind `json:"itemKind"`

	EncryptedFields     string `json:"encryptedFields"`
	ItemKeyByAccountKey string `json:"itemKeyByAccountKey"`

	// ItemKeyByRecipientKey is filled when the item is read by somebody it is
	// shared with.
	ItemKeyByRecipientKey string `json:"itemKeyByRecipientKey,omitempty"`

	// Revision is the number of the last change a reader must see.
	Revision int64 `json:"revision"`

	IsUsableByAgent   bool       `json:"isUsableByAgent"`
	ItemKeyByAgentKey string     `json:"itemKeyByAgentKey,omitempty"`
	LastUsedByAgentAt *time.Time `json:"lastUsedByAgentAt,omitempty"`

	// NeedsNewKey is set when access to the item narrowed, so that a copy of
	// its old key may still be held; only a re-key by the owner's device
	// clears it.
	NeedsNewKey bool `json:"needsNewKey"`

	// IsSavedByPerson says the current fields were saved by the person's own
	// tap. A save sets it from the call; the database keeps it with the item.
	IsSavedByPerson bool `json:"isSavedByPerson"`

	DeletedAt *time.Time `json:"deletedAt,omitempty"`
	CreatedAt time.Time  `json:"createdAt"`
	UpdatedAt time.Time  `json:"updatedAt"`

	// IsSharedWithMe is filled by the listing: the reader is not the owner.
	// OwnerName is the owner's name then, and for the owner's own items too.
	IsSharedWithMe bool   `json:"isSharedWithMe"`
	OwnerName      string `json:"ownerName,omitempty"`

	// OwnerPublicKey is the owner's current public key (base64), filled with
	// OwnerName. A key sealed for a recipient or for the agent opens only with
	// it, since the owner's key is mixed into the sealing.
	OwnerPublicKey string `json:"ownerPublicKey,omitempty"`

	// Shares are the owner's shares of the item with who each reaches, filled
	// by the listing for the owner only.
	Shares []*PasswordShare `json:"shares,omitempty"`
}

PasswordItem is one login, card or note, sealed. ItemKeyByAccountKey is the owner's copy of the item key. A recipient reading a shared item has their own copy in ItemKeyByRecipientKey instead, and Shares empty.

type PasswordItemKind added in v0.193.0

type PasswordItemKind string

PasswordItemKind says what an item holds.

const (
	PasswordItemKindLogin PasswordItemKind = "login"
	PasswordItemKindCard  PasswordItemKind = "card"
	PasswordItemKindNote  PasswordItemKind = "note"
)

func (PasswordItemKind) IsValid added in v0.193.0

func (self PasswordItemKind) IsValid() bool

IsValid reports whether the kind is one of the three.

type PasswordItemList added in v0.193.0

type PasswordItemList struct {
	// Items are the changed items: revision above what the device has, the
	// person's own (deleted ones included) and those shared with them.
	Items []*PasswordItem `json:"items"`

	// ItemIDs are every item the person can open now, so a device drops what
	// is gone.
	ItemIDs []string `json:"itemIds"`

	// Revision is the highest revision among everything visible, 0 if nothing.
	Revision int64 `json:"revision"`
}

PasswordItemList is what a person can reach now, as a device asks for it.

type PasswordItemRekey added in v0.193.0

type PasswordItemRekey struct {
	ItemID              string
	BaseRevision        int64
	EncryptedFields     string
	ItemKeyByAccountKey string
	ShareKeys           []*PasswordShareKey
	ItemKeyByAgentKey   *string

	// IsSavedByPerson says the call was the person's own tap, which decides
	// which replaced versions are kept.
	IsSavedByPerson bool
}

PasswordItemRekey is an item's fields sealed again under a new item key by the owner's device, because access to the item narrowed: the new key sealed for the account key, for each recipient who keeps access, and for the agent key. ItemKeyByAgentKey is nil to end the agent's use of the item.

type PasswordItemVersion added in v0.193.0

type PasswordItemVersion struct {
	ItemID              string
	Revision            int64
	ItemKind            PasswordItemKind
	EncryptedFields     string
	ItemKeyByAccountKey string

	// IsSavedByPerson says the person's own tap saved this content.
	IsSavedByPerson bool

	// ReplacedAt is when a later save replaced it.
	ReplacedAt time.Time
}

PasswordItemVersion is an earlier version of an item: the sealed fields and the item key (sealed by the account key) the item had before a later save replaced them. Revision names it among the item's versions; it is the revision the item had then.

type PasswordPassphraseChange added in v0.193.0

type PasswordPassphraseChange struct {
	AccountKeyByPassphrase   string
	PassphraseSalt           string
	PassphraseIterationCount int
	PassphraseProofHash      string
}

PasswordPassphraseChange is a new passphrase: the account key sealed by the key it makes, with the salt and iteration count that make that key, and a hash of its proof.

type PasswordRecipient added in v0.193.0

type PasswordRecipient struct {
	UserID   string `json:"userId"`
	Name     string `json:"name"`
	Username string `json:"username"`

	// PublicKey is empty for a person who has not set up Passwords.
	PublicKey string `json:"publicKey,omitempty"`

	// HasKey is whether a key sealed for this item and this public key is
	// stored. False where no item is in question.
	HasKey bool `json:"hasKey"`

	// HasTooMuchShared is whether storing a key for this item would take the
	// recipient past PasswordsSharedBytesMost or PasswordsSharedItemsMost, or
	// what one owner may share with them (PasswordsSharedBytesFromOneOwnerMost
	// and PasswordsSharedItemsFromOneOwnerMost), so that none is stored for
	// them. Only for a recipient without a key, where an item is in question.
	HasTooMuchShared bool `json:"hasTooMuchShared"`
}

PasswordRecipient is a person an item can be sealed for: their public key when they have set up Passwords, and whether the key is already sealed for the item in question.

type PasswordSetup added in v0.193.0

type PasswordSetup struct {
	UserID string `json:"userId"`

	AccountKeyByPassphrase   string    `json:"accountKeyByPassphrase"`
	PassphraseSalt           string    `json:"passphraseSalt"`
	PassphraseIterationCount int       `json:"passphraseIterationCount"`
	PassphraseProofHash      string    `json:"-"`
	AccountKeyByRecoveryKey  string    `json:"accountKeyByRecoveryKey"`
	RecoveryKeyProofHash     string    `json:"-"`
	PublicKey                string    `json:"publicKey"`
	PrivateKeyByAccountKey   string    `json:"privateKeyByAccountKey"`
	LockAfterMinutes         int       `json:"lockAfterMinutes"`
	CreatedAt                time.Time `json:"createdAt"`
	UpdatedAt                time.Time `json:"updatedAt"`
}

PasswordSetup is what a person set up: their account key sealed by the key their passphrase makes and by their recovery key, a hash of the proof of each, and their key pair. The hashes are never sent back to a client.

type PasswordShare added in v0.193.0

type PasswordShare struct {
	ID     string `json:"id"`
	ItemID string `json:"itemId"`

	GranteeUserID   string `json:"granteeUserId,omitempty"`
	GranteeCircleID string `json:"granteeCircleId,omitempty"`

	// GranteeName is the person's name or the circle's name.
	GranteeName string `json:"granteeName,omitempty"`

	CreatedAt time.Time `json:"createdAt"`

	// Recipients are everyone the share reaches now.
	Recipients []*PasswordRecipient `json:"recipients,omitempty"`
}

PasswordShare gives one person, or every member of one circle, the chance to be sealed the item's key. Exactly one of GranteeUserID and GranteeCircleID is set.

type PasswordShareGrantee added in v0.193.0

type PasswordShareGrantee struct {
	GranteeUserID   string
	GranteeCircleID string
}

PasswordShareGrantee names who an item is shared with in a change of its shares.

type PasswordShareKey added in v0.193.0

type PasswordShareKey struct {
	ItemID                string
	RecipientUserID       string
	ItemKeyByRecipientKey string
	RecipientPublicKey    string

	// ItemKeyByAccountKey is the item key the device opened to seal this key,
	// as the owner's copy of it is stored. When it is not empty, the key is
	// stored only while it is still the item's current one.
	ItemKeyByAccountKey string
}

PasswordShareKey is an item key sealed for one recipient's public key.

type PasswordWaitingShare added in v0.193.0

type PasswordWaitingShare struct {
	ItemID    string             `json:"itemId"`
	Recipient *PasswordRecipient `json:"recipient"`

	// HasMoreWaiting is set on every entry when more than
	// PasswordWaitingSharesMost wait and only the newest items are listed.
	HasMoreWaiting bool `json:"hasMoreWaiting"`
}

PasswordWaitingShare is a recipient of one of the owner's items who has set up Passwords but has no key for the item yet, so the owner's device has sealing to do.

type PaystubCheckState added in v0.155.0

type PaystubCheckState string

PaystubCheckState says whether a paystub's lines add up to its printed totals.

const (
	PaystubCheckStateBalanced   PaystubCheckState = "balanced"
	PaystubCheckStateUnbalanced PaystubCheckState = "unbalanced"
)

func (PaystubCheckState) IsValid added in v0.155.0

func (self PaystubCheckState) IsValid() bool

IsValid says the state is one of the two.

type PaystubDeductionKind added in v0.155.0

type PaystubDeductionKind string

PaystubDeductionKind is what a paystub's deduction pays for, as far as a W-2 and a tax return tell them apart.

const (
	// PaystubDeductionKindRetirementTraditional is a traditional 401(k),
	// 403(b) or 457 contribution, before income tax: W-2 box 12 D, E or G.
	PaystubDeductionKindRetirementTraditional PaystubDeductionKind = "retirement_traditional"
	// PaystubDeductionKindRetirementRoth is a Roth contribution, after
	// income tax: W-2 box 12 AA, BB or EE.
	PaystubDeductionKindRetirementRoth PaystubDeductionKind = "retirement_roth"
	// PaystubDeductionKindHSA is a health savings account contribution:
	// W-2 box 12 W, with the employer's.
	PaystubDeductionKindHSA PaystubDeductionKind = "hsa"
	// PaystubDeductionKindHealthPremium is a medical, dental or vision
	// premium: W-2 box 12 DD, with the employer's.
	PaystubDeductionKindHealthPremium PaystubDeductionKind = "health_premium"
	PaystubDeductionKindFSAHealth     PaystubDeductionKind = "fsa_health"
	// PaystubDeductionKindFSADependentCare is a dependent care account:
	// W-2 box 10.
	PaystubDeductionKindFSADependentCare PaystubDeductionKind = "fsa_dependent_care"
	PaystubDeductionKindCommuter         PaystubDeductionKind = "commuter"
	// PaystubDeductionKindInsurance is life or disability insurance.
	PaystubDeductionKindInsurance PaystubDeductionKind = "insurance"
	PaystubDeductionKindOther     PaystubDeductionKind = "other"
)

func (PaystubDeductionKind) IsValid added in v0.155.0

func (self PaystubDeductionKind) IsValid() bool

IsValid says the kind is one of the known deductions.

type PaystubLineKind added in v0.155.0

type PaystubLineKind string

PaystubLineKind is what a printed line of a paystub is.

const (
	// PaystubLineKindEarning is pay: regular, overtime, a bonus.
	PaystubLineKindEarning PaystubLineKind = "earning"
	// PaystubLineKindTax is a tax withheld, with the wages it was figured on.
	PaystubLineKindTax PaystubLineKind = "tax"
	// PaystubLineKindDeduction is taken out of the pay for something other
	// than a tax: a retirement plan, a health premium, an HSA. The
	// employer's part, when the paystub prints one, is beside it.
	PaystubLineKindDeduction PaystubLineKind = "deduction"
	// PaystubLineKindReimbursement is money paid back that is not pay:
	// expenses, printed as non-taxable earnings. It is outside gross pay
	// and its taxes, and is added to take-home pay.
	PaystubLineKindReimbursement PaystubLineKind = "reimbursement"
)

func (PaystubLineKind) IsValid added in v0.155.0

func (self PaystubLineKind) IsValid() bool

IsValid says the kind is one of the four.

type PaystubTaxKind added in v0.155.0

type PaystubTaxKind string

PaystubTaxKind is which tax a paystub's tax line withholds.

const (
	PaystubTaxKindFederalIncome  PaystubTaxKind = "federal_income"
	PaystubTaxKindSocialSecurity PaystubTaxKind = "social_security"
	PaystubTaxKindMedicare       PaystubTaxKind = "medicare"
	// PaystubTaxKindMedicareAdditional is the 0.9% withheld on Medicare
	// wages above 200,000 in the year, when the paystub prints it apart;
	// a W-2 counts it in box 6 with the rest of Medicare.
	PaystubTaxKindMedicareAdditional PaystubTaxKind = "medicare_additional"
	PaystubTaxKindStateIncome        PaystubTaxKind = "state_income"
	PaystubTaxKindLocalIncome        PaystubTaxKind = "local_income"
	// PaystubTaxKindStateDisability is a state's disability or family
	// leave insurance withheld from pay.
	PaystubTaxKindStateDisability PaystubTaxKind = "state_disability"
	PaystubTaxKindOther           PaystubTaxKind = "other"
)

func (PaystubTaxKind) IsValid added in v0.155.0

func (self PaystubTaxKind) IsValid() bool

IsValid says the kind is one of the known taxes.

type Permission

type Permission string

Permission is one named thing somebody may do, written resource:verb.

The vocabulary is Go, not a table: a permission the code does not know cannot be granted, and a role_permission row naming one the code has forgotten is ignored rather than fatal.

const (
	PermissionMailRead        Permission = "mail:read"         // read one's own mailboxes
	PermissionMailWrite       Permission = "mail:write"        // flag, move, delete in them
	PermissionMailSend        Permission = "mail:send"         // send as an address of them
	PermissionMailboxManage   Permission = "mailbox:manage"    // folders, rules, addresses of them
	PermissionMailAudit       Permission = "mail:audit"        // every message of the group's domains, as the operator sees it today
	PermissionMailAuditAll    Permission = "mail:audit-all"    // the same, over every domain
	PermissionDomainManage    Permission = "domain:manage"     // the group's domains: aliases, credentials, templates
	PermissionDomainManageAll Permission = "domain:manage-all" // every domain, present and future, and creating new ones
	PermissionQueueManage     Permission = "queue:manage"      // the delivery queue
	PermissionReportRead      Permission = "report:read"       // DMARC reports
	PermissionUserManage      Permission = "user:manage"
	PermissionGroupManage     Permission = "group:manage"
	PermissionRoleManage      Permission = "role:manage"
	PermissionServerManage    Permission = "server:manage" // settings, upgrades, certificates
	PermissionAuditRead       Permission = "audit:read"    // the audit log
	PermissionAgentUse        Permission = "agent:use"     // have an agent, grant it one's mailboxes, talk to it
	PermissionContactsUse     Permission = "contacts:use"  // keep an address book, and sync it to a device
	PermissionCalendarUse     Permission = "calendar:use"  // keep a calendar, and sync it to a device
	PermissionPhotosUse       Permission = "photos:use"    // keep a photo library, and back up a device to it
	PermissionCircleUse       Permission = "circle:use"    // make circles of people on this server, and join them
	PermissionLocationUse     Permission = "location:use"  // record where one goes, and share it with the circles one is in
	PermissionHealthUse       Permission = "health:use"    // keep one's Health data from the iPhone, and share some of it with the circles one is in
	PermissionJournalUse      Permission = "journal:use"   // keep a journal of one's days, which links to what one keeps elsewhere and which the agent writes in
	PermissionPasswordsUse    Permission = "passwords:use" // keep passwords, passkeys, cards and notes that only one's own devices can read, and share some of them
	PermissionShoppingUse     Permission = "shopping:use"  // keep shopping lists, share them with the circles one is in, and check them off at the store
	PermissionAgentAudit      Permission = "agent:audit"   // every person's agent state and usage, limits, switch-off; never content
	PermissionAgentObserve    Permission = "agent:observe" // every person's agent conversations and runs, read-only; each read is audited
	PermissionAgentAct        Permission = "agent:act"     // every person's agent conversations and runs, and a word with their agent as them; content, for the operator of a private server
)

func Permissions

func Permissions() []Permission

Permissions lists the whole vocabulary, in the order the role editor shows it.

func SeededRolePermissions

func SeededRolePermissions(name string) []Permission

SeededRolePermissions is what each seeded role holds on the day it is made.

func (Permission) IsValid

func (self Permission) IsValid() bool

IsValid reports whether the code knows this permission.

func (Permission) Kind

func (self Permission) Kind() PermissionKind

Kind is the permission's reach. A key the code does not know has no kind and grants nothing.

func (Permission) Widens

func (self Permission) Widens() Permission

Widens is, for an all-domains permission, the domain permission it stands in for on every domain: "domain:manage-all" widens "domain:manage". Empty for every other permission.

type PermissionKind

type PermissionKind string

PermissionKind is where a permission applies, declared with the vocabulary: there is no flag on a group, the permission itself says how far it reaches.

const (
	// PermissionKindServer applies everywhere, whatever domains the group has.
	PermissionKindServer PermissionKind = "server"

	// PermissionKindDomain applies over the group's domains only.
	PermissionKindDomain PermissionKind = "domain"

	// PermissionKindAllDomains applies over every domain, present and future;
	// the group's domains are not consulted.
	PermissionKindAllDomains PermissionKind = "all-domains"
)

type PersonRelationship added in v0.178.0

type PersonRelationship struct {
	ID                    string           `json:"id"`
	CreatedAt             time.Time        `json:"createdAt"`
	ModifiedAt            time.Time        `json:"modifiedAt"`
	UserID                string           `json:"userId"`
	RelatedUserID         string           `json:"relatedUserId"`
	RelationshipKind      RelationshipKind `json:"relationshipKind"`
	RelatedUserTermGender TermGender       `json:"relatedUserTermGender"`
}

PersonRelationship is what one person is to another who shares a circle with them. It is one fact between the two: UserID said, last, that RelatedUserID is their RelationshipKind. What UserID is to RelatedUserID is the opposite kind.

func (*PersonRelationship) KindFor added in v0.178.0

func (self *PersonRelationship) KindFor(userId string) RelationshipKind

KindFor is what the other person is to this one: the kind as said when this one said it, its opposite when the other did.

func (*PersonRelationship) Other added in v0.178.0

func (self *PersonRelationship) Other(userId string) string

Other is the person in the relationship who is not this one, or "" when this one is in neither side.

func (*PersonRelationship) TermGenderFor added in v0.178.0

func (self *PersonRelationship) TermGenderFor(userId string, otherPronoun Pronoun) TermGender

TermGenderFor is the gender of the word for the other person, as this one sees them. How the other person said they are described wins; then the word this one chose for them, when it was this one who said it; and neutral otherwise, since nobody else's word says anything about them.

type Photo added in v0.171.0

type Photo struct {
	ID                   string               `json:"id"`
	UserID               string               `json:"userId"`
	CreatedAt            time.Time            `json:"createdAt"`
	UpdatedAt            time.Time            `json:"updatedAt"`
	ClientPhotoID        string               `json:"clientPhotoId"`
	PhotoKind            PhotoKind            `json:"photoKind"`
	PhotoSource          PhotoSource          `json:"photoSource"`
	TakenAt              *time.Time           `json:"takenAt" graphapi:"nullable"`
	TakenAtOffsetMinutes *int                 `json:"takenAtOffsetMinutes" graphapi:"nullable"`
	WidthPixels          int                  `json:"widthPixels"`
	HeightPixels         int                  `json:"heightPixels"`
	DurationMS           int64                `json:"durationMS"`
	Latitude             *float64             `json:"latitude" graphapi:"nullable"`
	Longitude            *float64             `json:"longitude" graphapi:"nullable"`
	PlaceName            string               `json:"placeName"`
	CameraMake           string               `json:"cameraMake"`
	CameraModel          string               `json:"cameraModel"`
	OriginalFilename     string               `json:"originalFilename"`
	IsFavorite           bool                 `json:"isFavorite"`
	IsScreenshot         bool                 `json:"isScreenshot"`
	PhotoProcessingState PhotoProcessingState `json:"photoProcessingState"`
	// ProcessingAttemptCount is how many times making previews has been tried
	// since the photo last became ready or was asked to be tried again; a try
	// is counted when the photo is claimed. ProcessingErrorMessage is a fixed,
	// plain reason for the last failure, with no path or tool output in it.
	ProcessingAttemptCount int    `json:"processingAttemptCount"`
	ProcessingErrorMessage string `json:"processingErrorMessage"`
	// ProcessingOutageCount is how many failures in a row were not the file's
	// fault; each makes the photo wait longer than the one before.
	ProcessingOutageCount int `json:"-"`
	// ProcessingClaimedAt is when an instance took the photo to process it.
	ProcessingClaimedAt *time.Time `json:"-"`
	// ProcessingNotBefore is the earliest time a waiting photo is claimed
	// again, after a failure.
	ProcessingNotBefore *time.Time `json:"-"`
	TrashedAt           *time.Time `json:"trashedAt" graphapi:"nullable"`

	// IsLocationRemoved says the person removed the photo's location, so
	// that reading the file again does not put the camera's back.
	IsLocationRemoved bool `json:"-"`

	// FacesFoundAt is when the photo's faces were found, null until then.
	FacesFoundAt *time.Time `json:"-"`

	// PhotoDescription is what a model wrote about the picture, and
	// DescriptionVisibleText the words it could read in it. Both are empty
	// until somebody works with the photo: it is described when the agent
	// looks at it or the person asks, not before. They are text a model wrote
	// from a picture that may carry words meant for it, so a reader treats
	// them as evidence and never as instructions.
	PhotoDescription       string `json:"photoDescription"`
	DescriptionVisibleText string `json:"descriptionVisibleText"`

	// DescriptionModel is the model that wrote them.
	DescriptionModel string `json:"-"`

	// DescribedAt is when they were written, null while the photo is
	// undescribed.
	DescribedAt *time.Time `json:"describedAt" graphapi:"nullable"`

	// DescriptionRequestedAt is when a description was asked for and not yet
	// written.
	DescriptionRequestedAt *time.Time `json:"-"`

	// IsDescriptionRequested says a description is on its way: asked for
	// recently and not yet written. A request older than a day is taken to
	// have been lost, since the job that serves it gives up before then.
	IsDescriptionRequested bool `json:"isDescriptionRequested" gorm:"-"`

	// PhotoDocumentKind is what the description said the picture is: empty
	// until it is described, then none, or a document the person keeps
	// records of, which is handed to the job that records it.
	PhotoDocumentKind PhotoDocumentKind `json:"photoDocumentKind"`

	// DocumentTitle and DocumentText are what the transcription job wrote of
	// a photo kept as a document: a title, and everything written in the
	// picture as Markdown. Both are empty when the photo is not kept. Like
	// the description they are text a model read from a picture, so a reader
	// treats them as evidence and never as instructions.
	DocumentTitle string `json:"documentTitle"`
	DocumentText  string `json:"documentText"`

	// DocumentKeptAt is when the photo was kept as a document, null while it
	// is not.
	DocumentKeptAt *time.Time `json:"documentKeptAt" graphapi:"nullable"`

	// ReadingQueuedAt is when the photo was queued to be read because it was
	// new, null when it never was.
	ReadingQueuedAt *time.Time `json:"-"`

	// The preview addresses are worked out when the photo is read, from the
	// previews that exist; each is empty until its preview is made. They
	// carry the time the photo last changed, so a new preview is a new
	// address and the old one can be cached for good.
	SmallPreviewURL string `json:"smallPreviewUrl" gorm:"-"`
	LargePreviewURL string `json:"largePreviewUrl" gorm:"-"`
	VideoPreviewURL string `json:"videoPreviewUrl" gorm:"-"`

	// PhotoFileRoles are the roles of the files the server holds for the
	// photo, so that an uploader after a reinstall can send only the edited
	// version or the Live Photo's video that is missing. Worked out when the
	// photo is read.
	PhotoFileRoles []PhotoFileRole `json:"photoFileRoles" gorm:"-"`

	// IsOwnedByCaller says the photo is in the caller's own library; OwnerName
	// is whose it is when it is not, for a photo read through an album that
	// was shared with the caller. A photo that is not the caller's has no
	// place or favorite mark in it: those are the owner's.
	IsOwnedByCaller bool   `json:"isOwnedByCaller" gorm:"-"`
	OwnerName       string `json:"ownerName" gorm:"-"`
}

Photo is one item in a person's library: a picture, a video, or a Live Photo. The bytes are in its files.

func (*Photo) TakenAtOnClock added in v0.171.0

func (self *Photo) TakenAtOnClock() *time.Time

TakenAtOnClock is when the photo was taken on the clock where it was taken: its instant in its own offset. This is the one rule every place that writes a photo's date follows. Processing gives every photo that has a date an offset, so a date without one is only a photo not processed yet, and it is shown on the UTC clock until then.

type PhotoAccess added in v0.171.0

type PhotoAccess struct {
	PhotoID     string
	OwnerUserID string

	// IsOwner says the photo is the person's own, and then nothing is held
	// back from them.
	IsOwner bool

	// IsLocationIncluded says an album that reaches the person lets them see
	// where this photo was taken and receive its original files.
	IsLocationIncluded bool

	// IsFaceNamesIncluded says an album that reaches the person lets them see
	// the names the owner gave the faces in this photo.
	IsFaceNamesIncluded bool
}

PhotoAccess is why one person may read one photo that is not theirs.

type PhotoAlbum added in v0.171.0

type PhotoAlbum struct {
	ID string `json:"id"`

	// OwnerUserID is the person the album belongs to, null for a circle's
	// album, and CircleID the circle it belongs to, null for a person's.
	OwnerUserID *string `json:"ownerUserId" graphapi:"nullable"`
	CircleID    *string `json:"circleId" graphapi:"nullable"`

	AlbumTitle string    `json:"albumTitle"`
	CreatedAt  time.Time `json:"createdAt"`
	UpdatedAt  time.Time `json:"updatedAt"`

	// CoverPhotoID is the photo the person chose to stand for the album, if
	// they did. Until they do, and while the photo they chose is in the trash
	// or has no small preview yet, the album shows its newest photo.
	CoverPhotoID *string `json:"coverPhotoId" graphapi:"nullable"`

	// The rest is worked out when the album is read, from the photos that are
	// not in the trash: a photo in the trash stays in its albums but is not
	// counted or shown until it is restored.
	PhotoCount int `json:"photoCount" gorm:"-"`

	// FirstTakenAt and LastTakenAt bound the date the album's photos are
	// placed at (when taken, or when they arrived if that is not known). Null
	// for an album with no photos.
	FirstTakenAt *time.Time `json:"firstTakenAt" graphapi:"nullable" gorm:"-"`
	LastTakenAt  *time.Time `json:"lastTakenAt" graphapi:"nullable" gorm:"-"`

	// CoverPreviewURL is where the album's cover picture is fetched from:
	// empty when no photo of the album has a small preview yet.
	CoverPreviewURL string `json:"coverPreviewUrl" gorm:"-"`

	// CoverPreviewPhotoID and CoverPreviewPhotoUpdatedAt name the photo the
	// cover is made from and when it last changed, so that the API can address
	// its preview the way it addresses any other.
	CoverPreviewPhotoID        string     `json:"-" gorm:"-"`
	CoverPreviewPhotoUpdatedAt *time.Time `json:"-" gorm:"-"`

	// Whose the album is and what the caller may do with it, worked out for
	// the caller when it is read. OwnerUser is the person who owns it, nil for
	// a circle's album, and CircleName the circle's name for one.
	OwnerUser             *User   `json:"-" gorm:"-"`
	OwnerUsername         string  `json:"ownerUsername" gorm:"-"`
	OwnerName             string  `json:"ownerName" gorm:"-"`
	OwnerAvatarURL        *string `json:"ownerAvatarUrl" gorm:"-"`
	OwnerAvatarColorIndex int     `json:"ownerAvatarColorIndex" gorm:"-"`
	CircleName            string  `json:"circleName" gorm:"-"`
	IsOwnedByCaller       bool    `json:"isOwnedByCaller" gorm:"-"`

	// ShareLevel is the level the caller has: empty for the owner, contribute
	// for a member of the circle that owns the album, and the level it is
	// shared at for anybody else.
	ShareLevel PhotoAlbumShareLevel `json:"shareLevel" gorm:"-"`

	// CanCallerContribute says the caller may add their own photos, and
	// CanCallerManage that they may rename, delete and share the album: its
	// owner, or an admin of the circle that owns it.
	CanCallerContribute bool `json:"canCallerContribute" gorm:"-"`
	CanCallerManage     bool `json:"canCallerManage" gorm:"-"`

	// IsLocationIncluded says the share that reaches the caller lets them see
	// where the album's photos were taken.
	IsLocationIncluded bool `json:"isLocationIncluded" gorm:"-"`
}

PhotoAlbum is a named set of photos. It holds references: a photo can be in several albums, and deleting the album leaves the photos. An album belongs to a person or to a circle; the photos in it belong to whoever added them.

type PhotoAlbumAccess added in v0.171.0

type PhotoAlbumAccess struct {
	PhotoAlbumID string

	// OwnerUserID is the person who owns the album, empty for a circle's
	// album, and CircleID the circle that owns it, empty for a person's.
	OwnerUserID string
	CircleID    string

	// IsOwner says the album is the person's own.
	IsOwner bool

	// ShareLevel is the level the person has: empty for the owner, who has
	// more than any level, PhotoAlbumShareLevelContribute for a member of the
	// circle that owns the album, and the highest of the shares that reach
	// them for another person's.
	ShareLevel PhotoAlbumShareLevel

	// IsManager says the person may rename, delete and share the album: its
	// owner, or an admin of the circle that owns it.
	IsManager bool

	// IsLocationIncluded says a share that reaches the person lets them see
	// where photos were taken. A circle album has no share, so its members see
	// only their own photos' places.
	IsLocationIncluded bool

	// IsFaceNamesIncluded says a share that reaches the person lets them see
	// the names the owner gave the faces in the album's photos.
	IsFaceNamesIncluded bool
}

PhotoAlbumAccess is what one person may do with one album, worked out by the database from who owns the album, the circles they are in and the shares that reach them. It is the one answer every door asks.

func (*PhotoAlbumAccess) CanContribute added in v0.171.0

func (self *PhotoAlbumAccess) CanContribute() bool

CanContribute says the person may add their own photos to the album.

type PhotoAlbumItem added in v0.171.0

type PhotoAlbumItem struct {
	PhotoAlbumID  string    `json:"photoAlbumId"`
	PhotoID       string    `json:"photoId"`
	AddedByUserID string    `json:"addedByUserId"`
	AddedAt       time.Time `json:"addedAt"`
}

PhotoAlbumItem puts a photo in an album.

type PhotoAlbumReference added in v0.171.0

type PhotoAlbumReference struct {
	ID         string `json:"id"`
	AlbumTitle string `json:"albumTitle"`
}

PhotoAlbumReference is the album a photo is in, as the photo says it: enough to name it and to open it.

type PhotoAlbumShare added in v0.171.0

type PhotoAlbumShare struct {
	ID           string `json:"id"`
	PhotoAlbumID string `json:"photoAlbumId"`

	GranteeUserID   string `json:"granteeUserId,omitempty"`
	GranteeCircleID string `json:"granteeCircleId,omitempty"`

	ShareLevel PhotoAlbumShareLevel `json:"shareLevel"`

	// IsLocationIncluded says the people reached see where the album's photos
	// were taken and receive the original files, which carry it.
	IsLocationIncluded bool `json:"isLocationIncluded"`

	// IsFaceNamesIncluded says the people reached see the names the owner gave
	// the faces in the album's photos.
	IsFaceNamesIncluded bool `json:"isFaceNamesIncluded"`

	CreatedAt time.Time `json:"createdAt"`

	// CreatedByUserID is empty once that account is gone.
	CreatedByUserID string `json:"createdByUserId,omitempty"`

	// GranteeUser, GranteeUsername, GranteeName and GranteeCircleName are
	// filled in by the listing, for a screen that says who an album is shared
	// with.
	GranteeUser       *User  `json:"-"`
	GranteeUsername   string `json:"granteeUsername,omitempty"`
	GranteeName       string `json:"granteeName,omitempty"`
	GranteeCircleName string `json:"granteeCircleName,omitempty"`
}

PhotoAlbumShare gives one person, or every member of one circle, a level of access to one album. Exactly one of GranteeUserID and GranteeCircleID is set.

type PhotoAlbumShareLevel added in v0.171.0

type PhotoAlbumShareLevel string

PhotoAlbumShareLevel is what somebody an album is shared with may do with it.

const (
	// PhotoAlbumShareLevelView sees the album's photos and saves them to a
	// library of their own.
	PhotoAlbumShareLevelView PhotoAlbumShareLevel = "view"
	// PhotoAlbumShareLevelContribute also adds photos of their own to the
	// album and takes out the ones they added.
	PhotoAlbumShareLevelContribute PhotoAlbumShareLevel = "contribute"
)

func (PhotoAlbumShareLevel) IsValid added in v0.171.0

func (self PhotoAlbumShareLevel) IsValid() bool

IsValid says whether an album can be shared at this level.

type PhotoAlbumSuggestion added in v0.171.0

type PhotoAlbumSuggestion struct {
	// TakenAfter and TakenBefore bound the run the way a listing's filters do:
	// the first photo is taken on or after the first and the last before the
	// second.
	TakenAfter  time.Time `json:"takenAfter"`
	TakenBefore time.Time `json:"takenBefore"`

	// PlaceNames are the places in the run, the one with most photos first.
	PlaceNames []string `json:"placeNames"`

	// AlbumTitle is a proposal, in English, for the person to change.
	AlbumTitle string `json:"albumTitle"`

	PhotoCount int `json:"photoCount"`

	// SamplePhotoIDs are a few photos spread across the run, to show it by.
	SamplePhotoIDs []string `json:"samplePhotoIds"`
}

PhotoAlbumSuggestion is a run of photos that belong together and are in no album: a trip or an event. Nothing is created from it until somebody asks.

type PhotoBlob added in v0.171.0

type PhotoBlob struct {
	BlobSHA256    string     `json:"blobSha256"`
	BlobSizeBytes int64      `json:"blobSizeBytes"`
	CreatedAt     time.Time  `json:"createdAt"`
	DeletingAt    *time.Time `json:"-"`
}

PhotoBlob is the bytes of a file in the blob store, named by their SHA-256.

type PhotoDocumentKind added in v0.209.0

type PhotoDocumentKind string

PhotoDocumentKind says what kind of document a described picture is.

const (
	PhotoDocumentNone PhotoDocumentKind = "none"
	// PhotoDocumentReceipt is a receipt or an invoice for a purchase.
	PhotoDocumentReceipt PhotoDocumentKind = "receipt"
	// PhotoDocumentStatement is a statement of a bank, card or loan account,
	// or a list of an account's transactions on a screen.
	PhotoDocumentStatement PhotoDocumentKind = "statement"
	// PhotoDocumentTaxDocument is a paystub, a W-2, a 1099 or a 1098.
	PhotoDocumentTaxDocument PhotoDocumentKind = "taxDocument"
	// PhotoDocumentWhiteboard is a picture mostly of a whiteboard or a
	// blackboard, which is transcribed and kept.
	PhotoDocumentWhiteboard PhotoDocumentKind = "whiteboard"
	// PhotoDocumentNotes is a picture mostly of handwriting on paper or in a
	// notebook, which is transcribed and kept.
	PhotoDocumentNotes PhotoDocumentKind = "notes"
	// PhotoDocumentDocument is a picture mostly of a printed or filled-in
	// paper (a form, a letter, a certificate, a record, an ID), which is
	// transcribed and kept.
	PhotoDocumentDocument PhotoDocumentKind = "document"
	// PhotoDocumentPaymentCard is a picture mostly of a payment card. It is
	// recognized so that it is left alone: nothing read from it is stored.
	PhotoDocumentPaymentCard PhotoDocumentKind = "paymentCard"
)

func (PhotoDocumentKind) IsKeptAsDocument added in v0.252.0

func (self PhotoDocumentKind) IsKeptAsDocument() bool

IsKeptAsDocument says a photo of this kind is transcribed and kept as a document of the person's knowledge.

func (PhotoDocumentKind) IsValid added in v0.209.0

func (self PhotoDocumentKind) IsValid() bool

IsValid says whether the server knows this kind.

type PhotoFace added in v0.171.0

type PhotoFace struct {
	ID        string    `json:"id"`
	PhotoID   string    `json:"photoId"`
	UserID    string    `json:"userId"`
	CreatedAt time.Time `json:"createdAt"`

	BoxLeftFraction   float64 `json:"boxLeftFraction"`
	BoxTopFraction    float64 `json:"boxTopFraction"`
	BoxWidthFraction  float64 `json:"boxWidthFraction"`
	BoxHeightFraction float64 `json:"boxHeightFraction"`

	// DetectionScore is how sure the detector was that this is a face, from 0
	// to 1.
	DetectionScore float64 `json:"detectionScore"`

	// FaceVector is 128 numbers of unit length, kept to compare faces by.
	FaceVector []float32 `json:"-"`

	// PhotoFaceGroupID is the group the face is in, empty for a face too
	// small or too uncertain to be grouped. IsGroupConfirmed says the person
	// put it there, or took it out of another group, so it is not grouped
	// again.
	PhotoFaceGroupID string `json:"photoFaceGroupId"`
	IsGroupConfirmed bool   `json:"isGroupConfirmed"`

	// ContactID and ContactName are those of the face's group, empty while
	// the group is unnamed. FacePictureURL is where the face's picture is
	// fetched from. All three are worked out when the face is read.
	// IsOwnContact is set by whoever answers the caller: it says the group's
	// contact is the caller's own (User.ContactID), so the face is them.
	ContactID      string `json:"contactId" gorm:"-"`
	ContactName    string `json:"contactName" gorm:"-"`
	FacePictureURL string `json:"facePictureUrl" gorm:"-"`
	IsOwnContact   bool   `json:"isOwnContact" gorm:"-"`
}

PhotoFace is one face found in a photo. The box is in fractions of the picture from its top left corner, so it means the same on a preview as on the original. The vector the face was grouped by is never sent to a client.

type PhotoFaceGroup added in v0.171.0

type PhotoFaceGroup struct {
	ID        string    `json:"id"`
	UserID    string    `json:"userId"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`

	// ContactID is the contact that names the group, and ContactAddressBookID
	// the address book it is in (a contact is only unique inside its book).
	// Both are empty while the group is unnamed.
	ContactID            string `json:"contactId"`
	ContactAddressBookID string `json:"contactAddressBookId"`

	// ContactName, FaceCount, PhotoCount and FacePictureURL are worked out
	// when the group is read, from the photos that are not in the trash: a
	// face in a trashed photo is not counted until the photo is restored.
	// FacePictureURL is the picture of the group's cover face.
	ContactName    string `json:"contactName"`
	FaceCount      int    `json:"faceCount"`
	PhotoCount     int    `json:"photoCount"`
	FacePictureURL string `json:"facePictureUrl"`

	IsHidden bool `json:"isHidden"`

	// IsOwnContact says the contact that names the group is the caller's own
	// (User.ContactID), so the group is the caller themselves. It is set by
	// whoever answers the caller, and is false for a group nobody named.
	IsOwnContact bool `json:"isOwnContact"`

	// CoverPhotoFaceID is the face the group is shown by; the id of
	// FacePictureURL.
	CoverPhotoFaceID string `json:"coverPhotoFaceId"`

	// AccountUserID and Account say who the group's contact is on this server,
	// when the caller linked it to somebody in their circles and still shares
	// a circle with them. Both are null otherwise. They are the caller's own
	// note and are set by whoever answers the caller.
	AccountUserID *string                `json:"accountUserId"`
	Account       *PhotoFaceGroupAccount `json:"account"`
}

PhotoFaceGroup is the faces the server believes are one person. It is nobody until the person names it by choosing a contact.

type PhotoFaceGroupAccount added in v0.184.0

type PhotoFaceGroupAccount struct {
	UserID           string  `json:"userId"`
	Username         string  `json:"username"`
	Name             string  `json:"name"`
	AvatarURL        *string `json:"avatarUrl"`
	AvatarColorIndex int     `json:"avatarColorIndex"`
}

PhotoFaceGroupAccount is the person a group's contact is linked to, as the circles show them.

type PhotoFile added in v0.171.0

type PhotoFile struct {
	PhotoID          string        `json:"photoId"`
	PhotoFileRole    PhotoFileRole `json:"photoFileRole"`
	BlobSHA256       string        `json:"blobSha256"`
	ContentType      string        `json:"contentType"`
	FileSizeBytes    int64         `json:"fileSizeBytes"`
	OriginalFilename string        `json:"originalFilename"`
	CreatedAt        time.Time     `json:"createdAt"`

	// FileURL is where the owner downloads it; worked out when read.
	FileURL string `json:"fileUrl" gorm:"-"`
}

PhotoFile is one file a photo is made of.

type PhotoFileRole added in v0.171.0

type PhotoFileRole string

PhotoFileRole says which of a photo's files one is.

const (
	PhotoFileRoleOriginal PhotoFileRole = "original"
	// PhotoFileRoleEdited is the version the person made on a phone, which
	// previews are made from in preference to the original.
	PhotoFileRoleEdited    PhotoFileRole = "edited"
	PhotoFileRoleLiveVideo PhotoFileRole = "liveVideo"
)

func (PhotoFileRole) IsValid added in v0.171.0

func (self PhotoFileRole) IsValid() bool

IsValid says whether the server knows this role.

type PhotoKind added in v0.171.0

type PhotoKind string

PhotoKind says what a photo is made of.

const (
	PhotoKindPicture PhotoKind = "picture"
	PhotoKindVideo   PhotoKind = "video"
	// PhotoKindLivePhoto is a picture with a short video that plays when it
	// is pressed; the video is the photo's liveVideo file.
	PhotoKindLivePhoto PhotoKind = "livePhoto"
)

func (PhotoKind) IsValid added in v0.171.0

func (self PhotoKind) IsValid() bool

IsValid says whether the server knows this kind.

type PhotoPreview added in v0.171.0

type PhotoPreview struct {
	PhotoID          string           `json:"photoId"`
	PhotoPreviewSize PhotoPreviewSize `json:"photoPreviewSize"`
	ContentType      string           `json:"contentType"`
	PreviewSizeBytes int64            `json:"previewSizeBytes"`
	WidthPixels      int              `json:"widthPixels"`
	HeightPixels     int              `json:"heightPixels"`
	CreatedAt        time.Time        `json:"createdAt"`

	// PreviewURL is where the owner fetches it; worked out when read.
	PreviewURL string `json:"previewUrl" gorm:"-"`
}

PhotoPreview is one smaller copy made of a photo.

type PhotoPreviewSize added in v0.171.0

type PhotoPreviewSize string

PhotoPreviewSize names one of the smaller copies made of a photo.

const (
	// PhotoPreviewSmall is at most 400 pixels on the long side.
	PhotoPreviewSmall PhotoPreviewSize = "small"
	// PhotoPreviewLarge is at most 2048 pixels on the long side.
	PhotoPreviewLarge PhotoPreviewSize = "large"
	// PhotoPreviewVideo is a video every browser plays: H.264, at most 1280.
	PhotoPreviewVideo PhotoPreviewSize = "video"
)

func (PhotoPreviewSize) IsValid added in v0.171.0

func (self PhotoPreviewSize) IsValid() bool

IsValid says whether the server knows this size.

type PhotoProcessingState added in v0.171.0

type PhotoProcessingState string

PhotoProcessingState is where a photo is on its way to having previews and the metadata read from its file.

const (
	PhotoProcessingWaiting PhotoProcessingState = "waiting"
	PhotoProcessingReady   PhotoProcessingState = "ready"
	PhotoProcessingFailed  PhotoProcessingState = "failed"
)

type PhotoSource added in v0.171.0

type PhotoSource string

PhotoSource says where a photo came from.

const (
	PhotoSourceIPhone       PhotoSource = "iphone"
	PhotoSourceAndroid      PhotoSource = "android"
	PhotoSourceDashboard    PhotoSource = "dashboard"
	PhotoSourceCommandLine  PhotoSource = "commandLine"
	PhotoSourceConversation PhotoSource = "conversation"
	PhotoSourceMail         PhotoSource = "mail"
	PhotoSourceComputer     PhotoSource = "computer"
	// PhotoSourceShared is a photo somebody else shared and the person saved
	// to their own library.
	PhotoSourceShared PhotoSource = "shared"
)

func (PhotoSource) IsValid added in v0.171.0

func (self PhotoSource) IsValid() bool

IsValid says whether the server knows this source.

type PhotoUpload added in v0.171.0

type PhotoUpload struct {
	ID                string           `json:"id"`
	UserID            string           `json:"userId"`
	CreatedAt         time.Time        `json:"createdAt"`
	UpdatedAt         time.Time        `json:"updatedAt"`
	PhotoUploadState  PhotoUploadState `json:"photoUploadState"`
	DeclaredSizeBytes *int64           `json:"declaredSizeBytes" graphapi:"nullable"`
	ReceivedSizeBytes int64            `json:"receivedSizeBytes"`
	// PartCount is how many parts have a receipt, which is also the index the
	// next part is stored under.
	PartCount          int                `json:"partCount"`
	PhotoUploadHeaders PhotoUploadHeaders `json:"photoUploadHeaders" gorm:"column:upload_headers;serializer:json"`
	// PhotoID is the photo the upload became, once it is complete.
	PhotoID *string `json:"photoId" graphapi:"nullable"`
}

PhotoUpload is a file on its way in, received in parts.

type PhotoUploadHeaders added in v0.171.0

type PhotoUploadHeaders struct {
	ClientPhotoID        string        `json:"clientPhotoId"`
	PhotoFileRole        PhotoFileRole `json:"photoFileRole"`
	PhotoKind            PhotoKind     `json:"photoKind"`
	PhotoSource          PhotoSource   `json:"photoSource"`
	OriginalFilename     string        `json:"originalFilename"`
	ContentType          string        `json:"contentType"`
	TakenAt              *time.Time    `json:"takenAt,omitempty"`
	TakenAtOffsetMinutes *int          `json:"takenAtOffsetMinutes,omitempty"`
	Latitude             *float64      `json:"latitude,omitempty"`
	Longitude            *float64      `json:"longitude,omitempty"`
	IsFavorite           bool          `json:"isFavorite"`
	IsScreenshot         bool          `json:"isScreenshot"`
	DeclaredSHA256       string        `json:"declaredSha256,omitempty"`
}

PhotoUploadHeaders is what the first request of an upload said the file is. Kept with the upload because the request that completes it may be a later one, and may say nothing of this.

type PhotoUploadPart added in v0.171.0

type PhotoUploadPart struct {
	PhotoUploadID string    `json:"photoUploadId"`
	PartIndex     int       `json:"partIndex"`
	PartSizeBytes int64     `json:"partSizeBytes"`
	PartSHA256    string    `json:"partSha256"`
	StoredAt      time.Time `json:"storedAt"`
}

PhotoUploadPart is a receipt for one whole stored part of an upload.

type PhotoUploadState added in v0.171.0

type PhotoUploadState string

PhotoUploadState is where a resumable upload is.

const (
	PhotoUploadReceiving PhotoUploadState = "receiving"
	PhotoUploadComplete  PhotoUploadState = "complete"
	PhotoUploadFailed    PhotoUploadState = "failed"
)

type Place added in v0.175.0

type Place struct {
	ID     string `json:"id"`
	UserID string `json:"userId"`

	// PlaceName is what the person sees: the name they gave it, otherwise
	// the OpenStreetMap name, otherwise the street address, otherwise the
	// city.
	PlaceName string `json:"placeName"`

	// IsNamedByPerson is whether PlaceName is the person's own, which no
	// later answer from OpenStreetMap replaces.
	IsNamedByPerson bool `json:"isNamedByPerson"`

	// PlaceLabel is empty for a place with no label.
	PlaceLabel PlaceLabel `json:"placeLabel"`

	LatitudeDegrees  float64 `json:"latitudeDegrees"`
	LongitudeDegrees float64 `json:"longitudeDegrees"`
	RadiusMeters     float64 `json:"radiusMeters"`

	// OSMType is node, way or relation, or empty when no OpenStreetMap
	// object was found. OSMID is zero then.
	OSMType     string `json:"osmType,omitempty"`
	OSMID       int64  `json:"osmId,omitempty"`
	OSMName     string `json:"osmName,omitempty"`
	OSMCategory string `json:"osmCategory,omitempty"`
	AddressText string `json:"addressText,omitempty"`

	// IsAddressTyped is whether AddressText is one the person typed, which
	// moving the place keeps and no answer from OpenStreetMap replaces.
	IsAddressTyped bool `json:"isAddressTyped"`

	// NamedAt is when the provider answered, whatever it answered, and nil
	// while the place waits for a name. NamingClaimedAt is when an instance
	// took the place to name. NamingErrorMessage says why the last try failed.
	NamedAt            *time.Time `json:"namedAt,omitempty"`
	NamingClaimedAt    *time.Time `json:"namingClaimedAt,omitempty"`
	NamingErrorMessage string     `json:"namingErrorMessage,omitempty"`

	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`

	// VisitCount and LastVisitAt are filled in by the listing of places.
	VisitCount  int        `json:"visitCount"`
	LastVisitAt *time.Time `json:"lastVisitAt,omitempty"`
}

Place is somewhere with a name and a radius, belonging to one person.

type PlaceLabel added in v0.175.0

type PlaceLabel string

PlaceLabel is what a place means to its person, from a short fixed list. A name cannot be acted on and a label can: it puts an icon on the map, and it is what "at home" and "at work" mean to the agent wherever those are. The empty label is a place that means nothing in particular.

const (
	PlaceLabelHome   PlaceLabel = "home"
	PlaceLabelWork   PlaceLabel = "work"
	PlaceLabelSchool PlaceLabel = "school"
	// PlaceLabelFamily is somebody else's home that the person visits.
	PlaceLabelFamily PlaceLabel = "family"
	PlaceLabelGym    PlaceLabel = "gym"
)

The labels.

func (PlaceLabel) IsValid added in v0.175.0

func (self PlaceLabel) IsValid() bool

IsValid reports whether this is one of the labels. The empty label is not: it is the absence of one, and callers that accept it say so.

type PlaceVisit added in v0.175.0

type PlaceVisit struct {
	ID      string `json:"id"`
	UserID  string `json:"userId"`
	PlaceID string `json:"placeId"`

	// ArrivedAt is nil when iOS reported a departure whose arrival it did not
	// see. DepartedAt is nil while the person is still there.
	ArrivedAt  *time.Time `json:"arrivedAt,omitempty"`
	DepartedAt *time.Time `json:"departedAt,omitempty"`

	LatitudeDegrees  float64 `json:"latitudeDegrees"`
	LongitudeDegrees float64 `json:"longitudeDegrees"`
	AccuracyMeters   float64 `json:"accuracyMeters"`

	VisitSource VisitSource `json:"visitSource"`

	// ClientVisitKey is what the phone calls the visit, so that a report sent
	// twice is one visit. A visit recorded by hand is given one.
	ClientVisitKey string `json:"clientVisitKey"`

	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`

	// Place is filled in by the listing of visits.
	Place *Place `json:"place,omitempty"`
}

PlaceVisit is one visit to a place.

type Pronoun added in v0.178.0

type Pronoun string

Pronoun is how a person is described: he, she or they. A person says it of themselves; nobody else sets it. It is what their side of a relationship is worded with ("son" rather than "child"), and how their agent speaks of them. Empty is not said yet, and reads as they.

const (
	PronounHe   Pronoun = "he"
	PronounShe  Pronoun = "she"
	PronounThey Pronoun = "they"
)

The pronouns.

func (Pronoun) IsValid added in v0.178.0

func (self Pronoun) IsValid() bool

IsValid reports whether this is one of the pronouns.

func (Pronoun) TermGender added in v0.178.0

func (self Pronoun) TermGender() TermGender

TermGender is the gender of the words for a person described this way: neutral until they say.

type RateSource added in v0.87.0

type RateSource string

RateSource is who published an exchange rate.

const RateSourceECB RateSource = "ecb"

RateSourceECB is the European Central Bank's daily euro reference rates, the one source today.

func (RateSource) IsValid added in v0.87.0

func (self RateSource) IsValid() bool

IsValid says the source is a known one.

type ReachableAddressBook added in v0.194.0

type ReachableAddressBook struct {
	Book       *AddressBook
	CircleName string
	Access     AddressBookAccess
}

ReachableAddressBook is an address book a person can use with what they may do with it, and the name of the circle when it is a circle's.

type ReachableCalendar added in v0.170.0

type ReachableCalendar struct {
	Calendar *Calendar

	// ShareLevel is what the person may do with it, ShareLevelOwner for their
	// own.
	ShareLevel ShareLevel

	// OwnerUserID and Owner say whose it is; empty and nil for a circle's
	// calendar.
	OwnerUserID string
	Owner       *User

	// CircleName is the circle's name for a circle calendar.
	CircleName string
}

ReachableCalendar is a calendar as one person reaches it: their own, a circle's they are in, or another person's shared with them.

type ReachedAllFinance added in v0.210.0

type ReachedAllFinance struct {
	OwnerUserID   string
	OwnerUsername string
	OwnerName     string

	FinanceShareLevel FinanceShareLevel
}

ReachedAllFinance is a person's whole finance as somebody else reaches it: whose it is and the highest level of the shares of all their finance that reach the reader. The reader is never told which accounts it covers.

type ReachedFinanceAccount added in v0.194.0

type ReachedFinanceAccount struct {
	Account *FinanceAccount

	// ProviderKind is what the account's finance source signs in through,
	// which says which way a credit card's balance is signed.
	ProviderKind string

	FinanceShareLevel FinanceShareLevel

	OwnerUserID   string
	OwnerUsername string
	OwnerName     string
}

ReachedFinanceAccount is a finance account as a person other than its owner reaches it: the account as stored and the level at which it is shared with them. The account holds more than any level shows; the one place that builds what a reader sees from it is the API's describeSharedFinanceAccount.

type ReceiptCheckState added in v0.118.0

type ReceiptCheckState string

ReceiptCheckState is whether a receipt's lines add up to its printed totals.

const (
	ReceiptCheckStateBalanced   ReceiptCheckState = "balanced"
	ReceiptCheckStateUnbalanced ReceiptCheckState = "unbalanced"
)

Balanced: every line comes to the total, to the cent, and when a subtotal is printed the items and discounts come to it, with the fees or without them (a receipt prints its fees before the subtotal or after it). Unbalanced: they miss, by CheckDifferenceAmount.

func (ReceiptCheckState) IsValid added in v0.118.0

func (self ReceiptCheckState) IsValid() bool

IsValid says the state is one of the two.

type ReceiptLineKind added in v0.118.0

type ReceiptLineKind string

ReceiptLineKind is what one printed line of a receipt is.

const (
	ReceiptLineKindItem     ReceiptLineKind = "item"
	ReceiptLineKindDiscount ReceiptLineKind = "discount"
	ReceiptLineKindTax      ReceiptLineKind = "tax"
	ReceiptLineKindFee      ReceiptLineKind = "fee"
	ReceiptLineKindTip      ReceiptLineKind = "tip"
)

An item bought, a discount (negative, as printed), a tax, a fee (a bag, a delivery) or a tip.

func (ReceiptLineKind) IsValid added in v0.118.0

func (self ReceiptLineKind) IsValid() bool

IsValid says the kind is one of the five.

type ReceiptMatchSource added in v0.118.0

type ReceiptMatchSource string

ReceiptMatchSource is what matched a receipt to a finance transaction.

const (
	ReceiptMatchSourceReceiptMatcher ReceiptMatchSource = "receipt_matcher"
	ReceiptMatchSourcePerson         ReceiptMatchSource = "person"
)

The receipt matcher, which matches only an exact amount that is the one candidate, or the person (or their agent asked by them), whose match the matcher never removes or replaces.

func (ReceiptMatchSource) IsValid added in v0.118.0

func (self ReceiptMatchSource) IsValid() bool

IsValid says the source is one of the two.

type ReceiptMatchState added in v0.201.0

type ReceiptMatchState string

ReceiptMatchState is what became of a receipt line tied to a shopping item.

const (
	// ReceiptMatchStateApplied checked the item off and wrote its price.
	ReceiptMatchStateApplied ReceiptMatchState = "applied"

	// ReceiptMatchStateProposed is a match the matcher was unsure of, left
	// for a person to apply or dismiss.
	ReceiptMatchStateProposed ReceiptMatchState = "proposed"

	// ReceiptMatchStateDismissed was undone or refused, and is never
	// proposed again.
	ReceiptMatchStateDismissed ReceiptMatchState = "dismissed"
)

type ReceiptSourceKind added in v0.118.0

type ReceiptSourceKind string

ReceiptSourceKind is where a finance receipt was read from.

const (
	ReceiptSourceKindMail         ReceiptSourceKind = "mail"
	ReceiptSourceKindGmailMessage ReceiptSourceKind = "gmail_message"
	ReceiptSourceKindAttachment   ReceiptSourceKind = "attachment"
)

A message stored here (the mail row, which keeps its id as the person files it from folder to folder), a Gmail message the agent read through the Gmail skill, or a photo or PDF uploaded as an agent attachment.

func (ReceiptSourceKind) IsValid added in v0.118.0

func (self ReceiptSourceKind) IsValid() bool

IsValid says the kind is one of the three.

type Recording added in v0.140.0

type Recording struct {
	ID                    string                `json:"id"`
	UserID                string                `json:"userId"`
	CreatedAt             time.Time             `json:"createdAt"`
	RecordedAt            *time.Time            `json:"recordedAt" graphapi:"nullable"`
	UpdatedAt             time.Time             `json:"updatedAt"`
	ClientRecordingID     string                `json:"clientRecordingId"`
	RecordingTitle        string                `json:"recordingTitle"`
	RecordingTitleSource  RecordingTitleSource  `json:"recordingTitleSource"`
	RecordingSummary      string                `json:"recordingSummary"`
	RecordingOrigin       RecordingOrigin       `json:"recordingOrigin"`
	RecordingCaptureState RecordingCaptureState `json:"recordingCaptureState"`
	TimelineDurationMS    int64                 `json:"timelineDurationMS"`
	CaptureGaps           []RecordingGap        `json:"captureGaps"`
	SourceGeneration      int64                 `json:"sourceGeneration"`
	// ChatCallID is the call in a chat the recording was made from, when it
	// was: a transcribed call is a recording owned by whoever turned
	// transcription on.
	ChatCallID string     `json:"chatCallId,omitempty"`
	DeletedAt  *time.Time `json:"-"`
}

Recording is an account-owned evidence source, never a conversation turn.

type RecordingAttemptState added in v0.141.0

type RecordingAttemptState string

RecordingAttemptState distinguishes a rejected call from an unknown remote outcome.

const (
	RecordingAttemptPrepared  RecordingAttemptState = "prepared"
	RecordingAttemptSubmitted RecordingAttemptState = "submitted"
	RecordingAttemptComplete  RecordingAttemptState = "complete"
	RecordingAttemptFailed    RecordingAttemptState = "failed"
	RecordingAttemptUncertain RecordingAttemptState = "uncertain"
)

type RecordingAudioChunk added in v0.141.0

type RecordingAudioChunk struct {
	ID                       string `json:"id"`
	RecordingTranscriptRunID string `json:"recordingTranscriptRunId"`
	RecordingBlobID          string `json:"recordingBlobId"`
	ChunkIndex               int    `json:"chunkIndex"`
	TimelineStartMS          int64  `json:"timelineStartMS"`
	AudioDurationMS          int64  `json:"audioDurationMS"`
}

RecordingAudioChunk is a bounded derived WAV on the original media timeline.

type RecordingBlob added in v0.141.0

type RecordingBlob struct {
	ID                   string               `json:"id"`
	RecordingID          string               `json:"recordingId"`
	RecordingMediaID     string               `json:"recordingMediaId"`
	CreatedAt            time.Time            `json:"createdAt"`
	RecordingBlobPurpose RecordingBlobPurpose `json:"recordingBlobPurpose"`
	BlobSizeBytes        int64                `json:"blobSizeBytes"`
	BlobSHA256           string               `json:"blobSha256"`
	IsStoredVerified     bool                 `json:"isStoredVerified"`
}

RecordingBlob retains a cleanup reference before any derived byte is written.

type RecordingBlobPurpose added in v0.141.0

type RecordingBlobPurpose string

RecordingBlobPurpose identifies derived bytes that must share source deletion.

const (
	RecordingBlobAudio            RecordingBlobPurpose = "audio"
	RecordingBlobSpeakerReference RecordingBlobPurpose = "speakerReference"
	RecordingBlobAudioPreview     RecordingBlobPurpose = "audioPreview"
)

type RecordingCaptureState added in v0.140.0

type RecordingCaptureState string

RecordingCaptureState describes capture independently of processing.

const (
	RecordingCaptureActive      RecordingCaptureState = "active"
	RecordingCapturePaused      RecordingCaptureState = "paused"
	RecordingCaptureInterrupted RecordingCaptureState = "interrupted"
	RecordingCaptureStopped     RecordingCaptureState = "stopped"
	RecordingCaptureImported    RecordingCaptureState = "imported"
)

type RecordingDisclosure added in v0.194.0

type RecordingDisclosure struct {
	Recording    *Recording
	Owner        *User
	SpeakerNames []string

	// Passages are the owner's own projection of a page of the transcript:
	// the words and the speakers as the owner reads them.
	Passages      []*RecordingTranscriptSegment
	PassageOffset int64
	PassageCount  int64
}

RecordingDisclosure is what the owner's recording yields for a reader, before RedactRecording keeps what the reader's level allows. It is read whole, with the owner's own projections, so that redaction is the one place that decides what leaves.

type RecordingGap added in v0.140.0

type RecordingGap struct {
	GapID              string             `json:"gapId"`
	GapStartMS         int64              `json:"gapStartMS"`
	GapEndMS           int64              `json:"gapEndMS"`
	RecordingGapReason RecordingGapReason `json:"recordingGapReason"`
}

RecordingGap preserves a pause or microphone interruption on the source timeline.

type RecordingGapReason added in v0.140.0

type RecordingGapReason string

RecordingGapReason identifies a deliberate pause or an audio interruption.

const (
	RecordingGapPaused      RecordingGapReason = "paused"
	RecordingGapInterrupted RecordingGapReason = "interrupted"
)

type RecordingLearningView added in v0.144.0

type RecordingLearningView struct {
	SourceGeneration              int64                 `json:"sourceGeneration"`
	HasAgent                      bool                  `json:"hasAgent"`
	HasStoppedReading             bool                  `json:"hasStoppedReading"`
	KnowledgeSource               *AgentKnowledgeSource `json:"knowledgeSource" graphapi:"nullable"`
	PendingDocumentCount          int64                 `json:"pendingDocumentCount"`
	DigestedDocumentCount         int64                 `json:"digestedDocumentCount"`
	LastPublishedSourceGeneration int64                 `json:"lastPublishedSourceGeneration"`
	IsCurationPending             bool                  `json:"isCurationPending"`
}

RecordingLearningView exposes existing ingestion and digest bookkeeping for retained evidence. A digested passage has been processed; the count does not establish useful memories.

type RecordingLiveUtterance added in v0.154.0

type RecordingLiveUtterance struct {
	ID               string    `json:"id"`
	RecordingID      string    `json:"recordingId"`
	CreatedAt        time.Time `json:"createdAt"`
	UtteranceID      string    `json:"utteranceId"`
	UtteranceStartMS int64     `json:"utteranceStartMS"`
	UtteranceEndMS   int64     `json:"utteranceEndMS"`
	TranscriptText   string    `json:"transcriptText"`
}

RecordingLiveUtterance is something said during a capture, heard by the provider's streaming transcription before the saved audio has been transcribed. It has no speaker, and it is shown only until a completed speaker-separated run covers its time. The text is the provider's, so it is data, never an instruction.

type RecordingMedia added in v0.140.0

type RecordingMedia struct {
	ID                   string               `json:"id"`
	RecordingID          string               `json:"recordingId"`
	CreatedAt            time.Time            `json:"createdAt"`
	ClientMediaID        string               `json:"clientMediaId"`
	OriginalFilename     string               `json:"originalFilename"`
	OriginalContentType  string               `json:"originalContentType"`
	OriginalSizeBytes    int64                `json:"originalSizeBytes"`
	OriginalSHA256       string               `json:"originalSha256"`
	TimelineStartMS      int64                `json:"timelineStartMS"`
	MediaDurationMS      int64                `json:"mediaDurationMS"`
	PartCount            int                  `json:"partCount"`
	RecordingUploadState RecordingUploadState `json:"recordingUploadState"`
	CleanupNextPartIndex int                  `json:"-"`
	VerifiedAt           *time.Time           `json:"verifiedAt"`
	// SpeakerUserID and SpeakerName name the one person an original is the
	// microphone of (a call's track), so its transcript needs no guessing
	// who spoke; both are empty for an original of several voices.
	SpeakerUserID string `json:"speakerUserId,omitempty"`
	SpeakerName   string `json:"speakerName,omitempty"`
}

RecordingMedia represents original bytes through immutable ordered blob parts.

func (*RecordingMedia) HasKnownSpeaker added in v0.212.0

func (self *RecordingMedia) HasKnownSpeaker() bool

HasKnownSpeaker says the original is one named person's voice.

func (*RecordingMedia) PartSizeBytes added in v0.140.0

func (self *RecordingMedia) PartSizeBytes(partIndex int) int64

PartSizeBytes is the exact size of a part, including a shorter final part.

type RecordingMediaPart added in v0.140.0

type RecordingMediaPart struct {
	RecordingMediaID string    `json:"recordingMediaId"`
	PartIndex        int       `json:"partIndex"`
	PartSizeBytes    int64     `json:"partSizeBytes"`
	PartSHA256       string    `json:"partSha256"`
	StoredAt         time.Time `json:"storedAt"`
}

RecordingMediaPart is a durable upload receipt for one immutable part.

type RecordingOrigin added in v0.140.0

type RecordingOrigin string

RecordingOrigin distinguishes local capture from imported original media.

const (
	RecordingOriginCapture     RecordingOrigin = "capture"
	RecordingOriginAudioImport RecordingOrigin = "audioImport"
	RecordingOriginVideoImport RecordingOrigin = "videoImport"
)

type RecordingPlayback added in v0.147.0

type RecordingPlayback struct {
	RecordingMediaID    string `json:"recordingMediaId"`
	PlaybackPath        string `json:"playbackPath"`
	PlaybackContentType string `json:"playbackContentType"`
	PlaybackSizeBytes   int64  `json:"playbackSizeBytes"`
	PlaybackSHA256      string `json:"playbackSha256"`
	PlaybackDurationMS  int64  `json:"playbackDurationMS"`
	TimelineStartMS     int64  `json:"timelineStartMS"`
}

RecordingPlayback describes an owned audio preview, never an original receipt.

type RecordingProcessingState added in v0.141.0

type RecordingProcessingState string

RecordingProcessingState describes one immutable transcript version's progress.

const (
	RecordingProcessingQueued       RecordingProcessingState = "queued"
	RecordingProcessingPreparing    RecordingProcessingState = "preparing"
	RecordingProcessingTranscribing RecordingProcessingState = "transcribing"
	RecordingProcessingComplete     RecordingProcessingState = "complete"
	RecordingProcessingFailed       RecordingProcessingState = "failed"
	RecordingProcessingUncertain    RecordingProcessingState = "uncertain"
	RecordingProcessingCanceled     RecordingProcessingState = "canceled"
)

type RecordingReferenceInvalidation added in v0.144.0

type RecordingReferenceInvalidation struct {
	ID                              string    `json:"id"`
	RecordingID                     string    `json:"recordingId"`
	RecordingTranscriptRunID        string    `json:"recordingTranscriptRunId"`
	RecordingTranscriptionAttemptID string    `json:"recordingTranscriptionAttemptId"`
	ReferenceBlobID                 string    `json:"referenceBlobId"`
	ReferenceRecordingID            string    `json:"referenceRecordingId"`
	ReferenceTranscriptRunID        string    `json:"referenceTranscriptRunId"`
	SpeakerIdentityID               string    `json:"speakerIdentityId"`
	InvalidatedConfirmedName        string    `json:"invalidatedConfirmedName"`
	ReferencePassageStartMS         int64     `json:"referencePassageStartMS"`
	ReferencePassageEndMS           int64     `json:"referencePassageEndMS"`
	ReferenceSourceGeneration       int64     `json:"referenceSourceGeneration"`
	InvalidationMessage             string    `json:"invalidationMessage"`
	CreatedAt                       time.Time `json:"createdAt"`
	IsReconciled                    bool      `json:"isReconciled"`
}

RecordingReferenceInvalidation preserves changed conditioning provenance without rewriting generated speech.

type RecordingShare added in v0.194.0

type RecordingShare struct {
	ID          string `json:"id"`
	RecordingID string `json:"recordingId"`

	GranteeUserID   string `json:"granteeUserId,omitempty"`
	GranteeCircleID string `json:"granteeCircleId,omitempty"`

	RecordingShareLevel RecordingShareLevel `json:"recordingShareLevel"`

	CreatedAt time.Time `json:"createdAt"`

	// CreatedByUserID is empty once that account is gone.
	CreatedByUserID string `json:"createdByUserId,omitempty"`

	// The rest is filled in by the listings. RecordingTitle is the
	// recording's, and OwnerUserID, OwnerUsername and OwnerName say whose it
	// is, for a screen that lists what was shared with somebody. The grantee's
	// are for a screen that says who a recording is shared with.
	RecordingTitle    string `json:"recordingTitle,omitempty"`
	OwnerUserID       string `json:"ownerUserId,omitempty"`
	OwnerUsername     string `json:"ownerUsername,omitempty"`
	OwnerName         string `json:"ownerName,omitempty"`
	OwnerUser         *User  `json:"-"`
	GranteeUsername   string `json:"granteeUsername,omitempty"`
	GranteeName       string `json:"granteeName,omitempty"`
	GranteeCircleName string `json:"granteeCircleName,omitempty"`
}

RecordingShare gives one person, or every member of one circle, a level of access to one recording. Exactly one of GranteeUserID and GranteeCircleID is set.

type RecordingShareLevel added in v0.194.0

type RecordingShareLevel string

RecordingShareLevel is how much of a recording somebody may read. A person shares a recording with one person in a circle they share, or with a circle, at one of the two. Neither gives the audio, a voice sample, or the contact the owner tied a speaker's name to.

const (
	// RecordingShareLevelSummary is the title, the date, the length, the
	// generated summary and the names of the speakers the owner confirmed.
	RecordingShareLevelSummary RecordingShareLevel = "summary"

	// RecordingShareLevelTranscript is the summary, and the transcript as the
	// owner reads it: the latest completed version of each original with the
	// owner's corrections to the words and to who spoke.
	RecordingShareLevelTranscript RecordingShareLevel = "transcript"
)

The levels, from least to most.

func HighestRecordingShareLevel added in v0.194.0

func HighestRecordingShareLevel(first, second RecordingShareLevel) RecordingShareLevel

HighestRecordingShareLevel is the greater of two levels, so that a person reached by both a direct share and a circle's takes the better of them.

func ParseRecordingShareLevel added in v0.194.0

func ParseRecordingShareLevel(text string) (RecordingShareLevel, bool)

ParseRecordingShareLevel reads the word somebody typed, ignoring case and spaces. The second answer is false for anything that is not a level that can be given.

func (RecordingShareLevel) AtLeast added in v0.194.0

func (self RecordingShareLevel) AtLeast(other RecordingShareLevel) bool

AtLeast reports whether this level reaches the other.

func (RecordingShareLevel) IsGrantable added in v0.194.0

func (self RecordingShareLevel) IsGrantable() bool

IsGrantable reports whether a share may be made at this level.

func (RecordingShareLevel) Rank added in v0.194.0

func (self RecordingShareLevel) Rank() int

Rank orders the levels; zero is no access at all.

type RecordingSpeakerCorrection added in v0.144.0

type RecordingSpeakerCorrection struct {
	ID                              string    `json:"id"`
	RecordingID                     string    `json:"recordingId"`
	RecordingMediaID                string    `json:"recordingMediaId"`
	RecordingTranscriptionAttemptID string    `json:"recordingTranscriptionAttemptId"`
	SpeakerIdentityID               string    `json:"speakerIdentityId"`
	ClientCorrectionID              string    `json:"clientCorrectionId"`
	LocalSpeakerID                  string    `json:"localSpeakerId"`
	PassageStartMS                  int64     `json:"passageStartMS"`
	PassageEndMS                    int64     `json:"passageEndMS"`
	SourceGeneration                int64     `json:"sourceGeneration"`
	CreatedAt                       time.Time `json:"createdAt"`
	IsRemoved                       bool      `json:"isRemoved"`
}

RecordingSpeakerCorrection preserves a confirmed time interval independently of generated versions.

type RecordingSpeakerIdentity added in v0.144.0

type RecordingSpeakerIdentity struct {
	ID            string `json:"id"`
	UserID        string `json:"-"`
	ConfirmedName string `json:"confirmedName"`
	// IsAccountOwner marks the identity that is the person themselves, at most one per account.
	IsAccountOwner bool      `json:"isAccountOwner"`
	CreatedAt      time.Time `json:"createdAt"`
	// ContactAddressBookID and ContactID name the contact of the person's
	// address books that this name is, both empty for a name not tied to one.
	// The person ties a name to a contact; it is never made silently.
	ContactAddressBookID string `json:"contactAddressBookId" gorm:"column:contact_addressbook_id;default:null"`
	ContactID            string `json:"contactId" gorm:"column:contact_id;default:null"`
	// ContactName is that contact's name, read from the contact when the
	// identities are listed and never stored; empty when the name is not tied.
	ContactName string `json:"contactName" gorm:"-"`
}

RecordingSpeakerIdentity is an account-owned name confirmed by the person.

type RecordingTemporarySpeaker added in v0.154.0

type RecordingTemporarySpeaker struct {
	ID                   string `json:"-"`
	RecordingID          string `json:"-"`
	SpeakerLabel         string `json:"speakerLabel"`
	RecordingBlobID      string `json:"-"`
	SourceAttemptID      string `json:"-"`
	SourceLocalSpeakerID string `json:"-"`
	PassageStartMS       int64  `json:"-"`
	PassageEndMS         int64  `json:"-"`
	// SpeakerIdentityID is the confirmed identity once the person has named this speaker.
	SpeakerIdentityID string    `json:"speakerIdentityId"`
	CreatedAt         time.Time `json:"-"`
	// MergedIntoTemporarySpeakerID is the speaker this label was found to be
	// the voice of, when the provider said so; empty for a label that stands on its own.
	MergedIntoTemporarySpeakerID string `json:"-"`
	// MergedIntoSpeakerLabel is the label of that speaker, filled when listed
	// for the timeline, so a reader finds every merge on its first page.
	MergedIntoSpeakerLabel string `json:"mergedIntoSpeakerLabel" gorm:"-"`
	// MergeCheckedAt is when the provider was asked whether this label is an
	// earlier one, set whether or not it said so, so each label is asked once.
	MergeCheckedAt *time.Time `json:"-"`
	// LastHeardEndMS is the timeline millisecond this speaker was last heard, filled when listed.
	LastHeardEndMS int64 `json:"-" gorm:"-"`
	// SpokenMS is how long this speaker has spoken in the recording so far, filled when listed.
	SpokenMS int64 `json:"-" gorm:"-"`
}

RecordingTemporarySpeaker is a speaker of one recording that is still being captured, called "Speaker 1", "Speaker 2" and so on, until the person names it. Its voice sample is sent with later pieces of the same recording so the provider gives the same label again; the sample is never sent for another recording.

type RecordingTitleSource added in v0.153.0

type RecordingTitleSource string

RecordingTitleSource says who wrote a recording's title, which decides whether generating a new one may replace it.

const (
	// RecordingTitleSourceNone means the recording has no title yet.
	RecordingTitleSourceNone RecordingTitleSource = "none"
	// RecordingTitleSourceGenerated means the server named it from the transcript.
	RecordingTitleSourceGenerated RecordingTitleSource = "generated"
	// RecordingTitleSourceUser means the person typed it, and it is never replaced.
	RecordingTitleSourceUser RecordingTitleSource = "user"
)

type RecordingTranscriptRun added in v0.141.0

type RecordingTranscriptRun struct {
	ID                       string                   `json:"id"`
	RecordingID              string                   `json:"recordingId"`
	RecordingMediaID         string                   `json:"recordingMediaId"`
	AgentID                  string                   `json:"-"`
	CreatedAt                time.Time                `json:"createdAt"`
	UpdatedAt                time.Time                `json:"updatedAt"`
	ClientRunID              string                   `json:"clientRunId"`
	VersionNumber            int                      `json:"versionNumber"`
	RecordingProcessingState RecordingProcessingState `json:"recordingProcessingState"`
	ProviderModelName        string                   `json:"providerModelName"`
	OriginalSHA256           string                   `json:"originalSha256"`
	DerivedDurationMS        int64                    `json:"derivedDurationMS"`
	ProcessingErrorMessage   string                   `json:"processingErrorMessage"`
	IsReprocessingRequested  bool                     `json:"isReprocessingRequested"`
	CompletedAt              *time.Time               `json:"completedAt"`
	// HandoffStartMS is the timeline millisecond the second look at the end of
	// the previous piece of a capture starts at, set when speech ran across the
	// cut between them. That audio is a chunk of this version after the
	// piece's own, and the previous piece's passages from this millisecond on
	// are replaced by the ones read there.
	HandoffStartMS *int64 `json:"handoffStartMS"`
	// PublishedAt is when this version was stitched to the piece before it
	// and its passages became final for the piece after it to read. A version
	// can be published well before it is complete, because the second pass over
	// its words comes between the two. Empty on a version that has not been
	// stitched, and on every version from before this was kept; those are final
	// once complete.
	PublishedAt *time.Time `json:"-"`
	// SegmentCount is how many passages the version holds, filled when runs are
	// listed, so a client can tell a complete version with no speech from one with some.
	SegmentCount int64 `json:"segmentCount" gorm:"-"`
}

RecordingTranscriptRun is one version; explicit reprocessing creates a new one.

type RecordingTranscriptSegment added in v0.141.0

type RecordingTranscriptSegment struct {
	ID                              string `json:"id"`
	RecordingTranscriptRunID        string `json:"recordingTranscriptRunId"`
	RecordingTranscriptionAttemptID string `json:"recordingTranscriptionAttemptId"`
	LocalSpeakerID                  string `json:"localSpeakerId"`
	SegmentStartMS                  int64  `json:"segmentStartMS"`
	SegmentEndMS                    int64  `json:"segmentEndMS"`
	TranscriptText                  string `json:"transcriptText"`
	// AccurateTranscriptText is what the plain transcription model heard in
	// this segment's span on a second pass, empty when that pass did not run.
	// It replaces TranscriptText as the words a person's correction and the
	// glossary start from; speakers and times are the first pass's.
	AccurateTranscriptText      string               `json:"accurateTranscriptText"`
	EffectiveTranscriptText     string               `json:"effectiveTranscriptText" gorm:"-"`
	AppliedTextCorrectionID     string               `json:"appliedTextCorrectionId" gorm:"-"`
	AppliedTextCorrectionOrigin TextCorrectionOrigin `json:"appliedTextCorrectionOrigin" gorm:"-"`
	HasUnalignedTextCorrection  bool                 `json:"hasUnalignedTextCorrection" gorm:"-"`
	EffectiveSpeakerIdentityID  string               `json:"effectiveSpeakerIdentityId" gorm:"-"`
	EffectiveSpeakerName        string               `json:"effectiveSpeakerName" gorm:"-"`
	HasUserConfirmedSpeaker     bool                 `json:"hasUserConfirmedSpeaker" gorm:"-"`
	// IsRecognizedSpeaker is a speaker the transcription named after one of
	// the voice samples it was sent, which the person has not confirmed here.
	IsRecognizedSpeaker           bool   `json:"isRecognizedSpeaker" gorm:"-"`
	IsAccountOwner                bool   `json:"isAccountOwner" gorm:"-"`
	HasUnalignedSpeakerCorrection bool   `json:"hasUnalignedSpeakerCorrection" gorm:"-"`
	AppliedSpeakerCorrectionID    string `json:"appliedSpeakerCorrectionId" gorm:"-"`
	// TemporarySpeakerLabel is the label ("Speaker 1") of the temporary
	// speaker of the recording this passage was matched to, for a speaker
	// nobody has named yet. The same speaker has the same label in every piece.
	TemporarySpeakerLabel string `json:"temporarySpeakerLabel" gorm:"-"`
	// MergedTemporarySpeakerLabel is this passage's own label ("Speaker 9")
	// when it was found to be the voice of another speaker and reads as that
	// one instead; empty for a passage that stands on its own. It is what the
	// person separates from.
	MergedTemporarySpeakerLabel string `json:"mergedTemporarySpeakerLabel" gorm:"-"`
	// IsFiller is a passage of only filler ("Mm-hmm. Okay."), which the
	// conversation leaves out and nobody is asked to label.
	IsFiller bool `json:"isFiller" gorm:"-"`
}

RecordingTranscriptSegment is generated evidence with request-local attribution. Manual labels and passage corrections are stored separately from this version.

type RecordingTranscriptTextCorrection added in v0.144.0

type RecordingTranscriptTextCorrection struct {
	ID                           string    `json:"id"`
	RecordingID                  string    `json:"recordingId"`
	RecordingMediaID             string    `json:"recordingMediaId"`
	RecordingTranscriptRunID     string    `json:"recordingTranscriptRunId"`
	RecordingTranscriptSegmentID string    `json:"recordingTranscriptSegmentId"`
	ClientCorrectionID           string    `json:"clientCorrectionId"`
	PassageStartMS               int64     `json:"passageStartMS"`
	PassageEndMS                 int64     `json:"passageEndMS"`
	OriginalTranscriptText       string    `json:"originalTranscriptText"`
	CorrectedTranscriptText      string    `json:"correctedTranscriptText"`
	SourceGeneration             int64     `json:"sourceGeneration"`
	CreatedAt                    time.Time `json:"createdAt"`
	IsRemoved                    bool      `json:"isRemoved"`

	// IsFolded is set on a glossary fix that was removed because a later fix
	// of the same passage started from the text it produced. It was replaced,
	// not undone, so it does not stop the pass from proposing the fix again.
	IsFolded bool `json:"isFolded"`

	// TextCorrectionOrigin is who made it. For a glossary correction,
	// GlossaryTerm is the term from the person's own data that it spells
	// right, and OriginalPhrase and CorrectedPhrase are the words changed
	// inside the passage; they stay on the row after removal so the same
	// fix is not made again.
	TextCorrectionOrigin TextCorrectionOrigin `json:"textCorrectionOrigin"`
	GlossaryTerm         string               `json:"glossaryTerm"`
	OriginalPhrase       string               `json:"originalPhrase"`
	CorrectedPhrase      string               `json:"correctedPhrase"`
}

RecordingTranscriptTextCorrection preserves user edits independently of generated versions.

type RecordingTranscriptionAttempt added in v0.141.0

type RecordingTranscriptionAttempt struct {
	ID                       string                `json:"id"`
	RecordingTranscriptRunID string                `json:"recordingTranscriptRunId"`
	RecordingAudioChunkID    string                `json:"recordingAudioChunkId"`
	AttemptIndex             int                   `json:"attemptIndex"`
	CreatedAt                time.Time             `json:"createdAt"`
	SubmittedAt              *time.Time            `json:"submittedAt"`
	CompletedAt              *time.Time            `json:"completedAt"`
	RecordingAttemptState    RecordingAttemptState `json:"recordingAttemptState"`
	ProviderModelName        string                `json:"providerModelName"`
	AttemptErrorMessage      string                `json:"attemptErrorMessage"`
	InputAudioTokens         int64                 `json:"inputAudioTokens"`
	InputTextTokens          int64                 `json:"inputTextTokens"`
	PromptTokens             int64                 `json:"promptTokens"`
	CompletionTokens         int64                 `json:"completionTokens"`
	ProviderAudioDurationMS  int64                 `json:"providerAudioDurationMS"`
	HasProviderUsage         bool                  `json:"hasProviderUsage"`
	EstimatedCostAmount      *float64              `json:"estimatedCostAmount"`
	ActualCostAmount         *float64              `json:"actualCostAmount"`
	CurrencyCode             string                `json:"currencyCode"`
	ProviderUsageJSON        json.RawMessage       `json:"-"`
	ProviderResponseJSON     json.RawMessage       `json:"-"`
	ReferenceBlobIDs         []string              `json:"referenceBlobIds"`
}

RecordingTranscriptionAttempt keeps provider provenance and uncertain billing. Configured prices are estimates; ActualCostAmount requires external bill evidence.

type RecordingUploadState added in v0.140.0

type RecordingUploadState string

RecordingUploadState advances only after integrity and durable bytes are verified.

const (
	RecordingUploadPending  RecordingUploadState = "pending"
	RecordingUploadComplete RecordingUploadState = "complete"
)

type RecordingVoiceReference added in v0.144.0

type RecordingVoiceReference struct {
	ID                           string    `json:"id"`
	RecordingID                  string    `json:"recordingId"`
	RecordingMediaID             string    `json:"recordingMediaId"`
	RecordingTranscriptRunID     string    `json:"recordingTranscriptRunId"`
	RecordingSpeakerCorrectionID string    `json:"recordingSpeakerCorrectionId"`
	SpeakerIdentityID            string    `json:"speakerIdentityId"`
	RecordingBlobID              string    `json:"recordingBlobId"`
	PassageStartMS               int64     `json:"passageStartMS"`
	PassageEndMS                 int64     `json:"passageEndMS"`
	SourceGeneration             int64     `json:"sourceGeneration"`
	IsRevoked                    bool      `json:"isRevoked"`
	CreatedAt                    time.Time `json:"createdAt"`
}

RecordingVoiceReference retains source provenance and a durable derived-blob cleanup reference.

type RelationshipKind added in v0.178.0

type RelationshipKind string

RelationshipKind is what one person is to another, in words that do not depend on who they are: a parent, a spouse. Each kind has an opposite, which is what the other person is to the first.

const (
	RelationshipSpouse        RelationshipKind = "spouse"
	RelationshipPartner       RelationshipKind = "partner"
	RelationshipParent        RelationshipKind = "parent"
	RelationshipChild         RelationshipKind = "child"
	RelationshipSibling       RelationshipKind = "sibling"
	RelationshipGrandparent   RelationshipKind = "grandparent"
	RelationshipGrandchild    RelationshipKind = "grandchild"
	RelationshipAuntOrUncle   RelationshipKind = "aunt_or_uncle"
	RelationshipNieceOrNephew RelationshipKind = "niece_or_nephew"
	RelationshipCousin        RelationshipKind = "cousin"
	RelationshipParentInLaw   RelationshipKind = "parent_in_law"
	RelationshipChildInLaw    RelationshipKind = "child_in_law"
	RelationshipSiblingInLaw  RelationshipKind = "sibling_in_law"
	RelationshipStepParent    RelationshipKind = "step_parent"
	RelationshipStepChild     RelationshipKind = "step_child"
	RelationshipFriend        RelationshipKind = "friend"
	RelationshipColleague     RelationshipKind = "colleague"
)

The kinds of relationship.

func RelationshipKinds added in v0.178.0

func RelationshipKinds() []RelationshipKind

RelationshipKinds is every kind, in the order they are offered.

func (RelationshipKind) HasGenderedWords added in v0.178.0

func (self RelationshipKind) HasGenderedWords() bool

HasGenderedWords reports whether the kind is said differently of a man and a woman; a cousin is a cousin either way.

func (RelationshipKind) IsValid added in v0.178.0

func (self RelationshipKind) IsValid() bool

IsValid reports whether this is one of the kinds.

func (RelationshipKind) Opposite added in v0.178.0

func (self RelationshipKind) Opposite() RelationshipKind

Opposite is what the other person is to the first: a parent's child.

func (RelationshipKind) Word added in v0.178.0

func (self RelationshipKind) Word(termGender TermGender) string

Word is the kind in English, in a word of the given gender: a parent who is described as he is a "father".

type RelationshipNote added in v0.178.0

type RelationshipNote struct {
	PersonName       string           `json:"personName"`
	RelationshipKind RelationshipKind `json:"relationshipKind"`
	TermGender       TermGender       `json:"termGender"`
	RelationshipWord string           `json:"relationshipWord"`
}

RelationshipNote is the detail of a relationship_set or relationship_removed note: who said it, and what they now are to the person who reads it. The kind and the gender are there so that each client words it in its own language; the English word is for the rest.

func ParseRelationshipNote added in v0.178.0

func ParseRelationshipNote(detail string) *RelationshipNote

ParseRelationshipNote reads the detail of a relationship note, or returns nil when it is not one.

type RelationshipTerm added in v0.178.0

type RelationshipTerm struct {
	Term             string
	RelationshipKind RelationshipKind
	TermGender       TermGender
}

RelationshipTerm is one word a person picks for somebody: its kind and the gender of the word. "wife" is a spouse, in a feminine word.

func ParseRelationshipTerm added in v0.178.0

func ParseRelationshipTerm(word string) (RelationshipTerm, error)

ParseRelationshipTerm reads a word a person picked, such as "wife" or "father-in-law", or the name of a kind such as "aunt_or_uncle". The refusal lists the words there are.

func RelationshipTerms added in v0.178.0

func RelationshipTerms() []RelationshipTerm

RelationshipTerms is every word a person can pick, each once, by kind and then neutral, masculine and feminine. A word that is the same in every gender (cousin) is there once, neutral.

type Report

type Report struct {
	// ID of the Report
	ID string `json:"id,omitempty"`

	// Timestamp when the Report was created
	CreatedAt time.Time `json:"createdAt,omitempty"`

	// Timestamp when the Report was last modified
	ModifiedAt time.Time `json:"modifiedAt,omitempty"`

	// The Mail that the Report was parsed from
	MailID string `json:"mailId,omitempty"`
	Mail   *Mail  `json:"-"`

	// Domain that the Report belongs to
	DomainID string  `json:"domainId,omitempty"`
	Domain   *Domain `json:"-"`

	// Report start date
	BeginAt time.Time `json:"beginAt,omitempty"`

	// Report end date
	EndAt time.Time `json:"endAt,omitempty"`

	// Number of instances
	Count uint64 `json:"count,omitempty"`

	// IP address of the sender
	IP string `json:"ip,omitempty"`

	// Reverse DNS name of the IP address
	RDNS string `json:"rdns,omitempty"`

	// Location of the sender
	Location *geoip.Location `json:"location,omitempty"`

	// From domain identifier
	FromDomain string `json:"fromDomain,omitempty"`

	// Sender domain identifier
	SenderDomain string `json:"senderDomain,omitempty"`

	// Disposition reported, what happened to the mail
	Disposition string `json:"disposition,omitempty"`

	// DKIM alignment
	DKIMAligned bool `json:"dkimAligned,omitempty"`

	// SPF alignment
	SPFAligned bool `json:"spfAligned,omitempty"`

	// Parsed original DMARC feedback
	Feedback *dmarc.Feedback `json:"feedback,omitempty"`
}

Report is a collected DMARC report for a Domain.

type RevisionActor

type RevisionActor string

RevisionActor is who made a change.

Worth recording because the answer changes what a reader should do about it: a sentence the person wrote is theirs and stands, one the nightly run wrote is a summary that can be rewritten, and one a source put there is only as good as the source.

const (
	ActorPerson   RevisionActor = "person"
	ActorAgent    RevisionActor = "agent"
	ActorRemember RevisionActor = "remember"
	ActorDream    RevisionActor = "dream"
	ActorIngest   RevisionActor = "ingest"
)

The actors.

type RevisionKind

type RevisionKind string

RevisionKind is what sort of change was made.

const (
	RevisionPage       RevisionKind = "page"
	RevisionRenamed    RevisionKind = "renamed"
	RevisionMoved      RevisionKind = "moved"
	RevisionFactAdded  RevisionKind = "fact_added"
	RevisionFactEdited RevisionKind = "fact_edited"
	RevisionFactGone   RevisionKind = "fact_removed"
	RevisionFactMerged RevisionKind = "fact_merged"
	RevisionFactFolded RevisionKind = "fact_folded"
	RevisionFactStruck RevisionKind = "fact_struck"
	RevisionLinked     RevisionKind = "linked"
	RevisionUnlinked   RevisionKind = "unlinked"
	RevisionCreated    RevisionKind = "created"
)

The kinds. A page's own words, its name and where it sits; a fact put on it, changed or taken off; a link made or broken.

Folded and struck are not removed, and the difference is the whole point: a fact the agent decided against on its own stays on the page as a dormant row, so the decision can be read and undone. Only the person's own forgetting leaves a RevisionFactGone.

type Role

type Role struct {
	ID          string       `json:"id"`
	CreatedAt   time.Time    `json:"createdAt"`
	ModifiedAt  time.Time    `json:"modifiedAt"`
	Name        string       `json:"name"`
	Description string       `json:"description,omitempty"`
	Permissions []Permission `json:"permissions"`
}

Role is a named set of permissions. Attached to groups, never to users: a user in a group holds the group's roles over the group's domains.

Three are seeded and are ordinary rows from then on; there is no built-in flag and nothing a seeded role may not do.

func (*Role) Validate

func (self *Role) Validate() error

Validate reports everything wrong with the role.

type SPFResult

type SPFResult struct {
	// Sender domain name
	Domain string `json:"domain,omitempty"`

	// Sender IP address
	IP string `json:"ip,omitempty"`

	// SPF result
	Result string `json:"result,omitempty"`
}

SPFResult holds authentication results related to SPF.

type SavingPace added in v0.98.0

type SavingPace string

SavingPace is how a month's saving, income less spending, is heading against the saving its budgets expect.

const (
	SavingPaceBehind  SavingPace = "behind"
	SavingPaceOnTrack SavingPace = "on_track"
	SavingPaceAhead   SavingPace = "ahead"
)

The three paces: the month is heading for less saved than its budgets expect, about what they expect, or more.

func (SavingPace) IsValid added in v0.98.0

func (self SavingPace) IsValid() bool

IsValid says the pace is one of the three.

type SavingSummary added in v0.98.0

type SavingSummary struct {
	// Month is "2006-01"; AsOf the day it is computed for, "2006-01-02",
	// which is the last day of a past month. For a year, Month is empty and
	// DayOfMonth and DaysInMonth are of AsOf's month.
	Month       string `json:"month"`
	AsOf        string `json:"asOf"`
	DayOfMonth  int    `json:"dayOfMonth"`
	DaysInMonth int    `json:"daysInMonth"`

	// Year, MonthsElapsedCount, DayOfYear and DaysInYear are as a
	// BudgetStatus's: set for the saving of a year, zero for a month's.
	Year               string `json:"year"`
	MonthsElapsedCount int    `json:"monthsElapsedCount"`
	DayOfYear          int    `json:"dayOfYear"`
	DaysInYear         int    `json:"daysInYear"`

	// BudgetedMonths are the months, "2006-01" in order, in which at least
	// one budget, income or spending, was in force; BudgetedMonthCount is
	// how many, and BudgetedMonthsElapsedCount how many of them have begun
	// by AsOf. Of a year, every expected, actual and projected amount
	// counts these months only, so a year whose budgets began in September
	// compares September onward with September onward. A year with none
	// counts all its months instead, expects nothing, and its SavingPace
	// says nothing. Of a month, the month itself when it has a budget.
	BudgetedMonths             []string `json:"budgetedMonths"`
	BudgetedMonthCount         int      `json:"budgetedMonthCount"`
	BudgetedMonthsElapsedCount int      `json:"budgetedMonthsElapsedCount"`

	// ReportingCurrencyCode is what every amount is in. A budget is
	// converted at AsOf's rate, and income and spending at the rate of the
	// day each came in or went out. Empty, and every amount zero, when
	// there is no currency to report in yet.
	ReportingCurrencyCode string `json:"reportingCurrencyCode"`

	// IncomeBudgetCount and SpendingBudgetCount are how many budgets of
	// each kind are in force in the month, or for a year, how many
	// spending categories of each kind had a budget in any of its months.
	IncomeBudgetCount   int `json:"incomeBudgetCount"`
	SpendingBudgetCount int `json:"spendingBudgetCount"`

	// ExpectedIncomeAmount is the income budgets added up, and
	// ExpectedSpendingAmount the spending budgets; ExpectedSavingAmount is
	// the first less the second.
	ExpectedIncomeAmount   string `json:"expectedIncomeAmount"`
	ExpectedSpendingAmount string `json:"expectedSpendingAmount"`
	ExpectedSavingAmount   string `json:"expectedSavingAmount"`

	// IncomeAmount, SpendingAmount and SavingAmount are the month's so
	// far: the whole month for a month that is over.
	IncomeAmount   string `json:"incomeAmount"`
	SpendingAmount string `json:"spendingAmount"`
	SavingAmount   string `json:"savingAmount"`

	// ProjectedIncomeAmount is the income so far plus what each income
	// budget still expects; ProjectedSpendingAmount the spending projected
	// to the month's end the way a budget projects a spending category's;
	// ProjectedSavingAmount the first less the second. For a month that is
	// over they are the month's own figures.
	ProjectedIncomeAmount   string `json:"projectedIncomeAmount"`
	ProjectedSpendingAmount string `json:"projectedSpendingAmount"`
	ProjectedSavingAmount   string `json:"projectedSavingAmount"`

	// SavingDifferenceAmount is ProjectedSavingAmount less
	// ExpectedSavingAmount: how far the month is heading from what its
	// budgets expect, or for a month that is over, how far it ended.
	SavingDifferenceAmount string     `json:"savingDifferenceAmount"`
	SavingPace             SavingPace `json:"savingPace"`

	// UnconvertedCurrencyCodes are the currencies left out for want of an
	// exchange rate into ReportingCurrencyCode.
	UnconvertedCurrencyCodes []string `json:"unconvertedCurrencyCodes"`
}

SavingSummary is one month's saving, income less spending, as its budgets expect it and as it is going, in one currency. Spending and income are counted the way cash flow counts them, transfers left out and every spending category included, whether or not it has a budget.

type SavingsTarget added in v0.87.0

type SavingsTarget struct {
	ID                string `json:"id"`
	AgentID           string `json:"agentId"`
	SavingsTargetName string `json:"savingsTargetName"`

	// TargetAmount is a decimal, in CurrencyCode, to reach by TargetOn
	// ("2006-01-02").
	TargetAmount  string        `json:"targetAmount"`
	CurrencyCode  string        `json:"currencyCode"`
	TargetOn      string        `json:"targetOn"`
	TargetMeasure TargetMeasure `json:"targetMeasure"`

	// StartingAmount is what the assets were worth when it started, for
	// an asset_value target, or the net worth then, for a net_worth one;
	// StartedOn when it started.
	StartingAmount string `json:"startingAmount,omitempty" graphapi:"nullable"`
	StartedOn      string `json:"startedOn"`
	ClosedOn       string `json:"closedOn,omitempty" graphapi:"nullable"`

	// AssetIDs are the assets an asset_value target measures, and
	// FinanceAccountIDs the finance accounts it measures whole: every
	// asset the account values, its holdings included, as they are on the
	// day the progress is read. An asset reached both ways counts once.
	AssetIDs          []string `json:"assetIds"`
	FinanceAccountIDs []string `json:"financeAccountIds"`

	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`
}

SavingsTarget is an amount to save by a date. Not an agent goal, which is a sentence a conversation works toward.

type SecurityKind added in v0.88.0

type SecurityKind string

SecurityKind is what a security is: a share, a fund, a bond, a coin, cash. Plaid's vocabulary, written with underscores.

const (
	SecurityKindCash           SecurityKind = "cash"
	SecurityKindCryptocurrency SecurityKind = "cryptocurrency"
	SecurityKindDerivative     SecurityKind = "derivative"
	SecurityKindEquity         SecurityKind = "equity"
	SecurityKindETF            SecurityKind = "etf"
	SecurityKindFixedIncome    SecurityKind = "fixed_income"
	SecurityKindLoan           SecurityKind = "loan"
	SecurityKindMutualFund     SecurityKind = "mutual_fund"
	SecurityKindOther          SecurityKind = "other"
)

The nine kinds; anything a provider sends outside them is other.

func (SecurityKind) IsValid added in v0.88.0

func (self SecurityKind) IsValid() bool

IsValid says the kind is one of the nine.

type Service added in v0.139.0

type Service string

Service identifies an optional hosted service, independently of account permissions.

const (
	ServiceMailRouting Service = "mailRouting"
	ServiceMailboxes   Service = "mailboxes"
	ServiceCalendar    Service = "calendar"
	ServiceReminders   Service = "reminders"
	ServiceContacts    Service = "contacts"
	ServicePhotos      Service = "photos"
)

type ServiceUnavailableError added in v0.139.0

type ServiceUnavailableError struct{ Service Service }

ServiceUnavailableError reports a disabled or not-yet-running service.

func (*ServiceUnavailableError) Error added in v0.139.0

func (self *ServiceUnavailableError) Error() string

func (*ServiceUnavailableError) Extensions added in v0.139.0

func (self *ServiceUnavailableError) Extensions() map[string]interface{}

Extensions gives API clients a stable error code.

type Session

type Session struct {
	// ID of the Session, and the half of the cookie that is not secret
	ID string `json:"id,omitempty"`

	// Timestamp when the Session was created, which is when somebody logged in
	CreatedAt time.Time `json:"createdAt,omitempty"`

	// Timestamp when the Session was last modified
	ModifiedAt time.Time `json:"modifiedAt,omitempty"`

	// The User this Session belongs to. By identifier, so that renaming an
	// account does not sign it out of itself.
	UserID string `json:"userId,omitempty"`

	// The name that account signs in with, filled in by the queries that
	// resolve it. Not a column: the username can change and this must not be
	// a second copy of it that goes stale.
	Username string `json:"username,omitempty"`

	// When it stops working, whatever else happens
	ExpiresAt time.Time `json:"expiresAt,omitempty"`

	// When it was last used. Not written on every request: see the note on
	// db.TouchInterval.
	UsedAt time.Time `json:"usedAt,omitempty"`

	// When it was ended, by logging out or by being revoked from the list.
	// Set rather than deleted, so the list can say so before the row is swept.
	RevokedAt time.Time `json:"revokedAt,omitempty"`

	// Where it was last used from, so a person can recognize their own
	IP        string `json:"ip,omitempty"`
	UserAgent string `json:"userAgent,omitempty"`

	// ImpersonatorUserID is the operator who signed in as this account,
	// for a session that is an impersonation, and ImpersonatorSessionID
	// the operator's own session, which it lasts no longer than.
	// ImpersonatorUsername is looked up, like Username.
	ImpersonatorUserID    string `json:"impersonatorUserId,omitempty"`
	ImpersonatorSessionID string `json:"impersonatorSessionId,omitempty"`
	ImpersonatorUsername  string `json:"impersonatorUsername,omitempty"`
}

Session is one signed-in browser.

It is a row rather than a signed cookie so that it can be listed and ended on its own. The cookie carries an identifier and a secret; this is everything the server knows about it.

func (*Session) Active

func (self *Session) Active(now time.Time) bool

Active reports whether this Session would authenticate a request now.

func (*Session) IsImpersonation added in v0.107.0

func (self *Session) IsImpersonation() bool

IsImpersonation says whether an operator is behind this session rather than the account it belongs to.

type ShareKind added in v0.194.0

type ShareKind string

ShareKind names a kind of thing a person shares with other people, for the one place that lists them all (the Sharing page, "teanode sharing") and for the notes that tell a person something was shared with them.

const (
	ShareKindCalendar   ShareKind = "calendar"
	ShareKindLocation   ShareKind = "location"
	ShareKindHealth     ShareKind = "health"
	ShareKindMemoryPage ShareKind = "memory_page"
	ShareKindSkill      ShareKind = "skill"
	ShareKindPhotoAlbum ShareKind = "photo_album"
	ShareKindRecording  ShareKind = "recording"
	ShareKindFinance    ShareKind = "finance"
	ShareKindPasswords  ShareKind = "passwords"
	ShareKindShopping   ShareKind = "shopping_list"
)

The kinds. Each is shared by its own table, with its own rules; a skill is shared with one person only, and passwords a whole item at a time. A finance share is of one account, and is the person's own tap to make.

func (ShareKind) IsValid added in v0.194.0

func (self ShareKind) IsValid() bool

IsValid reports whether this is one of the kinds.

type ShareLevel added in v0.170.0

type ShareLevel string

ShareLevel is how much of a calendar somebody may see, and whether they may change it. A person shares their calendar with a circle or with one person in a circle they share, at one of the first four. docs/decisions/ 20261016-a-calendar-is-shared-at-a-level.md says why these four.

const (
	// ShareLevelBusy is when the person is busy and nothing else: the same
	// answer free-busy gives, from the same code.
	ShareLevelBusy ShareLevel = "busy"
	// ShareLevelTitles adds the time, title and location of each event.
	ShareLevelTitles ShareLevel = "titles"
	// ShareLevelDetails is everything in the event, including its
	// description and its guests.
	ShareLevelDetails ShareLevel = "details"
	// ShareLevelEdit is details, and the reader may add, change and remove
	// events. A circle's own calendar is edit for every member.
	ShareLevelEdit ShareLevel = "edit"
	// ShareLevelOwner is the calendar's owner.
	ShareLevelOwner ShareLevel = "owner"
)

The levels, from least to most. ShareLevelOwner is not a level anybody can be given: it is what a person's own calendar is to them, so that "may this person do this to this calendar" has one answer for the owner too.

func HighestShareLevel added in v0.170.0

func HighestShareLevel(first, second ShareLevel) ShareLevel

HighestShareLevel is the greater of two levels, so that a person reached by both a direct share and a circle's takes the better of them.

func (ShareLevel) AtLeast added in v0.170.0

func (self ShareLevel) AtLeast(other ShareLevel) bool

AtLeast reports whether this level reaches the other.

func (ShareLevel) CanRead added in v0.170.0

func (self ShareLevel) CanRead() bool

CanRead reports whether the level shows events at all, as events rather than as busy time.

func (ShareLevel) CanWrite added in v0.170.0

func (self ShareLevel) CanWrite() bool

CanWrite reports whether the level may add, change and remove events.

func (ShareLevel) IsGrantable added in v0.170.0

func (self ShareLevel) IsGrantable() bool

IsGrantable reports whether a share may be made at this level.

func (ShareLevel) Rank added in v0.170.0

func (self ShareLevel) Rank() int

Rank orders the levels; zero is no access at all.

type ShareReachedNote added in v0.194.0

type ShareReachedNote struct {
	MemberName string      `json:"memberName"`
	CircleName string      `json:"circleName"`
	ShareKinds []ShareKind `json:"shareKinds"`
}

ShareReachedNote is the detail of a share_reached note: a person joined a circle that the reader shares things with, so they can now see those. It is one note for each owner, listing the kinds.

func ParseShareReachedNote added in v0.194.0

func ParseShareReachedNote(detail string) *ShareReachedNote

ParseShareReachedNote reads the detail of a share_reached note, or returns nil when it is not one.

type ShareReceivedNote added in v0.194.0

type ShareReceivedNote struct {
	SharerName   string    `json:"sharerName"`
	ShareKind    ShareKind `json:"shareKind"`
	ShareLevel   string    `json:"shareLevel,omitempty"`
	ShareSubject string    `json:"shareSubject,omitempty"`

	// ShareSubjectID is which thing was shared (the calendar, page path, skill
	// name, album, recording or finance account), only to tell two shares of
	// one kind at one level apart when deciding whether a person was just told.
	// It is not sent to a client: a name or an identifier the person has no
	// part in does not belong in a conversation.
	ShareSubjectID string `json:"-"`

	// ShareScopes are what else it gives: the Health categories, quotes for a
	// page shared with the words each fact was read in, location for an album
	// shared with where its photos were taken.
	ShareScopes []string `json:"shareScopes,omitempty"`
}

ShareReceivedNote is the detail of a share_received note: who shared what with the person, as JSON so that each client words it in its own language. ShareLevel is the level of a calendar, location, album, recording or finance share (busy, titles, details, edit; current, history; view, contribute; summary, transcript; balance, spending, transactions) and empty for the rest. ShareSubject is the page's name, the album's title, the skill's name or the recording's title. A recording's title is the sharer's own text and may summarize what other people said, and a finance share names no account: the note goes into the conversation of the person's agent, which has no part in either, so it says that a recording or an account was shared and leaves out which.

func ParseShareReceivedNote added in v0.194.0

func ParseShareReceivedNote(detail string) *ShareReceivedNote

ParseShareReceivedNote reads the detail of a share_received note, or returns nil when it is not one.

type ShareRow added in v0.194.0

type ShareRow struct {
	ShareKind ShareKind
	ShareID   string

	// SubjectID and SubjectName are the calendar, the album, the page, the
	// skill, the recording or the finance account shared: its identifier and
	// what it is called (a recording's title, an account's name). Both are
	// empty for a person's location and Health, which are shared whole.
	// SubjectMask is the last digits of a finance account's number, when the
	// provider gave them, and empty for every other kind.
	SubjectID   string
	SubjectName string
	SubjectMask string

	// IsSubjectDeleted is true for a share of a memory page that no longer
	// exists, which its owner can still stop. SubjectName is then the path.
	IsSubjectDeleted bool

	OwnerUserID   string
	OwnerUsername string
	OwnerName     string
	OwnerUser     *User

	// GranteeUserID and GranteeCircleID are who it is shared with: one of
	// them, never both.
	GranteeUserID     string
	GranteeUsername   string
	GranteeName       string
	GranteeCircleID   string
	GranteeCircleName string

	// ShareLevel is the level of a calendar, location, album, recording or
	// finance share, and empty for the other kinds. ShareScopes are the rest of what it gives: the
	// Health categories, the skill's tools, "quotes" for a page shared with
	// the words each fact was read in, "location" for an album shared with
	// where its photos were taken.
	ShareLevel  string
	ShareScopes []string

	// ItemCount is how many password items it reaches, for the passwords kind
	// only: an item's title is sealed, so a share of passwords is counted and
	// never named.
	ItemCount int

	CreatedAt time.Time
}

ShareRow is one share of one thing, read for the list of everything shared: what it is, who owns it, who it is for and how much it gives. The owner is the person whose thing it is; for the shares a person made, that is them.

type ShareTarget added in v0.170.0

type ShareTarget struct {
	UserID   string
	CircleID string

	// Description says who it is, in a result and on a card somebody approves:
	// the username, or the circle with its name in quotes and how many people
	// it is, `the circle "Family" (4 people)`.
	Description string
}

ShareTarget is who a share is for: one person or one circle, never both.

func ResolveShareTarget added in v0.170.0

func ResolveShareTarget(typed string, people []ShareablePerson, circles []ShareableCircle) (*ShareTarget, error)

ResolveShareTarget finds who typed words name: the id of a circle the account is in, the username of somebody it shares a circle with, or the name of a circle. A username of somebody the account may share with wins over a circle of the same name, so that whoever names a circle cannot take a share meant for a person; the circle is still reached by its id. Circle names are not unique, so a name that is nobody's username and matches more than one circle is refused with the ids and sizes of the circles it could be; an id never is ambiguous.

type ShareableCircle added in v0.170.0

type ShareableCircle struct {
	ID          string
	Name        string
	MemberCount int
}

ShareableCircle is a circle the signed-in account is in.

type ShareablePerson added in v0.170.0

type ShareablePerson struct {
	UserID   string
	Username string
}

ShareablePerson is somebody the signed-in account shares a circle with, as far as naming a share's target goes.

type SharedChild added in v0.170.0

type SharedChild struct {
	Path     string        `json:"path"`
	Name     string        `json:"name"`
	NodeKind AgentNodeKind `json:"nodeKind"`
	Opening  string        `json:"opening"`
}

SharedChild is a page under a shared page, which is shared with it.

type SharedEdge added in v0.170.0

type SharedEdge struct {
	FromPath string            `json:"fromPath"`
	ToPath   string            `json:"toPath"`
	FromName string            `json:"fromName,omitempty"`
	ToName   string            `json:"toName,omitempty"`
	Relation AgentEdgeRelation `json:"relation"`

	// IsProposed says the owner's agent only guessed the link.
	IsProposed bool `json:"isProposed"`
}

SharedEdge is a link between two shared pages. A link to a page that is not shared with the reader is not part of the view at all, and neither is the note the owner's agent wrote on it: a note is free text written from the owner's other pages and their sources, and says what nobody chose to share.

type SharedFact added in v0.170.0

type SharedFact struct {
	// Number is the fact's number on its page, so that it is cited as
	// people/a-grandparent#3 whoever reads it.
	Number   int           `json:"number"`
	FactKind AgentFactKind `json:"factKind"`
	Text     string        `json:"text"`

	HappenedAt        *time.Time `json:"happenedAt,omitempty"`
	HappenedPrecision string     `json:"happenedPrecision,omitempty"`

	// SaidAt is when the fact was first learned.
	SaidAt     *time.Time `json:"saidAt,omitempty"`
	IsInferred bool       `json:"isInferred"`

	// EvidenceSource names where the owner's agent read it in the owner's
	// terms ("from Ada's mail"), and nothing that identifies the source
	// itself. Empty when the fact has no evidence a reader may be told of.
	EvidenceSource string `json:"evidenceSource,omitempty"`

	// EvidenceQuote is the words it was read in, only when the share says
	// the quotes are shared.
	EvidenceQuote string `json:"evidenceQuote,omitempty"`
}

SharedFact is one fact of a shared page as the reader sees it.

func (*SharedFact) Line added in v0.170.0

func (self *SharedFact) Line() string

Line is the fact as a page shows it, the same line a fact of one's own page is shown as.

type SharedFinanceSpendingRow added in v0.194.0

type SharedFinanceSpendingRow struct {
	// SpendingMonth is "2006-01".
	SpendingMonth        string `json:"spendingMonth"`
	SpendingCategoryName string `json:"spendingCategoryName"`
	CurrencyCode         string `json:"currencyCode"`

	// MoneyOut and MoneyIn are decimals, both positive.
	MoneyOut                string `json:"moneyOut"`
	MoneyIn                 string `json:"moneyIn"`
	FinanceTransactionCount int    `json:"financeTransactionCount"`
}

SharedFinanceSpendingRow is one month of one spending category of a shared finance account, in one currency. The name is the owner's own for the category and empty for transactions that have none. Transfers between the owner's accounts and mirrored copies are left out, as in the owner's own totals.

type SharedFinanceTransaction added in v0.194.0

type SharedFinanceTransaction struct {
	ID string `json:"id"`

	// PostedOn is the day it posted, "2006-01-02".
	PostedOn string `json:"postedOn"`

	// Amount is a decimal; negative is money leaving the account.
	Amount       string `json:"amount"`
	CurrencyCode string `json:"currencyCode"`

	// MerchantName is written by outsiders; empty when the provider gave none.
	MerchantName         string `json:"merchantName,omitempty" graphapi:"nullable"`
	SpendingCategoryName string `json:"spendingCategoryName,omitempty" graphapi:"nullable"`
}

SharedFinanceTransaction is a transaction of a shared finance account as a reader at the transactions level sees it. It has no description, no provider data, no annotation and no receipt, because the type has no field for them.

type SharedHit added in v0.170.0

type SharedHit struct {
	OwnerUserID   string `json:"ownerUserId"`
	OwnerUsername string `json:"ownerUsername"`
	OwnerName     string `json:"ownerName"`

	Path string `json:"path"`
	Name string `json:"name"`

	// Opening is the page's opening for a page, and empty for a fact.
	Opening string `json:"opening,omitempty"`

	// FactNumber is zero for a page.
	FactNumber int    `json:"factNumber"`
	Text       string `json:"text,omitempty"`
}

SharedHit is a page or a fact of a shared page that a search found.

type SharedPage added in v0.170.0

type SharedPage struct {
	OwnerUserID   string `json:"ownerUserId"`
	OwnerUsername string `json:"ownerUsername"`
	OwnerName     string `json:"ownerName"`
	OwnerUser     *User  `json:"-"`

	Path     string        `json:"path"`
	Name     string        `json:"name"`
	NodeKind AgentNodeKind `json:"nodeKind"`
	Aliases  []string      `json:"aliases"`

	// Opening is what the page is about, the owner's summary of it. Empty
	// when the page has a fact the reader is not shown or one read in a chat
	// or a recording, and when the owner did not share quotes and the
	// summary quotes somebody.
	Opening string `json:"opening"`

	// IsQuoteShared says at least one share reaching the reader for this
	// page includes the quotes.
	IsQuoteShared bool `json:"isQuoteShared"`

	Facts    []*SharedFact  `json:"facts"`
	Edges    []*SharedEdge  `json:"edges"`
	Children []*SharedChild `json:"children"`
}

SharedPage is one page the owner shared, as the reader sees it: its name, opening and facts, the links to other shared pages, and the pages under it. Not its overview: see SharedOverviewNotice.

func (*SharedPage) Reference added in v0.170.0

func (self *SharedPage) Reference(number int) string

Reference is how a fact of this page is cited: the path and number, and whose page it is.

type SharedRecording added in v0.194.0

type SharedRecording struct {
	RecordingID string `json:"recordingId"`

	// The owner, for a screen that says whose recording it is.
	OwnerUserID   string `json:"ownerUserId"`
	OwnerUsername string `json:"ownerUsername"`
	OwnerName     string `json:"ownerName"`

	RecordingTitle      string              `json:"recordingTitle"`
	CreatedAt           time.Time           `json:"createdAt"`
	RecordedAt          *time.Time          `json:"recordedAt" graphapi:"nullable"`
	TimelineDurationMS  int64               `json:"timelineDurationMS"`
	RecordingSummary    string              `json:"recordingSummary"`
	RecordingShareLevel RecordingShareLevel `json:"recordingShareLevel"`

	// SpeakerNames are the names the owner confirmed for speakers of the
	// recording, each once. Empty in a listing, which does not read the
	// transcript to find them, and on a page of passages after the first,
	// which has them from the first page.
	SpeakerNames []string `json:"speakerNames"`

	// Passages are a page of the transcript, only at the transcript level,
	// and PassageCount how many there are in all. HasMorePassages says to
	// read on from the offset after this page.
	Passages        []*SharedRecordingPassage `json:"passages"`
	PassageCount    int64                     `json:"passageCount"`
	HasMorePassages bool                      `json:"hasMorePassages"`
}

SharedRecording is a recording as a reader sees it, at the level a share gives them and no more. It is made by RedactRecording and nowhere else.

func RedactRecording added in v0.194.0

func RedactRecording(disclosure *RecordingDisclosure, shareLevel RecordingShareLevel) *SharedRecording

RedactRecording is a recording as a reader at the level may see it: the one place a reader's view of a recording is made, so that every door that shows a recording to somebody who is not its owner shows the same thing. It copies named fields and nothing else, so a field added to Recording or to a transcript segment later is not shared until it is named here.

Never in it, at any level: the originals and their playback, the voice samples, the contacts a speaker's name is tied to, whether a speaker is the owner, and the processing history and its costs.

type SharedRecordingPassage added in v0.194.0

type SharedRecordingPassage struct {
	SegmentStartMS int64 `json:"segmentStartMS"`
	SegmentEndMS   int64 `json:"segmentEndMS"`

	// SpeakerName is the name the owner confirmed, else the label the passage
	// has in the owner's own transcript.
	SpeakerName    string `json:"speakerName"`
	TranscriptText string `json:"transcriptText"`

	// IsFiller is a passage of only filler ("Mm-hmm. Okay."), as in the
	// owner's transcript, so that a reader can leave it out as the owner's
	// screens do.
	IsFiller bool `json:"isFiller"`
}

SharedRecordingPassage is one passage of a transcript as a reader at the transcript level sees it.

type SharedRoot added in v0.170.0

type SharedRoot struct {
	// ShareIDs are the shares that give the reader this root; more than one
	// when it reaches them as a person and through a circle.
	ShareIDs []string `json:"shareIds"`

	OwnerUserID   string `json:"ownerUserId"`
	OwnerUsername string `json:"ownerUsername"`
	OwnerName     string `json:"ownerName"`
	OwnerUser     *User  `json:"-"`

	Path     string        `json:"path"`
	Name     string        `json:"name"`
	NodeKind AgentNodeKind `json:"nodeKind"`

	// Opening is the first sentence of the page's summary.
	Opening       string `json:"opening"`
	IsQuoteShared bool   `json:"isQuoteShared"`
}

SharedRoot is a root of a shared subtree as a reader lists it.

type ShoppingItem added in v0.201.0

type ShoppingItem struct {
	ID              string `json:"id"`
	ShoppingListID  string `json:"shoppingListId"`
	ItemDescription string `json:"itemDescription"`
	ItemDetails     string `json:"itemDetails"`

	// StoreName is the store to get it from, empty for any store.
	StoreName    string `json:"storeName"`
	StoreKey     string `json:"storeKey"`
	IsStoreBrand bool   `json:"isStoreBrand"`
	AisleName    string `json:"aisleName"`
	AisleRank    int    `json:"aisleRank"`
	ItemRank     int    `json:"itemRank"`

	// NeededQuantity is a decimal above zero, as text ("2", "1.5").
	NeededQuantity string `json:"neededQuantity"`
	QuantityUnit   string `json:"quantityUnit"`

	// UnitPriceAmount is the latest price seen, a decimal as text, empty
	// when none is known.
	UnitPriceAmount string `json:"unitPriceAmount"`
	CurrencyCode    string `json:"currencyCode"`

	ShoppingItemState ShoppingItemState `json:"shoppingItemState"`
	CartedByUserID    string            `json:"cartedByUserId"`
	CartedAt          *time.Time        `json:"cartedAt"`

	OutOfStockAt        *time.Time `json:"outOfStockAt"`
	OutOfStockByUserID  string     `json:"outOfStockByUserId"`
	OutOfStockStoreName string     `json:"outOfStockStoreName"`
	LastBoughtAt        *time.Time `json:"lastBoughtAt"`

	PictureFileID     string                `json:"pictureFileId"`
	PicturePageURL    string                `json:"picturePageUrl"`
	PictureSource     ShoppingPictureSource `json:"pictureSource"`
	PictureSearchedAt *time.Time            `json:"pictureSearchedAt"`

	// PicturePath is where a signed-in reader of the list gets the picture
	// from this server, empty when there is none. Filled for a reader, not
	// stored.
	PicturePath string `json:"picturePath"`

	CreatedByUserID string    `json:"createdByUserId"`
	CreatedAt       time.Time `json:"createdAt"`
	UpdatedAt       time.Time `json:"updatedAt"`

	// Names a reader is shown: the list it is on, and who put it in the cart
	// or found it out of stock.
	ListName         string `json:"listName"`
	CartedByName     string `json:"cartedByName"`
	OutOfStockByName string `json:"outOfStockByName"`
}

ShoppingItem is one thing on one list.

type ShoppingItemChange added in v0.201.0

type ShoppingItemChange struct {
	ItemDescription *string
	ItemDetails     *string
	StoreName       *string
	IsStoreBrand    *bool
	AisleName       *string
	NeededQuantity  *string
	QuantityUnit    *string
}

ShoppingItemChange is what a change to an item sets; a nil field is left as it is.

type ShoppingItemPrice added in v0.201.0

type ShoppingItemPrice struct {
	ID               string              `json:"id"`
	ShoppingItemID   string              `json:"shoppingItemId"`
	StoreName        string              `json:"storeName"`
	StoreKey         string              `json:"storeKey"`
	UnitPriceAmount  string              `json:"unitPriceAmount"`
	CurrencyCode     string              `json:"currencyCode"`
	Quantity         string              `json:"quantity"`
	QuantityUnit     string              `json:"quantityUnit"`
	ObservedOn       string              `json:"observedOn"`
	PriceSource      ShoppingPriceSource `json:"priceSource"`
	FinanceReceiptID string              `json:"financeReceiptId"`
	CreatedByUserID  string              `json:"createdByUserId"`
	CreatedAt        time.Time           `json:"createdAt"`
}

ShoppingItemPrice is one price seen for an item at a store.

type ShoppingItemState added in v0.201.0

type ShoppingItemState string

ShoppingItemState is where an item on a shopping list is: to buy, checked off at the store, or bought or not wanted now. A bought item stays on its list, so a list is reused week after week.

const (
	// ShoppingItemStateNeeded is an item to buy, NeededQuantity of it.
	ShoppingItemStateNeeded ShoppingItemState = "needed"

	// ShoppingItemStateInCart is an item checked off at the store. It stays
	// in the cart until the trip is finished, a receipt matches it, or a new
	// trip on its list starts long after; then it is bought.
	ShoppingItemStateInCart ShoppingItemState = "in_cart"

	// ShoppingItemStateNotNeeded is an item that was bought, or is not wanted
	// now. "Need again" makes it needed.
	ShoppingItemStateNotNeeded ShoppingItemState = "not_needed"
)

func (ShoppingItemState) IsValid added in v0.201.0

func (self ShoppingItemState) IsValid() bool

IsValid reports whether the state is one of the three.

type ShoppingList added in v0.201.0

type ShoppingList struct {
	ID        string    `json:"id"`
	UserID    string    `json:"userId"`
	ListName  string    `json:"listName"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`

	// Whose it is, for a list somebody shared with the reader.
	OwnerUsername string `json:"ownerUsername"`
	OwnerName     string `json:"ownerName"`

	// What the reader may do with it and how they see it.
	IsOwner    bool `json:"isOwner"`
	IsReminded bool `json:"isReminded"`

	// How many of its items are in each state.
	NeededCount    int `json:"neededCount"`
	InCartCount    int `json:"inCartCount"`
	NotNeededCount int `json:"notNeededCount"`

	// Whether anybody besides the owner has it.
	IsShared bool `json:"isShared"`
}

ShoppingList is one person's named list of things to buy.

type ShoppingListAccess added in v0.201.0

type ShoppingListAccess struct {
	ShoppingListID string
	OwnerUserID    string
	IsOwner        bool
}

ShoppingListAccess is how a person reaches a list.

type ShoppingListShare added in v0.201.0

type ShoppingListShare struct {
	ID              string    `json:"id"`
	ShoppingListID  string    `json:"shoppingListId"`
	GranteeUserID   string    `json:"granteeUserId"`
	GranteeCircleID string    `json:"granteeCircleId"`
	CreatedByUserID string    `json:"createdByUserId"`
	CreatedAt       time.Time `json:"createdAt"`

	// Names for listings: the list, whose it is, and who it is for.
	ListName          string `json:"listName"`
	OwnerUserID       string `json:"ownerUserId"`
	OwnerUsername     string `json:"ownerUsername"`
	OwnerName         string `json:"ownerName"`
	GranteeUsername   string `json:"granteeUsername"`
	GranteeName       string `json:"granteeName"`
	GranteeCircleName string `json:"granteeCircleName"`
}

ShoppingListShare gives one person or one circle a list.

type ShoppingPictureSource added in v0.201.0

type ShoppingPictureSource string

ShoppingPictureSource is where an item's picture came from.

const (
	// ShoppingPictureSourceWeb is a picture the agent found on a web page.
	ShoppingPictureSourceWeb ShoppingPictureSource = "web"

	// ShoppingPictureSourceUpload is a picture a person gave.
	ShoppingPictureSourceUpload ShoppingPictureSource = "upload"
)

type ShoppingPriceSource added in v0.201.0

type ShoppingPriceSource string

ShoppingPriceSource is where a price came from.

const (
	// ShoppingPriceSourceReceipt is a price read from a receipt.
	ShoppingPriceSourceReceipt ShoppingPriceSource = "receipt"

	// ShoppingPriceSourcePerson is a price a person typed.
	ShoppingPriceSourcePerson ShoppingPriceSource = "person"
)

type ShoppingReceiptMatch added in v0.201.0

type ShoppingReceiptMatch struct {
	ID                        string            `json:"id"`
	FinanceReceiptID          string            `json:"financeReceiptId"`
	ReceiptLineNumber         int               `json:"receiptLineNumber"`
	FinanceReceiptLineID      string            `json:"financeReceiptLineId"`
	ShoppingItemID            string            `json:"shoppingItemId"`
	ReceiptMatchState         ReceiptMatchState `json:"receiptMatchState"`
	MatchedQuantity           string            `json:"matchedQuantity"`
	PreviousShoppingItemState ShoppingItemState `json:"previousShoppingItemState"`
	PreviousNeededQuantity    string            `json:"previousNeededQuantity"`
	ShoppingItemPriceID       string            `json:"shoppingItemPriceId"`
	DecidedByUserID           string            `json:"decidedByUserId"`
	CreatedAt                 time.Time         `json:"createdAt"`
	DecidedAt                 *time.Time        `json:"decidedAt"`
}

ShoppingReceiptMatch ties a line of a receipt to a shopping item.

type ShoppingReceiptMatchProposal added in v0.201.0

type ShoppingReceiptMatchProposal struct {
	FinanceReceiptLineID string
	ShoppingItemID       string
	MatchedQuantity      string
	IsSure               bool
}

ShoppingReceiptMatchProposal is one tie the matcher would make: a line, an item, how many of it the line bought (empty when the line does not say), and whether the matcher is sure.

type ShoppingStore added in v0.201.0

type ShoppingStore struct {
	StoreName   string `json:"storeName"`
	StoreKey    string `json:"storeKey"`
	NeededCount int    `json:"neededCount"`
	IsReminded  bool   `json:"isReminded"`
}

ShoppingStore is a store some of the reader's items are for, with how many of them are needed there.

type ShoppingTrip added in v0.201.0

type ShoppingTrip struct {
	ID              string     `json:"id"`
	UserID          string     `json:"userId"`
	StoreName       string     `json:"storeName"`
	StoreKey        string     `json:"storeKey"`
	StartedAt       time.Time  `json:"startedAt"`
	FinishedAt      *time.Time `json:"finishedAt"`
	ShoppingListIDs []string   `json:"shoppingListIds"`

	// Who is shopping, for the others.
	ShopperUsername string `json:"shopperUsername"`
	ShopperName     string `json:"shopperName"`

	// How many items the trip bought are still bought: what resuming it puts
	// back in the cart. Zero while it is open.
	BoughtItemCount int `json:"boughtItemCount"`
}

ShoppingTrip is somebody shopping a store now, for some lists.

type SkillShare added in v0.170.0

type SkillShare struct {
	ID         string    `json:"id"`
	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`

	// OwnerAgentID is the agent of the person whose skill it is.
	OwnerAgentID string `json:"ownerAgentId"`

	// SkillName is the installed skill; ToolNames are the tools of it that
	// are shared, by the name the skill declares.
	SkillName string   `json:"skillName"`
	ToolNames []string `json:"toolNames"`

	// GranteeUserID is the person who may call them.
	GranteeUserID string `json:"granteeUserId"`

	// PaymentLimitMinor is the most one payment may be, and MonthlyLimitMinor
	// the most the ran and failed calls of a calendar month may come to, in the minor
	// unit of CurrencyCode (cents). Nil is no limit of that kind. A call above
	// either waits for the owner.
	PaymentLimitMinor *int64 `json:"paymentLimitMinor,omitempty"`
	MonthlyLimitMinor *int64 `json:"monthlyLimitMinor,omitempty"`

	// CurrencyCode is the three letters, lower case, the limits are in. Empty
	// when there are no limits.
	CurrencyCode string `json:"currencyCode,omitempty"`

	// IsApprovalRequired says every call waits for the owner, whatever its
	// amount.
	IsApprovalRequired bool `json:"isApprovalRequired"`

	// The rest is read along with the row. The owner is the account the
	// agent belongs to.
	OwnerUserID     string `json:"ownerUserId,omitempty"`
	OwnerUsername   string `json:"ownerUsername,omitempty"`
	OwnerName       string `json:"ownerName,omitempty"`
	OwnerUser       *User  `json:"-"`
	GranteeUsername string `json:"granteeUsername,omitempty"`
	GranteeName     string `json:"granteeName,omitempty"`
	GranteeUser     *User  `json:"-"`
}

SkillShare gives one person the use of named tools of one skill, on the owner's computer, within limits.

func (*SkillShare) IsSharing added in v0.170.0

func (self *SkillShare) IsSharing(toolName string) bool

IsSharing says whether the tool is one of those shared.

func (*SkillShare) OpensNothingBeyond added in v0.170.0

func (self *SkillShare) OpensNothingBeyond(replaced *SkillShare) bool

OpensNothingBeyond says whether sharing these terms lets the person do no more than the share they replace already did, so that the change only takes something away: it asks the owner every time, or it keeps to tools the share already had, in the same currency, with limits at or below the old ones. With no share to replace (nil), only asking every time qualifies, because that is the one share under which nothing runs without the owner's word.

type SkillShareCall added in v0.170.0

type SkillShareCall struct {
	ID         string    `json:"id"`
	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`

	// SkillShareID is the share it was made through, empty once that share
	// has ended: the call stays, with what it was a call of below.
	SkillShareID string `json:"skillShareId"`

	// OwnerAgentID, GranteeUserID and SkillName are what the call was a call
	// of, kept on the call so that it still says so when its share is gone.
	OwnerAgentID  string `json:"ownerAgentId"`
	GranteeUserID string `json:"granteeUserId"`
	SkillName     string `json:"skillName"`

	// GranteeRunID and GranteeConversationID are the turn of the grantee's
	// agent that made the call, and the conversation that turn was in: where
	// the outcome of a call that waited is told.
	GranteeRunID          string `json:"granteeRunId,omitempty"`
	GranteeConversationID string `json:"granteeConversationId,omitempty"`

	ToolName string `json:"toolName"`

	// ToolArguments are exactly what the grantee's agent called the tool
	// with, which is what the owner is shown and what approving runs.
	ToolArguments map[string]any `json:"toolArguments"`

	// RequestReason is the grantee's agent's own words for why. Another
	// person's words: shown as theirs, never read as an instruction.
	RequestReason string `json:"requestReason,omitempty"`

	// AmountMinor and CurrencyCode are what the server read from the
	// arguments by the skill's declaration; nil and empty when it could not.
	AmountMinor  *int64 `json:"amountMinor,omitempty"`
	CurrencyCode string `json:"currencyCode,omitempty"`

	CallState SkillShareCallState `json:"callState"`

	// ToolOutput is what the call answered, or why it did not complete.
	ToolOutput map[string]any `json:"toolOutput,omitempty"`

	AnsweredAt *time.Time `json:"answeredAt,omitempty"`
	AnswerNote string     `json:"answerNote,omitempty"`
	ExpiresAt  *time.Time `json:"expiresAt,omitempty"`
	WokenAt    *time.Time `json:"wokenAt,omitempty"`

	// The people, read along with the calls of shares that ended, which have
	// no share to name them. Empty on any other call.
	OwnerUserID     string `json:"ownerUserId,omitempty"`
	OwnerUsername   string `json:"ownerUsername,omitempty"`
	OwnerName       string `json:"ownerName,omitempty"`
	GranteeUsername string `json:"granteeUsername,omitempty"`
	GranteeName     string `json:"granteeName,omitempty"`
	GranteeUser     *User  `json:"-"`
}

SkillShareCall is one call of a shared tool, whatever came of it.

func (*SkillShareCall) IsShareEnded added in v0.170.0

func (self *SkillShareCall) IsShareEnded() bool

IsShareEnded says the share the call was made through is gone.

func (*SkillShareCall) ToolArgumentsJSON added in v0.170.0

func (self *SkillShareCall) ToolArgumentsJSON() []byte

ToolArgumentsJSON is the arguments as stored.

type SkillShareCallNote added in v0.170.0

type SkillShareCallNote struct {
	SkillShareID  string `json:"skillShareId"`
	CallID        string `json:"callId"`
	GranteeName   string `json:"granteeName"`
	GranteeUserID string `json:"granteeUserId"`
}

SkillShareCallNote is the detail of a skill_share_call_waiting note: which call waits, in which share, and who asked, so that the card in the drawer and the app reads the rest of it from the call itself and shows its present state.

func ParseSkillShareCallNote added in v0.170.0

func ParseSkillShareCallNote(detail string) *SkillShareCallNote

ParseSkillShareCallNote reads the detail of a skill_share_call_waiting note, or returns nil when it is not one.

type SkillShareCallState added in v0.170.0

type SkillShareCallState string

SkillShareCallState says how one call of a shared tool stands.

const (
	// SkillShareCallRan is a call carried out on the owner's computer.
	SkillShareCallRan SkillShareCallState = "ran"

	// SkillShareCallFailed is a call that was tried and did not complete, or
	// could not be tried because the owner's computer was not connected.
	SkillShareCallFailed SkillShareCallState = "failed"

	// SkillShareCallRefused is a call the server refused before it ran:
	// a request for a spend request that did not come through the share.
	SkillShareCallRefused SkillShareCallState = "refused"

	// SkillShareCallWaitingForApproval is a call that needs the owner's word.
	SkillShareCallWaitingForApproval SkillShareCallState = "waiting_for_approval"

	// SkillShareCallDeclined is a call the owner said no to.
	SkillShareCallDeclined SkillShareCallState = "declined"

	// SkillShareCallExpired is a call the owner did not answer in time.
	SkillShareCallExpired SkillShareCallState = "expired"
)

The states. Ran is written before the call is carried out and changed to failed if it then errors, so that the month's total counts a call in flight.

func SkillShareCallStatesAsked added in v0.170.0

func SkillShareCallStatesAsked(words []string) ([]SkillShareCallState, error)

SkillShareCallStatesAsked reads the states somebody asks to see calls in, by the words they say: the operation's own names, and "waiting" for waiting_for_approval. Each state once, in the order asked; none when no state was asked, which is every call. The command line and the agent's tool both read them this way.

func (SkillShareCallState) AskedWord added in v0.170.0

func (self SkillShareCallState) AskedWord() string

AskedWord is the state as SkillShareCallStatesAsked takes it, which is what the command line prints and the agent's tool answers: waiting for waiting_for_approval, and the operation's own name for any other.

func (SkillShareCallState) IsValid added in v0.170.0

func (self SkillShareCallState) IsValid() bool

IsValid says the state is one of the six.

type SpamFilterCheck

type SpamFilterCheck struct {
	// Symbol is the check's short name, for example SPF_FAIL.
	Symbol string `json:"symbol"`

	// Score is the points this check contributed. Negative for a check that
	// vouches for a message rather than accusing it.
	Score float64 `json:"score"`

	// Description is a sentence for a human reading the dashboard.
	Description string `json:"description,omitempty"`
}

SpamFilterCheck is one check that fired, and what it contributed.

type SpamFilterResult

type SpamFilterResult struct {
	// Spam score
	Score float64 `json:"score"`

	// Spam symbols
	Symbols []string `json:"symbols,omitempty"`

	// Checks is the breakdown behind Score: which checks fired and what each
	// one cost. Empty for a message scored by an external SpamAssassin
	// daemon, whose protocol reports names without points.
	Checks []SpamFilterCheck `json:"checks,omitempty"`

	// Spam filter result
	Result string `json:"result,omitempty"`
}

SpamFilterResult holds authentication results related to spam filtering.

type SpamRuleSet

type SpamRuleSet struct {
	// Channel is where the rules came from.
	Channel string `json:"channel"`

	// Version is what the source called this set, and is what an instance
	// compares against the copy it has parsed.
	Version string `json:"version"`

	// Content is the rule text as stored. Absent from listings, which do not
	// display it.
	Content []byte `json:"-"`

	// RulesLoaded and RulesSkipped are how much of it this server could use.
	// A published set contains rules that need plugins this server does not
	// have, and patterns its regular expression engine will not compile.
	RulesLoaded  int `json:"rulesLoaded"`
	RulesSkipped int `json:"rulesSkipped"`

	UpdatedAt time.Time `json:"updatedAt,omitempty"`

	// Error is why the last attempt to update this channel failed, or empty.
	Error string `json:"error,omitempty"`
}

SpamRuleSet is one channel's stored pattern rules.

Stored in the database rather than on an instance's disk so that every instance evaluates the same rules; see the migration that creates the table for why that matters.

type SpamTokenCount

type SpamTokenCount struct {
	SpamCount int64
	HamCount  int64
}

SpamTokenCount is what has been learned about one token.

type SpamTokenDelta

type SpamTokenDelta struct {
	Token     string
	SpamCount int64
	HamCount  int64
}

SpamTokenDelta is a change to one token's counts.

type SpamTraining

type SpamTraining struct {
	// MailID is the message that was marked.
	MailID string `json:"mailId"`

	// Label is SpamTrainingLabelSpam or SpamTrainingLabelHam.
	Label string `json:"label"`

	CreatedAt  time.Time `json:"createdAt,omitempty"`
	ModifiedAt time.Time `json:"modifiedAt,omitempty"`
}

SpamTraining records that a message was used to teach the classifier.

Keeping this, rather than only the counts, is what makes marking a message idempotent and un-marking exact: without it, pressing "this is spam" twice would count the message twice and quietly bias the corpus with no way to tell.

type SpendingCategory added in v0.87.0

type SpendingCategory struct {
	ID                   string `json:"id"`
	AgentID              string `json:"agentId"`
	SpendingCategoryName string `json:"spendingCategoryName"`

	// ParentSpendingCategoryID is the one level of parent, empty for a
	// top-level spending category.
	ParentSpendingCategoryID string `json:"parentSpendingCategoryId,omitempty" graphapi:"nullable"`

	// IsIncome says money in it is income rather than a refund of
	// spending; IsHidden that it is left out of lists and charts.
	IsIncome bool `json:"isIncome"`
	IsHidden bool `json:"isHidden"`

	// IsTransfer says it is the agent's transfer category, built in and
	// one per agent: a finance transaction in it moved money between the
	// person's own accounts and is neither spending nor income. It cannot
	// be deleted, be income, or have a parent or children.
	IsTransfer bool `json:"isTransfer"`

	// IsOther says it is the agent's other category, built in and one per
	// agent: what fits no other spending category, and the person's (or
	// the categorize model's) choice for it, where no spending category at
	// all would mean not decided yet. Money out in it is spending, and
	// money in it is income rather than a refund, though no income budget
	// counts it. It cannot be deleted, be an income category, or have a
	// parent or children.
	IsOther bool `json:"isOther"`

	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`
}

SpendingCategory is a label in the person's own list. Never called just "category", so it cannot be confused with the provider's.

type SpendingCategoryBudgetStatus added in v0.87.0

type SpendingCategoryBudgetStatus struct {
	SpendingCategoryID   string `json:"spendingCategoryId"`
	SpendingCategoryName string `json:"spendingCategoryName"`

	BudgetAmount string `json:"budgetAmount"`
	CurrencyCode string `json:"currencyCode"`

	// BudgetToDateAmount is the part of BudgetAmount for the days so far:
	// the month's budget spread evenly over its days up to AsOf, the whole
	// of it once the month is over. For a year, each month's budget in
	// force that month, whole for the months that are over and spread
	// over the days so far for the month in progress.
	BudgetToDateAmount string `json:"budgetToDateAmount"`

	// BudgetedMonthCount is how many months the budget was in force: one
	// for a month, and for a year the months of it that had a budget for
	// this spending category, which BudgetAmount adds up.
	BudgetedMonthCount int `json:"budgetedMonthCount"`

	// FirstBudgetedMonth and LastBudgetedMonth, "2006-01", are the first
	// and last of those months: the month itself for a month. A year's
	// budgeted months need not run unbroken between them.
	FirstBudgetedMonth string `json:"firstBudgetedMonth"`
	LastBudgetedMonth  string `json:"lastBudgetedMonth"`

	// SpendingAmount is the month's spending so far, and
	// SpendingBySameDayLastMonthAmount last month's by the same day. For a
	// year, SpendingAmount is the spending of the months that had this
	// budget, and nothing is compared with last month.
	SpendingAmount                   string `json:"spendingAmount"`
	SpendingBySameDayLastMonthAmount string `json:"spendingBySameDayLastMonthAmount"`

	// FixedChargesDueAmount is what merchants that charged this spending
	// category in each of the last three full months are expected to
	// charge again this month and have not yet. For a year, those of the
	// month in progress.
	FixedChargesDueAmount string `json:"fixedChargesDueAmount"`

	// ExpectedRepeatCharges are those merchants, one by one, so a
	// projection can be explained: the ones in the budget's currency, or
	// converted into it, add up to FixedChargesDueAmount, and the rest are
	// in their own currency and in UnconvertedFixedChargesDue. Largest
	// first.
	ExpectedRepeatCharges []*ExpectedRepeatCharge `json:"expectedRepeatCharges"`

	// ProjectedAmount is where the month is expected to end: SpendingAmount,
	// plus FixedChargesDueAmount, plus the rest of the spending at the rate
	// it has come this month for the days left. For a year
	// (ProjectSpendingCategoryYear), the months that are over as they
	// ended, the month in progress as projected, and each budgeted month
	// still to come at the average of those.
	ProjectedAmount string     `json:"projectedAmount"`
	BudgetPace      BudgetPace `json:"budgetPace"`

	// UnconvertedSpending is spending left out because its currency has no
	// exchange rate into the budget's, and
	// UnconvertedSpendingBySameDayLastMonth the same for last month's
	// spending by the same day. UnconvertedFixedChargesDue is the repeat
	// charges still expected this month that were left out of
	// FixedChargesDueAmount, and so of the projection, for the same reason.
	UnconvertedSpending                   []*CurrencyAmount `json:"unconvertedSpending"`
	UnconvertedSpendingBySameDayLastMonth []*CurrencyAmount `json:"unconvertedSpendingBySameDayLastMonth"`
	UnconvertedFixedChargesDue            []*CurrencyAmount `json:"unconvertedFixedChargesDue"`
}

SpendingCategoryBudgetStatus is one spending category against its budget. Every amount is a decimal in CurrencyCode, the budget's: spending in another currency is converted at the rate of the day it posted.

type SpendingCategoryDay added in v0.87.0

type SpendingCategoryDay struct {
	SpendingCategoryID string `json:"spendingCategoryId"`
	CurrencyCode       string `json:"currencyCode"`

	// SpentOn is the day, "2006-01-02".
	SpentOn        string `json:"spentOn"`
	SpendingAmount string `json:"spendingAmount"`
}

SpendingCategoryDay is one day's spending in one spending category and one currency: money out less refunds, transfers left out. Positive is spending; a day of refunds can be negative. The other category and what is not categorized yet count money out only, since their money in is income. SpendingCategoryID is empty for money out not categorized yet.

type SpendingRule added in v0.87.0

type SpendingRule struct {
	ID      string `json:"id"`
	AgentID string `json:"agentId"`

	// MatchText is matched case-insensitively as a substring of the
	// merchant, or of the description when there is no merchant.
	MatchText string `json:"matchText"`

	// FinanceAccountID limits it to one finance account; empty is any.
	// MinimumAmount and MaximumAmount bound the signed amount, both ends
	// included; empty is unbounded.
	FinanceAccountID string `json:"financeAccountId,omitempty" graphapi:"nullable"`
	MinimumAmount    string `json:"minimumAmount,omitempty" graphapi:"nullable"`
	MaximumAmount    string `json:"maximumAmount,omitempty" graphapi:"nullable"`

	// SpendingCategoryID is what it assigns.
	SpendingCategoryID string `json:"spendingCategoryId"`

	// RulePriority orders the rules: the lowest that matches wins.
	RulePriority int `json:"rulePriority"`

	CreatedAt  time.Time `json:"createdAt"`
	ModifiedAt time.Time `json:"modifiedAt"`
}

SpendingRule assigns a spending category to the finance transactions that match it; the transfer category marks them transfers.

type StatementImportOrigin added in v0.100.0

type StatementImportOrigin string

StatementImportOrigin is how a statement reached the server.

const (
	StatementImportOriginMail            StatementImportOrigin = "mail"
	StatementImportOriginUpload          StatementImportOrigin = "upload"
	StatementImportOriginMessage         StatementImportOrigin = "message"
	StatementImportOriginTransactionRows StatementImportOrigin = "transaction_rows"
)

A statement mailed to the person's import address, a file uploaded from the dashboard or the command line, the attachment of a message the person pointed at, or transaction rows sent instead of a file (what the agent read off screenshots, with ImportTransactions).

type StorageDiskWarning added in v0.234.0

type StorageDiskWarning struct {
	DiskLabel       string    `json:"diskLabel"`
	WarningDays     int       `json:"warningDays"`
	ProjectedFullOn time.Time `json:"projectedFullOn"`
	SentAt          time.Time `json:"sentAt"`
}

StorageDiskWarning is the warning last sent about a disk.

type StorageFileKindSize added in v0.234.0

type StorageFileKindSize struct {
	FileKind  string
	SizeBytes int64
}

StorageFileKindSize is what the rows say one kind of file holds.

type StorageMeasureKind added in v0.234.0

type StorageMeasureKind string

StorageMeasureKind says what a stored sample measures.

const (
	// StorageMeasureDatabase is the whole database, under the key "total".
	StorageMeasureDatabase StorageMeasureKind = "database"

	// StorageMeasureDatabaseArea is the tables of one area, such as mail or
	// photos, with their indexes.
	StorageMeasureDatabaseArea StorageMeasureKind = "databaseArea"

	// StorageMeasureFileKind is one kind of file in the blob store, such as
	// photo originals.
	StorageMeasureFileKind StorageMeasureKind = "fileKind"

	// StorageMeasureDisk is a disk the server measured: the bytes in use,
	// with its total and free bytes beside them.
	StorageMeasureDisk StorageMeasureKind = "disk"
)

type StoragePersonFileSize added in v0.234.0

type StoragePersonFileSize struct {
	UserID    string
	FileKind  string
	SizeBytes int64
}

StoragePersonFileSize is what one person's files of one kind hold.

type StorageRelationSize added in v0.234.0

type StorageRelationSize struct {
	TableName  string
	TotalBytes int64
}

StorageRelationSize is the size of one table with its indexes and its out-of-line storage.

type StorageUsageSample added in v0.234.0

type StorageUsageSample struct {
	SampledOn     time.Time          `json:"sampledOn"`
	MeasureKind   StorageMeasureKind `json:"measureKind"`
	MeasureKey    string             `json:"measureKey"`
	MeasuredBytes int64              `json:"measuredBytes"`

	// DiskTotalBytes and DiskFreeBytes are set for a disk and nil for
	// everything else.
	DiskTotalBytes *int64    `json:"diskTotalBytes,omitempty"`
	DiskFreeBytes  *int64    `json:"diskFreeBytes,omitempty"`
	SampledAt      time.Time `json:"sampledAt"`
}

StorageUsageSample is one measurement taken on one UTC day.

type Submission added in v0.48.0

type Submission struct {
	OwnerID        string
	SubmissionID   string
	MailboxID      string
	RequestDigest  string
	MailID         string
	SentItemID     string
	DraftItemID    string
	ReplyItemID    string
	ForwardItemID  string
	AcceptedAt     time.Time
	ReconciledAt   *time.Time
	ReconcileAfter *time.Time
}

Submission records local acceptance and the mailbox changes still owed to it. It survives deletion of the stored mail so an old identifier cannot send again.

type SyncCredential added in v0.139.0

type SyncCredential struct {
	ID                 string     `json:"id"`
	UserID             string     `json:"userId"`
	CreatedAt          time.Time  `json:"createdAt"`
	CredentialName     string     `json:"credentialName"`
	Selector           string     `json:"-"`
	PasswordHash       string     `json:"-"`
	HasCalendarAccess  bool       `json:"hasCalendarAccess"`
	HasRemindersAccess bool       `json:"hasRemindersAccess"`
	HasContactsAccess  bool       `json:"hasContactsAccess"`
	HasPhotosAccess    bool       `json:"hasPhotosAccess"`
	LastUsedAt         *time.Time `json:"lastUsedAt,omitempty"`
}

SyncCredential authorizes a device to synchronize selected account collections.

func (*SyncCredential) Allows added in v0.139.0

func (self *SyncCredential) Allows(service Service) bool

Allows reports the credential's scope, independently of deployment policy.

func (*SyncCredential) RedactForAudit added in v0.139.0

func (self *SyncCredential) RedactForAudit() any

RedactForAudit never records credential hashes.

type TargetMeasure added in v0.87.0

type TargetMeasure string

TargetMeasure is how a savings target's progress is measured.

const (
	TargetMeasureCashFlow   TargetMeasure = "cash_flow"
	TargetMeasureAssetValue TargetMeasure = "asset_value"
	TargetMeasureNetWorth   TargetMeasure = "net_worth"
)

The three measures: money not spent (income minus spending since the start), what chosen assets and finance accounts are worth now against what they were, or net worth now against what it was.

func (TargetMeasure) IsValid added in v0.87.0

func (self TargetMeasure) IsValid() bool

IsValid says the measure is one of the three.

type TaxFormKind added in v0.155.0

type TaxFormKind string

TaxFormKind is which tax form a finance tax form is.

const (
	// TaxFormKindW2 is a Form W-2, Wage and Tax Statement.
	TaxFormKindW2 TaxFormKind = "w2"
	// TaxFormKind1099Int is a Form 1099-INT, interest income.
	TaxFormKind1099Int TaxFormKind = "1099_int"
	// TaxFormKind1099Div is a Form 1099-DIV, dividends and distributions.
	TaxFormKind1099Div TaxFormKind = "1099_div"
	// TaxFormKind1099B is a Form 1099-B, proceeds from broker
	// transactions, kept as its totals by term and by whether the broker
	// reported the cost basis, as a brokerage's summary prints them.
	TaxFormKind1099B TaxFormKind = "1099_b"
	// TaxFormKind1098 is a Form 1098, mortgage interest, which itemizing
	// counts.
	TaxFormKind1098 TaxFormKind = "1098"
)

func (TaxFormKind) IsValid added in v0.155.0

func (self TaxFormKind) IsValid() bool

IsValid says the kind is a known form.

type TaxYearSetting added in v0.159.0

type TaxYearSetting struct {
	AgentID string `json:"-" graphapi:"ignore"`
	TaxYear int    `json:"taxYear"`
	// ChildCount is children under 17 at the year's end, for the child
	// tax credit; OtherDependentCount other dependents, for the credit for
	// them. Children under 13 are who dependent care is paid for.
	ChildCount          int `json:"childCount"`
	OtherDependentCount int `json:"otherDependentCount"`
	// DependentCareExpenseAmount is what was paid for the care of a child
	// under 13 so the parents could work.
	DependentCareExpenseAmount string `json:"dependentCareExpenseAmount"`
	// OtherIncomeAmount is the household's income no paystub or form here
	// shows, such as a spouse's pay; it is taxed as wages are, without
	// payroll taxes, and counts as the spouse's earned income.
	OtherIncomeAmount string `json:"otherIncomeAmount"`
	// CharitableContributionAmount and PropertyTaxAmount are itemized
	// deductions no form here shows.
	CharitableContributionAmount string `json:"charitableContributionAmount"`
	PropertyTaxAmount            string `json:"propertyTaxAmount"`
	// StateIncomeTaxPaidAmount is state and local income tax paid besides
	// what paychecks withheld (an estimated payment, last year's balance
	// due), which itemizing counts with the withholding.
	StateIncomeTaxPaidAmount string `json:"stateIncomeTaxPaidAmount"`
	// EstimatedShortTermGainAmount and EstimatedLongTermGainAmount are the
	// gains (negative for losses) realized so far in a year whose 1099-Bs
	// have not come, as a brokerage reports them; empty when not given.
	// EstimatedGainNote says where they came from and when.
	EstimatedShortTermGainAmount string     `json:"estimatedShortTermGainAmount,omitempty" graphapi:"nullable"`
	EstimatedLongTermGainAmount  string     `json:"estimatedLongTermGainAmount,omitempty" graphapi:"nullable"`
	EstimatedGainNote            string     `json:"estimatedGainNote"`
	ModifiedAt                   *time.Time `json:"modifiedAt,omitempty" graphapi:"nullable"`
}

TaxYearSetting is what a tax year's estimate needs that no paystub or form says, as the person or the agent gave it. Amounts are dollars with cents.

type Template

type Template struct {
	// ID of the Template
	ID string `json:"id,omitempty"`

	// Timestamp when the Template was created
	CreatedAt time.Time `json:"createdAt,omitempty"`

	// Timestamp when the Template was last modified
	ModifiedAt time.Time `json:"modifiedAt,omitempty"`

	// Domain that the Template belongs to
	DomainID string  `json:"domainId,omitempty"`
	Domain   *Domain `json:"-"`

	// Layout that the Template uses
	LayoutID string  `json:"layoutId,omitempty"`
	Layout   *Layout `json:"-"`

	// Name of the Template, must be unique within the Domain
	Name string `json:"name,omitempty"`

	// Comment about this Template
	Comment string `json:"comment,omitempty"`

	// Locale of the default Subject, HTMLContent and TextContent, such as "en" or "zh-CN"; optional
	Locale string `json:"locale,omitempty"`

	// Subject line
	Subject string `json:"subject,omitempty"`

	// HTML content
	HTMLContent string `json:"htmlContent,omitempty"`

	// Text content
	TextContent string `json:"textContent,omitempty"`

	// Translations of the subject and content into other locales
	Translations []*TemplateTranslation `json:"translations,omitempty"`

	// Names of the variables the Template and its Layout read when rendered, in every locale.
	// Derived when the Template is read rather than stored.
	Variables []string `json:"variables,omitempty"`
}

Template is a mail template.

type TemplateTranslation

type TemplateTranslation struct {
	// Locale this translation is in, such as "zh-CN"
	Locale string `json:"locale"`

	// Subject line
	Subject string `json:"subject,omitempty"`

	// HTML content
	HTMLContent string `json:"htmlContent,omitempty"`

	// Text content
	TextContent string `json:"textContent,omitempty"`
}

TemplateTranslation is a Template's subject and content in one locale.

type TermGender added in v0.178.0

type TermGender string

TermGender is the gender of a word for a relationship: "wife" is feminine, "husband" masculine, "spouse" neutral. It belongs to a word somebody chose, not to a person.

const (
	TermGenderMasculine TermGender = "masculine"
	TermGenderFeminine  TermGender = "feminine"
	TermGenderNeutral   TermGender = "neutral"
)

The genders of a word.

func (TermGender) IsValid added in v0.178.0

func (self TermGender) IsValid() bool

IsValid reports whether this is one of the genders.

type TextCorrectionOrigin added in v0.153.0

type TextCorrectionOrigin string

TextCorrectionOrigin says who made a text correction.

const (
	// TextCorrectionOriginPerson is a correction the person typed. It always wins.
	TextCorrectionOriginPerson TextCorrectionOrigin = "person"

	// TextCorrectionOriginGlossary is a fix the term correction pass made
	// from the person's own notes, contacts and calendar. The person may undo it.
	TextCorrectionOriginGlossary TextCorrectionOrigin = "glossary"
)

type ThreadSummary

type ThreadSummary struct {
	ThreadID  string `json:"threadId"`
	MailboxID string `json:"mailboxId"`
	AgentID   string `json:"agentId"`

	Summary string `json:"summary"`

	// ThroughMailID is the newest message the summary covers; a
	// conversation whose newest message is another one has outgrown it.
	ThroughMailID string `json:"throughMailId"`
	MessageCount  int    `json:"messageCount"`

	Model     string    `json:"model"`
	RunID     string    `json:"runId"`
	CreatedAt time.Time `json:"createdAt"`
}

ThreadSummary is what the agent wrote about a conversation for one mailbox, and how far into the conversation it read. It is rewritten from the previous one when the conversation grows, so a long conversation is never sent whole twice.

type Token

type Token struct {
	// ID of the Token, and the half of the token string that is not secret.
	// It appears in the log, so a token can be traced back to a row here and
	// revoked.
	ID string `json:"id,omitempty"`

	// Timestamp when the Token was created
	CreatedAt time.Time `json:"createdAt,omitempty"`

	// Timestamp when the Token was last modified
	ModifiedAt time.Time `json:"modifiedAt,omitempty"`

	// The User this Token belongs to. By identifier, so that renaming an
	// account does not revoke what it issued.
	UserID string `json:"userId,omitempty"`

	// The name that account signs in with, filled in by the queries that
	// resolve it. Not a column, for the same reason as on a Session.
	Username string `json:"username,omitempty"`

	// What holds it, for example "laptop". Not unique.
	Name string `json:"name,omitempty"`

	// When it stops working. Zero means it does not expire.
	ExpiresAt time.Time `json:"expiresAt,omitempty"`

	// When it was last used, and from where
	UsedAt    time.Time `json:"usedAt,omitempty"`
	IP        string    `json:"ip,omitempty"`
	UserAgent string    `json:"userAgent,omitempty"`

	// When it was revoked. Set rather than deleted, so the list can say so.
	RevokedAt time.Time `json:"revokedAt,omitempty"`

	// ClientID is the program a person authorized to hold this token, when
	// one was. Empty on a token somebody minted for themselves, which is
	// every token that existed before programs could be authorized.
	ClientID string `json:"clientId,omitempty"`

	// Resource is what this token is good for. Empty means what it has
	// always meant: this server, the way a token minted by hand is. A token
	// naming a resource is refused anywhere else, so one issued for the
	// agent tools endpoint cannot be replayed against the rest of the API.
	Resource string `json:"resource,omitempty"`

	// ClientKind says the token is the TeaNode phone app's own sign-in
	// (ClientKindApp), made in a place where a person was tapping: a connect
	// code made on the dashboard or in the app, or the app's consent
	// approved there. Empty on every other token, including one a program
	// got through a connect code or an approval that a command line token
	// made, because that sign-in could have been made by a program running
	// on the person's computer. Only a token of this kind is taken as a
	// person's tap (see CredentialKind).
	ClientKind TokenClientKind `json:"clientKind,omitempty"`
}

Token authenticates a program the way a Session authenticates a browser.

It belongs to an operator and acts as them, so removing the account removes its tokens. It used to live inside the account in the configuration, which meant recording when it was last used would have rewritten the whole configuration and had every instance reload it. When a token was last used is data, not a setting.

func (*Token) Active

func (self *Token) Active(now time.Time) bool

Active reports whether this Token would authenticate a request now.

func (*Token) Refreshable added in v0.49.0

func (self *Token) Refreshable(now time.Time) bool

Refreshable says whether a token can still be renewed: not revoked, and not further past its expiry than RefreshWindow.

type TokenClientKind added in v0.170.0

type TokenClientKind string

TokenClientKind is the marker on a token that its holder is the phone app.

const ClientKindApp TokenClientKind = "app"

ClientKindApp is the phone app's own sign-in.

type TradeKind added in v0.88.0

type TradeKind string

TradeKind is what a trade was.

const (
	TradeKindBuy      TradeKind = "buy"
	TradeKindSell     TradeKind = "sell"
	TradeKindCancel   TradeKind = "cancel"
	TradeKindTransfer TradeKind = "transfer"
)

A buy or a sell, a trade the institution cancelled, and a security moved into or out of the account (from another brokerage, or by a split or a merger).

func (TradeKind) IsValid added in v0.88.0

func (self TradeKind) IsValid() bool

IsValid says the kind is one of the four.

type TravelModeCorrection added in v0.203.0

type TravelModeCorrection struct {
	ID     string `json:"id"`
	UserID string `json:"userId"`

	StartedAt  time.Time `json:"startedAt"`
	EndedAt    time.Time `json:"endedAt"`
	TravelMode string    `json:"travelMode"`

	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

TravelModeCorrection is the person saying that the span of time from StartedAt to EndedAt was traveled the way TravelMode says.

type TravelTotal added in v0.203.0

type TravelTotal struct {
	PeriodStartDay  string  `json:"periodStartDay"`
	TravelMode      string  `json:"travelMode"`
	DistanceMeters  float64 `json:"distanceMeters"`
	DurationSeconds int64   `json:"durationSeconds"`
	LegCount        int     `json:"legCount"`
}

TravelTotal is the distance and time traveled one way in one period. PeriodStartDay is the first day of the period, as YYYY-MM-DD in the traveler's time zone.

type Trip added in v0.203.0

type Trip struct {
	ID     string `json:"id"`
	UserID string `json:"userId"`

	StartedAt time.Time `json:"startedAt"`
	EndedAt   time.Time `json:"endedAt"`

	FromVisitID string `json:"fromVisitId,omitempty"`
	ToVisitID   string `json:"toVisitId,omitempty"`

	DistanceMeters float64 `json:"distanceMeters"`

	CreatedAt time.Time `json:"createdAt"`

	// Legs are oldest first, filled in by the listing of trips.
	Legs []*TripLeg `json:"legs,omitempty"`
}

Trip is the travel between the departure of one visit and the arrival of the next. It is derived data, built again whenever the visits, positions or motion activity around it change. FromVisitID and ToVisitID are empty when the visit is gone.

type TripLeg added in v0.203.0

type TripLeg struct {
	ID     string `json:"id"`
	TripID string `json:"tripId"`
	UserID string `json:"userId"`

	StartedAt time.Time `json:"startedAt"`
	EndedAt   time.Time `json:"endedAt"`

	TravelMode            string `json:"travelMode"`
	DetectedTravelMode    string `json:"detectedTravelMode"`
	IsTravelModeCorrected bool   `json:"isTravelModeCorrected"`
	DetectionSource       string `json:"detectionSource"`

	DistanceMeters float64 `json:"distanceMeters"`
}

TripLeg is a part of a trip made one way. DetectedTravelMode is what was worked out from motion activity or speed; TravelMode is the way after the person's corrections, which is the one to show and to count. They differ exactly when IsTravelModeCorrected. DetectionSource is motion or speed. TravelMode and IsTravelModeCorrected are filled in by the reads, not stored.

type UnattendedRisk added in v0.113.0

type UnattendedRisk string

UnattendedRisk is a reason a call needs the person's word, as the person allows it for when they are not there.

const (
	UnattendedRiskOutward     UnattendedRisk = "outward"
	UnattendedRiskMoney       UnattendedRisk = "money"
	UnattendedRiskDestructive UnattendedRisk = "destructive"
	UnattendedRiskGranting    UnattendedRisk = "granting"
	UnattendedRiskListed      UnattendedRisk = "listed"
)

The reasons a person may allow: the call speaks for them (sends mail, posts a message), spends or moves their money (a payment, an order, a trade, a transfer), cannot be undone (deletes for good, overwrites), gives somebody access, or is a tool on their own "ask me first" list.

const UnattendedRiskOperatorListed UnattendedRisk = "operatorListed"

UnattendedRiskOperatorListed is the reason no person can allow: a tool on the operator's "ask first" list, which only ever makes the agent more careful.

const UnattendedRiskPersonsAnswer UnattendedRisk = "personsAnswer"

UnattendedRiskPersonsAnswer is the other reason no person can allow: the call answers something that waits for the person's own word, such as the call a person they shared a paying skill with is waiting on. Only the person gives that, so an allowance for when they are not there never covers it.

func (UnattendedRisk) IsValid added in v0.113.0

func (self UnattendedRisk) IsValid() bool

IsValid says the reason is one a person may allow.

type Usage

type Usage struct {
	// Unix timestamp, seconds since epoch
	Timestamp uint64 `json:"timestamp,omitempty"`

	// Interval length in seconds
	Interval uint64 `json:"interval,omitempty"`

	// Values recorded
	Values []uint64 `json:"values,omitempty"`
}

Usage is a record of resource usage.

func FilterUsages

func FilterUsages(usages []Usage, maxHourlyUsages uint64) []Usage

func MergeUsages

func MergeUsages(existingUsages, newUsages []Usage) []Usage

func NewUsages

func NewUsages(now time.Time, values []uint64) []Usage

func SmoothUsages

func SmoothUsages(usages []Usage, fromTimestamp, toTimestamp, interval uint64) Usage

type User

type User struct {
	// ID of the User, stable for its lifetime
	ID string `json:"id,omitempty"`

	// Timestamp when the User was created
	CreatedAt time.Time `json:"createdAt,omitempty"`

	// Timestamp when the User was last modified
	ModifiedAt time.Time `json:"modifiedAt,omitempty"`

	// Username they sign in with. Unique without regard to case.
	Username string `json:"username,omitempty"`

	// Name is what to call this person, when they have said. The username is
	// what they sign in with, which is not always something to greet somebody
	// by. Optional.
	Name string `json:"name,omitempty"`

	// PasswordHash is a bcrypt hash, and never leaves the server. Empty for
	// a user who signs in only with a passkey or through an identity
	// provider.
	PasswordHash string `json:"-"`

	// Email receives notifications, such as a domain whose DNS records have
	// stopped resolving. Optional, and not a mailbox address: a mailbox may
	// have several.
	Email string `json:"email,omitempty"`

	// ContactID names the address book entry that is this person
	// themselves -- what a contacts program calls "my card". It carries
	// their own addresses, which is how a commit or a sent message is told
	// from somebody else's, and the agent's "self" page reads it live
	// rather than copying it. Optional; empty until they choose one.
	ContactID string `json:"contactId,omitempty"`

	// AvatarFileID names the stored file holding their picture, empty when
	// they have none. It is a storage key, not an address: the picture is
	// served at /api/v1/avatar/user/<id>, and this id is never sent to a
	// client.
	AvatarFileID string `json:"avatarFileId,omitempty"`

	// AvatarUpdatedAt is when the picture last changed. It versions the
	// picture's address and its ETag.
	AvatarUpdatedAt *time.Time `json:"avatarUpdatedAt,omitempty"`

	// DisabledAt, when set, means this person cannot sign in and their
	// mailboxes take no new mail. The mail they have and their memberships
	// are kept, so enabling them again restores everything.
	DisabledAt *time.Time `json:"disabledAt,omitempty"`

	// Locale is the language the web UI greets them in, when they chose one.
	Locale string `json:"locale,omitempty"`

	// LocaleSeen is the language their browser or command line last said,
	// learned rather than chosen; what the agent writes in when Locale is
	// empty.
	LocaleSeen string `json:"localeSeen,omitempty"`

	// Timezone is where they are, as an IANA name. Learned from the browser
	// while TimezoneMode is auto; kept as set while it is fixed.
	Timezone       string     `json:"timezone,omitempty"`
	TimezoneMode   string     `json:"timezoneMode,omitempty"` // auto | fixed; empty is auto
	TimezoneSeenAt *time.Time `json:"timezoneSeenAt,omitempty"`

	// MeasurementSystem is the units they read measurements in: metric, us,
	// or empty to follow their language and region. See measurement.go.
	MeasurementSystem string `json:"measurementSystem,omitempty"`

	// Pronoun is how they are described, as they said it; empty until they
	// do. See relationship.go.
	Pronoun Pronoun `json:"pronoun,omitempty"`

	// GroupIDs are the groups this person is in. Loaded with the user.
	GroupIDs []string `json:"groupIds,omitempty"`
}

User is somebody with an account on this server: a person who signs in to the web UI, reads a mailbox, and holds whatever permissions the groups they are in give them.

Keyed by an identifier rather than by the name they sign in with. The name can change, and a key that changes is not a key: sessions, API tokens, passkeys, mailboxes and group memberships all name an account, and every one of them would have had to be rewritten by a rename.

func (*User) Disabled

func (self *User) Disabled() bool

Disabled reports whether this person may not sign in.

func (*User) DisplayName

func (self *User) DisplayName() string

DisplayName is what to call this person: the name they gave, or the name they sign in with when they have not given one.

func (*User) RedactForAudit

func (self *User) RedactForAudit() any

RedactForAudit is the user as an audit row records it: without the hash.

func (*User) UsesUSUnits added in v0.202.0

func (self *User) UsesUSUnits() bool

UsesUSUnits says whether numbers are written in US units for this person. It reads the language they chose, else the one their browser last said.

func (*User) Validate

func (self *User) Validate() error

Validate reports everything wrong with the user.

type UserIdentity

type UserIdentity struct {
	ID         string    `json:"id"`
	CreatedAt  time.Time `json:"createdAt"`
	UserID     string    `json:"userId"`
	Provider   string    `json:"provider"`
	Subject    string    `json:"subject"`
	Email      string    `json:"email,omitempty"`
	LastSeenAt time.Time `json:"lastSeenAt"`
}

UserIdentity is an account's identity at an identity provider: the provider's name in this server's settings, and the subject the provider calls the person. Looked up on every single sign-on; created on the first.

type ValidationError

type ValidationError struct {
	Path    string
	Message string
}

ValidationError is one thing wrong with a row, named by the field it is wrong in, so that a form can put the message beside the field.

func (*ValidationError) Error

func (self *ValidationError) Error() string

type ValidationErrors

type ValidationErrors []*ValidationError

ValidationErrors is every problem found at once, so that fixing a row is not a game of whack-a-mole.

func (ValidationErrors) ErrOrNil

func (self ValidationErrors) ErrOrNil() error

ErrOrNil is the error to return: nil when nothing was found.

func (ValidationErrors) Error

func (self ValidationErrors) Error() string

type ValuationSource added in v0.87.0

type ValuationSource string

ValuationSource is where a valuation came from. An asset's own is the one its values normally come from; a valuation's is the one it did.

const (
	ValuationSourceFinanceSync   ValuationSource = "finance_sync"
	ValuationSourceAgentReading  ValuationSource = "agent_reading"
	ValuationSourceManual        ValuationSource = "manual"
	ValuationSourceAgentEstimate ValuationSource = "agent_estimate"
)

The four valuation sources: a finance account's balance at a sync, the agent reading an account through a connected server, the person, and the agent estimating from the web where the person allowed it.

func (ValuationSource) IsValid added in v0.87.0

func (self ValuationSource) IsValid() bool

IsValid says the source is one of the four.

type VisitSource added in v0.175.0

type VisitSource string

VisitSource is how a visit came to be recorded.

const (
	// VisitSourceVisit is iOS visit monitoring, which reports arrivals and
	// departures on its own schedule.
	VisitSourceVisit VisitSource = "visit"
	// VisitSourceRegion is the phone entering or leaving a place the person
	// named.
	VisitSourceRegion VisitSource = "region"
	// VisitSourceCheckIn is a visit the person recorded by hand.
	VisitSourceCheckIn VisitSource = "check_in"
	// VisitSourceBrowser is a visit recorded from the dashboard.
	VisitSourceBrowser VisitSource = "browser"
)

The sources of a visit.

func (VisitSource) IsValid added in v0.175.0

func (self VisitSource) IsValid() bool

IsValid reports whether this is one of the sources.

Jump to

Keyboard shortcuts

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