domain

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 30, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package domain contains the core business logic and domain models.

Package domain contains the core business logic and domain models.

Index

Constants

View Source
const (
	// TimeoutAPI is the default timeout for Nylas API calls (90s).
	TimeoutAPI = 90 * time.Second

	// TimeoutAI is the timeout for AI/LLM operations (120s).
	// AI providers may take longer due to model inference time.
	TimeoutAI = 120 * time.Second

	// TimeoutMCP is the timeout for MCP proxy operations (90s).
	// Allows time for tool execution and response processing.
	TimeoutMCP = 90 * time.Second

	// TimeoutHealthCheck is the timeout for health/connectivity checks (10s).
	TimeoutHealthCheck = 10 * time.Second

	// TimeoutOAuth is the timeout for OAuth authentication flows (5m).
	// OAuth requires user interaction in browser, so needs longer timeout.
	TimeoutOAuth = 5 * time.Minute

	// TimeoutBulkOperation is the timeout for bulk operations like fetching
	// all Slack messages or channels (10m).
	TimeoutBulkOperation = 10 * time.Minute

	// TimeoutQuickCheck is the timeout for quick checks like version checking (5s).
	TimeoutQuickCheck = 5 * time.Second

	// HTTP Server timeouts
	HTTPReadHeaderTimeout = 10 * time.Second  // Time to read request headers
	HTTPReadTimeout       = 30 * time.Second  // Time to read entire request
	HTTPWriteTimeout      = 30 * time.Second  // Time to write response
	HTTPIdleTimeout       = 120 * time.Second // Keep-alive connection idle timeout
)

Timeout constants for consistent behavior across the application. Use these instead of hardcoding timeout values.

View Source
const (
	FolderInbox   = "inbox"
	FolderSent    = "sent"
	FolderDrafts  = "drafts"
	FolderTrash   = "trash"
	FolderSpam    = "spam"
	FolderArchive = "archive"
	FolderAll     = "all"
)

SystemFolder constants for common folder types.

View Source
const (
	NotetakerStateScheduled       = "scheduled"
	NotetakerStateConnecting      = "connecting"
	NotetakerStateWaitingForEntry = "waiting_for_entry"
	NotetakerStateAttending       = "attending"
	NotetakerStateMediaProcessing = "media_processing"
	NotetakerStateComplete        = "complete"
	NotetakerStateCancelled       = "cancelled"
	NotetakerStateFailed          = "failed"
)

NotetakerState constants for notetaker states.

View Source
const (
	// Grant triggers
	TriggerGrantCreated          = "grant.created"
	TriggerGrantDeleted          = "grant.deleted"
	TriggerGrantExpired          = "grant.expired"
	TriggerGrantUpdated          = "grant.updated"
	TriggerGrantIMAPSyncComplete = "grant.imap_sync_completed"

	// Message triggers
	TriggerMessageCreated         = "message.created"
	TriggerMessageUpdated         = "message.updated"
	TriggerMessageOpened          = "message.opened"
	TriggerMessageBounceDetected  = "message.bounce_detected"
	TriggerMessageSendSuccess     = "message.send_success"
	TriggerMessageSendFailed      = "message.send_failed"
	TriggerMessageOpenedTruncated = "message.opened.truncated"
	TriggerMessageLinkClicked     = "message.link_clicked"

	// Thread triggers
	TriggerThreadReplied = "thread.replied"

	// Event triggers
	TriggerEventCreated = "event.created"
	TriggerEventUpdated = "event.updated"
	TriggerEventDeleted = "event.deleted"

	// Contact triggers
	TriggerContactCreated = "contact.created"
	TriggerContactUpdated = "contact.updated"
	TriggerContactDeleted = "contact.deleted"

	// Calendar triggers
	TriggerCalendarCreated = "calendar.created"
	TriggerCalendarUpdated = "calendar.updated"
	TriggerCalendarDeleted = "calendar.deleted"

	// Folder triggers
	TriggerFolderCreated = "folder.created"
	TriggerFolderUpdated = "folder.updated"
	TriggerFolderDeleted = "folder.deleted"

	// Notetaker triggers
	TriggerNotetakerMedia = "notetaker.media"
)

Common webhook trigger types.

Variables

View Source
var (
	// Auth errors
	ErrNotConfigured   = errors.New("nylas not configured")
	ErrAuthFailed      = errors.New("authentication failed")
	ErrAuthTimeout     = errors.New("authentication timed out")
	ErrInvalidProvider = errors.New("invalid provider")
	ErrGrantNotFound   = errors.New("grant not found")
	ErrNoDefaultGrant  = errors.New("no default grant set")
	ErrInvalidGrant    = errors.New("invalid or expired grant")
	ErrTokenExpired    = errors.New("token expired")
	ErrAPIError        = errors.New("nylas API error")
	ErrNetworkError    = errors.New("network error")
	ErrInvalidInput    = errors.New("invalid input")

	// Secret store errors
	ErrSecretNotFound    = errors.New("secret not found")
	ErrSecretStoreFailed = errors.New("secret store operation failed")

	// Config errors
	ErrConfigNotFound = errors.New("config not found")
	ErrConfigInvalid  = errors.New("config invalid")

	// OTP errors
	ErrOTPNotFound     = errors.New("no OTP found in recent messages")
	ErrAccountNotFound = errors.New("account not found")
	ErrNoMessages      = errors.New("no messages found")

	// Slack errors
	ErrSlackNotConfigured    = errors.New("slack not configured")
	ErrSlackAuthFailed       = errors.New("slack authentication failed")
	ErrSlackRateLimited      = errors.New("slack rate limited")
	ErrSlackChannelNotFound  = errors.New("slack channel not found")
	ErrSlackMessageNotFound  = errors.New("slack message not found")
	ErrSlackPermissionDenied = errors.New("slack permission denied")

	// Resource not found errors - use these instead of creating ad-hoc errors.
	// Wrap with additional context: fmt.Errorf("%w: %s", domain.ErrContactNotFound, id)
	ErrContactNotFound     = errors.New("contact not found")
	ErrEventNotFound       = errors.New("event not found")
	ErrCalendarNotFound    = errors.New("calendar not found")
	ErrMessageNotFound     = errors.New("message not found")
	ErrFolderNotFound      = errors.New("folder not found")
	ErrDraftNotFound       = errors.New("draft not found")
	ErrThreadNotFound      = errors.New("thread not found")
	ErrAttachmentNotFound  = errors.New("attachment not found")
	ErrWebhookNotFound     = errors.New("webhook not found")
	ErrNotetakerNotFound   = errors.New("notetaker not found")
	ErrTemplateNotFound    = errors.New("template not found")
	ErrApplicationNotFound = errors.New("application not found")
	ErrConnectorNotFound   = errors.New("connector not found")
	ErrCredentialNotFound  = errors.New("credential not found")

	// Scheduler errors
	ErrBookingNotFound       = errors.New("booking not found")
	ErrSessionNotFound       = errors.New("session not found")
	ErrConfigurationNotFound = errors.New("configuration not found")
	ErrPageNotFound          = errors.New("page not found")
)

Sentinel errors for the application.

View Source
var SupportedAirProviders = []Provider{ProviderGoogle, ProviderMicrosoft}

SupportedAirProviders lists providers supported by the Air web UI.

Functions

func AllTriggerTypes

func AllTriggerTypes() []string

AllTriggerTypes returns all available trigger types.

func Each

func Each[T any](items []T, fn func(T))

Each iterates over items and calls the function for each.

func Filter

func Filter[T any](items []T, predicate FilterFunc[T]) []T

Filter returns items matching the predicate.

func Map

func Map[T, R any](items []T, fn MapFunc[T, R]) []R

Map transforms a slice using the provided function.

func TriggerTypeCategories

func TriggerTypeCategories() map[string][]string

TriggerTypeCategories returns trigger types grouped by category.

Types

type AIConfig

type AIConfig struct {
	DefaultProvider string            `yaml:"default_provider"` // ollama, claude, openai, groq
	Fallback        *AIFallbackConfig `yaml:"fallback,omitempty"`
	Privacy         *PrivacyConfig    `yaml:"privacy,omitempty"`
	Features        *FeaturesConfig   `yaml:"features,omitempty"`
	Ollama          *OllamaConfig     `yaml:"ollama,omitempty"`
	Claude          *ClaudeConfig     `yaml:"claude,omitempty"`
	OpenAI          *OpenAIConfig     `yaml:"openai,omitempty"`
	Groq            *GroqConfig       `yaml:"groq,omitempty"`
	OpenRouter      *OpenRouterConfig `yaml:"openrouter,omitempty"`
}

AIConfig represents AI/LLM configuration.

func DefaultAIConfig

func DefaultAIConfig() *AIConfig

DefaultAIConfig returns a default AI configuration for first-time setup.

func (*AIConfig) IsConfigured

func (c *AIConfig) IsConfigured() bool

IsConfigured returns true if the AI config has at least one provider configured.

func (*AIConfig) ValidateForProvider

func (c *AIConfig) ValidateForProvider(provider string) error

ValidateForProvider validates that the required fields are set for the given provider.

type AIFallbackConfig

type AIFallbackConfig struct {
	Enabled   bool     `yaml:"enabled"`
	Providers []string `yaml:"providers"` // Try in order
}

AIFallbackConfig represents fallback configuration.

type APIConfig

type APIConfig struct {
	BaseURL string `yaml:"base_url,omitempty"` // API base URL
}

APIConfig represents API-specific configuration.

type AcceptancePatterns

type AcceptancePatterns struct {
	ByDayOfWeek  map[string]float64 `json:"by_day_of_week"`  // Monday -> 0.92
	ByTimeOfDay  map[string]float64 `json:"by_time_of_day"`  // "09:00" -> 0.85
	ByDayAndTime map[string]float64 `json:"by_day_and_time"` // "Monday-09:00" -> 0.95
	Overall      float64            `json:"overall"`         // Overall acceptance rate
}

AcceptancePatterns tracks meeting acceptance rates.

type AdaptiveChangeType

type AdaptiveChangeType string

AdaptiveChangeType represents the type of adaptive change.

const (
	ChangeTypeIncreaseFocusTime AdaptiveChangeType = "increase_focus_time" // Add more focus blocks
	ChangeTypeRescheduleMeeting AdaptiveChangeType = "reschedule_meeting"  // Move meeting
	ChangeTypeShortenMeeting    AdaptiveChangeType = "shorten_meeting"     // Reduce duration
	ChangeTypeDeclineMeeting    AdaptiveChangeType = "decline_meeting"     // Decline meeting
	ChangeTypeMoveMeetingLater  AdaptiveChangeType = "move_meeting_later"  // Postpone meeting
	ChangeTypeProtectBlock      AdaptiveChangeType = "protect_block"       // Add focus protection
)

type AdaptiveImpact

type AdaptiveImpact struct {
	FocusTimeGained      float64  `json:"focus_time_gained"` // Hours gained
	MeetingsRescheduled  int      `json:"meetings_rescheduled"`
	MeetingsDeclined     int      `json:"meetings_declined"`
	DurationSaved        int      `json:"duration_saved"` // Minutes saved
	ConflictsResolved    int      `json:"conflicts_resolved"`
	ParticipantsAffected int      `json:"participants_affected"`
	PredictedBenefit     string   `json:"predicted_benefit"`
	Risks                []string `json:"risks,omitempty"`
}

AdaptiveImpact represents the impact of adaptive scheduling changes.

type AdaptiveScheduleChange

type AdaptiveScheduleChange struct {
	ID             string                 `json:"id"`
	Timestamp      time.Time              `json:"timestamp"`
	Trigger        AdaptiveTrigger        `json:"trigger"`
	ChangeType     AdaptiveChangeType     `json:"change_type"`
	AffectedEvents []string               `json:"affected_events"` // Event IDs
	Changes        []ScheduleModification `json:"changes"`
	Reason         string                 `json:"reason"`
	Impact         AdaptiveImpact         `json:"impact"`
	UserApproval   ApprovalStatus         `json:"user_approval"`
	AutoApplied    bool                   `json:"auto_applied"`
	Confidence     float64                `json:"confidence"` // 0-100
}

AdaptiveScheduleChange represents a change made by adaptive scheduling.

type AdaptiveTrigger

type AdaptiveTrigger string

AdaptiveTrigger represents what triggered the adaptive scheduling.

const (
	TriggerDeadlineChange   AdaptiveTrigger = "deadline_change"    // Project deadline changed
	TriggerMeetingOverload  AdaptiveTrigger = "meeting_overload"   // Too many meetings scheduled
	TriggerPriorityShift    AdaptiveTrigger = "priority_shift"     // Priority changed
	TriggerFocusTimeAtRisk  AdaptiveTrigger = "focus_time_at_risk" // Focus time being eroded
	TriggerConflictDetected AdaptiveTrigger = "conflict_detected"  // Schedule conflict
	TriggerPatternDetected  AdaptiveTrigger = "pattern_detected"   // Pattern learned
)

type AgendaItem

type AgendaItem struct {
	Title       string `json:"title"`
	Duration    int    `json:"duration"` // In minutes
	Description string `json:"description,omitempty"`
	Source      string `json:"source,omitempty"` // Quote from email thread
	Owner       string `json:"owner,omitempty"`  // Who should lead this item
	Decision    bool   `json:"decision"`         // Does this require a decision?
}

AgendaItem represents a single agenda item.

type AppearanceSettings

type AppearanceSettings struct {
	CompanyName     string `json:"company_name,omitempty"`
	Color           string `json:"color,omitempty"`
	SubmitText      string `json:"submit_text,omitempty"`
	ThankYouMessage string `json:"thank_you_message,omitempty"`
}

AppearanceSettings represents UI customization settings

type Application

type Application struct {
	ID               string            `json:"id,omitempty"`
	ApplicationID    string            `json:"application_id,omitempty"`
	OrganizationID   string            `json:"organization_id,omitempty"`
	Region           string            `json:"region,omitempty"`
	Environment      string            `json:"environment,omitempty"`
	BrandingSettings *BrandingSettings `json:"branding,omitempty"`
	CallbackURIs     []CallbackURI     `json:"callback_uris,omitempty"`
	Metadata         map[string]string `json:"metadata,omitempty"`
	CreatedAt        *UnixTime         `json:"created_at,omitempty"`
	UpdatedAt        *UnixTime         `json:"updated_at,omitempty"`
}

Application represents a Nylas application

type ApprovalStatus

type ApprovalStatus string

ApprovalStatus represents the status of an override approval.

const (
	ApprovalPending  ApprovalStatus = "pending"
	ApprovalApproved ApprovalStatus = "approved"
	ApprovalDenied   ApprovalStatus = "denied"
	ApprovalExpired  ApprovalStatus = "expired"
)

type Attachment

type Attachment struct {
	ID          string `json:"id,omitempty"`
	GrantID     string `json:"grant_id,omitempty"`
	Filename    string `json:"filename"`
	ContentType string `json:"content_type"`
	Size        int64  `json:"size"`
	ContentID   string `json:"content_id,omitempty"`
	IsInline    bool   `json:"is_inline,omitempty"`
	Content     []byte `json:"-"` // Binary content, not serialized to JSON
}

