Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
use async_graphql::{Enum, ID, SimpleObject, Union};
use chrono::{DateTime, Utc};
use rootcause::Report;
use scheduled_action::domain::{
event_trigger::{ActionTrigger, EventName, RoutineTrigger},
models::{ActionKind, ResolvedTaskTarget, ScheduledAction},
};
use serde_json::Value;
/// An AI routine the authenticated user can access.
#[derive(SimpleObject)]
pub struct GraphqlScheduledAction {
/// Stable identifier of the routine.
id: ID,
/// Name shown for the routine.
name: String,
/// Whether automatic dispatch runs this routine.
enabled: bool,
/// What starts a run of this routine.
trigger: GraphqlScheduledActionTrigger,
/// The agent step this routine hands off to: its only one, or the first of
/// several in different branches. Null when no step runs an agent.
agent_task: Option<GraphqlScheduledActionAgentTask>,
/// When the current execution claim stops blocking configuration changes.
/// The timestamp stays present after that instant so clients can compare it themselves.
claim_expires_at: Option<String>,
/// When the routine was created, as RFC 3339.
created_at: String,
/// When the routine row last changed, including execution bookkeeping, as RFC 3339.
updated_at: String,
}
/// The way a routine starts.
#[derive(Union)]
pub(crate) enum GraphqlScheduledActionTrigger {
Cron(GraphqlScheduledActionCronTrigger),
Events(GraphqlScheduledActionEventsTrigger),
Once(GraphqlScheduledActionOnceTrigger),
Multiple(GraphqlScheduledActionMultipleTrigger),
}
/// A routine that runs a single time.
#[derive(SimpleObject)]
pub(crate) struct GraphqlScheduledActionOnceTrigger {
/// When the routine runs, as RFC 3339.
at: String,
/// Whether that run is still ahead. False once it has run.
pending: bool,
}
/// A routine that runs on a cron schedule.
#[derive(SimpleObject)]
pub(crate) struct GraphqlScheduledActionCronTrigger {
/// Cron expression in the six- or seven-field format the scheduler accepts.
schedule: String,
/// Time zone name the cron expression is evaluated in.
timezone: String,
/// Next cron firing, as RFC 3339. Null when the routine is disabled.
next_run_at: Option<String>,
}
/// Any of several schedules and optional Macro event filters.
#[derive(SimpleObject)]
pub(crate) struct GraphqlScheduledActionMultipleTrigger {
/// Each schedule retains its own timezone and next firing.
schedules: Vec<GraphqlScheduledActionCronTrigger>,
/// Single runs at exact times.
once: Vec<GraphqlScheduledActionOnceTrigger>,
/// Events that can also trigger this routine.
events: Option<GraphqlScheduledActionEventsTrigger>,
}
/// A routine that runs when matching events are published.
#[derive(SimpleObject)]
pub(crate) struct GraphqlScheduledActionEventsTrigger {
/// Event filters. A run starts when any filter matches.
filters: Vec<GraphqlScheduledActionEventFilter>,
}
/// One event filter. The event name and entity id must both match.
#[derive(SimpleObject)]
pub(crate) struct GraphqlScheduledActionEventFilter {
/// Event names that can satisfy this filter.
events: Vec<GraphqlScheduledActionEventName>,
/// Entity ids that can satisfy this filter. Null matches every id; an empty list matches nothing.
entity_ids: Option<Vec<ID>>,
/// Which GitHub App deliveries satisfy a `GITHUB` filter.
github: Option<GraphqlScheduledActionGithubSelector>,
/// Exact payload tests a GitHub delivery must pass, as a reader would state them.
payload_match: Vec<String>,
/// The task property that must have changed, and the values it must gain.
property: Option<GraphqlScheduledActionPropertySelector>,
/// Yes/no question the triggering content must answer with yes before the routine runs.
condition: Option<String>,
}
/// A task property a filter watches.
#[derive(SimpleObject)]
pub(crate) struct GraphqlScheduledActionPropertySelector {
/// The property definition that must have changed.
definition_id: ID,
/// Select option or referenced entity ids, one of which the change must add. Empty matches any change.
values: Vec<String>,
}
/// GitHub deliveries a filter watches. Empty lists match everything.
#[derive(SimpleObject)]
pub(crate) struct GraphqlScheduledActionGithubSelector {
/// GitHub event names, such as `workflow_run`.
events: Vec<String>,
/// Payload actions, such as `completed`.
actions: Vec<String>,
/// Repositories, as `owner/name`.
repositories: Vec<String>,
/// Whether deliveries caused by bots also match.
include_bots: bool,
}
/// The agent task a routine runs.
#[derive(SimpleObject)]
pub(crate) struct GraphqlScheduledActionAgentTask {
/// Model the task runs. Null when the selected agent uses its default model.
model: Option<String>,
/// Selected agent. Null for model-only tasks.
agent: Option<GraphqlScheduledActionAgent>,
/// Always empty: the agent step's instructions are in `userPrompt`.
prompt: String,
/// The agent step's instructions.
user_prompt: String,
}
/// An agent selected to run a routine.
#[derive(SimpleObject)]
pub(crate) struct GraphqlScheduledActionAgent {
/// Stable identifier of the selected agent.
bot_id: ID,
}
/// Events a routine filter can name.
#[derive(Enum, Copy, Clone, Eq, PartialEq)]
pub(crate) enum GraphqlScheduledActionEventName {
/// A document was created.
DocumentCreated,
/// A document was updated.
DocumentUpdated,
/// A document was deleted.
DocumentDeleted,
/// A task was created.
TaskCreated,
/// A task's status changed.
TaskStatusChanged,
/// A task's priority changed.
TaskPriorityChanged,
/// A task property changed.
TaskPropertyChanged,
/// A new email was received.
EmailMessageReceived,
/// A channel was created.
ChannelCreated,
/// A channel message was posted.
ChannelMessagePosted,
/// A user was mentioned in a channel.
ChannelMentioned,
/// A channel message was patched.
ChannelMessagePatched,
/// A channel message attachment was created.
ChannelMessageAttachmentCreated,
/// A call the routine's owner started began.
CallStarted,
/// A call the routine's owner joined ended.
CallEnded,
/// Macro's GitHub App received a delivery.
Github,
}
impl From<EventName> for GraphqlScheduledActionEventName {
fn from(name: EventName) -> Self {
match name {
EventName::DocumentCreated => Self::DocumentCreated,
EventName::DocumentUpdated => Self::DocumentUpdated,
EventName::DocumentDeleted => Self::DocumentDeleted,
EventName::TaskCreated => Self::TaskCreated,
EventName::TaskStatusChanged => Self::TaskStatusChanged,
EventName::TaskPriorityChanged => Self::TaskPriorityChanged,
EventName::TaskPropertyChanged => Self::TaskPropertyChanged,
EventName::EmailMessageReceived => Self::EmailMessageReceived,
EventName::ChannelCreated => Self::ChannelCreated,
EventName::ChannelMessagePosted => Self::ChannelMessagePosted,
EventName::ChannelMentioned => Self::ChannelMentioned,
EventName::ChannelMessagePatched => Self::ChannelMessagePatched,
EventName::ChannelMessageAttachmentCreated => Self::ChannelMessageAttachmentCreated,
EventName::CallStarted => Self::CallStarted,
EventName::CallEnded => Self::CallEnded,
EventName::Github => Self::Github,
}
}
}
pub(crate) fn scheduled_action(action: ScheduledAction) -> Result<GraphqlScheduledAction, Report> {
let Some(id) = action.id else {
return Err(rootcause::report!(
"listed scheduled action is missing an id"
));
};
let trigger = trigger(&action);
let agent_task = agent_task(&action.kind, &action.task);
let claim_expires_at = action.claim_expires_at().map(|at| at.to_rfc3339());
let created_at = action.created_at.to_rfc3339();
let updated_at = action.updated_at.to_rfc3339();
Ok(GraphqlScheduledAction {
id: ID(id.to_string()),
name: action.name,
enabled: action.enabled,
trigger,
agent_task,
claim_expires_at,
created_at,
updated_at,
})
}
fn trigger(action: &ScheduledAction) -> GraphqlScheduledActionTrigger {
match &action.trigger {
ActionTrigger::Cron { schedule, timezone } => {
let next_run_at = if action.enabled {
action.next_run_at.map(|at| at.to_rfc3339())
} else {
None
};
GraphqlScheduledActionTrigger::Cron(GraphqlScheduledActionCronTrigger {
schedule: schedule.as_str().to_owned(),
timezone: timezone.to_string(),
next_run_at,
})
}
ActionTrigger::Multiple { triggers } => {
GraphqlScheduledActionTrigger::Multiple(GraphqlScheduledActionMultipleTrigger {
schedules: triggers
.as_slice()
.iter()
.filter_map(|trigger| match trigger {
RoutineTrigger::Cron { schedule, timezone } => {
Some(GraphqlScheduledActionCronTrigger {
schedule: schedule.as_str().to_owned(),
timezone: timezone.to_string(),
next_run_at: action
.enabled
.then(|| {
schedule
.next_run_after_now(*timezone)
.map(|at| at.to_rfc3339())
})
.flatten(),
})
}
RoutineTrigger::Once { .. } | RoutineTrigger::Events { .. } => None,
})
.collect(),
once: triggers
.as_slice()
.iter()
.filter_map(|trigger| match trigger {
RoutineTrigger::Once { at } => Some(once_trigger(action, *at)),
RoutineTrigger::Cron { .. } | RoutineTrigger::Events { .. } => None,
})
.collect(),
events: action.trigger.event_filters().map(event_filters),
})
}
ActionTrigger::Events { filters } => {
GraphqlScheduledActionTrigger::Events(event_filters(filters))
}
ActionTrigger::Once { at } => {
GraphqlScheduledActionTrigger::Once(once_trigger(action, *at))
}
}
}
/// Pending firings never come after `next_run_at`, so a once time at or after
/// it has yet to run.
fn once_trigger(action: &ScheduledAction, at: DateTime<Utc>) -> GraphqlScheduledActionOnceTrigger {
GraphqlScheduledActionOnceTrigger {
at: at.to_rfc3339(),
pending: action.next_run_at.is_some_and(|next| next <= at),
}
}
fn agent_task(kind: &ActionKind, task: &Value) -> Option<GraphqlScheduledActionAgentTask> {
match kind {
ActionKind::Agent => {
let program = routine_program::RoutineProgram::from_task(task).ok()?;
let step = program.agent_steps().into_iter().next()?;
ResolvedTaskTarget::of(step).ok()?;
Some(GraphqlScheduledActionAgentTask {
model: step.model.clone(),
agent: step.agent.map(|agent| GraphqlScheduledActionAgent {
bot_id: ID(agent.bot_id.to_string()),
}),
prompt: String::new(),
user_prompt: step.instructions.clone(),
})
}
}
}
fn event_filters(
filters: &scheduled_action::domain::event_trigger::EventFilters,
) -> GraphqlScheduledActionEventsTrigger {
GraphqlScheduledActionEventsTrigger {
filters: filters
.as_slice()
.iter()
.map(|filter| GraphqlScheduledActionEventFilter {
events: filter.events().iter().copied().map(Into::into).collect(),
entity_ids: filter
.ids()
.map(|ids| ids.iter().map(|id| ID(id.to_string())).collect()),
github: filter
.github()
.map(|selector| GraphqlScheduledActionGithubSelector {
events: selector.events().to_vec(),
actions: selector.actions().to_vec(),
repositories: selector.repositories().to_vec(),
include_bots: selector.include_bots(),
}),
payload_match: filter
.payload()
.map(|conditions| {
conditions
.as_slice()
.iter()
.map(|condition| condition.describe())
.collect()
})
.unwrap_or_default(),
property: filter.property().map(|selector| {
GraphqlScheduledActionPropertySelector {
definition_id: ID(selector.definition_id().to_string()),
values: selector.values().to_vec(),
}
}),
condition: filter
.condition()
.map(|condition| condition.as_str().to_owned()),
})
.collect(),
}
}