Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

7.9 KB
Raw Blame
#![deny(missing_docs)]
//! This crate provides types for entities and actions on those events that can occur in macro
//! Please avoid writing real business logic in this crate unless it is applicable specifically to only the
//! types that exist inside this crate.

use cowlike::CowLike;
use serde::{Deserialize, Serialize};
use std::{borrow::Cow, str::FromStr};
pub use strum::ParseError;
use strum::{AsRefStr, Display, EnumString, IntoStaticStr};
use utoipa::ToSchema;

#[cfg(test)]
mod tests;

mod external_chat;
pub use external_chat::{ExternalChatKind, ExternalChatProvider};

/// The type of an entity in Macro
#[derive(
    Debug,
    Clone,
    Copy,
    Serialize,
    Deserialize,
    Display,
    PartialEq,
    EnumString,
    Hash,
    ToSchema,
    Eq,
    IntoStaticStr,
    AsRefStr,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum EntityType {
    /// The entity is a user
    User,
    /// The entity is an AI Chat session
    Chat,
    /// The entity is a channel (slack-like) conversation
    Channel,
    /// The entity is a message in a channel
    ChannelMessage,
    /// The entity is a document
    Document,
    /// The entity is a collection of other entities
    Project,
    /// The entity is an email thread
    EmailThread,
    /// The entity is a calendar event
    CalendarEvent,
    /// The entity is a team
    Team,
    /// The entity is a voice/video call
    Call,
    /// The entity is a foreign entity stored from an external system
    ForeignEntity,
    /// A public file in the static file service
    StaticFile,
    /// The entity is a CRM company tracked by a team
    CrmCompany,
    /// The entity is a CRM contact tracked by a team
    CrmContact,
    /// A customizable company or contact pipeline with its own grants.
    CrmPipeline,
    /// The entity is a reminder set by a user
    Reminder,
    /// The entity is an AI skill: either a skill document or a built-in
    /// system skill (see the `system_skills` crate)
    Skill,
    /// The entity is an AI coding agent session (see the `agent_session`
    /// crate)
    AgentSession,
    /// The entity is a scheduled action (see the `scheduled_action` service)
    ScheduledAction,
    /// The entity is an initiative (a named grouping of tasks)
    Initiative,
    /// The entity is a Macro Database: a collection of user-defined tables
    /// (see the `databases` crate)
    Database,
    /// The entity is a row of a table in a Macro Database
    DatabaseRow,
    /// The entity is a Macro Form: a questionnaire whose answers land as rows
    /// of one database table (see the `forms` crate)
    Form,
    /// A chat from another messaging service (see [`ExternalChatProvider`])
    /// a person added to Macro as an independently shared entity.
    ExternalChat,
}

impl EntityType {
    /// Returns if the given entity type is a valid entity that is stored in
    /// entity_access
    pub fn is_valid_entity_access_entity(&self) -> bool {
        match self {
            EntityType::User => false,
            EntityType::Team => false,
            EntityType::Channel | EntityType::ChannelMessage => false,
            EntityType::Chat => true,
            EntityType::Document => true,
            EntityType::Project => true,
            EntityType::EmailThread => true,
            // Calendar events use owner or inbox-delegation authorization and
            // are not represented in entity_access/project membership.
            EntityType::CalendarEvent => false,
            // Calls are handled by entity_access by resolving through the call's
            // owning channel (access is inherited from channel membership).
            EntityType::Call => true,
            EntityType::ForeignEntity => false,
            EntityType::StaticFile => false,
            // CRM companies/contacts derive access via team membership joins
            // — they aren't rows in the `entity_access` table.
            EntityType::CrmCompany => false,
            EntityType::CrmContact => false,
            EntityType::CrmPipeline => false,
            // A reminder is private to the user who set it. Access resolves
            // from its owner column, not from a row in the `entity_access`
            // table — the same shape as channels and CRM entities.
            EntityType::Reminder => false,
            // Skill refs are access-checked against the underlying document
            // (system skills are visible to everyone).
            EntityType::Skill => false,
            // Agent sessions hold `entity_access` rows - the owner with
            // owner, the channel the bot was mentioned in as editor - but
            // are not something you file into a project.
            EntityType::AgentSession => false,
            // Scheduled actions are owner-scoped and are not something you
            // file into a project. Access currently resolves from the owner
            // column, not from a row in the `entity_access` table.
            EntityType::ScheduledAction => false,
            // Initiatives hold `entity_access` rows but are not something
            // you file into a project.
            EntityType::Initiative => false,
            // A database's permissions are `entity_access` rows: the creator
            // as owner, whoever it is later shared with, and the grants of
            // the folder it is filed in.
            EntityType::Database => true,
            // Rows carry no `entity_access` rows of their own; access
            // resolves through the parent database.
            EntityType::DatabaseRow => false,
            // A form's grants are `entity_access` rows, including those of
            // the folder it is filed in.
            EntityType::Form => true,
            EntityType::ExternalChat => true,
        }
    }
    /// provide an entity string slice to upgrade this type into an [Entity]
    pub fn with_entity_str<'a>(self, entity_id: &'a str) -> Entity<'a> {
        Entity {
            entity_type: self,
            entity_id: Cow::Borrowed(entity_id),
        }
    }
    /// provide an entity string to upgrade this type into an [Entity]
    pub fn with_entity_string(self, entity_id: String) -> Entity<'static> {
        Entity {
            entity_type: self,
            entity_id: Cow::Owned(entity_id),
        }
    }
}

impl TryFrom<String> for EntityType {
    type Error = strum::ParseError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        EntityType::from_str(&value)
    }
}

/// The Entity describes the minimum amount of information required to describe a unique thing in Macro
/// This contains the type of the entity [EntityType] and the string id of that entity
#[non_exhaustive]
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema, Hash, PartialEq, Eq)]
pub struct Entity<'a> {
    /// The type of entity we are describing
    pub entity_type: EntityType,
    /// The id of that entity
    pub entity_id: Cow<'a, str>,
}

impl<'a> CowLike<'a> for Entity<'a> {
    type Owned<'b> = Entity<'b>;

    fn into_owned(self) -> Entity<'static> {
        Entity {
            entity_type: self.entity_type,
            entity_id: Cow::Owned(self.entity_id.into_owned()),
        }
    }

    fn copied(&'a self) -> Self {
        Entity {
            entity_type: self.entity_type,
            entity_id: Cow::Borrowed(&self.entity_id),
        }
    }
}

/// An owned entity wrapper for APIs that require a non-lifetime-parameterized type.
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct OwnedEntity(Entity<'static>);

impl OwnedEntity {
    /// Borrow the wrapped entity.
    pub fn as_entity(&self) -> &Entity<'static> {
        &self.0
    }

    /// Consume the wrapper and return the wrapped entity.
    pub fn into_entity(self) -> Entity<'static> {
        self.0
    }
}

impl From<Entity<'static>> for OwnedEntity {
    fn from(entity: Entity<'static>) -> Self {
        Self(entity)
    }
}

impl From<OwnedEntity> for Entity<'static> {
    fn from(entity: OwnedEntity) -> Self {
        entity.into_entity()
    }
}