Attachment represents an email attachment.

type AvailabilityBuffer

type AvailabilityBuffer struct {
	Before int `json:"before,omitempty"`
	After  int `json:"after,omitempty"`
}

AvailabilityBuffer represents buffer time before/after meetings

type AvailabilityData

type AvailabilityData struct {
	TimeSlots []AvailableSlot `json:"time_slots"`
	Order     []string        `json:"order,omitempty"` // For round-robin scheduling
}

AvailabilityData contains the time slots data from availability API.

type AvailabilityParticipant

type AvailabilityParticipant struct {
	Email       string   `json:"email"`
	CalendarIDs []string `json:"calendar_ids,omitempty"`
}

AvailabilityParticipant represents a participant in availability check.

type AvailabilityRequest

type AvailabilityRequest struct {
	StartTime       int64                     `json:"start_time"`
	EndTime         int64                     `json:"end_time"`
	DurationMinutes int                       `json:"duration_minutes"`
	Participants    []AvailabilityParticipant `json:"participants"`
	IntervalMinutes int                       `json:"interval_minutes,omitempty"`
	RoundTo         int                       `json:"round_to,omitempty"`
}

AvailabilityRequest for finding available meeting times.

type AvailabilityResponse

type AvailabilityResponse struct {
	Data AvailabilityData `json:"data"`
}

AvailabilityResponse contains available time slots.

type AvailabilityRules

type AvailabilityRules struct {
	DurationMinutes    int                 `json:"duration_minutes"`
	IntervalMinutes    int                 `json:"interval_minutes,omitempty"`
	RoundTo            int                 `json:"round_to,omitempty"`
	AvailabilityMethod string              `json:"availability_method,omitempty"` // "max-fairness", "max-availability"
	Buffer             *AvailabilityBuffer `json:"buffer,omitempty"`
}

AvailabilityRules defines availability rules for scheduling

type AvailableSlot

type AvailableSlot struct {
	StartTime int64    `json:"start_time"`
	EndTime   int64    `json:"end_time"`
	Emails    []string `json:"emails,omitempty"`
}

AvailableSlot represents an available meeting slot.

type Booking

type Booking struct {
	BookingID        string               `json:"booking_id"`
	EventID          string               `json:"event_id,omitempty"`
	Title            string               `json:"title"`
	Organizer        Participant          `json:"organizer"`              // Reuses Participant from calendar.go
	Participants     []Participant        `json:"participants,omitempty"` // Reuses Participant from calendar.go
	StartTime        time.Time            `json:"start_time"`
	EndTime          time.Time            `json:"end_time"`
	Status           string               `json:"status"` // "confirmed", "cancelled", "pending"
	Description      string               `json:"description,omitempty"`
	Location         string               `json:"location,omitempty"`
	Timezone         string               `json:"timezone,omitempty"`
	Conferencing     *ConferencingDetails `json:"conferencing,omitempty"` // Reuses ConferencingDetails from calendar.go
	AdditionalFields map[string]any       `json:"additional_fields,omitempty"`
	Metadata         map[string]string    `json:"metadata,omitempty"`
	CreatedAt        time.Time            `json:"created_at,omitempty"`
	UpdatedAt        time.Time            `json:"updated_at,omitempty"`
}

Booking represents a scheduled booking

type BotConfig

type BotConfig struct {
	Name      string `json:"name,omitempty"`
	AvatarURL string `json:"avatar_url,omitempty"`
}

BotConfig represents the configuration for a notetaker bot.

type BrandingSettings

type BrandingSettings struct {
	Name              string `json:"name,omitempty"`
	IconURL           string `json:"icon_url,omitempty"`
	WebsiteURL        string `json:"website_url,omitempty"`
	Description       string `json:"description,omitempty"`
	PrivacyPolicyURL  string `json:"privacy_policy_url,omitempty"`
	TermsOfServiceURL string `json:"terms_of_service_url,omitempty"`
}

BrandingSettings represents application branding configuration

type BreakBlock

type BreakBlock struct {
	Name  string `yaml:"name"`           // Break name (e.g., "Lunch", "Coffee Break")
	Start string `yaml:"start"`          // Start time (HH:MM format)
	End   string `yaml:"end"`            // End time (HH:MM format)
	Type  string `yaml:"type,omitempty"` // Optional type: "lunch", "coffee", "custom"
}

BreakBlock represents a break period within working hours.

func (BreakBlock) Validate

func (b BreakBlock) Validate() error

Validate checks that BreakBlock has valid time format and end is after start.

type Calendar

type Calendar struct {
	ID          string `json:"id"`
	GrantID     string `json:"grant_id"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Location    string `json:"location,omitempty"`
	Timezone    string `json:"timezone,omitempty"`
	ReadOnly    bool   `json:"read_only"`
	IsPrimary   bool   `json:"is_primary,omitempty"`
	IsOwner     bool   `json:"is_owner,omitempty"`
	HexColor    string `json:"hex_color,omitempty"`
	Object      string `json:"object,omitempty"`
}

Calendar represents a calendar from Nylas.

type CalendarListResponse

type CalendarListResponse struct {
	Data       []Calendar `json:"data"`
	Pagination Pagination `json:"pagination,omitempty"`
}

CalendarListResponse represents a paginated calendar list response.

type CallbackURI

type CallbackURI struct {
	ID       string `json:"id,omitempty"`
	Platform string `json:"platform,omitempty"`
	URL      string `json:"url,omitempty"`
}

CallbackURI represents a callback URI configuration

type ChatMessage

type ChatMessage struct {
	Role    string `json:"role"`    // system, user, assistant, tool
	Content string `json:"content"` // Message content
	Name    string `json:"name,omitempty"`
}

ChatMessage represents a chat message for AI/LLM interactions.

type ChatRequest

type ChatRequest struct {
	Messages    []ChatMessage `json:"messages"`
	Model       string        `json:"model,omitempty"`
	MaxTokens   int           `json:"max_tokens,omitempty"`
	Temperature float64       `json:"temperature,omitempty"`
	Stream      bool          `json:"stream,omitempty"`
}

ChatRequest represents a request to an LLM provider.

type ChatResponse

type ChatResponse struct {
	Content   string     `json:"content"`
	ToolCalls []ToolCall `json:"tool_calls,omitempty"`
	Usage     TokenUsage `json:"usage"`
	Model     string     `json:"model,omitempty"`
	Provider  string     `json:"provider,omitempty"`
}

ChatResponse represents a response from an LLM provider.

type ClaudeConfig

type ClaudeConfig struct {
	APIKey string `yaml:"api_key,omitempty"` // Can use ${ENV_VAR}
	Model  string `yaml:"model"`             // e.g., claude-3-5-sonnet-20241022
}

ClaudeConfig represents Claude/Anthropic-specific configuration.

type ClickEvent

type ClickEvent struct {
	ClickID   string    `json:"click_id"`
	Timestamp time.Time `json:"timestamp"`
	URL       string    `json:"url"`
	IPAddress string    `json:"ip"`
	UserAgent string    `json:"user_agent"`
	LinkIndex int       `json:"link_index"`
}

ClickEvent represents a link click tracking event.

type Conferencing

type Conferencing struct {
	Provider string               `json:"provider,omitempty"` // Google Meet, Zoom, etc.
	Details  *ConferencingDetails `json:"details,omitempty"`
}

Conferencing represents video conferencing details.

type ConferencingDetails

type ConferencingDetails struct {
	URL         string   `json:"url,omitempty"`
	MeetingCode string   `json:"meeting_code,omitempty"`
	Password    string   `json:"password,omitempty"`
	Phone       []string `json:"phone,omitempty"`
}

ConferencingDetails contains conferencing URLs and info.

type ConferencingSettings

type ConferencingSettings struct {
	Provider   string               `json:"provider"` // "Google Meet", "Zoom", "Microsoft Teams"
	Autocreate bool                 `json:"autocreate,omitempty"`
	Details    *ConferencingDetails `json:"details,omitempty"` // Reuses ConferencingDetails from calendar.go
}

ConferencingSettings represents video conferencing settings

type Config

type Config struct {
	Region       string      `yaml:"region"`
	CallbackPort int         `yaml:"callback_port"`
	DefaultGrant string      `yaml:"default_grant"`
	Grants       []GrantInfo `yaml:"grants"`

	// API settings
	API *APIConfig `yaml:"api,omitempty"`

	// TUI settings
	TUITheme string `yaml:"tui_theme,omitempty"`

	// Working hours settings
	WorkingHours *WorkingHoursConfig `yaml:"working_hours,omitempty"`

	// AI settings
	AI *AIConfig `yaml:"ai,omitempty"`
}

Config represents the application configuration. Note: client_id is stored in keystore, not config file.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a config with sensible defaults.

type ConfigStatus

type ConfigStatus struct {
	IsConfigured    bool   `json:"configured"`
	Region          string `json:"region"`
	ClientID        string `json:"client_id,omitempty"`
	OrgID           string `json:"org_id,omitempty"`
	HasAPIKey       bool   `json:"has_api_key"`
	HasClientSecret bool   `json:"has_client_secret"`
	SecretStore     string `json:"secret_store"`
	ConfigPath      string `json:"config_path"`
	GrantCount      int    `json:"grant_count"`
	DefaultGrant    string `json:"default_grant,omitempty"`
}

ConfigStatus represents the current configuration status.

type ConfigurationAvailability

type ConfigurationAvailability struct {
	CalendarIDs []string    `json:"calendar_ids,omitempty"`
	OpenHours   []OpenHours `json:"open_hours,omitempty"`
}

ConfigurationAvailability holds participant availability settings

type ConfigurationParticipant

type ConfigurationParticipant struct {
	Email        string                    `json:"email"`
	Name         string                    `json:"name,omitempty"`
	IsOrganizer  bool                      `json:"is_organizer,omitempty"`
	Availability ConfigurationAvailability `json:"availability,omitempty"`
	Booking      *ParticipantBooking       `json:"booking,omitempty"`
}

ConfigurationParticipant represents a participant in a scheduler configuration

type ConfirmBookingRequest

type ConfirmBookingRequest struct {
	Status         string         `json:"status"` // "confirmed" or "cancelled"
	Reason         string         `json:"reason,omitempty"`
	AdditionalData map[string]any `json:"additional_data,omitempty"`
}

ConfirmBookingRequest represents a request to confirm a booking

type Conflict

type Conflict struct {
	ID               string           `json:"id"`
	Type             ConflictType     `json:"type"`
	Severity         ConflictSeverity `json:"severity"`
	ProposedEvent    *Event           `json:"proposed_event"`
	ConflictingEvent *Event           `json:"conflicting_event,omitempty"`
	Description      string           `json:"description"`
	Impact           string           `json:"impact"`
	Suggestion       string           `json:"suggestion"`
	CanAutoResolve   bool             `json:"can_auto_resolve"`
}

Conflict represents a detected scheduling conflict.

type ConflictAnalysis

type ConflictAnalysis struct {
	ProposedEvent    *Event             `json:"proposed_event"`
	HardConflicts    []Conflict         `json:"hard_conflicts"`
	SoftConflicts    []Conflict         `json:"soft_conflicts"`
	TotalConflicts   int                `json:"total_conflicts"`
	CanProceed       bool               `json:"can_proceed"`
	Recommendations  []string           `json:"recommendations"`
	AlternativeTimes []RescheduleOption `json:"alternative_times,omitempty"`
	AIRecommendation string             `json:"ai_recommendation"`
}

ConflictAnalysis represents the result of conflict detection.

type ConflictSeverity

type ConflictSeverity string

ConflictSeverity represents how severe a conflict is.

const (
	SeverityCritical ConflictSeverity = "critical" // Must resolve
	SeverityHigh     ConflictSeverity = "high"     // Should resolve
	SeverityMedium   ConflictSeverity = "medium"   // Consider resolving
	SeverityLow      ConflictSeverity = "low"      // Optional to resolve
)

type ConflictType

type ConflictType string

ConflictType represents the type of scheduling conflict.

const (
	ConflictTypeHard            ConflictType = "hard"              // Overlapping times
	ConflictTypeSoftBackToBack  ConflictType = "soft_back_to_back" // No buffer time
	ConflictTypeSoftFocusTime   ConflictType = "soft_focus_time"   // Interrupts focus time
	ConflictTypeSoftTravelTime  ConflictType = "soft_travel_time"  // Insufficient travel time
	ConflictTypeSoftOverload    ConflictType = "soft_overload"     // Too many meetings
	ConflictTypeSoftLowPriority ConflictType = "soft_low_priority" // Low-value meeting
)

type Connector

type Connector struct {
	ID        string             `json:"id,omitempty"`
	Name      string             `json:"name"`
	Provider  string             `json:"provider"` // "google", "microsoft", "icloud", "yahoo", "imap"
	Settings  *ConnectorSettings `json:"settings,omitempty"`
	Scopes    []string           `json:"scopes,omitempty"`
	CreatedAt *UnixTime          `json:"created_at,omitempty"`
	UpdatedAt *UnixTime          `json:"updated_at,omitempty"`
}

Connector represents a provider connector (Google, Microsoft, iCloud, Yahoo, IMAP)

type ConnectorCredential

type ConnectorCredential struct {
	ID             string         `json:"id,omitempty"`
	Name           string         `json:"name"`
	ConnectorID    string         `json:"connector_id,omitempty"`
	CredentialType string         `json:"credential_type"` // "oauth", "service_account", "connector"
	CredentialData map[string]any `json:"credential_data,omitempty"`
	CreatedAt      *UnixTime      `json:"created_at,omitempty"`
	UpdatedAt      *UnixTime      `json:"updated_at,omitempty"`
}

ConnectorCredential represents authentication credentials for a connector

type ConnectorSettings

type ConnectorSettings struct {
	// OAuth providers (Google, Microsoft, etc.)
	ClientID     string `json:"client_id,omitempty"`
	ClientSecret string `json:"client_secret,omitempty"`
	Tenant       string `json:"tenant,omitempty"` // For Microsoft

	// IMAP-specific settings
	IMAPHost     string `json:"imap_host,omitempty"`
	IMAPPort     int    `json:"imap_port,omitempty"`
	SMTPHost     string `json:"smtp_host,omitempty"`
	SMTPPort     int    `json:"smtp_port,omitempty"`
	IMAPSecurity string `json:"imap_security,omitempty"` // "ssl", "starttls", "none"
	SMTPSecurity string `json:"smtp_security,omitempty"` // "ssl", "starttls", "none"
}

ConnectorSettings holds provider-specific configuration

type Contact

type Contact struct {
	ID                string             `json:"id"`
	GrantID           string             `json:"grant_id"`
	Object            string             `json:"object,omitempty"`
	GivenName         string             `json:"given_name,omitempty"`
	MiddleName        string             `json:"middle_name,omitempty"`
	Surname           string             `json:"surname,omitempty"`
	Suffix            string             `json:"suffix,omitempty"`
	Nickname          string             `json:"nickname,omitempty"`
	Birthday          string             `json:"birthday,omitempty"`
	CompanyName       string             `json:"company_name,omitempty"`
	JobTitle          string             `json:"job_title,omitempty"`
	ManagerName       string             `json:"manager_name,omitempty"`
	Notes             string             `json:"notes,omitempty"`
	PictureURL        string             `json:"picture_url,omitempty"`
	Picture           string             `json:"picture,omitempty"` // Base64-encoded image data (when profile_picture=true)
	Emails            []ContactEmail     `json:"emails,omitempty"`
	PhoneNumbers      []ContactPhone     `json:"phone_numbers,omitempty"`
	WebPages          []ContactWebPage   `json:"web_pages,omitempty"`
	IMAddresses       []ContactIM        `json:"im_addresses,omitempty"`
	PhysicalAddresses []ContactAddress   `json:"physical_addresses,omitempty"`
	Groups            []ContactGroupInfo `json:"groups,omitempty"`
	Source            string             `json:"source,omitempty"`
}

Contact represents a contact from Nylas.

func (Contact) DisplayName

func (c Contact) DisplayName() string

DisplayName returns a formatted display name for the contact.

func (Contact) PrimaryEmail

func (c Contact) PrimaryEmail() string

PrimaryEmail returns the primary email address.

func (Contact) PrimaryPhone

func (c Contact) PrimaryPhone() string

PrimaryPhone returns the primary phone number.

type ContactAddress

type ContactAddress struct {
	Type          string `json:"type,omitempty"` // home, work, other
	StreetAddress string `json:"street_address,omitempty"`
	City          string `json:"city,omitempty"`
	State         string `json:"state,omitempty"`
	PostalCode    string `json:"postal_code,omitempty"`
	Country       string `json:"country,omitempty"`
}

ContactAddress represents a contact's physical address.

type ContactEmail

type ContactEmail struct {
	Email string `json:"email"`
	Type  string `json:"type,omitempty"` // home, work, school, other
}

ContactEmail represents a contact's email address.

type ContactGroup

type ContactGroup struct {
	ID      string `json:"id"`
	GrantID string `json:"grant_id"`
	Name    string `json:"name"`
	Path    string `json:"path,omitempty"`
	Object  string `json:"object,omitempty"`
}

ContactGroup represents a contact group from Nylas.

type ContactGroupInfo

type ContactGroupInfo struct {
	ID string `json:"id"`
}

ContactGroupInfo represents a contact group reference.

type ContactGroupListResponse

type ContactGroupListResponse struct {
	Data       []ContactGroup `json:"data"`
	Pagination Pagination     `json:"pagination,omitempty"`
}

ContactGroupListResponse represents a paginated contact group list response.

type ContactIM

type ContactIM struct {
	IMAddress string `json:"im_address"`
	Type      string `json:"type,omitempty"` // aim, msn, yahoo, skype, qq, google_talk, icq, jabber, other
}

ContactIM represents a contact's instant messaging address.

type ContactListResponse

type ContactListResponse struct {
	Data       []Contact  `json:"data"`
	Pagination Pagination `json:"pagination,omitempty"`
}

ContactListResponse represents a paginated contact list response.

type ContactPhone

type ContactPhone struct {
	Number string `json:"number"`
	Type   string `json:"type,omitempty"` // mobile, home, work, pager, business_fax, home_fax, other
}

ContactPhone represents a contact's phone number.

type ContactQueryParams

type ContactQueryParams struct {
	Limit          int    `json:"limit,omitempty"`
	PageToken      string `json:"page_token,omitempty"`
	Email          string `json:"email,omitempty"`
	PhoneNumber    string `json:"phone_number,omitempty"`
	Source         string `json:"source,omitempty"` // address_book, inbox, domain
	Group          string `json:"group,omitempty"`
	Recurse        bool   `json:"recurse,omitempty"`
	ProfilePicture bool   `json:"profile_picture,omitempty"` // Include Base64-encoded profile picture
}

ContactQueryParams for filtering contacts.

type ContactWebPage

type ContactWebPage struct {
	URL  string `json:"url"`
	Type string `json:"type,omitempty"` // profile, blog, home, work, other
}

ContactWebPage represents a contact's web page.

type CreateApplicationRequest

type CreateApplicationRequest struct {
	Name             string            `json:"name"`
	Region           string            `json:"region,omitempty"` // "us", "eu", etc.
	BrandingSettings *BrandingSettings `json:"branding,omitempty"`
	CallbackURIs     []string          `json:"callback_uris,omitempty"`
	Metadata         map[string]string `json:"metadata,omitempty"`
}

CreateApplicationRequest represents a request to create an application

type CreateCalendarRequest

type CreateCalendarRequest struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Location    string `json:"location,omitempty"`
	Timezone    string `json:"timezone,omitempty"`
}

CreateCalendarRequest for creating a new calendar.

type CreateConnectorRequest

type CreateConnectorRequest struct {
	Name     string             `json:"name"`
	Provider string             `json:"provider"` // "google", "microsoft", "icloud", "yahoo", "imap"
	Settings *ConnectorSettings `json:"settings,omitempty"`
	Scopes   []string           `json:"scopes,omitempty"`
}

CreateConnectorRequest represents a request to create a connector

type CreateContactGroupRequest

type CreateContactGroupRequest struct {
	Name string `json:"name"`
}

CreateContactGroupRequest for creating a new contact group.

type CreateContactRequest

type CreateContactRequest struct {
	GivenName         string             `json:"given_name,omitempty"`
	MiddleName        string             `json:"middle_name,omitempty"`
	Surname           string             `json:"surname,omitempty"`
	Suffix            string             `json:"suffix,omitempty"`
	Nickname          string             `json:"nickname,omitempty"`
	Birthday          string             `json:"birthday,omitempty"`
	CompanyName       string             `json:"company_name,omitempty"`
	JobTitle          string             `json:"job_title,omitempty"`
	ManagerName       string             `json:"manager_name,omitempty"`
	Notes             string             `json:"notes,omitempty"`
	Emails            []ContactEmail     `json:"emails,omitempty"`
	PhoneNumbers      []ContactPhone     `json:"phone_numbers,omitempty"`
	WebPages          []ContactWebPage   `json:"web_pages,omitempty"`
	IMAddresses       []ContactIM        `json:"im_addresses,omitempty"`
	PhysicalAddresses []ContactAddress   `json:"physical_addresses,omitempty"`
	Groups            []ContactGroupInfo `json:"groups,omitempty"`
}

CreateContactRequest for creating a new contact.

type CreateCredentialRequest

type CreateCredentialRequest struct {
	Name           string         `json:"name"`
	CredentialType string         `json:"credential_type"` // "oauth", "service_account", "connector"
	CredentialData map[string]any `json:"credential_data,omitempty"`
}

CreateCredentialRequest represents a request to create a credential

type CreateDraftRequest

type CreateDraftRequest struct {
	Subject      string             `json:"subject"`
	Body         string             `json:"body"`
	To           []EmailParticipant `json:"to,omitempty"`
	Cc           []EmailParticipant `json:"cc,omitempty"`
	Bcc          []EmailParticipant `json:"bcc,omitempty"`
	ReplyTo      []EmailParticipant `json:"reply_to,omitempty"`
	ReplyToMsgID string             `json:"reply_to_message_id,omitempty"`
	Attachments  []Attachment       `json:"attachments,omitempty"`
	Metadata     map[string]string  `json:"metadata,omitempty"`
}

CreateDraftRequest for creating a new draft.

type CreateEventRequest

type CreateEventRequest struct {
	Title        string            `json:"title"`
	Description  string            `json:"description,omitempty"`
	Location     string            `json:"location,omitempty"`
	When         EventWhen         `json:"when"`
	Participants []Participant     `json:"participants,omitempty"`
	Busy         bool              `json:"busy"`
	Visibility   string            `json:"visibility,omitempty"`
	Recurrence   []string          `json:"recurrence,omitempty"`
	Conferencing *Conferencing     `json:"conferencing,omitempty"`
	Reminders    *Reminders        `json:"reminders,omitempty"`
	CalendarID   string            `json:"calendar_id,omitempty"`
	Metadata     map[string]string `json:"metadata,omitempty"`
}

CreateEventRequest for creating a new event.

type CreateFolderRequest

type CreateFolderRequest struct {
	Name            string `json:"name"`
	ParentID        string `json:"parent_id,omitempty"`
	BackgroundColor string `json:"background_color,omitempty"`
	TextColor       string `json:"text_color,omitempty"`
}

CreateFolderRequest for creating a new folder.

type CreateInboundInboxRequest

type CreateInboundInboxRequest struct {
	// Email is the local part of the email address (before @).
	// The full address will be: {email}@{your-app}.nylas.email
	Email string `json:"email"`
}

CreateInboundInboxRequest represents a request to create a new inbound inbox.

type CreateNotetakerRequest

type CreateNotetakerRequest struct {
	MeetingLink string     `json:"meeting_link"`
	JoinTime    int64      `json:"join_time,omitempty"` // Unix timestamp for when to join
	BotConfig   *BotConfig `json:"bot_config,omitempty"`
}

CreateNotetakerRequest for creating a new notetaker.

type CreateSchedulerConfigurationRequest

type CreateSchedulerConfigurationRequest struct {
	Name                string                     `json:"name"`
	Slug                string                     `json:"slug,omitempty"`
	RequiresSessionAuth bool                       `json:"requires_session_auth,omitempty"`
	Participants        []ConfigurationParticipant `json:"participants"`
	Availability        AvailabilityRules          `json:"availability"`
	EventBooking        EventBooking               `json:"event_booking"`
	Scheduler           SchedulerSettings          `json:"scheduler"`
	AppearanceSettings  *AppearanceSettings        `json:"appearance,omitempty"`
}

CreateSchedulerConfigurationRequest represents a request to create a scheduler configuration

type CreateSchedulerPageRequest

type CreateSchedulerPageRequest struct {
	ConfigurationID string `json:"configuration_id"`
	Name            string `json:"name"`
	Slug            string `json:"slug"`
	CustomDomain    string `json:"custom_domain,omitempty"`
}

CreateSchedulerPageRequest represents a request to create a scheduler page

type CreateSchedulerSessionRequest

type CreateSchedulerSessionRequest struct {
	ConfigurationID  string         `json:"configuration_id"`
	TimeToLive       int            `json:"ttl,omitempty"` // Session TTL in minutes
	Slug             string         `json:"slug,omitempty"`
	AdditionalFields map[string]any `json:"additional_fields,omitempty"`
}

CreateSchedulerSessionRequest represents a request to create a scheduler session

type CreateVirtualCalendarGrantRequest

type CreateVirtualCalendarGrantRequest struct {
	Provider string                       `json:"provider"` // Must be "virtual-calendar"
	Settings VirtualCalendarGrantSettings `json:"settings"`
	Scope    []string                     `json:"scope"` // ["calendar"]
}

CreateVirtualCalendarGrantRequest for creating a virtual calendar grant.

type CreateWebhookRequest

type CreateWebhookRequest struct {
	TriggerTypes               []string `json:"trigger_types"`
	WebhookURL                 string   `json:"webhook_url"`
	Description                string   `json:"description,omitempty"`
	NotificationEmailAddresses []string `json:"notification_email_addresses,omitempty"`
}

CreateWebhookRequest for creating a new webhook.

type DSTTransition

type DSTTransition struct {
	Date      time.Time `json:"date"`
	Offset    int       `json:"offset"`    // Seconds from UTC
	Name      string    `json:"name"`      // "PDT", "PST", etc.
	IsDST     bool      `json:"is_dst"`    // Whether this is DST or standard time
	Direction string    `json:"direction"` // "forward" (spring) or "backward" (fall)
}

DSTTransition represents a DST change.

type DSTWarning

type DSTWarning struct {
	IsNearTransition bool      `json:"is_near_transition"` // True if within warning window
	TransitionDate   time.Time `json:"transition_date"`    // When the DST change occurs
	Direction        string    `json:"direction"`          // "forward" (spring) or "backward" (fall)
	DaysUntil        int       `json:"days_until"`         // Days until transition (negative if past)
	TransitionName   string    `json:"transition_name"`    // Timezone name at transition (e.g., "PDT")
	InTransitionGap  bool      `json:"in_transition_gap"`  // True if time falls in spring forward gap
	InDuplicateHour  bool      `json:"in_duplicate_hour"`  // True if time occurs twice (fall back)
	Warning          string    `json:"warning"`            // User-facing warning message
	Severity         string    `json:"severity"`           // "error", "warning", or "info"
}

DSTWarning provides warning information about DST transitions. Used to alert users when scheduling events near or during DST changes.

type DateRange

type DateRange struct {
	Start time.Time `json:"start"`
	End   time.Time `json:"end"`
}

DateRange represents a range of dates.

type DaySchedule

type DaySchedule struct {
	Enabled bool         `yaml:"enabled"`          // Whether working hours apply
	Start   string       `yaml:"start,omitempty"`  // Start time (HH:MM format)
	End     string       `yaml:"end,omitempty"`    // End time (HH:MM format)
	Breaks  []BreakBlock `yaml:"breaks,omitempty"` // Break periods (lunch, coffee, etc.)
}

DaySchedule represents working hours for a specific day.

func DefaultWorkingHours

func DefaultWorkingHours() *DaySchedule

DefaultWorkingHours returns standard 9-5 working hours.

type DeduplicationRequest

type DeduplicationRequest struct {
	Contacts       []Contact `json:"contacts"`
	FuzzyThreshold float64   `json:"fuzzy_threshold"` // 0.0-1.0 (similarity threshold)
	MatchFields    []string  `json:"match_fields"`    // Fields to compare (email, phone, name)
	AutoMerge      bool      `json:"auto_merge"`      // Automatically merge duplicates
	MergeStrategy  string    `json:"merge_strategy"`  // "newest", "oldest", "most_complete"
}

DeduplicationRequest contains parameters for contact deduplication.

type DeduplicationResult

type DeduplicationResult struct {
	OriginalCount     int              `json:"original_count"`
	DeduplicatedCount int              `json:"deduplicated_count"`
	DuplicateGroups   []DuplicateGroup `json:"duplicate_groups"`
	MergedContacts    []Contact        `json:"merged_contacts,omitempty"`
}

DeduplicationResult contains deduplication results.

type DeliverabilityIssue

type DeliverabilityIssue struct {
	Severity string `json:"severity"` // "critical", "warning", "info"
	Category string `json:"category"` // "authentication", "content", "formatting", etc.
	Message  string `json:"message"`
	Fix      string `json:"fix,omitempty"`
}

DeliverabilityIssue represents a specific deliverability problem.

type DeliverabilityReport

type DeliverabilityReport struct {
	Score           int                   `json:"score"` // 0-100
	Issues          []DeliverabilityIssue `json:"issues"`
	SPFStatus       string                `json:"spf_status"`
	DKIMStatus      string                `json:"dkim_status"`
	DMARCStatus     string                `json:"dmarc_status"`
	SpamScore       float64               `json:"spam_score"`
	MobileOptimized bool                  `json:"mobile_optimized"`
	Recommendations []string              `json:"recommendations"`
}

DeliverabilityReport contains email deliverability analysis.

type Draft

type Draft struct {
	ID           string             `json:"id"`
	GrantID      string             `json:"grant_id"`
	Subject      string             `json:"subject"`
	Body         string             `json:"body"`
	From         []EmailParticipant `json:"from"`
	To           []EmailParticipant `json:"to"`
	Cc           []EmailParticipant `json:"cc,omitempty"`
	Bcc          []EmailParticipant `json:"bcc,omitempty"`
	ReplyTo      []EmailParticipant `json:"reply_to,omitempty"`
	ReplyToMsgID string             `json:"reply_to_message_id,omitempty"`
	ThreadID     string             `json:"thread_id,omitempty"`
	Attachments  []Attachment       `json:"attachments,omitempty"`
	CreatedAt    time.Time          `json:"created_at"`
	UpdatedAt    time.Time          `json:"updated_at"`
}

Draft represents an email draft.

type DraftListResponse

type DraftListResponse struct {
	Data       []Draft    `json:"data"`
	Pagination Pagination `json:"pagination,omitempty"`
}

DraftListResponse represents a paginated draft list response.

type DuplicateGroup

type DuplicateGroup struct {
	Contacts      []Contact `json:"contacts"`
	MatchScore    float64   `json:"match_score"` // 0.0-1.0
	MatchedFields []string  `json:"matched_fields"`
	Suggested     *Contact  `json:"suggested,omitempty"` // Suggested merge result
}

DuplicateGroup represents a group of duplicate contacts.

type DurationOptimization

type DurationOptimization struct {
	EventID             string        `json:"event_id"`
	CurrentDuration     int           `json:"current_duration"`     // Minutes
	RecommendedDuration int           `json:"recommended_duration"` // Minutes
	HistoricalData      DurationStats `json:"historical_data"`
	TimeSavings         int           `json:"time_savings"` // Minutes saved
	Confidence          float64       `json:"confidence"`   // 0-100
	Reason              string        `json:"reason"`
	Recommendation      string        `json:"recommendation"`
}

DurationOptimization represents meeting duration optimization recommendations.

type DurationPatterns

type DurationPatterns struct {
	ByParticipant map[string]DurationStats `json:"by_participant"`
	ByType        map[string]DurationStats `json:"by_type"` // "1-on-1", "team", "client"
	Overall       DurationStats            `json:"overall"`
}

DurationPatterns tracks actual vs scheduled meeting durations.

type DurationStats

type DurationStats struct {
	AverageScheduled int     `json:"average_scheduled"` // Minutes
	AverageActual    int     `json:"average_actual"`    // Minutes
	Variance         float64 `json:"variance"`          // Standard deviation
	OverrunRate      float64 `json:"overrun_rate"`      // % of meetings that run over
}

DurationStats contains duration statistics.

type EmailAnalysisRequest

type EmailAnalysisRequest struct {
	ThreadID      string `json:"thread_id"`
	IncludeAgenda bool   `json:"include_agenda"`
	IncludeTime   bool   `json:"include_time"`
}

EmailAnalysisRequest represents a request to analyze an email thread.

type EmailMessage

type EmailMessage struct {
	From        string            `json:"from"`
	To          []string          `json:"to"`
	Cc          []string          `json:"cc,omitempty"`
	Bcc         []string          `json:"bcc,omitempty"`
	Subject     string            `json:"subject"`
	HTMLBody    string            `json:"html_body,omitempty"`
	TextBody    string            `json:"text_body,omitempty"`
	Headers     map[string]string `json:"headers,omitempty"`
	Attachments []Attachment      `json:"attachments,omitempty"`
}

EmailMessage represents an email message for generation.

type EmailParticipant

type EmailParticipant = Person

EmailParticipant represents an email participant (sender/recipient). This is an alias for Person, which provides String() and DisplayName() methods.

type EmailTemplate

type EmailTemplate struct {
	ID         string            `json:"id"`
	Name       string            `json:"name"`
	Subject    string            `json:"subject"`
	HTMLBody   string            `json:"html_body"`
	TextBody   string            `json:"text_body,omitempty"`
	Variables  []string          `json:"variables"`
	Category   string            `json:"category,omitempty"`
	UsageCount int               `json:"usage_count,omitempty"`
	CreatedAt  time.Time         `json:"created_at"`
	UpdatedAt  time.Time         `json:"updated_at"`
	Metadata   map[string]string `json:"metadata,omitempty"`
}

EmailTemplate represents an email template.

type EmailThreadAnalysis

type EmailThreadAnalysis struct {
	ThreadID          string                 `json:"thread_id"`
	Subject           string                 `json:"subject"`
	MessageCount      int                    `json:"message_count"`
	ParticipantCount  int                    `json:"participant_count"`
	Purpose           string                 `json:"purpose"`            // Primary meeting purpose
	Topics            []string               `json:"topics"`             // Key topics discussed
	Priority          MeetingPriority        `json:"priority"`           // Detected priority level
	SuggestedDuration int                    `json:"suggested_duration"` // In minutes
	Participants      []ParticipantInfo      `json:"participants"`
	Agenda            *MeetingAgenda         `json:"agenda,omitempty"`
	BestMeetingTime   *MeetingTimeSuggestion `json:"best_meeting_time,omitempty"`
	UrgencyIndicators []string               `json:"urgency_indicators,omitempty"`
}

EmailThreadAnalysis represents the AI analysis of an email thread.

type EmailValidation

type EmailValidation struct {
	Email       string `json:"email"`
	Valid       bool   `json:"valid"`
	FormatValid bool   `json:"format_valid"`
	MXExists    bool   `json:"mx_exists"`
	Disposable  bool   `json:"disposable"`
	Suggestion  string `json:"suggestion,omitempty"` // Did you mean...?
}

EmailValidation contains email address validation results.

type Event

type Event struct {
	ID            string            `json:"id"`
	GrantID       string            `json:"grant_id"`
	CalendarID    string            `json:"calendar_id"`
	Title         string            `json:"title"`
	Description   string            `json:"description,omitempty"`
	Location      string            `json:"location,omitempty"`
	When          EventWhen         `json:"when"`
	Participants  []Participant     `json:"participants,omitempty"`
	Organizer     *Participant      `json:"organizer,omitempty"`
	Status        string            `json:"status,omitempty"` // confirmed, cancelled, tentative
	Busy          bool              `json:"busy"`
	ReadOnly      bool              `json:"read_only"`
	Visibility    string            `json:"visibility,omitempty"` // public, private
	Recurrence    []string          `json:"recurrence,omitempty"`
	Conferencing  *Conferencing     `json:"conferencing,omitempty"`
	Reminders     *Reminders        `json:"reminders,omitempty"`
	Metadata      map[string]string `json:"metadata,omitempty"`
	MasterEventID string            `json:"master_event_id,omitempty"`
	ICalUID       string            `json:"ical_uid,omitempty"`
	HtmlLink      string            `json:"html_link,omitempty"`
	CreatedAt     time.Time         `json:"created_at,omitempty"`
	UpdatedAt     time.Time         `json:"updated_at,omitempty"`
	Object        string            `json:"object,omitempty"`
}

Event represents a calendar event from Nylas.

func (Event) GetLockedTimezone

func (e Event) GetLockedTimezone() string

GetLockedTimezone returns the locked timezone for the event, if set. Returns empty string if timezone is not locked.

func (Event) IsTimezoneLocked

func (e Event) IsTimezoneLocked() bool

IsTimezoneLocked returns true if the event has timezone locking enabled.

type EventBooking

type EventBooking struct {
	Title           string                `json:"title"`
	Description     string                `json:"description,omitempty"`
	Location        string                `json:"location,omitempty"`
	Timezone        string                `json:"timezone,omitempty"`
	BookingType     string                `json:"booking_type,omitempty"` // "booking", "organizer-confirmation"
	Conferencing    *ConferencingSettings `json:"conferencing,omitempty"`
	DisableEmails   bool                  `json:"disable_emails,omitempty"`
	ReminderMinutes []int                 `json:"reminder_minutes,omitempty"`
	Metadata        map[string]string     `json:"metadata,omitempty"`
}

EventBooking represents event booking settings

type EventListResponse

type EventListResponse struct {
	Data       []Event    `json:"data"`
	Pagination Pagination `json:"pagination,omitempty"`
}

EventListResponse represents a paginated event list response.

type EventQueryParams

type EventQueryParams struct {
	Limit           int    `json:"limit,omitempty"`
	PageToken       string `json:"page_token,omitempty"`
	CalendarID      string `json:"calendar_id,omitempty"`
	Title           string `json:"title,omitempty"`
	Location        string `json:"location,omitempty"`
	ShowCancelled   bool   `json:"show_cancelled,omitempty"`
	Start           int64  `json:"start,omitempty"` // Unix timestamp
	End             int64  `json:"end,omitempty"`   // Unix timestamp
	MetadataPair    string `json:"metadata_pair,omitempty"`
	Busy            *bool  `json:"busy,omitempty"`
	OrderBy         string `json:"order_by,omitempty"` // start, end
	ExpandRecurring bool   `json:"expand_recurring,omitempty"`
}

EventQueryParams for filtering events.

type EventWhen

type EventWhen struct {
	// For timespan events
	StartTime     int64  `json:"start_time,omitempty"`
	EndTime       int64  `json:"end_time,omitempty"`
	StartTimezone string `json:"start_timezone,omitempty"`
	EndTimezone   string `json:"end_timezone,omitempty"`

	// For date events (all-day)
	Date    string `json:"date,omitempty"`
	EndDate string `json:"end_date,omitempty"`

	// For datespan events (multi-day all-day)
	StartDate string `json:"start_date,omitempty"`

	Object string `json:"object,omitempty"` // timespan, date, datespan
}

EventWhen represents when an event occurs.

func (EventWhen) EndDateTime

func (w EventWhen) EndDateTime() time.Time

EndDateTime returns the end time as a time.Time. If EndTimezone is specified, the time is returned in that timezone. Returns zero time if no valid end time is set or if date parsing fails. This is a convenience getter for deserialized API data.

func (EventWhen) IsAllDay

func (w EventWhen) IsAllDay() bool

IsAllDay returns true if this is an all-day event.

func (EventWhen) StartDateTime

func (w EventWhen) StartDateTime() time.Time

StartDateTime returns the start time as a time.Time. If StartTimezone is specified, the time is returned in that timezone. Returns zero time if no valid start time is set or if date parsing fails. This is a convenience getter for deserialized API data.

func (EventWhen) Validate

func (w EventWhen) Validate() error

Validate checks that EventWhen has exactly one valid time specification.

type FeaturesConfig

type FeaturesConfig struct {
	NaturalLanguageScheduling bool `yaml:"natural_language_scheduling"` // Enable natural language scheduling
	PredictiveScheduling      bool `yaml:"predictive_scheduling"`       // Enable predictive scheduling
	FocusTimeProtection       bool `yaml:"focus_time_protection"`       // Enable focus time protection
	ConflictResolution        bool `yaml:"conflict_resolution"`         // Enable conflict resolution
	EmailContextAnalysis      bool `yaml:"email_context_analysis"`      // Enable email context analysis
}

FeaturesConfig represents feature toggles for AI capabilities.

type FilterFunc

type FilterFunc[T any] func(T) bool

FilterFunc is a predicate function for filtering list items.

type FocusProtectionRule

type FocusProtectionRule struct {
	// 8-byte aligned fields
	DeclineMessage   string   `json:"decline_message"`   // Custom decline message
	AlternativeTimes []string `json:"alternative_times"` // Suggested alternative time slots
	// Bool fields grouped to minimize padding
	AutoDecline          bool `json:"auto_decline"`           // Auto-decline meeting requests
	SuggestAlternatives  bool `json:"suggest_alternatives"`   // Suggest alternative times
	AllowCriticalMeeting bool `json:"allow_critical_meeting"` // Allow critical priority meetings
	RequireApproval      bool `json:"require_approval"`       // Require manual approval
}

FocusProtectionRule defines how a focus block is protected. Field order optimized for memory alignment.

type FocusTimeAnalysis

type FocusTimeAnalysis struct {
	UserEmail          string           `json:"user_email"`
	AnalyzedPeriod     DateRange        `json:"analyzed_period"`
	GeneratedAt        time.Time        `json:"generated_at"`
	PeakProductivity   []TimeBlock      `json:"peak_productivity"`    // Peak focus time blocks
	DeepWorkSessions   DurationStats    `json:"deep_work_sessions"`   // Deep work session stats
	MostProductiveDay  string           `json:"most_productive_day"`  // Best day for deep work
	LeastProductiveDay string           `json:"least_productive_day"` // Worst day for deep work
	RecommendedBlocks  []FocusTimeBlock `json:"recommended_blocks"`   // AI-recommended focus blocks
	CurrentProtection  float64          `json:"current_protection"`   // Current hours/week protected
	TargetProtection   float64          `json:"target_protection"`    // Target hours/week to protect
	Insights           []string         `json:"insights"`             // AI insights about focus patterns
	Confidence         float64          `json:"confidence"`           // Confidence in recommendations (0-100)
}

FocusTimeAnalysis represents the analysis of productivity patterns for focus time.

type FocusTimeBlock

type FocusTimeBlock struct {
	DayOfWeek string  `json:"day_of_week"`
	StartTime string  `json:"start_time"`
	EndTime   string  `json:"end_time"`
	Duration  int     `json:"duration"` // Minutes
	Score     float64 `json:"score"`    // Productivity score
	Reason    string  `json:"reason"`
	Conflicts int     `json:"conflicts"` // Number of meetings that would conflict
}

FocusTimeBlock represents a suggested focus time block.

type FocusTimeNotificationPrefs

type FocusTimeNotificationPrefs struct {
	NotifyOnDecline    bool `json:"notify_on_decline"`    // Notify when declining meetings
	NotifyOnOverride   bool `json:"notify_on_override"`   // Notify when override requested
	NotifyOnAdaptation bool `json:"notify_on_adaptation"` // Notify on adaptive changes
	DailySummary       bool `json:"daily_summary"`        // Send daily focus time summary
	WeeklySummary      bool `json:"weekly_summary"`       // Send weekly focus time summary
}

FocusTimeNotificationPrefs represents notification preferences.

type FocusTimeSettings

type FocusTimeSettings struct {
	// 8-byte aligned fields
	TargetHoursPerWeek   float64                    `json:"target_hours_per_week"` // Target focus hours per week
	MinBlockDuration     int                        `json:"min_block_duration"`    // Minimum focus block minutes
	MaxBlockDuration     int                        `json:"max_block_duration"`    // Maximum focus block minutes
	ProtectedDays        []string                   `json:"protected_days"`        // Days to protect (e.g., "Wednesday")
	ExcludedTimeRanges   []TimeRange                `json:"excluded_time_ranges"`  // Times to exclude from protection
	NotificationSettings FocusTimeNotificationPrefs `json:"notification_settings"`
	// Bool fields grouped to minimize padding
	Enabled             bool `json:"enabled"`
	AutoBlock           bool `json:"auto_block"`            // Auto-create focus blocks
	AutoDecline         bool `json:"auto_decline"`          // Auto-decline meeting requests
	AllowUrgentOverride bool `json:"allow_urgent_override"` // Allow override for urgent meetings
	RequireApproval     bool `json:"require_approval"`      // Require approval for overrides
}

FocusTimeSettings represents user preferences for focus time protection. Field order optimized for memory alignment (8-byte fields first, bools grouped at end).

type Folder

type Folder struct {
	ID              string   `json:"id"`
	GrantID         string   `json:"grant_id"`
	Name            string   `json:"name"`
	SystemFolder    string   `json:"system_folder,omitempty"`
	ParentID        string   `json:"parent_id,omitempty"`
	BackgroundColor string   `json:"background_color,omitempty"`
	TextColor       string   `json:"text_color,omitempty"`
	TotalCount      int      `json:"total_count"`
	UnreadCount     int      `json:"unread_count"`
	ChildIDs        []string `json:"child_ids,omitempty"`
	Attributes      []string `json:"attributes,omitempty"`
}

Folder represents an email folder/label.

type FolderListResponse

type FolderListResponse struct {
	Data       []Folder   `json:"data"`
	Pagination Pagination `json:"pagination,omitempty"`
}

FolderListResponse represents a paginated folder list response.

type FreeBusyCalendar

type FreeBusyCalendar struct {
	Email     string     `json:"email"`
	TimeSlots []TimeSlot `json:"time_slots,omitempty"`
	Object    string     `json:"object,omitempty"`
}

FreeBusyCalendar represents a calendar's availability.

type FreeBusyRequest

type FreeBusyRequest struct {
	StartTime int64    `json:"start_time"` // Unix timestamp
	EndTime   int64    `json:"end_time"`   // Unix timestamp
	Emails    []string `json:"emails"`
}

FreeBusyRequest for checking availability.

type FreeBusyResponse

type FreeBusyResponse struct {
	Data []FreeBusyCalendar `json:"data"`
}

FreeBusyResponse represents availability data.

type Grant

type Grant struct {
	ID           string   `json:"id"`
	Provider     Provider `json:"provider"`
	Email        string   `json:"email"`
	GrantStatus  string   `json:"grant_status"`
	Scope        []string `json:"scope,omitempty"`
	CreatedAt    UnixTime `json:"created_at,omitempty"`
	UpdatedAt    UnixTime `json:"updated_at,omitempty"`
	AccessToken  string   `json:"access_token,omitempty"`
	RefreshToken string   `json:"refresh_token,omitempty"`
}

Grant represents a Nylas grant (authenticated account).

func (*Grant) IsValid

func (g *Grant) IsValid() bool

IsValid returns true if the grant is in a valid state.

type GrantInfo

type GrantInfo struct {
	ID       string   `yaml:"id" json:"id"`
	Email    string   `yaml:"email" json:"email"`
	Provider Provider `yaml:"provider" json:"provider"`
}

GrantInfo is a lightweight representation of a grant for storage.

type GrantStats

type GrantStats struct {
	Total      int            `json:"total"`
	ByProvider map[string]int `json:"by_provider"`
	ByStatus   map[string]int `json:"by_status"`
	Valid      int            `json:"valid"`
	Invalid    int            `json:"invalid"`
	Revoked    int            `json:"revoked"`
}

GrantStats represents grant statistics

type GrantStatus

type GrantStatus struct {
	ID        string   `json:"id"`
	Email     string   `json:"email"`
	Provider  Provider `json:"provider"`
	Status    string   `json:"status"`
	IsDefault bool     `json:"is_default"`
	Error     string   `json:"error,omitempty"`
}

GrantStatus represents the status information for a grant.

type GrantsQueryParams

type GrantsQueryParams struct {
	Limit       int    `json:"limit,omitempty"`
	Offset      int    `json:"offset,omitempty"`
	ConnectorID string `json:"connector_id,omitempty"`
	Status      string `json:"status,omitempty"` // "valid", "invalid"
}

GrantsQueryParams represents query parameters for listing grants

type GroqConfig

type GroqConfig struct {
	APIKey string `yaml:"api_key,omitempty"` // Can use ${ENV_VAR}
	Model  string `yaml:"model"`             // e.g., mixtral-8x7b-32768
}

GroqConfig represents Groq-specific configuration.

type Header struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

Header represents an email header.

type InboundInbox

type InboundInbox struct {
	ID          string   `json:"id"`           // Grant ID
	Email       string   `json:"email"`        // Full email address (e.g., [email protected])
	GrantStatus string   `json:"grant_status"` // Status of the inbox
	CreatedAt   UnixTime `json:"created_at"`
	UpdatedAt   UnixTime `json:"updated_at"`
}

InboundInbox represents a Nylas Inbound inbox (a grant with provider=inbox). Inbound inboxes receive emails at managed addresses without OAuth.

func (*InboundInbox) IsValid

func (i *InboundInbox) IsValid() bool

IsValid returns true if the inbound inbox is in a valid state.

type InboundMessage

type InboundMessage = Message

InboundMessage represents an email received at an inbound inbox. This is an alias for Message but provides semantic clarity.

type InboundWebhookEvent

type InboundWebhookEvent struct {
	Type      string          `json:"type"`       // e.g., "message.created"
	Source    string          `json:"source"`     // "inbox" for inbound emails
	GrantID   string          `json:"grant_id"`   // The inbound inbox grant ID
	MessageID string          `json:"message_id"` // The message ID
	Message   *InboundMessage `json:"message"`    // The message object (if included)
}

InboundWebhookEvent contains metadata specific to inbound webhook events.

func (*InboundWebhookEvent) IsInboundEvent

func (e *InboundWebhookEvent) IsInboundEvent() bool

IsInboundEvent returns true if the event is from an inbound inbox.

type InvolvementLevel

type InvolvementLevel string

InvolvementLevel represents how involved a participant is in the thread.

const (
	InvolvementHigh   InvolvementLevel = "high"   // Active contributor, decision maker
	InvolvementMedium InvolvementLevel = "medium" // Regular participant
	InvolvementLow    InvolvementLevel = "low"    // Minimal involvement, FYI
)

type MapFunc

type MapFunc[T, R any] func(T) R

MapFunc transforms an item of type T to type R.

type MediaData

type MediaData struct {
	Recording  *MediaFile `json:"recording,omitempty"`
	Transcript *MediaFile `json:"transcript,omitempty"`
}

MediaData represents the media output from a notetaker session.

type MediaFile

type MediaFile struct {
	URL         string `json:"url,omitempty"`
	ContentType string `json:"content_type,omitempty"`
	Size        int64  `json:"size,omitempty"`
	ExpiresAt   int64  `json:"expires_at,omitempty"`
}

MediaFile represents a media file from a notetaker session.

type MeetingAgenda

type MeetingAgenda struct {
	Title    string       `json:"title"`
	Duration int          `json:"duration"` // In minutes
	Items    []AgendaItem `json:"items"`
	Notes    []string     `json:"notes,omitempty"` // Additional context
}

MeetingAgenda represents an auto-generated meeting agenda.

type MeetingAnalysis

type MeetingAnalysis struct {
	Period          DateRange        `json:"period"`
	TotalMeetings   int              `json:"total_meetings"`
	Patterns        *MeetingPattern  `json:"patterns"`
	Recommendations []Recommendation `json:"recommendations"`
	Insights        []string         `json:"insights"`
}

MeetingAnalysis represents the analysis of historical meetings.

type MeetingFinderRequest

type MeetingFinderRequest struct {
	TimeZones         []string      `json:"time_zones"`
	Duration          time.Duration `json:"duration"`
	WorkingHoursStart string        `json:"working_hours_start"` // "09:00"
	WorkingHoursEnd   string        `json:"working_hours_end"`   // "17:00"
	DateRange         DateRange     `json:"date_range"`
	ExcludeWeekends   bool          `json:"exclude_weekends"`
}

MeetingFinderRequest contains parameters for finding meeting times across zones.

type MeetingInfo

type MeetingInfo struct {
	Provider    string `json:"provider,omitempty"` // zoom, google_meet, teams
	MeetingCode string `json:"meeting_code,omitempty"`
}

MeetingInfo represents information about the meeting.

type MeetingMetadata

type MeetingMetadata struct {
	EventID           string          `json:"event_id"`
	Priority          MeetingPriority `json:"priority"`
	IsRecurring       bool            `json:"is_recurring"`
	ParticipantCount  int             `json:"participant_count"`
	HistoricalMoves   int             `json:"historical_moves"` // Times this meeting was rescheduled
	LastMoved         time.Time       `json:"last_moved,omitempty"`
	DeclineRate       float64         `json:"decline_rate"`
	AvgRescheduleLead int             `json:"avg_reschedule_lead"` // Days notice for rescheduling
}

MeetingMetadata contains learned metadata about a meeting.

type MeetingPattern

type MeetingPattern struct {
	UserEmail      string                        `json:"user_email"`
	AnalyzedPeriod DateRange                     `json:"analyzed_period"`
	LastUpdated    time.Time                     `json:"last_updated"`
	Acceptance     AcceptancePatterns            `json:"acceptance"`
	Duration       DurationPatterns              `json:"duration"`
	Timezone       TimezonePatterns              `json:"timezone"`
	Productivity   ProductivityPatterns          `json:"productivity"`
	Participants   map[string]ParticipantPattern `json:"participants"`
}

MeetingPattern represents learned patterns from calendar history.

type MeetingPriority

type MeetingPriority string

MeetingPriority represents the priority level of a meeting.

const (
	PriorityCritical MeetingPriority = "critical" // Cannot be moved
	PriorityHigh     MeetingPriority = "high"     // Hard to move
	PriorityMedium   MeetingPriority = "medium"   // Can be moved
	PriorityLow      MeetingPriority = "low"      // Easy to move
	PriorityFlexible MeetingPriority = "flexible" // Very flexible
)

type MeetingScore

type MeetingScore struct {
	Score            int           `json:"score"`        // 0-100
	Confidence       float64       `json:"confidence"`   // 0-100
	SuccessRate      float64       `json:"success_rate"` // Historical success rate
	Factors          []ScoreFactor `json:"factors"`      // Contributing factors
	Recommendation   string        `json:"recommendation"`
	AlternativeTimes []time.Time   `json:"alternative_times,omitempty"`
}

MeetingScore represents the predicted value/success of a meeting.

type MeetingSlot

type MeetingSlot struct {
	StartTime time.Time            `json:"start_time"`
	EndTime   time.Time            `json:"end_time"`
	Times     map[string]time.Time `json:"times"` // zone -> local time
	Score     float64              `json:"score"` // Quality score (0-1)
}

MeetingSlot represents a potential meeting time across zones.

type MeetingTimeSlots

type MeetingTimeSlots struct {
	Slots      []MeetingSlot `json:"slots"`
	TimeZones  []string      `json:"time_zones"`
	TotalSlots int           `json:"total_slots"`
}

MeetingTimeSlots represents available meeting times across zones.

type MeetingTimeSuggestion

type MeetingTimeSuggestion struct {
	Time      string `json:"time"`      // ISO 8601 format
	Timezone  string `json:"timezone"`  // IANA timezone ID
	Score     int    `json:"score"`     // 0-100
	Reasoning string `json:"reasoning"` // Why this time was chosen
}

MeetingTimeSuggestion represents a suggested meeting time based on thread analysis.

type Message

type Message struct {
	ID          string             `json:"id"`
	GrantID     string             `json:"grant_id"`
	ThreadID    string             `json:"thread_id,omitempty"`
	Subject     string             `json:"subject"`
	From        []EmailParticipant `json:"from"`
	To          []EmailParticipant `json:"to,omitempty"`
	Cc          []EmailParticipant `json:"cc,omitempty"`
	Bcc         []EmailParticipant `json:"bcc,omitempty"`
	ReplyTo     []EmailParticipant `json:"reply_to,omitempty"`
	Body        string             `json:"body"`
	Snippet     string             `json:"snippet"`
	Date        time.Time          `json:"date"`
	Unread      bool               `json:"unread"`
	Starred     bool               `json:"starred"`
	Folders     []string           `json:"folders,omitempty"`
	Attachments []Attachment       `json:"attachments,omitempty"`
	Headers     []Header           `json:"headers,omitempty"`
	RawMIME     string             `json:"raw_mime,omitempty"` // RFC822/MIME format
	Metadata    map[string]string  `json:"metadata,omitempty"`
	CreatedAt   time.Time          `json:"created_at"`
	Object      string             `json:"object,omitempty"`
}

Message represents an email message from Nylas.

type MessageListResponse

type MessageListResponse struct {
	Data       []Message  `json:"data"`
	Pagination Pagination `json:"pagination,omitempty"`
}

MessageListResponse represents a paginated message list response.

type MessageQueryParams

type MessageQueryParams struct {
	Limit          int      `json:"limit,omitempty"`
	Offset         int      `json:"offset,omitempty"`
	PageToken      string   `json:"page_token,omitempty"` // Cursor for pagination
	Subject        string   `json:"subject,omitempty"`
	From           string   `json:"from,omitempty"`
	To             string   `json:"to,omitempty"`
	Cc             string   `json:"cc,omitempty"`
	Bcc            string   `json:"bcc,omitempty"`
	In             []string `json:"in,omitempty"` // Folder IDs
	Unread         *bool    `json:"unread,omitempty"`
	Starred        *bool    `json:"starred,omitempty"`
	ThreadID       string   `json:"thread_id,omitempty"`
	ReceivedBefore int64    `json:"received_before,omitempty"`
	ReceivedAfter  int64    `json:"received_after,omitempty"`
	HasAttachment  *bool    `json:"has_attachment,omitempty"`
	SearchQuery    string   `json:"q,omitempty"`             // Full-text search
	Fields         string   `json:"fields,omitempty"`        // e.g., "include_headers"
	MetadataPair   string   `json:"metadata_pair,omitempty"` // Metadata filtering (format: "key:value", only key1-key5 supported)
}

MessageQueryParams for filtering messages.

type Notetaker

type Notetaker struct {
	ID           string       `json:"id"`
	State        string       `json:"state"` // scheduled, connecting, waiting_for_entry, attending, media_processing, complete, cancelled, failed
	MeetingLink  string       `json:"meeting_link,omitempty"`
	JoinTime     time.Time    `json:"join_time,omitempty"`
	MeetingTitle string       `json:"meeting_title,omitempty"`
	MediaData    *MediaData   `json:"media_data,omitempty"`
	BotConfig    *BotConfig   `json:"bot_config,omitempty"`
	MeetingInfo  *MeetingInfo `json:"meeting_info,omitempty"`
	CreatedAt    time.Time    `json:"created_at,omitempty"`
	UpdatedAt    time.Time    `json:"updated_at,omitempty"`
	Object       string       `json:"object,omitempty"`
}

Notetaker represents a Nylas Notetaker bot instance.

type NotetakerListResponse

type NotetakerListResponse struct {
	Data       []Notetaker `json:"data"`
	Pagination Pagination  `json:"pagination,omitempty"`
}

NotetakerListResponse represents a list of notetakers.

type NotetakerQueryParams

type NotetakerQueryParams struct {
	Limit     int    `json:"limit,omitempty"`
	PageToken string `json:"page_token,omitempty"`
	State     string `json:"state,omitempty"` // Filter by state
}

NotetakerQueryParams for filtering notetakers.

type OTPResult

type OTPResult struct {
	Code      string    `json:"code"`
	From      string    `json:"from"`
	Subject   string    `json:"subject"`
	Received  time.Time `json:"received"`
	MessageID string    `json:"message_id"`
}

OTPResult represents an extracted OTP code.

type OllamaConfig

type OllamaConfig struct {
	Host  string `yaml:"host"`  // e.g., http://localhost:11434
	Model string `yaml:"model"` // e.g., mistral:latest
}

OllamaConfig represents Ollama-specific configuration.

type OpenAIConfig

type OpenAIConfig struct {
	APIKey string `yaml:"api_key,omitempty"` // Can use ${ENV_VAR}
	Model  string `yaml:"model"`             // e.g., gpt-4-turbo
}

OpenAIConfig represents OpenAI-specific configuration.

type OpenEvent

type OpenEvent struct {
	OpenedID  string    `json:"opened_id"`
	Timestamp time.Time `json:"timestamp"`
	IPAddress string    `json:"ip"`
	UserAgent string    `json:"user_agent"`
}

OpenEvent represents an email open tracking event.

type OpenHours

type OpenHours struct {
	Days     []int    `json:"days"`  // [1, 2, 3, 4, 5] for Monday-Friday (0=Sunday, 1=Monday, ..., 6=Saturday)
	Start    string   `json:"start"` // "09:00"
	End      string   `json:"end"`   // "17:00"
	Timezone string   `json:"timezone,omitempty"`
	ExDates  []string `json:"exdates,omitempty"` // Excluded dates
}

OpenHours represents available hours

type OpenRouterConfig

type OpenRouterConfig struct {
	APIKey string `yaml:"api_key,omitempty"` // Can use ${ENV_VAR}
	Model  string `yaml:"model"`             // e.g., anthropic/claude-3.5-sonnet
}

OpenRouterConfig represents OpenRouter-specific configuration.

type OverrideRequest

type OverrideRequest struct {
	ID                    string          `json:"id"`
	ProtectedBlockID      string          `json:"protected_block_id"`
	MeetingRequest        *Event          `json:"meeting_request"`
	RequestedBy           string          `json:"requested_by"`
	Reason                string          `json:"reason"`
	Priority              MeetingPriority `json:"priority"`
	IsUrgent              bool            `json:"is_urgent"`
	ApprovalStatus        ApprovalStatus  `json:"approval_status"`
	ApprovedBy            string          `json:"approved_by,omitempty"`
	ApprovedAt            time.Time       `json:"approved_at,omitempty"`
	AlternativesSuggested []time.Time     `json:"alternatives_suggested,omitempty"`
	CreatedAt             time.Time       `json:"created_at"`
}

OverrideRequest represents a request to override a protected focus block.

type Paginated

type Paginated interface {
	GetPagination() Pagination
	HasMore() bool
}

Paginated is implemented by all paginated response types.

type Pagination

type Pagination struct {
	NextCursor string `json:"next_cursor,omitempty"`
	HasMore    bool   `json:"has_more"`
}

Pagination represents pagination info in API responses.

type ParsedEmail

type ParsedEmail struct {
	Headers     map[string]string `json:"headers"`
	From        string            `json:"from"`
	To          []string          `json:"to"`
	Cc          []string          `json:"cc,omitempty"`
	Bcc         []string          `json:"bcc,omitempty"`
	Subject     string            `json:"subject"`
	Date        time.Time         `json:"date"`
	HTMLBody    string            `json:"html_body,omitempty"`
	TextBody    string            `json:"text_body,omitempty"`
	Attachments []Attachment      `json:"attachments,omitempty"`
}

ParsedEmail represents a parsed .eml file.

type Participant

type Participant struct {
	Person
	Status  string `json:"status,omitempty"` // yes, no, maybe, noreply
	Comment string `json:"comment,omitempty"`
}

Participant represents an event participant. Embeds Person for name/email and adds RSVP status.

type ParticipantBooking

type ParticipantBooking struct {
	CalendarID string `json:"calendar_id"`
}

ParticipantBooking represents booking calendar settings for a participant

type ParticipantInfo

type ParticipantInfo struct {
	Email         string           `json:"email"`
	Name          string           `json:"name,omitempty"`
	Required      bool             `json:"required"`
	Involvement   InvolvementLevel `json:"involvement"`
	MentionCount  int              `json:"mention_count"`
	MessageCount  int              `json:"message_count"`
	LastMessageAt string           `json:"last_message_at,omitempty"`
}

ParticipantInfo represents a participant with their involvement level.

type ParticipantPattern

type ParticipantPattern struct {
	Email           string   `json:"email"`
	MeetingCount    int      `json:"meeting_count"`
	AcceptanceRate  float64  `json:"acceptance_rate"`
	PreferredDays   []string `json:"preferred_days"`
	PreferredTimes  []string `json:"preferred_times"`
	AverageDuration int      `json:"average_duration"` // Minutes
	Timezone        string   `json:"timezone"`
}

ParticipantPattern tracks patterns for specific participants.

type PatternStore

type PatternStore interface {
	SavePattern(pattern *MeetingPattern) error
	LoadPattern(userEmail string) (*MeetingPattern, error)
	DeletePattern(userEmail string) error
}

PatternStore defines the interface for storing learned patterns.

type Person

type Person struct {
	Name  string `json:"name,omitempty"`
	Email string `json:"email"`
}

Person represents a person with name and email. This is the base type for EmailParticipant and embedded in Participant.

func (Person) DisplayName

func (p Person) DisplayName() string

DisplayName returns the name if available, otherwise the email.

func (Person) String

func (p Person) String() string

String returns a formatted display string for the person.

type PrivacyConfig

type PrivacyConfig struct {
	AllowCloudAI     bool `yaml:"allow_cloud_ai"`     // Require explicit opt-in for cloud AI
	DataRetention    int  `yaml:"data_retention"`     // Days to keep learned patterns (0 = disabled)
	LocalStorageOnly bool `yaml:"local_storage_only"` // Only use local storage, no cloud
}

PrivacyConfig represents privacy settings for AI features.

type ProductivityPatterns

type ProductivityPatterns struct {
	PeakFocus      []TimeBlock        `json:"peak_focus"`      // Best focus time blocks
	LowEnergy      []TimeBlock        `json:"low_energy"`      // Low productivity times
	MeetingDensity map[string]float64 `json:"meeting_density"` // DayOfWeek -> avg meetings per day
	FocusBlocks    []TimeBlock        `json:"focus_blocks"`    // Recommended focus time blocks
}

ProductivityPatterns tracks productive time blocks.

type ProtectedBlock

type ProtectedBlock struct {
	// 8-byte aligned fields
	ID                string              `json:"id"`
	CalendarEventID   string              `json:"calendar_event_id,omitempty"` // Linked calendar event
	StartTime         time.Time           `json:"start_time"`
	EndTime           time.Time           `json:"end_time"`
	CreatedAt         time.Time           `json:"created_at"`
	UpdatedAt         time.Time           `json:"updated_at"`
	RecurrencePattern string              `json:"recurrence_pattern,omitempty"` // e.g., "weekly"
	Priority          MeetingPriority     `json:"priority"`
	Reason            string              `json:"reason"` // Why this block is protected
	OverrideReason    string              `json:"override_reason,omitempty"`
	ProtectionRules   FocusProtectionRule `json:"protection_rules"`
	Duration          int                 `json:"duration"` // Minutes
	// Bool fields grouped to minimize padding
	IsRecurring      bool `json:"is_recurring"`
	AllowOverride    bool `json:"allow_override"`    // Can be overridden
	OverrideApproved bool `json:"override_approved"` // Override was approved
}

ProtectedBlock represents an active focus time block on the calendar. Field order optimized for memory alignment (8-byte fields first, bools grouped at end).

type Provider

type Provider string

Provider represents an email provider type.

const (
	ProviderGoogle    Provider = "google"
	ProviderMicrosoft Provider = "microsoft"
	ProviderIMAP      Provider = "imap"
	ProviderVirtual   Provider = "virtual"
	ProviderInbox     Provider = "inbox" // Nylas Native Auth
)

func ParseProvider

func ParseProvider(s string) (Provider, error)

ParseProvider converts a string to a Provider.

func (Provider) DisplayName

func (p Provider) DisplayName() string

DisplayName returns the user-friendly name for the provider.

func (Provider) IsSupportedByAir

func (p Provider) IsSupportedByAir() bool

IsSupportedByAir checks if the provider is supported by the Air web UI.

func (Provider) IsValid

func (p Provider) IsValid() bool

IsValid checks if the provider is a known type.

type Recommendation

type Recommendation struct {
	Type        string  `json:"type"`     // "focus_time", "decline_pattern", "duration_adjustment"
	Priority    string  `json:"priority"` // "high", "medium", "low"
	Title       string  `json:"title"`
	Description string  `json:"description"`
	Confidence  float64 `json:"confidence"` // 0-100
	Action      string  `json:"action"`     // Suggested action
	Impact      string  `json:"impact"`     // Expected impact
}

Recommendation represents an AI-generated recommendation.

type RecurringEventInfo

type RecurringEventInfo struct {
	MasterEventID     string   `json:"master_event_id"`
	RecurrenceRule    []string `json:"recurrence"`
	OriginalStartTime *int64   `json:"original_start_time,omitempty"` // For modified instances
	ExpandRecurring   bool     `json:"expand_recurring,omitempty"`
}

RecurringEventInfo provides information about a recurring event series.

type Reminder

type Reminder struct {
	ReminderMinutes int    `json:"reminder_minutes"`
	ReminderMethod  string `json:"reminder_method,omitempty"` // email, popup
}

Reminder represents a single reminder.

type Reminders

type Reminders struct {
	UseDefault bool       `json:"use_default"`
	Overrides  []Reminder `json:"overrides,omitempty"`
}

Reminders represents event reminders.

type ReplyEvent

type ReplyEvent struct {
	MessageID     string    `json:"message_id"`
	Timestamp     time.Time `json:"timestamp"`
	ThreadID      string    `json:"thread_id,omitempty"`
	RootMessageID string    `json:"root_message_id,omitempty"`
}

ReplyEvent represents a reply tracking event.

type RescheduleBookingRequest

type RescheduleBookingRequest struct {
	StartTime int64  `json:"start_time"`         // Unix timestamp for new start time
	EndTime   int64  `json:"end_time"`           // Unix timestamp for new end time
	Timezone  string `json:"timezone,omitempty"` // Timezone for the booking (e.g., "America/New_York")
	Reason    string `json:"reason,omitempty"`   // Reason for rescheduling
}

RescheduleBookingRequest represents a request to reschedule a booking

type RescheduleOption

type RescheduleOption struct {
	ProposedTime     time.Time  `json:"proposed_time"`
	EndTime          time.Time  `json:"end_time"`
	Score            int        `json:"score"` // 0-100
	Confidence       float64    `json:"confidence"`
	Pros             []string   `json:"pros"`
	Cons             []string   `json:"cons"`
	Conflicts        []Conflict `json:"conflicts"`         // Any remaining conflicts
	ParticipantMatch float64    `json:"participant_match"` // % of participants available
	AIInsight        string     `json:"ai_insight"`
}

RescheduleOption represents an alternative time for rescheduling.

type RescheduleRequest

type RescheduleRequest struct {
	EventID            string      `json:"event_id"`
	Reason             string      `json:"reason"`
	PreferredTimes     []time.Time `json:"preferred_times,omitempty"`
	MustInclude        []string    `json:"must_include,omitempty"` // Participant emails
	AvoidDays          []string    `json:"avoid_days,omitempty"`
	MinNoticeDays      int         `json:"min_notice_days"`
	MaxDelayDays       int         `json:"max_delay_days"`
	NotifyParticipants bool        `json:"notify_participants"`
}

RescheduleRequest represents a request to reschedule a meeting.

type RescheduleResult

type RescheduleResult struct {
	Success           bool              `json:"success"`
	OriginalEvent     *Event            `json:"original_event"`
	NewEvent          *Event            `json:"new_event,omitempty"`
	SelectedOption    *RescheduleOption `json:"selected_option,omitempty"`
	NotificationsSent int               `json:"notifications_sent"`
	Message           string            `json:"message"`
	CascadingChanges  []string          `json:"cascading_changes,omitempty"`
}

RescheduleResult represents the result of a rescheduling operation.

type Resource

type Resource interface {
	GetID() string
}

Resource is implemented by all domain resources with ID.

type ScheduleModification

type ScheduleModification struct {
	EventID      string    `json:"event_id"`
	Action       string    `json:"action"` // "reschedule", "shorten", "decline", "protect"
	OldStartTime time.Time `json:"old_start_time,omitempty"`
	NewStartTime time.Time `json:"new_start_time,omitempty"`
	OldDuration  int       `json:"old_duration,omitempty"` // Minutes
	NewDuration  int       `json:"new_duration,omitempty"` // Minutes
	Description  string    `json:"description"`
}

ScheduleModification represents a specific schedule modification.

type ScheduledMessage

type ScheduledMessage struct {
	ScheduleID string `json:"schedule_id"`
	Status     string `json:"status"` // pending, scheduled, sending, sent, failed, cancelled
	CloseTime  int64  `json:"close_time"`
}

ScheduledMessage represents a scheduled email.

type ScheduledMessageListResponse

type ScheduledMessageListResponse struct {
	Data []ScheduledMessage `json:"data"`
}

ScheduledMessageListResponse represents a list of scheduled messages.

type SchedulerConfiguration

type SchedulerConfiguration struct {
	ID                  string                     `json:"id,omitempty"`
	Name                string                     `json:"name"`
	Slug                string                     `json:"slug,omitempty"`
	RequiresSessionAuth bool                       `json:"requires_session_auth,omitempty"`
	Participants        []ConfigurationParticipant `json:"participants"`
	Availability        AvailabilityRules          `json:"availability"`
	EventBooking        EventBooking               `json:"event_booking"`
	Scheduler           SchedulerSettings          `json:"scheduler"`
	AppearanceSettings  *AppearanceSettings        `json:"appearance,omitempty"`
	CreatedAt           *time.Time                 `json:"created_at,omitempty"`
	ModifiedAt          *time.Time                 `json:"modified_at,omitempty"`
}

SchedulerConfiguration represents a scheduling configuration (meeting type)

type SchedulerPage

type SchedulerPage struct {
	ID              string    `json:"id,omitempty"`
	ConfigurationID string    `json:"configuration_id"`
	Name            string    `json:"name"`
	Slug            string    `json:"slug"`
	URL             string    `json:"url,omitempty"`
	CustomDomain    string    `json:"custom_domain,omitempty"`
	CreatedAt       time.Time `json:"created_at,omitempty"`
	ModifiedAt      time.Time `json:"modified_at,omitempty"`
}

SchedulerPage represents a hosted scheduling page

type SchedulerSession

type SchedulerSession struct {
	SessionID       string    `json:"session_id"`
	ConfigurationID string    `json:"configuration_id"`
	BookingURL      string    `json:"booking_url,omitempty"`
	CreatedAt       time.Time `json:"created_at,omitempty"`
	ExpiresAt       time.Time `json:"expires_at,omitempty"`
}

SchedulerSession represents a scheduling session

type SchedulerSettings

type SchedulerSettings struct {
	AvailableDaysInFuture int            `json:"available_days_in_future,omitempty"`
	MinBookingNotice      int            `json:"min_booking_notice,omitempty"`
	MinCancellationNotice int            `json:"min_cancellation_notice,omitempty"`
	ConfirmationMethod    string         `json:"confirmation_method,omitempty"` // "automatic", "manual"
	ReschedulingURL       string         `json:"rescheduling_url,omitempty"`
	CancellationURL       string         `json:"cancellation_url,omitempty"`
	AdditionalFields      map[string]any `json:"additional_fields,omitempty"`
	CancellationPolicy    string         `json:"cancellation_policy,omitempty"`
}

SchedulerSettings represents scheduler UI settings

type ScoreFactor

type ScoreFactor struct {
	Name        string `json:"name"`
	Impact      int    `json:"impact"` // -100 to +100
	Description string `json:"description"`
}

ScoreFactor represents a factor contributing to the meeting score.

type SendMessageRequest

type SendMessageRequest struct {
	Subject      string             `json:"subject"`
	Body         string             `json:"body"`
	From         []EmailParticipant `json:"from,omitempty"`
	To           []EmailParticipant `json:"to"`
	Cc           []EmailParticipant `json:"cc,omitempty"`
	Bcc          []EmailParticipant `json:"bcc,omitempty"`
	ReplyTo      []EmailParticipant `json:"reply_to,omitempty"`
	ReplyToMsgID string             `json:"reply_to_message_id,omitempty"`
	TrackingOpts *TrackingOptions   `json:"tracking_options,omitempty"`
	Attachments  []Attachment       `json:"attachments,omitempty"`
	SendAt       int64              `json:"send_at,omitempty"` // Unix timestamp for scheduled sending
	Metadata     map[string]string  `json:"metadata,omitempty"`
}

SendMessageRequest represents a request to send an email.

func (SendMessageRequest) Validate

func (r SendMessageRequest) Validate() error

Validate checks that SendMessageRequest has at least one recipient.

type SendRSVPRequest

type SendRSVPRequest struct {
	Status  string `json:"status"` // yes, no, maybe
	Comment string `json:"comment,omitempty"`
}

SendRSVPRequest for responding to an event invitation.

type SlackAttachment

type SlackAttachment struct {
	ID          string `json:"id"`           // Unique file identifier (e.g., "F1234567890")
	Name        string `json:"name"`         // Original filename
	Title       string `json:"title"`        // Display title (may differ from name)
	MimeType    string `json:"mime_type"`    // MIME type (e.g., "image/png", "application/pdf")
	FileType    string `json:"file_type"`    // Slack file type (e.g., "png", "pdf")
	Size        int64  `json:"size"`         // File size in bytes
	DownloadURL string `json:"download_url"` // Private download URL (requires auth)
	Permalink   string `json:"permalink"`    // Permanent link to file in Slack
	UserID      string `json:"user_id"`      // User who uploaded the file
	Created     int64  `json:"created"`      // Unix timestamp when uploaded
	// Image-specific fields
	ImageWidth  int `json:"image_width,omitempty"`  // Original width in pixels
	ImageHeight int `json:"image_height,omitempty"` // Original height in pixels
	// Thumbnail URLs (for images)
	Thumb360 string `json:"thumb_360,omitempty"` // 360px thumbnail URL
	Thumb480 string `json:"thumb_480,omitempty"` // 480px thumbnail URL
}

SlackAttachment represents a file attached to a message.

type SlackAuth

type SlackAuth struct {
	UserID    string `json:"user_id"`              // Authenticated user's ID
	TeamID    string `json:"team_id"`              // Workspace ID (e.g., "T1234567890")
	TeamName  string `json:"team_name"`            // Workspace display name
	UserName  string `json:"user_name"`            // Authenticated user's username
	UserEmail string `json:"user_email,omitempty"` // User's email (if available)
}

SlackAuth represents authentication information for a Slack workspace connection.

type SlackChannel

type SlackChannel struct {
	ID           string    `json:"id"`                      // Channel ID (e.g., "C1234567890" for public, "G..." for private)
	Name         string    `json:"name"`                    // Channel name without # prefix (empty for DMs)
	IsChannel    bool      `json:"is_channel"`              // True if this is a public channel
	IsGroup      bool      `json:"is_group"`                // True if this is a private channel (legacy)
	IsIM         bool      `json:"is_im"`                   // True if this is a direct message (1:1 conversation)
	IsMPIM       bool      `json:"is_mpim"`                 // Multi-Party Instant Message - a group DM with multiple users
	IsPrivate    bool      `json:"is_private"`              // True if channel is private (not visible to all workspace members)
	IsArchived   bool      `json:"is_archived"`             // True if channel has been archived
	IsMember     bool      `json:"is_member"`               // True if the authenticated user is a member
	IsShared     bool      `json:"is_shared"`               // True if shared with another workspace
	IsOrgShared  bool      `json:"is_org_shared"`           // True if shared across workspaces in the same Enterprise Grid org
	IsExtShared  bool      `json:"is_ext_shared"`           // True if shared with an external workspace (Slack Connect)
	Topic        string    `json:"topic,omitempty"`         // Current topic shown in channel header
	Purpose      string    `json:"purpose,omitempty"`       // Channel description shown in channel details
	MemberCount  int       `json:"member_count"`            // Number of members in the channel
	Created      time.Time `json:"created"`                 // When the channel was created
	LastActivity time.Time `json:"last_activity,omitempty"` // Timestamp of last message or activity
}

SlackChannel represents a Slack channel, DM, or group DM.

func (SlackChannel) ChannelDisplayName

func (c SlackChannel) ChannelDisplayName() string

ChannelDisplayName returns the best display name for a channel. Returns "DM" for direct messages, "Group DM" for MPIMs, or "#name" for channels.

func (SlackChannel) ChannelType

func (c SlackChannel) ChannelType() string

ChannelType returns the type of channel as a string. Returns one of: "dm", "group_dm", "private", or "public".

type SlackChannelListResponse

type SlackChannelListResponse struct {
	Channels   []SlackChannel `json:"channels"`              // Channels matching the query
	NextCursor string         `json:"next_cursor,omitempty"` // Cursor for fetching the next page
}

SlackChannelListResponse represents a paginated list of channels.

type SlackChannelQueryParams

type SlackChannelQueryParams struct {
	// Types: public_channel, private_channel, mpim (group DM), im (direct message)
	Types           []string `json:"types,omitempty"`            // Channel types to include (defaults to all)
	ExcludeArchived bool     `json:"exclude_archived,omitempty"` // Skip archived channels
	Limit           int      `json:"limit,omitempty"`            // Max channels to return (default: 100, max: 1000)
	Cursor          string   `json:"cursor,omitempty"`           // Pagination cursor from previous response
	TeamID          string   `json:"team_id,omitempty"`          // Required for Enterprise Grid workspaces
}

SlackChannelQueryParams defines filters for listing channels in a workspace.

type SlackFileListResponse

type SlackFileListResponse struct {
	Files      []SlackAttachment `json:"files"`
	NextCursor string            `json:"next_cursor,omitempty"`
}

SlackFileListResponse represents a paginated list of files.

type SlackFileQueryParams

type SlackFileQueryParams struct {
	ChannelID string   `json:"channel_id,omitempty"` // Filter by channel
	UserID    string   `json:"user_id,omitempty"`    // Filter by uploader
	Types     []string `json:"types,omitempty"`      // File types: images, pdfs, docs, etc.
	Limit     int      `json:"limit,omitempty"`      // Max files to return (default: 20)
	Cursor    string   `json:"cursor,omitempty"`     // Pagination cursor
}

SlackFileQueryParams defines filters for listing files in a workspace.

type SlackMessage

type SlackMessage struct {
	ID          string            `json:"id"`                    // Message timestamp (ts) - unique identifier within the channel
	ChannelID   string            `json:"channel_id"`            // Channel where the message was posted
	UserID      string            `json:"user_id"`               // Slack user ID of the sender (e.g., "U1234567890")
	Username    string            `json:"username"`              // Display name of the sender (resolved from user profile)
	Text        string            `json:"text"`                  // Message content (may contain Slack markup)
	Timestamp   time.Time         `json:"timestamp"`             // When the message was sent
	ThreadTS    string            `json:"thread_ts,omitempty"`   // Thread timestamp - unique identifier for the parent message of a thread
	ReplyCount  int               `json:"reply_count,omitempty"` // Number of replies in the thread
	IsReply     bool              `json:"is_reply"`              // True if this message is a reply within a thread
	Edited      bool              `json:"edited"`                // True if the message has been edited
	Attachments []SlackAttachment `json:"attachments,omitempty"` // Files and media attached to the message
	Reactions   []SlackReaction   `json:"reactions,omitempty"`   // Emoji reactions on the message
}

SlackMessage represents a message in Slack.

func (SlackMessage) IsThread

func (m SlackMessage) IsThread() bool

IsThread returns true if the message is part of a thread. A message is in a thread if it has a ThreadTS value (either parent or reply).

type SlackMessageListResponse

type SlackMessageListResponse struct {
	Messages   []SlackMessage `json:"messages"`              // Messages in reverse chronological order
	HasMore    bool           `json:"has_more"`              // True if more messages exist beyond this page
	NextCursor string         `json:"next_cursor,omitempty"` // Cursor for fetching the next page
}

SlackMessageListResponse represents a paginated list of messages.

type SlackMessageQueryParams

type SlackMessageQueryParams struct {
	ChannelID string    `json:"channel_id"`          // Required: channel to fetch messages from
	Limit     int       `json:"limit,omitempty"`     // Max messages to return (default: 100, max: 1000)
	Cursor    string    `json:"cursor,omitempty"`    // Pagination cursor from previous response
	Oldest    time.Time `json:"oldest,omitempty"`    // Only return messages after this time
	Newest    time.Time `json:"newest,omitempty"`    // Only return messages before this time
	Inclusive bool      `json:"inclusive,omitempty"` // Include messages with exact Oldest/Newest timestamps
}

SlackMessageQueryParams defines filters for querying messages in a channel.

type SlackReaction

type SlackReaction struct {
	Name  string   `json:"name"`  // Emoji name without colons (e.g., "thumbsup", "heart")
	Count int      `json:"count"` // Number of users who added this reaction
	Users []string `json:"users"` // User IDs who reacted with this emoji
}

SlackReaction represents an emoji reaction.

type SlackSendMessageRequest

type SlackSendMessageRequest struct {
	ChannelID string `json:"channel_id"`                // Required: channel to post the message to
	Text      string `json:"text"`                      // Required: message content (supports Slack markup)
	ThreadTS  string `json:"thread_ts,omitempty"`       // Thread timestamp to reply to (creates threaded reply)
	Broadcast bool   `json:"reply_broadcast,omitempty"` // Also post thread reply to channel (requires ThreadTS)
}

SlackSendMessageRequest represents the parameters for sending a message to a channel.

type SlackUser

type SlackUser struct {
	ID           string            `json:"id"`                      // User ID (e.g., "U1234567890")
	Name         string            `json:"name"`                    // Username handle (e.g., "jsmith")
	RealName     string            `json:"real_name"`               // Full name from profile (e.g., "John Smith")
	DisplayName  string            `json:"display_name"`            // Custom display name set by user (may be empty)
	Title        string            `json:"title,omitempty"`         // Job title (e.g., "Software Engineer")
	Email        string            `json:"email,omitempty"`         // User's email address (requires users:read.email scope)
	Phone        string            `json:"phone,omitempty"`         // Phone number
	Avatar       string            `json:"avatar,omitempty"`        // URL to user's profile image (72x72 pixels)
	IsBot        bool              `json:"is_bot"`                  // True if this is a bot user
	IsAdmin      bool              `json:"is_admin"`                // True if user has admin privileges
	Status       string            `json:"status,omitempty"`        // Custom status text (e.g., "In a meeting")
	StatusEmoji  string            `json:"status_emoji,omitempty"`  // Status emoji (e.g., ":calendar:")
	Timezone     string            `json:"timezone,omitempty"`      // User's timezone in IANA format (e.g., "America/New_York")
	CustomFields map[string]string `json:"custom_fields,omitempty"` // Custom profile fields (label -> value)
}

SlackUser represents a Slack workspace member.

func (SlackUser) BestDisplayName

func (u SlackUser) BestDisplayName() string

BestDisplayName returns the best display name for a user. Priority: DisplayName > RealName > Name (username handle).

type SlackUserListResponse

type SlackUserListResponse struct {
	Users      []SlackUser `json:"users"`                 // Workspace members (excludes deleted users)
	NextCursor string      `json:"next_cursor,omitempty"` // Cursor for fetching the next page
}

SlackUserListResponse represents a paginated list of users.

type SmartComposeRequest

type SmartComposeRequest struct {
	Prompt string `json:"prompt"` // AI instruction (max 1000 tokens)
}

SmartComposeRequest represents a request to generate an AI email draft.

type SmartComposeSuggestion

type SmartComposeSuggestion struct {
	Suggestion string `json:"suggestion"` // The generated email text
}

SmartComposeSuggestion represents an AI-generated email suggestion.

type SpamAnalysis

type SpamAnalysis struct {
	Score       float64       `json:"score"` // 0-10 (lower is better)
	IsSpam      bool          `json:"is_spam"`
	Triggers    []SpamTrigger `json:"triggers"`
	Passed      []string      `json:"passed"`
	Suggestions []string      `json:"suggestions"`
}

SpamAnalysis contains spam score analysis.

type SpamTrigger

type SpamTrigger struct {
	Rule        string  `json:"rule"`
	Description string  `json:"description"`
	Score       float64 `json:"score"`
	Severity    string  `json:"severity"` // "high", "medium", "low"
}

SpamTrigger represents a spam filter trigger.

type TemplateRequest

type TemplateRequest struct {
	Name      string            `json:"name"`
	Subject   string            `json:"subject"`
	HTMLBody  string            `json:"html_body"`
	TextBody  string            `json:"text_body,omitempty"`
	Variables []string          `json:"variables"`
	InlineCSS bool              `json:"inline_css"`
	Sanitize  bool              `json:"sanitize"`
	Metadata  map[string]string `json:"metadata,omitempty"`
}

TemplateRequest contains parameters for building email templates.

type Thread

type Thread struct {
	ID                    string             `json:"id"`
	GrantID               string             `json:"grant_id"`
	LatestDraftOrMessage  Message            `json:"latest_draft_or_message,omitempty"`
	HasAttachments        bool               `json:"has_attachments"`
	HasDrafts             bool               `json:"has_drafts"`
	Starred               bool               `json:"starred"`
	Unread                bool               `json:"unread"`
	EarliestMessageDate   time.Time          `json:"earliest_message_date"`
	LatestMessageRecvDate time.Time          `json:"latest_message_received_date"`
	LatestMessageSentDate time.Time          `json:"latest_message_sent_date"`
	Participants          []EmailParticipant `json:"participants"`
	MessageIDs            []string           `json:"message_ids"`
	DraftIDs              []string           `json:"draft_ids"`
	FolderIDs             []string           `json:"folders"`
	Snippet               string             `json:"snippet"`
	Subject               string             `json:"subject"`
}

Thread represents an email thread/conversation.

type ThreadListResponse

type ThreadListResponse struct {
	Data       []Thread   `json:"data"`
	Pagination Pagination `json:"pagination,omitempty"`
}

ThreadListResponse represents a paginated thread list response.

type ThreadQueryParams

type ThreadQueryParams struct {
	Limit           int      `json:"limit,omitempty"`
	Offset          int      `json:"offset,omitempty"`
	PageToken       string   `json:"page_token,omitempty"` // Cursor for pagination
	Subject         string   `json:"subject,omitempty"`
	From            string   `json:"from,omitempty"`
	To              string   `json:"to,omitempty"`
	In              []string `json:"in,omitempty"`
	Unread          *bool    `json:"unread,omitempty"`
	Starred         *bool    `json:"starred,omitempty"`
	LatestMsgBefore int64    `json:"latest_message_before,omitempty"`
	LatestMsgAfter  int64    `json:"latest_message_after,omitempty"`
	HasAttachment   *bool    `json:"has_attachment,omitempty"`
	SearchQuery     string   `json:"q,omitempty"`
}

ThreadQueryParams for filtering threads.

type TimeBlock

type TimeBlock struct {
	DayOfWeek string  `json:"day_of_week"` // "Monday", "Tuesday", etc.
	StartTime string  `json:"start_time"`  // "09:00"
	EndTime   string  `json:"end_time"`    // "11:00"
	Score     float64 `json:"score"`       // Productivity score 0-100
}

TimeBlock represents a recurring time block.

type TimeRange

type TimeRange struct {
	StartTime string `json:"start_time"` // "09:00"
	EndTime   string `json:"end_time"`   // "17:00"
}

TimeRange represents a time range within a day.

type TimeSlot

type TimeSlot struct {
	StartTime int64  `json:"start_time"`
	EndTime   int64  `json:"end_time"`
	Status    string `json:"status,omitempty"` // busy, free
	Object    string `json:"object,omitempty"`
}

TimeSlot represents a busy time slot.

type TimeZoneInfo

type TimeZoneInfo struct {
	Name         string     `json:"name"`               // IANA name (e.g., "America/Los_Angeles")
	Abbreviation string     `json:"abbreviation"`       // Current abbreviation (e.g., "PST", "PDT")
	Offset       int        `json:"offset"`             // Current offset from UTC in seconds
	IsDST        bool       `json:"is_dst"`             // Whether currently observing DST
	NextDST      *time.Time `json:"next_dst,omitempty"` // Next DST transition
}

TimeZoneInfo provides detailed information about a time zone.

type Timestamped

type Timestamped interface {
	GetCreatedAt() time.Time
	GetUpdatedAt() time.Time
}

Timestamped is implemented by resources with creation/update timestamps.

type TimezonePatterns

type TimezonePatterns struct {
	PreferredTimes map[string][]string `json:"preferred_times"` // Timezone -> preferred hours
	Distribution   map[string]int      `json:"distribution"`    // Timezone -> count
	CrossTZTimes   []string            `json:"cross_tz_times"`  // Preferred times for cross-TZ meetings
}

TimezonePatterns tracks timezone preferences.

type TokenUsage

type TokenUsage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	TotalTokens      int `json:"total_tokens"`
}

TokenUsage represents token usage statistics.

type Tool

type Tool struct {
	Name        string         `json:"name"`
	Description string         `json:"description"`
	Parameters  map[string]any `json:"parameters"`
}

Tool represents a function/tool available to the LLM.

type ToolCall

type ToolCall struct {
	ID        string         `json:"id"`
	Function  string         `json:"function"`
	Arguments map[string]any `json:"arguments"`
}

ToolCall represents a tool invocation from the LLM.

type TrackingData

type TrackingData struct {
	MessageID string       `json:"message_id"`
	Opens     []OpenEvent  `json:"opens,omitempty"`
	Clicks    []ClickEvent `json:"clicks,omitempty"`
	Replies   []ReplyEvent `json:"replies,omitempty"`
}

TrackingData represents tracking statistics for a message.

type TrackingOptions

type TrackingOptions struct {
	Opens bool   `json:"opens"`
	Links bool   `json:"links"`
	Label string `json:"label,omitempty"`
}

TrackingOptions for email tracking.

type UnixTime

type UnixTime struct {
	time.Time
}

UnixTime wraps time.Time to handle Unix timestamp JSON unmarshaling

func (*UnixTime) UnmarshalJSON

func (ut *UnixTime) UnmarshalJSON(data []byte) error

UnmarshalJSON handles both Unix timestamps (integers) and RFC3339 strings

type UpdateApplicationRequest

type UpdateApplicationRequest struct {
	Name             *string           `json:"name,omitempty"`
	BrandingSettings *BrandingSettings `json:"branding,omitempty"`
	CallbackURIs     []string          `json:"callback_uris,omitempty"`
	Metadata         map[string]string `json:"metadata,omitempty"`
}

UpdateApplicationRequest represents a request to update an application

type UpdateCalendarRequest

type UpdateCalendarRequest struct {
	Name        *string `json:"name,omitempty"`
	Description *string `json:"description,omitempty"`
	Location    *string `json:"location,omitempty"`
	Timezone    *string `json:"timezone,omitempty"`
	HexColor    *string `json:"hex_color,omitempty"`
}

UpdateCalendarRequest for updating a calendar.

type UpdateConnectorRequest

type UpdateConnectorRequest struct {
	Name     *string            `json:"name,omitempty"`
	Settings *ConnectorSettings `json:"settings,omitempty"`
	Scopes   []string           `json:"scopes,omitempty"`
}

UpdateConnectorRequest represents a request to update a connector

type UpdateContactGroupRequest

type UpdateContactGroupRequest struct {
	Name *string `json:"name,omitempty"`
}

UpdateContactGroupRequest for updating a contact group.

type UpdateContactRequest

type UpdateContactRequest struct {
	GivenName         *string            `json:"given_name,omitempty"`
	MiddleName        *string            `json:"middle_name,omitempty"`
	Surname           *string            `json:"surname,omitempty"`
	Suffix            *string            `json:"suffix,omitempty"`
	Nickname          *string            `json:"nickname,omitempty"`
	Birthday          *string            `json:"birthday,omitempty"`
	CompanyName       *string            `json:"company_name,omitempty"`
	JobTitle          *string            `json:"job_title,omitempty"`
	ManagerName       *string            `json:"manager_name,omitempty"`
	Notes             *string            `json:"notes,omitempty"`
	Emails            []ContactEmail     `json:"emails,omitempty"`
	PhoneNumbers      []ContactPhone     `json:"phone_numbers,omitempty"`
	WebPages          []ContactWebPage   `json:"web_pages,omitempty"`
	IMAddresses       []ContactIM        `json:"im_addresses,omitempty"`
	PhysicalAddresses []ContactAddress   `json:"physical_addresses,omitempty"`
	Groups            []ContactGroupInfo `json:"groups,omitempty"`
}

UpdateContactRequest for updating a contact.

type UpdateCredentialRequest

type UpdateCredentialRequest struct {
	Name           *string        `json:"name,omitempty"`
	CredentialData map[string]any `json:"credential_data,omitempty"`
}

UpdateCredentialRequest represents a request to update a credential

type UpdateEventRequest

type UpdateEventRequest struct {
	Title        *string           `json:"title,omitempty"`
	Description  *string           `json:"description,omitempty"`
	Location     *string           `json:"location,omitempty"`
	When         *EventWhen        `json:"when,omitempty"`
	Participants []Participant     `json:"participants,omitempty"`
	Busy         *bool             `json:"busy,omitempty"`
	Visibility   *string           `json:"visibility,omitempty"`
	Recurrence   []string          `json:"recurrence,omitempty"`
	Conferencing *Conferencing     `json:"conferencing,omitempty"`
	Reminders    *Reminders        `json:"reminders,omitempty"`
	Metadata     map[string]string `json:"metadata,omitempty"`
}

UpdateEventRequest for updating an event.

type UpdateFolderRequest

type UpdateFolderRequest struct {
	Name            string `json:"name,omitempty"`
	ParentID        string `json:"parent_id,omitempty"`
	BackgroundColor string `json:"background_color,omitempty"`
	TextColor       string `json:"text_color,omitempty"`
}

UpdateFolderRequest for updating a folder.

type UpdateMessageRequest

type UpdateMessageRequest struct {
	Unread  *bool    `json:"unread,omitempty"`
	Starred *bool    `json:"starred,omitempty"`
	Folders []string `json:"folders,omitempty"`
}

UpdateMessageRequest for updating message properties.

type UpdateRecurringEventRequest

type UpdateRecurringEventRequest struct {
	UpdateEventRequest
	MasterEventID string `json:"master_event_id,omitempty"` // For instance updates
}

UpdateRecurringEventRequest for updating recurring event instances.

type UpdateSchedulerConfigurationRequest

type UpdateSchedulerConfigurationRequest struct {
	Name                *string                    `json:"name,omitempty"`
	Slug                *string                    `json:"slug,omitempty"`
	RequiresSessionAuth *bool                      `json:"requires_session_auth,omitempty"`
	Participants        []ConfigurationParticipant `json:"participants,omitempty"`
	Availability        *AvailabilityRules         `json:"availability,omitempty"`
	EventBooking        *EventBooking              `json:"event_booking,omitempty"`
	Scheduler           *SchedulerSettings         `json:"scheduler,omitempty"`
	AppearanceSettings  *AppearanceSettings        `json:"appearance,omitempty"`
}

UpdateSchedulerConfigurationRequest represents a request to update a scheduler configuration

type UpdateSchedulerPageRequest

type UpdateSchedulerPageRequest struct {
	Name         *string `json:"name,omitempty"`
	Slug         *string `json:"slug,omitempty"`
	CustomDomain *string `json:"custom_domain,omitempty"`
}

UpdateSchedulerPageRequest represents a request to update a scheduler page

type UpdateWebhookRequest

type UpdateWebhookRequest struct {
	TriggerTypes               []string `json:"trigger_types,omitempty"`
	WebhookURL                 string   `json:"webhook_url,omitempty"`
	Description                string   `json:"description,omitempty"`
	NotificationEmailAddresses []string `json:"notification_email_addresses,omitempty"`
	Status                     string   `json:"status,omitempty"` // active, inactive
}

UpdateWebhookRequest for updating a webhook.

type Validator

type Validator interface {
	Validate() error
}

Validator is implemented by types that can validate themselves.

type VirtualCalendarGrant

type VirtualCalendarGrant struct {
	ID          string `json:"id"`
	Provider    string `json:"provider"` // Always "virtual-calendar"
	Email       string `json:"email"`    // Custom identifier
	GrantStatus string `json:"grant_status"`
	CreatedAt   int64  `json:"created_at"`
	UpdatedAt   int64  `json:"updated_at"`
}

VirtualCalendarGrant represents a virtual calendar account/grant.

type VirtualCalendarGrantSettings

type VirtualCalendarGrantSettings struct {
	Email string `json:"email"` // Custom identifier (not required to be email format)
}

VirtualCalendarGrantSettings for virtual calendar grant creation.

type Webhook

type Webhook struct {
	ID                         string    `json:"id"`
	Description                string    `json:"description,omitempty"`
	TriggerTypes               []string  `json:"trigger_types"`
	WebhookURL                 string    `json:"webhook_url"`
	WebhookSecret              string    `json:"webhook_secret,omitempty"`
	Status                     string    `json:"status"` // active, inactive, failing
	NotificationEmailAddresses []string  `json:"notification_email_addresses,omitempty"`
	StatusUpdatedAt            time.Time `json:"status_updated_at,omitempty"`
	CreatedAt                  time.Time `json:"created_at,omitempty"`
	UpdatedAt                  time.Time `json:"updated_at,omitempty"`
}

Webhook represents a Nylas webhook subscription.

type WebhookListResponse

type WebhookListResponse struct {
	Data       []Webhook  `json:"data"`
	Pagination Pagination `json:"pagination,omitempty"`
}

WebhookListResponse represents a paginated webhook list.

type WebhookMockPayloadRequest

type WebhookMockPayloadRequest struct {
	TriggerType string `json:"trigger_type"`
}

WebhookMockPayloadRequest for getting a mock payload.

type WebhookPayload

type WebhookPayload struct {
	ID        string            `json:"id"`
	Timestamp time.Time         `json:"timestamp"`
	Method    string            `json:"method"`
	URL       string            `json:"url"`
	Headers   map[string]string `json:"headers"`
	Body      []byte            `json:"body"`
	Signature string            `json:"signature,omitempty"`
	Verified  bool              `json:"verified"`
}

WebhookPayload represents a captured webhook.

type WebhookServerConfig

type WebhookServerConfig struct {
	Port              int               `json:"port"`
	Host              string            `json:"host"`
	PersistentURL     string            `json:"persistent_url,omitempty"`
	SaveToFile        bool              `json:"save_to_file"`
	FilePath          string            `json:"file_path,omitempty"`
	ValidateSignature bool              `json:"validate_signature"`
	Secret            string            `json:"secret,omitempty"`
	Headers           map[string]string `json:"headers,omitempty"`
}

WebhookServerConfig contains configuration for local webhook server.

type WebhookTestRequest

type WebhookTestRequest struct {
	WebhookURL string `json:"webhook_url"`
}

WebhookTestRequest for sending a test webhook event.

type WorkingHoursConfig

type WorkingHoursConfig struct {
	Default   *DaySchedule `yaml:"default,omitempty"`
	Monday    *DaySchedule `yaml:"monday,omitempty"`
	Tuesday   *DaySchedule `yaml:"tuesday,omitempty"`
	Wednesday *DaySchedule `yaml:"wednesday,omitempty"`
	Thursday  *DaySchedule `yaml:"thursday,omitempty"`
	Friday    *DaySchedule `yaml:"friday,omitempty"`
	Saturday  *DaySchedule `yaml:"saturday,omitempty"`
	Sunday    *DaySchedule `yaml:"sunday,omitempty"`
	Weekend   *DaySchedule `yaml:"weekend,omitempty"` // Applies to Sat/Sun if specific days not set
}

WorkingHoursConfig represents working hours configuration.

func (*WorkingHoursConfig) GetScheduleForDay

func (w *WorkingHoursConfig) GetScheduleForDay(weekday string) *DaySchedule

GetScheduleForDay returns the schedule for a given weekday. Checks day-specific, weekend, then default in order of precedence. Weekday is case-insensitive (e.g., "Monday", "monday", "MONDAY" all work).

Jump to

Keyboard shortcuts

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