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.

90.8 KB
Raw Blame
use anthropic::toolset::AnthropicToolContext;
use axum::extract::FromRef;
use bots::{
    domain::service::BotServiceImpl, inbound::toolset::BotToolContext,
    outbound::pg_bots_repo::PgBotsRepo,
};
use calendar_events::inbound::team_toolset::TeamCalendarToolContext;
use calendar_events::inbound::toolset::CalendarToolContext;
use call::domain::models::{CallError, CallWebhookEvent, EgressS3Config};
use call::domain::ports::CallRtcClient;
use call::domain::service::{CallRecordQueryServiceImpl, CallServiceImpl};
use call::inbound::toolset::CallToolContext;
use call::outbound::pg_call_repo::PgCallRepo;
use call::outbound::s3_recording_storage::S3RecordingStorage;
use channels::domain::ports::ChannelEventDispatcher;
use channels::domain::service::NoopChannelEventDispatcher;
use channels::domain::side_effects::{ChannelSideEffectService, SpawnedChannelEventDispatcher};
use channels::domain::{list_service::ChannelListServiceImpl, service::ChannelServiceImpl};
use channels::inbound::toolset::ChannelToolContext;
use channels::outbound::{
    connection_gateway_realtime::ConnectionGatewayChannelRealtimePublisher,
    contacts_dispatcher::ContactsChannelDispatcher, notification_sender::NotificationChannelSender,
    pg_channel_reference_share_permissions::PgChannelReferenceSharePermissions,
    pg_channels_repo::PgChannelsRepo, pg_side_effect_context::PgChannelSideEffectContext,
};
use chat::domain::service::ChatServiceImpl;
use chat::inbound::toolset::ChatToolContext;
use chat::outbound::postgres::PgChatRepo;
pub use cognition::inbound::toolset::CognitionToolContext as ToolCognitionToolContext;
use connection::domain::ports::ConnectionService;
use connection_gateway_client::ConnectionGatewayClient;
use contacts::domain::service::{ContactsDomainService, SqsContactsIngress};
use contacts::outbound::gateway::ConnectionGatewayNotifier;
use contacts::outbound::ingress::SqsContactsQueue;
use contacts::outbound::repository::DbContactsRepository;
use crm::inbound::toolset::CrmToolContext;
use databases::inbound::toolset::DatabasesToolContext;
use databases_sql::toolset::DatabasesSqlToolContext;
use databases_sql::{DatabasesSql, ViewOnlyAccess};
use documents::{
    domain::ports::{TaskPropertiesPort, credited_task_edit_receipt, task_property_edit_receipt},
    inbound::toolset::DocumentToolContext,
};
use email::{
    domain::service::EmailServiceImpl, inbound::toolset::EmailToolContext, outbound::EmailPgRepo,
};
use entity_access::domain::models::{
    EditAccessLevel, EntityAccessAuth, EntityAccessReceipt, ViewAccessLevel,
};
use entity_access::domain::ports::EntityAccessService as _;
use entity_registry::OwnerGrantPolicy;
use entity_registry_db_utils::OwnedEntityRegistrar;
use foreign_entity::{
    domain::service::ForeignEntityServiceImpl,
    outbound::pg_foreign_entity_repo::PgForeignEntityRepo,
};
use github_pull_requests::{
    domain::service::GithubPullRequestServiceImpl,
    outbound::pg_github_pull_request_repo::PgGithubPullRequestRepo,
};
use lexical_mention_extractor::LexicalMentionExtractor;
use macro_event_broker::{
    EventBrokerError, KafkaEventPublisher, MacroEvent, MacroEventBroker, MacroEventBrokerService,
    NoopMacroEventBroker,
};
use macro_user_id::user_id::MacroUserIdStr;
use models_properties::service::property_change_source::PropertyChangeSource;
use models_properties::service::property_value::PropertyValue;
use notification::domain::service::SqsNotificationIngress;
use notification::inbound::ai_tool::NotificationToolContext;
use projects::inbound::toolset::ProjectToolContext;
use properties::inbound::toolset::PropertiesToolContext;
use skills::inbound::toolset::SkillToolContext;
use soup::{domain::service::SoupImpl, inbound::toolset::SoupToolContext};
use std::sync::Arc;
use system_properties::{
    PgSystemPropertiesRepository, PriorityOption, StatusOption, SystemPropertiesService as _,
    SystemPropertiesServiceImpl,
};
use teams::{inbound::toolset::TeamToolContext, outbound::team_repo::TeamRepositoryImpl};
use tokio_util::task::TaskTracker;

mod activity_metadata;
mod agent_name;
mod channel_media;
#[cfg(any(test, feature = "test-support"))]
pub use channel_media::build_channel_media_upload_tool_context_test;
pub use channel_media::{
    ToolChannelMediaUploadToolContext, build_channel_media_upload_tool_context,
};
mod agent_sessions;
mod coding_agents;
pub use agent_sessions::{ToolReadAgentSessionContext, build_read_agent_session_context};
pub use coding_agents::{ToolCodingAgentToolContext, build_coding_agent_tool_context};
mod images;
#[cfg(any(test, feature = "test-support"))]
pub use images::build_image_generation_tool_context_test;
pub use images::{ToolImageGenerationToolContext, build_image_generation_tool_context};

mod forms;
pub use forms::{FormsToolConfig, ToolFormsToolContext, build_forms_tool_context};

mod initiatives;
pub use initiatives::{
    ToolInitiativeService, ToolInitiativeToolContext, build_initiative_tool_context,
};

use activity_metadata::ToolActivityMetadataResolver;
pub use ai_toolset::RequestContext;

/// Type alias for the frecency service implementation
pub type ToolFrecencyService = frecency::domain::services::FrecencyQueryServiceImpl<
    frecency::outbound::postgres::FrecencyPgStorage,
>;

/// Type alias for the CRM service implementation used by tools.
///
/// Tools only read CRM rows; the populate path runs in the email-service
/// pubsub worker. The no-op resolver keeps reqwest/scraper out of the
/// tool binary at the cost of a silent negative cache if populate is
/// ever invoked here.
pub type ToolCrmService = crm::domain::service::CrmServiceImpl<
    crm::outbound::companies_repo::CompaniesRepositoryImpl,
    crm::outbound::no_op_resolver::NoOpCompanyMetadataResolver,
>;

/// Type alias for the entity access management service implementation.
pub type ToolEamService =
    entity_access_management::domain::service::EntityAccessManagementServiceImpl<
        entity_access_management::outbound::PgRepository,
    >;

/// Type alias for the email service implementation
pub type ToolEmailService = EmailServiceImpl<
    EmailPgRepo,
    ToolFrecencyService,
    email::domain::ports::NoOpEnqueuer,
    ToolCrmService,
    ToolEamService,
>;

/// Event broker used by AI tools, with spawned publish tasks tracked for
/// graceful shutdown by the hosting process.
pub type ToolEventBroker = MacroEventBrokerService<KafkaEventPublisher, TaskTracker>;

/// Event broker for tool domains (bots, properties, databases) across hosts that either do or do
/// not have Kafka lifecycle publishing configured.
#[derive(Clone)]
pub enum MaybeToolEventBroker {
    /// Publish lifecycle events through the shared Kafka broker.
    Real(ToolEventBroker),
    /// Drop lifecycle events in hosts that do not configure Kafka.
    NoOp(NoopMacroEventBroker),
}

impl MacroEventBroker for MaybeToolEventBroker {
    fn send_event<E: MacroEvent + ?Sized>(
        &self,
        event: &E,
    ) -> Result<tokio::task::JoinHandle<Result<(), EventBrokerError>>, EventBrokerError> {
        match self {
            Self::Real(broker) => broker.send_event(event),
            Self::NoOp(broker) => broker.send_event(event),
        }
    }
}

/// Concrete bot domain service used by AI tools.
pub type ToolBotService = BotServiceImpl<
    PgBotsRepo,
    MaybeToolEventBroker,
    crate::mcp_app_catalog::PipedreamMcpAppCatalog,
>;

/// Bot-management AI tool context.
pub type ToolBotToolContext = BotToolContext<ToolBotService, ToolEntityAccessService>;

/// Build bot-management tools over the canonical Postgres repository and
/// entity-access service.
pub fn build_bot_tool_context(
    pool: sqlx::PgPool,
    event_broker: MaybeToolEventBroker,
    entity_access_service: Arc<ToolEntityAccessService>,
    document_storage_service_url: String,
    pipedream: Option<Arc<pipedream_mcp::outbound::api::PipedreamClient>>,
) -> ToolBotToolContext {
    BotToolContext {
        service: Arc::new(
            BotServiceImpl::new(PgBotsRepo::new(pool), event_broker).with_mcp_apps(
                crate::mcp_app_catalog::PipedreamMcpAppCatalog::new(pipedream),
            ),
        ),
        entity_access_service,
        document_storage_service_url: document_storage_service_url
            .trim_end_matches('/')
            .to_string(),
    }
}

/// Type alias for the send-capable email service implementation used by user
/// tools. Carries the real event broker: these tools mutate email state, and
/// the Gmail-echo suppression means events skipped here are never recovered.
pub type ToolUserEmailService = EmailServiceImpl<
    EmailPgRepo,
    ToolFrecencyService,
    sqs_client::SQS,
    ToolCrmService,
    ToolEamService,
    ToolEventBroker,
>;

/// Type alias for the channel list service implementation.
pub type ToolCommsService = ChannelListServiceImpl<
    PgChannelsRepo,
    PgChannelsRepo,
    frecency::outbound::postgres::FrecencyPgStorage,
>;

/// A channel event dispatcher injected into the tool service, wired via
/// [`build_channel_tool_context_with_side_effects`] (or a host-owned
/// side-effect service, as in the document-storage service) so agent-sent
/// messages notify and broadcast. The no-op variant exists for tests and
/// hosts without the side-effect clients.
pub type ToolChannelEventDispatcher = std::sync::Arc<dyn ChannelEventDispatcher>;

/// Channel reference-sharing adapter used by AI tools, including `ShareWithChannel`.
pub type ToolChannelSharePermissions = PgChannelReferenceSharePermissions<ToolEntityAccessService>;

/// Type alias for the channel messages service implementation used by AI tools.
pub type ToolChannelMessagesService =
    ChannelServiceImpl<PgChannelsRepo, ToolChannelEventDispatcher, ToolChannelSharePermissions>;

/// Type alias for the channel AI tool context.
pub type ToolChannelToolContext =
    ChannelToolContext<ToolChannelMessagesService, ToolEntityAccessService>;

/// Build the channel AI tool context from a Postgres pool with no side
/// effects. Messages sent through it are persisted, but never notify connected
/// clients or publish the channel macro events that drive live search indexing.
/// Only for tests and hosts that genuinely lack the side-effect clients;
/// production hosts should use [`build_channel_tool_context_with_side_effects`].
/// `lexical_client` derives the mention list for messages the agent sends,
/// since bot-authored content arrives without the editor-tracked mentions.
pub fn build_channel_tool_context_without_side_effects(
    pool: sqlx::PgPool,
    lexical_client: Arc<lexical_client::LexicalClient>,
) -> ToolChannelToolContext {
    let messages = Arc::new(shared_message_service(
        pool.clone(),
        messages::domain::ports::NoMessageEventPublisher,
        lexical_client.clone(),
    ));
    build_channel_tool_context_with_dispatcher(
        pool,
        std::sync::Arc::new(NoopChannelEventDispatcher),
        messages,
    )
}

/// Shared message service with no side effects. Messages posted through it
/// are persisted but notify no one, so it is only for tests and read paths.
pub fn build_message_service_without_side_effects(
    pool: sqlx::PgPool,
    lexical_client: Arc<lexical_client::LexicalClient>,
) -> Arc<dyn messages::domain::api::MessageServiceApi> {
    Arc::new(shared_message_service(
        pool,
        messages::domain::ports::NoMessageEventPublisher,
        lexical_client,
    ))
}

/// Shared message service used by agent tools: the same persistence, reference
/// authorization, and group-mention policy as the channel HTTP API, over the
/// delivery `effects` a host composed.
pub fn shared_message_service<E: messages::domain::ports::MessageEventPublisher>(
    pool: sqlx::PgPool,
    effects: E,
    lexical_client: Arc<lexical_client::LexicalClient>,
) -> messages::domain::service::MessageService<
    messages::outbound::pg_message_repo::PgMessageRepository,
    E,
> {
    messages::domain::service::MessageService::new(
        messages::outbound::pg_message_repo::PgMessageRepository::new(pool.clone())
            .with_initiatives(initiative::domain::lookup::InitiativeLookup::new(
                initiative::outbound::PgInitiativeRepo::new(pool.clone()),
            ))
            .with_crm(crm::outbound::lookup::PgCrmParentReader::new(pool.clone())),
        effects,
    )
    .with_group_recipients(channels::domain::group_mentions::ChannelGroupRecipients(
        PgChannelsRepo::new(pool.clone()),
    ))
    .with_mention_extractor(LexicalMentionExtractor::new(lexical_client))
    .with_references(
        messages::outbound::entity_access_audience::EntityAccessMessageReferences(
            entity_access::domain::service::EntityAccessServiceImpl::new(
                entity_access::outbound::PgAccessRepository::new(pool),
            ),
        ),
    )
}

/// Clients a host provides to wire the real channel side effects for AI
/// tools. Notification-ingress and contacts queue names are resolved through
/// `macro_queues`, so hosts only supply the shared clients.
pub struct ChannelSideEffectClients {
    /// Connection gateway client used to fan realtime updates out to
    /// connected clients.
    pub connection_gateway: Arc<ConnectionGatewayClient>,
    /// SQS client used for the notification-ingress and contacts queues.
    pub sqs: aws_sdk_sqs::Client,
    /// Broker publishing channel events to the `macro.channels` topic.
    pub macro_event_broker: ToolEventBroker,
}

/// Build the channel AI tool context dispatching the same side effects as the
/// document-storage channel API: realtime updates via the connection gateway,
/// notifications via the notification-ingress queue, contact sync via the
/// contacts queue, and channel events on the macro event broker. Those channel
/// macro events drive live search indexing. Hosts that let the agent send
/// channel messages need this so mentions and replies notify their recipients.
pub fn build_channel_tool_context_with_side_effects(
    pool: sqlx::PgPool,
    lexical_client: Arc<lexical_client::LexicalClient>,
    clients: &ChannelSideEffectClients,
) -> ToolChannelToolContext {
    let dispatcher = channel_event_dispatcher(&pool, clients);
    let messages = message_service_with_side_effects(
        pool.clone(),
        lexical_client.clone(),
        clients,
        dispatcher.clone(),
    );
    build_channel_tool_context_with_dispatcher(pool, dispatcher, messages)
}

/// Build the shared message service with the same delivery as the
/// document-storage message API: channel side effects for channel messages,
/// and realtime updates and comment notifications for document discussions.
/// Hosts that let the agent comment on documents need this so participants
/// are notified.
pub fn build_message_service_with_side_effects(
    pool: sqlx::PgPool,
    lexical_client: Arc<lexical_client::LexicalClient>,
    clients: &ChannelSideEffectClients,
) -> Arc<dyn messages::domain::api::MessageServiceApi> {
    let dispatcher = channel_event_dispatcher(&pool, clients);
    message_service_with_side_effects(pool, lexical_client, clients, dispatcher)
}

fn notification_ingress(
    clients: &ChannelSideEffectClients,
) -> Arc<SqsNotificationIngress<notification::outbound::queue::SqsQueue>> {
    Arc::new(SqsNotificationIngress {
        queue: notification::outbound::queue::SqsQueue::new(
            clients.sqs.clone(),
            macro_queues::NotificationIngressQueue::new().to_string(),
        ),
    })
}

fn channel_event_dispatcher(
    pool: &sqlx::PgPool,
    clients: &ChannelSideEffectClients,
) -> ToolChannelEventDispatcher {
    let contacts_ingress = Arc::new(SqsContactsIngress {
        queue: SqsContactsQueue::new(
            clients.sqs.clone(),
            macro_queues::ContactsQueue::new().to_string(),
        ),
    });
    let side_effects = ChannelSideEffectService::new(
        PgChannelSideEffectContext::new(pool.clone()),
        ConnectionGatewayChannelRealtimePublisher::new(clients.connection_gateway.clone()),
        NotificationChannelSender::new(notification_ingress(clients)),
        ContactsChannelDispatcher::new(contacts_ingress),
    )
    .with_macro_event_broker(clients.macro_event_broker.clone());
    Arc::new(SpawnedChannelEventDispatcher::new(side_effects))
}

fn message_service_with_side_effects(
    pool: sqlx::PgPool,
    lexical_client: Arc<lexical_client::LexicalClient>,
    clients: &ChannelSideEffectClients,
    dispatcher: ToolChannelEventDispatcher,
) -> Arc<dyn messages::domain::api::MessageServiceApi> {
    let access = entity_access::domain::service::EntityAccessServiceImpl::new(
        entity_access::outbound::PgAccessRepository::new(pool.clone()),
    );
    let realtime = messages::outbound::connection_gateway::ConnectionGatewayMessages(
        clients.connection_gateway.clone(),
    );
    let effects = messages::domain::effects::MessageEffects::new(
        messages::outbound::broker::BrokerMessagePublisher::new(clients.macro_event_broker.clone()),
        messages::domain::ports::NoMessageEventPublisher,
        messages::domain::delivery::ParentMessagePublisher::new(
            channels::domain::message_delivery::ChannelMessageDelivery::new(
                PgChannelsRepo::new(pool.clone()),
                dispatcher,
                channels::outbound::pg_channel_reference_share_permissions::PgChannelReferenceSharePermissions::new(
                    pool.clone(),
                    Arc::new(access.clone()),
                ),
                realtime.clone(),
                channels::outbound::pg_agent_creations::PgAgentCreations::new(
                    pool.clone(),
                ),
            ),
            messages::domain::delivery::DiscussionDelivery::new(
                messages::outbound::pg_discussion_context::PgDiscussionContext(pool.clone())
                    .with_initiatives(
                        initiative::domain::lookup::InitiativeLookup::new(
                            initiative::outbound::PgInitiativeRepo::new(pool.clone()),
                        ),
                        build_properties_service(pool.clone(), Arc::new(access.clone())),
                    )
                    .with_crm(crm::outbound::lookup::PgCrmParentReader::new(pool.clone())),
                messages::outbound::entity_access_audience::EntityAccessMessageAudience(access),
                realtime,
                messages::outbound::notification_sender::MessageNotificationSender(
                    notification_ingress(clients),
                ),
            )
            .with_sharing(messages::outbound::pg_discussion_context::PgDiscussionContext(
                pool.clone(),
            )),
        ),
    );
    Arc::new(shared_message_service(pool, effects, lexical_client))
}

/// Build the channel AI tool context wired to `dispatcher`, so messages sent by
/// agent tools fire the host's notification, realtime, and macro-event side
/// effects. Channel macro events drive live search indexing.
pub fn build_channel_tool_context_with_dispatcher(
    pool: sqlx::PgPool,
    dispatcher: ToolChannelEventDispatcher,
    messages: Arc<dyn messages::domain::api::MessageServiceApi>,
) -> ToolChannelToolContext {
    let access = entity_access::domain::service::EntityAccessServiceImpl::new(
        entity_access::outbound::PgAccessRepository::new(pool.clone()),
    );
    ChannelToolContext::new(
        messages,
        ChannelServiceImpl::with_dependencies(
            PgChannelsRepo::new(pool.clone()),
            dispatcher,
            PgChannelReferenceSharePermissions::new(pool, Arc::new(access.clone())),
        ),
        access,
    )
}

/// Type alias for the calendar occurrence read service used by AI tools.
pub type ToolCalendarReadService = calendar_events::domain::service::CalendarService<
    calendar_events::outbound::pg::PgCalendarRepository,
>;

/// Type alias for the calendar mutation client used by AI tools. Mutations
/// call the calendar service — the calendar write authority holding the Google
/// client, token minting, and request gate — with internal auth on behalf
/// of the requesting user, so tool-driven edits behave identically to
/// UI-driven ones.
pub type ToolCalendarMutationService =
    calendar_events::outbound::calendar_service_mutations::CalendarServiceMutations;

/// Type alias for the meeting-link provider used by AI tools. Macro calls
/// attached to events are minted through the same call service the call
/// tools run on, owned by the requesting user.
pub type ToolCalendarMeetingLinks =
    calendar_events::outbound::call_meeting_links::CallServiceMeetingLinks<ToolCallService>;

/// Type alias for the calendar AI tool context.
pub type ToolCalendarToolContext = CalendarToolContext<
    ToolCalendarMutationService,
    ToolCalendarReadService,
    ToolCalendarMeetingLinks,
>;

/// Source-scoped team calendar domain service for read-only AI availability.
pub type ToolTeamCalendarService = calendar_events::domain::team::CalendarTeamServiceImpl<
    calendar_events::outbound::pg_team::PgCalendarTeamRepository,
>;

/// Team availability tool dependencies, separate from provider mutation access.
pub type ToolTeamCalendarToolContext = TeamCalendarToolContext<ToolTeamCalendarService>;

/// Construct the authorized availability service at the AI composition root.
pub fn build_team_calendar_tool_context(
    pool: sqlx::PgPool,
    enabled: bool,
) -> ToolTeamCalendarToolContext {
    TeamCalendarToolContext {
        service: Arc::new(calendar_events::domain::team::CalendarTeamServiceImpl::new(
            calendar_events::outbound::pg_team::PgCalendarTeamRepository::new(pool),
            enabled,
        )),
    }
}

/// Build the calendar AI tool context: reads query the local occurrence
/// projections from `pool`; mutations call the calendar service at
/// `calendar_service_url` with the shared internal API key; Macro calls
/// attached to new events are minted through `call_service` and linked on
/// `app_url`, the browser origin users open meetings on.
/// `shared_event_copies` lets the agent add copies of channel-shared events.
pub fn build_calendar_tool_context(
    pool: sqlx::PgPool,
    calendar_service_url: macro_service_urls::CalendarServiceUrl,
    internal_api_key: String,
    call_service: Arc<ToolCallService>,
    app_url: macro_service_urls::AppServiceUrl,
    shared_event_copies: bool,
) -> ToolCalendarToolContext {
    CalendarToolContext::new(
        Arc::new(
            calendar_events::outbound::calendar_service_mutations::CalendarServiceMutations::new(
                calendar_service_url.to_string(),
                internal_api_key,
            ),
        ),
        Arc::new(calendar_events::domain::service::CalendarService::new(
            calendar_events::outbound::pg::PgCalendarRepository::new(pool),
        )),
        Arc::new(
            calendar_events::outbound::call_meeting_links::CallServiceMeetingLinks::new(
                call_service,
                app_url.as_str(),
            ),
        ),
    )
    .with_shared_event_copies(shared_event_copies)
}

/// Settings-only scheduling service; no provider/calendar writes are exposed here.
pub type ToolBookingLinkService = calendar_scheduling::domain::service::Service<
    calendar_scheduling::outbound::postgres::PostgresRepository,
    (),
    calendar_scheduling::outbound::macro_services::MacroDirectory<ToolTeamService>,
>;
/// Booking-link tool dependencies.
pub type ToolBookingLinkToolContext =
    calendar_scheduling::inbound::toolset::BookingLinkToolContext<ToolBookingLinkService>;
/// Construct scheduling adapters at the AI composition root.
pub fn build_booking_link_tool_context(
    pool: sqlx::PgPool,
    environment: macro_env::Environment,
) -> ToolBookingLinkToolContext {
    calendar_scheduling::inbound::toolset::BookingLinkToolContext {
        service: Arc::new(calendar_scheduling::domain::service::Service::new(
            calendar_scheduling::outbound::postgres::PostgresRepository::new(pool.clone()),
            (),
            calendar_scheduling::outbound::macro_services::MacroDirectory(TeamRepositoryImpl::new(
                pool,
            )),
        )),
        public_origin: match environment {
            macro_env::Environment::Production => "https://macro.com",
            macro_env::Environment::Develop => "https://dev.macro.com",
            macro_env::Environment::Local => "",
        }
        .into(),
    }
}

/// Booking administration is executed by the calendar service, including provider recovery.
pub type ToolBookingManagementToolContext =
    calendar_scheduling::inbound::toolset::BookingManagementToolContext<
        calendar_scheduling::outbound::administration_client::SchedulingAdministrationClient,
    >;
/// Construct the authenticated scheduling client at the host composition root.
pub fn build_booking_management_tool_context(
    calendar_url: macro_service_urls::CalendarServiceUrl,
    internal_api_key: String,
    environment: macro_env::Environment,
) -> ToolBookingManagementToolContext {
    calendar_scheduling::inbound::toolset::BookingManagementToolContext {
        service: Arc::new(calendar_scheduling::outbound::administration_client::SchedulingAdministrationClient::new(calendar_url.to_string(), internal_api_key)),
        public_origin: match environment {
            macro_env::Environment::Production => "https://macro.com",
            macro_env::Environment::Develop => "https://dev.macro.com",
            macro_env::Environment::Local => "",
        }.into(),
    }
}

/// Type alias for the CRM AI tool context.
pub type ToolCrmToolContext =
    CrmToolContext<ToolCrmService, ToolEntityAccessService, ToolPropertiesService>;

/// Build the CRM AI tool context from a Postgres pool.
pub fn build_crm_tool_context(pool: sqlx::PgPool) -> ToolCrmToolContext {
    let entity_access_service = Arc::new(
        entity_access::domain::service::EntityAccessServiceImpl::new(
            entity_access::outbound::PgAccessRepository::new(pool.clone()),
        ),
    );
    // This CRM-only context does not assign tasks. Task writes use the host's
    // shared properties context, which carries its lifecycle event broker.
    let properties = build_properties_service(pool.clone(), entity_access_service.clone());
    CrmToolContext {
        service: Arc::new(crm::domain::service::CrmServiceImpl::new(
            crm::outbound::companies_repo::CompaniesRepositoryImpl::new(pool.clone()),
            crm::outbound::no_op_resolver::NoOpCompanyMetadataResolver,
        )),
        entity_access_service,
        properties,
    }
}

/// CRM pipelines over the databases service and access the database tools
/// use, so a pipeline write reaches open clients the same way.
pub type ToolPipelineService = crm::domain::pipelines::PipelineServiceImpl<
    crm::outbound::pipelines::PgPipelineRepo<
        databases::outbound::pg_cell_store::PgCellStore<properties::PropertiesPgRepo>,
    >,
    ToolDatabasesService,
    ToolEntityAccessService,
    crm::outbound::stage_definitions::PropertiesStageDefinitionStore<ToolPropertiesService>,
>;

/// Pipeline workflows: entries by record and fields by name, for agents.
pub type ToolPipelineWorkflows = crm::domain::pipeline_workflows::PipelineWorkflowServiceImpl<
    ToolPipelineService,
    ToolCrmService,
    ToolEntityAccessService,
>;

/// Type alias for the CRM pipeline AI tool context.
pub type ToolPipelineToolContext =
    crm::inbound::toolset::pipelines::PipelineToolContext<ToolPipelineWorkflows>;

/// Build the pipeline tools over the database tools' service and access and
/// the CRM tools' records and stage template.
pub fn build_pipeline_tool_context(
    pool: sqlx::PgPool,
    databases: &ToolDatabasesToolContext,
    crm: &ToolCrmToolContext,
) -> ToolPipelineToolContext {
    let pipelines = crm::domain::pipelines::PipelineServiceImpl::new(
        crm::outbound::pipelines::PgPipelineRepo::new(
            pool.clone(),
            databases::outbound::pg_cell_store::PgCellStore::new(
                pool.clone(),
                properties::PropertiesPgRepo::new(pool),
            ),
        ),
        databases.service.clone(),
        databases.entity_access_service.clone(),
        crm::outbound::stage_definitions::PropertiesStageDefinitionStore::new(
            crm.properties.clone(),
        ),
    );
    crm::inbound::toolset::pipelines::PipelineToolContext {
        service: Arc::new(
            crm::domain::pipeline_workflows::PipelineWorkflowServiceImpl::new(
                Arc::new(pipelines),
                crm.service.clone(),
                databases.entity_access_service.clone(),
            ),
        ),
        actor: databases.actor,
    }
}

/// CRM CSV imports and exports over the pipeline workflows, the CRM's
/// records and Macro documents.
pub type ToolCrmTransferService = crm::domain::crm_transfer::CrmTransferServiceImpl<
    ToolPipelineWorkflows,
    crm::domain::crm_transfer::CrmTransferRecords<ToolCrmService, ToolEntityAccessService>,
    crate::crm_csv_files::DocumentCsvFiles<ToolDocumentService, ToolEntityAccessService>,
>;

/// Type alias for the CRM CSV AI tool context.
pub type ToolCrmTransferToolContext =
    crm::inbound::toolset::transfer::CrmTransferToolContext<ToolCrmTransferService>;

/// Build the CRM CSV tools over the pipeline tools' workflows, the CRM
/// tools' records, and the document tools' files.
pub fn build_crm_transfer_tool_context(
    pipelines: &ToolPipelineToolContext,
    crm: &ToolCrmToolContext,
    documents: &ToolDocumentToolContext,
) -> ToolCrmTransferToolContext {
    crm::inbound::toolset::transfer::CrmTransferToolContext {
        service: Arc::new(crm::domain::crm_transfer::CrmTransferServiceImpl::new(
            pipelines.service.clone(),
            crm::domain::crm_transfer::CrmTransferRecords::new(
                crm.service.clone(),
                crm.entity_access_service.clone(),
            ),
            crate::crm_csv_files::DocumentCsvFiles::new(
                documents.service.clone(),
                documents.creator.clone(),
                documents.entity_access_service.clone(),
            ),
        )),
        actor: pipelines.actor,
    }
}

/// Type alias for the skill service implementation used by AI tools.
pub type ToolSkillService = skills::domain::service::SkillServiceImpl<
    skills::outbound::search_service_searcher::SearchServiceSkillSearcher,
    skills::outbound::soup_skill_lister::SoupSkillLister<ToolSoupService>,
    skills::outbound::document_skill_reader::DocumentSkillReader<
        ToolDocumentService,
        ToolEntityAccessService,
    >,
>;

/// Type alias for the skill AI tool context.
pub type ToolSkillToolContext = SkillToolContext<ToolSkillService>;

/// Build the skill AI tool context from a search service client (skill
/// search), soup service (listing), and document services (reading).
pub fn build_skill_tool_context(
    search_service_client: Arc<search_service_client::SearchServiceClient>,
    soup_service: Arc<ToolSoupService>,
    documents: &ToolDocumentToolContext,
) -> ToolSkillToolContext {
    SkillToolContext::new(skills::domain::service::SkillServiceImpl::new(
        skills::outbound::search_service_searcher::SearchServiceSkillSearcher::new(
            search_service_client,
        ),
        skills::outbound::soup_skill_lister::SoupSkillLister::new(soup_service),
        skills::outbound::document_skill_reader::DocumentSkillReader::new(
            documents.service.clone(),
            documents.entity_access_service.clone(),
            documents.lexical_client.clone(),
        ),
    ))
}

/// Type alias for the team member listing service used by AI tools.
pub type ToolTeamService = TeamRepositoryImpl;

/// Type alias for the team AI tool context.
pub type ToolTeamToolContext = TeamToolContext<ToolTeamService, ToolEntityAccessService>;

/// Build the team repository used for roster lookups (e.g. resolving
/// imported items' emails to teammates).
pub fn build_team_repository(pool: sqlx::PgPool) -> Arc<ToolTeamService> {
    Arc::new(TeamRepositoryImpl::new(pool))
}

/// Build the import ledger for hosts that run Notion workspace imports: it
/// tells the agent session presenting a plan's review when the plan is ready
/// and when its write ends.
pub fn build_import_repo(pool: sqlx::PgPool) -> import::outbound::pg_import_repo::PgImportRepo {
    import::outbound::pg_import_repo::PgImportRepo::new(pool.clone()).with_session_notifications(
        Arc::new(agent_session::outbound::notifications::PgNotificationStore(
            pool,
        )),
    )
}

/// Build the team AI tool context from a Postgres pool.
pub fn build_team_tool_context(pool: sqlx::PgPool) -> ToolTeamToolContext {
    TeamToolContext::new(
        TeamRepositoryImpl::new(pool.clone()),
        entity_access::domain::service::EntityAccessServiceImpl::new(
            entity_access::outbound::PgAccessRepository::new(pool),
        ),
    )
}

/// No-op task properties service for tests and contexts that do not create tasks.
#[derive(Clone)]
pub struct NoOpTaskProperties;

impl TaskPropertiesPort for NoOpTaskProperties {
    async fn update_task_status(
        &self,
        _access: &EntityAccessReceipt<EditAccessLevel>,
        _credited_user: Option<&MacroUserIdStr<'static>>,
        _source: Option<&PropertyChangeSource>,
        _status: &str,
    ) -> anyhow::Result<()> {
        Ok(())
    }
    async fn attach_task_properties(&self, _entity_ids: Vec<String>) -> anyhow::Result<()> {
        Ok(())
    }
    async fn set_entity_property(
        &self,
        _principal: &model_owner::CreationPrincipal,
        _entity_id: &str,
        _property_definition_id: uuid::Uuid,
        _value: Option<models_properties::api::requests::SetPropertyValue>,
    ) -> anyhow::Result<()> {
        Ok(())
    }
    async fn copy_task_properties(
        &self,
        _from_task_id: &str,
        _to_task_id: &str,
    ) -> anyhow::Result<()> {
        Ok(())
    }
}

/// Adapter implementing [`TaskPropertiesPort`] with the real properties services.
#[derive(Clone)]
pub struct TaskPropertiesAdapter {
    /// System properties service used to attach/copy task property rows.
    pub system_properties: Arc<ToolSystemPropertiesService>,
    /// Properties service used to assign concrete task property values.
    pub properties: Arc<ToolPropertiesService>,
    /// Canonical entity access service used to authorize task property writes.
    pub entity_access_service: Arc<ToolEntityAccessService>,
}

impl TaskPropertiesPort for TaskPropertiesAdapter {
    async fn attach_task_properties(&self, entity_ids: Vec<String>) -> anyhow::Result<()> {
        self.system_properties
            .attach_task_properties(entity_ids)
            .await
            .map_err(Into::into)
    }

    #[tracing::instrument(
        skip_all,
        fields(
            task_id = %access.entity().entity_id,
            status,
            unchanged = tracing::field::Empty,
            credited = tracing::field::Empty
        ),
        err
    )]
    async fn update_task_status(
        &self,
        access: &EntityAccessReceipt<EditAccessLevel>,
        credited_user: Option<&MacroUserIdStr<'static>>,
        source: Option<&PropertyChangeSource>,
        status: &str,
    ) -> anyhow::Result<()> {
        use properties::PropertiesService as _;

        let status_option = StatusOption::try_from(status).map_err(|e| anyhow::anyhow!(e))?;
        let current = self
            .properties
            .get_system_property_value(
                &access.clone().try_into_requirement::<ViewAccessLevel>()?,
                system_properties::SystemPropertyKey::Status,
            )
            .await?;
        // PR edits and comments re-send In Review; an unchanged status publishes nothing.
        if current == Some(PropertyValue::SelectOption(vec![status_option.uuid()])) {
            tracing::Span::current().record("unchanged", true);
            return Ok(());
        }
        let access =
            credited_task_edit_receipt(self.entity_access_service.as_ref(), access, credited_user)
                .await;
        tracing::Span::current().record(
            "credited",
            matches!(access.auth(), EntityAccessAuth::Authenticated(_)),
        );
        self.properties
            .set_entity_property_with_source(
                &access,
                system_properties::SystemPropertyKey::STATUS_UUID,
                Some(
                    models_properties::api::requests::SetPropertyValue::SelectOption {
                        option_id: status_option.uuid(),
                    },
                ),
                source.cloned(),
            )
            .await
            .map(|_| ())
            .map_err(Into::into)
    }

    async fn set_entity_property(
        &self,
        principal: &model_owner::CreationPrincipal,
        entity_id: &str,
        property_definition_id: uuid::Uuid,
        value: Option<models_properties::api::requests::SetPropertyValue>,
    ) -> anyhow::Result<()> {
        use properties::PropertiesService as _;

        let entity_access_receipt =
            task_property_edit_receipt(self.entity_access_service.as_ref(), principal, entity_id)
                .await?;
        self.properties
            .set_entity_property(&entity_access_receipt, property_definition_id, value)
            .await
            .map(|_| ())
            .map_err(Into::into)
    }

    async fn copy_task_properties(
        &self,
        from_task_id: &str,
        to_task_id: &str,
    ) -> anyhow::Result<()> {
        self.system_properties
            .copy_task_properties(from_task_id, to_task_id)
            .await
            .map_err(Into::into)
    }
}

/// No-op connection service
#[derive(Clone)]
pub struct NoOpConnectionService;

impl ConnectionService for NoOpConnectionService {
    async fn send_invalidation_event<'a, T: std::fmt::Debug + serde::Serialize + Send>(
        &self,
        _invalidation_event: connection::domain::models::InvalidationEvent<'a, T>,
    ) -> Result<(), connection::domain::models::ConnectionError> {
        Ok(())
    }

    async fn send_channel_message<'a>(
        &self,
        _users: &[MacroUserIdStr<'a>],
        _message_type: &str,
        _message: serde_json::Value,
    ) -> Result<(), connection::domain::models::ConnectionError> {
        Ok(())
    }
}

/// No-op RTC client used by the call tool context — the AI read-only tools
/// never touch RTC, so token/egress methods bail rather than silently succeed.
#[derive(Clone)]
pub struct NoOpCallRtcClient;

impl CallRtcClient for NoOpCallRtcClient {
    async fn prepare_room(&self, room_name: &str) -> anyhow::Result<()> {
        self.create_room(room_name).await
    }
    async fn generate_guest_token(
        &self,
        _room_name: &str,
        _guest_id: call::domain::meetings::GuestId,
        _display_name: &str,
    ) -> anyhow::Result<String> {
        anyhow::bail!("call RTC client not configured")
    }

    async fn remove_guest(
        &self,
        _room_name: &str,
        _guest_id: call::domain::meetings::GuestId,
    ) -> anyhow::Result<()> {
        anyhow::bail!("call RTC client not configured")
    }

    async fn create_room(&self, _room_name: &str) -> anyhow::Result<()> {
        Ok(())
    }

    async fn delete_room(&self, _room_name: &str) -> anyhow::Result<()> {
        Ok(())
    }

    async fn list_rooms(&self) -> anyhow::Result<Vec<call::domain::models::RtcRoom>> {
        Ok(Vec::new())
    }

    async fn generate_token<'a>(
        &self,
        _room_name: &str,
        _participant_identity: MacroUserIdStr<'a>,
    ) -> anyhow::Result<String> {
        anyhow::bail!("call RTC client not configured")
    }

    async fn list_live_participants(
        &self,
        _room_name: &str,
    ) -> anyhow::Result<Option<Vec<call::domain::models::LiveCallParticipant>>> {
        anyhow::bail!("call RTC client not configured")
    }

    async fn generate_bot_token(
        &self,
        _room_name: &str,
        _bot_id: bot_id::BotId,
        _name: Option<String>,
    ) -> anyhow::Result<String> {
        anyhow::bail!("call RTC client not configured")
    }

    async fn remove_bot(&self, _room_name: &str, _bot_id: bot_id::BotId) -> anyhow::Result<()> {
        anyhow::bail!("call RTC client not configured")
    }

    async fn generate_named_token<'a>(
        &self,
        _room_name: &str,
        _participant_identity: MacroUserIdStr<'a>,
        _name: &str,
    ) -> anyhow::Result<String> {
        anyhow::bail!("call RTC client not configured")
    }

    async fn generate_program_token<'a>(
        &self,
        _room_name: &str,
        _participant_identity: MacroUserIdStr<'a>,
        _program: &str,
        _name: Option<String>,
    ) -> anyhow::Result<String> {
        anyhow::bail!("call RTC client not configured")
    }

    async fn build_voip_push_payloads<'a>(
        &self,
        _request: call::domain::models::VoipPushPayloadRequest<'a>,
    ) -> Vec<(
        MacroUserIdStr<'static>,
        notification::domain::models::apple::VoipPushPayload,
    )> {
        Vec::new()
    }

    async fn remove_participant<'a>(
        &self,
        _room_name: &str,
        _participant_identity: MacroUserIdStr<'a>,
    ) -> anyhow::Result<()> {
        Ok(())
    }

    async fn list_meeting_participants(
        &self,
        _room_name: &str,
    ) -> anyhow::Result<Option<Vec<call::domain::meetings::MeetingRtcParticipant>>> {
        Ok(None)
    }

    async fn list_participant_identities(
        &self,
        _room_name: &str,
    ) -> anyhow::Result<Option<Vec<String>>> {
        Ok(Some(Vec::new()))
    }

    async fn start_room_composite_egress(
        &self,
        _room_name: &str,
        _s3_config: &EgressS3Config,
    ) -> anyhow::Result<String> {
        anyhow::bail!("call RTC client not configured")
    }

    async fn stop_egress(&self, _egress_id: &str) -> anyhow::Result<()> {
        Ok(())
    }

    fn receive_webhook(
        &self,
        _body: &str,
        _auth_token: &str,
    ) -> Result<CallWebhookEvent, CallError> {
        Err(CallError::Auth)
    }

    fn verify_access_token(
        &self,
        _token: &str,
    ) -> anyhow::Result<call::domain::models::VerifiedRingToken> {
        anyhow::bail!("call RTC client not configured")
    }

    async fn dispatch_transcription_agent(&self, _room_name: &str) -> anyhow::Result<()> {
        Ok(())
    }
}

/// No-op notification ingress used by the call tool context — reads never
/// push notifications.
#[derive(Clone)]
pub struct NoOpNotificationIngress;

impl notification::domain::service::NotificationIngress for NoOpNotificationIngress {
    async fn send_notification<
        'a,
        T: notification::domain::models::Notification + Clone + 'static,
        U: serde::Serialize + Send + Sync + 'static,
    >(
        &'a self,
        _req: notification::domain::models::SendNotificationRequest<'a, T, U>,
    ) -> Result<
        Option<notification::domain::models::NotificationResult<'a>>,
        rootcause::Report<notification::domain::service::SendNotificationError>,
    > {
        Ok(None)
    }
}

/// No-op SNS endpoint manager used by AI notification tools.
///
/// The exposed AI tools list and update notifications. Updating notifications
/// can clear existing push notifications via the notification delivery queue,
/// but it does not create or mutate SNS platform endpoints. Device
/// registration APIs are not exposed through the AI toolset, so SNS endpoint
/// operations intentionally fail if called accidentally.
#[derive(Clone)]
pub struct NoOpSnsEndpointManager;

impl notification::domain::ports::SnsEndpointManager for NoOpSnsEndpointManager {
    async fn create_platform_endpoint(
        &self,
        _platform_arn: &str,
        _token: &str,
    ) -> Result<String, rootcause::Report> {
        rootcause::bail!("SNS endpoint manager not configured for AI tools")
    }

    async fn get_endpoint_attributes(
        &self,
        _endpoint_arn: &str,
    ) -> Result<std::collections::HashMap<String, String>, rootcause::Report> {
        rootcause::bail!("SNS endpoint manager not configured for AI tools")
    }

    async fn set_endpoint_attributes(
        &self,
        _endpoint_arn: &str,
        _attributes: std::collections::HashMap<String, String>,
    ) -> Result<(), rootcause::Report> {
        rootcause::bail!("SNS endpoint manager not configured for AI tools")
    }

    async fn delete_endpoint(&self, _endpoint_arn: &str) -> Result<(), rootcause::Report> {
        rootcause::bail!("SNS endpoint manager not configured for AI tools")
    }
}

/// Notification delivery queue used by AI tools.
///
/// Most production contexts provide the real notification SQS queue so marking
/// notifications seen/done can clear mobile pushes. Some auxiliary binaries
/// that expose the shared tool context do not have a notification queue
/// configured; those can use `NoOp`, which still updates database state but
/// skips push-clearing delivery messages.
#[derive(Clone)]
pub enum ToolNotificationQueue {
    Sqs(notification::outbound::queue::SqsQueue),
    NoOp,
}

impl notification::domain::ports::NotificationQueue for ToolNotificationQueue {
    async fn publish<'a, T: serde::Serialize + Send + Sync, U: serde::Serialize + Send + Sync>(
        &self,
        messages: Vec<notification::domain::models::queue_message::QueueMessage<'a, T, U>>,
    ) -> Result<(), rootcause::Report> {
        match self {
            ToolNotificationQueue::Sqs(queue) => {
                notification::domain::ports::NotificationQueue::publish(queue, messages).await
            }
            ToolNotificationQueue::NoOp => Ok(()),
        }
    }

    async fn receive_messages(
        &self,
    ) -> Result<Vec<notification::domain::models::queue_message::RawQueueMessage>, rootcause::Report>
    {
        match self {
            ToolNotificationQueue::Sqs(queue) => {
                notification::domain::ports::NotificationQueue::receive_messages(queue).await
            }
            ToolNotificationQueue::NoOp => Ok(Vec::new()),
        }
    }

    async fn delete_message(&self, receipt_handle: &str) -> Result<(), rootcause::Report> {
        match self {
            ToolNotificationQueue::Sqs(queue) => {
                notification::domain::ports::NotificationQueue::delete_message(
                    queue,
                    receipt_handle,
                )
                .await
            }
            ToolNotificationQueue::NoOp => Ok(()),
        }
    }
}

/// Type alias for the entity access management service implementation used by AI tools
pub type ToolEntityAccessManagementService =
    entity_access_management::domain::service::EntityAccessManagementServiceImpl<
        entity_access_management::outbound::PgRepository,
    >;

/// Type alias for the document service implementation used by AI tools
pub type ToolDocumentService = documents::domain::service::DocumentServiceImpl<
    documents::outbound::pg_document_repo::PgDocumentRepo<PgBotsRepo>,
    documents::outbound::s3_upload_url::S3UploadUrlAdapter,
    TaskPropertiesAdapter,
    NoOpConnectionService,
    ToolEntityAccessManagementService,
    ToolForeignEntityService,
    ToolEventBroker,
    sync_service_client::SyncServiceClient,
>;

/// Type alias for the entity access service implementation
pub type ToolEntityAccessService = entity_access::domain::service::EntityAccessServiceImpl<
    entity_access::outbound::PgAccessRepository,
>;

/// Type alias for the document tool context
pub type ToolDocumentToolContext = DocumentToolContext<
    ToolDocumentService,
    ToolEntityAccessService,
    documents::outbound::editing_worker_client::ReqwestEditingWorkerClient,
>;

/// Type alias for the discussion tool context.
pub type ToolMessageToolContext =
    messages::inbound::toolset::MessageToolContext<ToolEntityAccessService>;

/// Build the discussion tool context over the message service and access
/// checks the document tools comment through, so a host wires one message
/// service for every Discussion.
pub fn build_message_tool_context(documents: &ToolDocumentToolContext) -> ToolMessageToolContext {
    messages::inbound::toolset::MessageToolContext::new(
        documents.messages.clone(),
        documents.entity_access_service.clone(),
    )
    .with_actor(documents.actor)
}

/// Type alias for the foreign entity service implementation used by AI tools.
pub type ToolForeignEntityService = ForeignEntityServiceImpl<PgForeignEntityRepo>;

/// Type alias for the GitHub pull request service used by AI tools.
pub type ToolGithubPullRequestService =
    GithubPullRequestServiceImpl<ToolForeignEntityService, PgGithubPullRequestRepo>;

/// Type alias for the soup service implementation
pub type ToolSoupService = SoupImpl<
    soup::outbound::pg_soup_repo::PgSoupRepo,
    ToolFrecencyService,
    email::domain::ports::ReadonlyEmailPreviewAdapter<ToolEmailService>,
    ToolCommsService,
    ToolCallRecordQueryService,
    crm::domain::service::NoOpCrmService,
    ToolGithubPullRequestService,
>;

/// No-op notification service for properties (tools don't send assignment notifications)
#[derive(Clone)]
pub struct NoOpNotificationService;

impl properties::NotificationService for NoOpNotificationService {
    type Err = anyhow::Error;

    async fn send_task_assigned<'a>(
        &self,
        _notification: properties::domain::model::TaskAssignedNotification<'a>,
    ) -> Result<(), Self::Err> {
        Ok(())
    }
}

/// Type alias for the system properties service implementation used by AI tools.
pub type ToolSystemPropertiesService = SystemPropertiesServiceImpl<PgSystemPropertiesRepository>;

/// Type alias for the properties service implementation used by AI tools
pub type ToolPropertiesService = properties::PropertiesServiceImpl<
    properties::PropertiesPgRepo,
    properties::PermissionServiceImpl<ToolEntityAccessService>,
    NoOpNotificationService,
    MaybeToolEventBroker,
>;

/// Imported-document property enrichment backed by the AI tool host's Properties service.
pub type ToolDocumentPropertiesApplicator =
    import::outbound::document_properties::DocumentPropertiesApplicator<ToolPropertiesService>;

/// Type alias for the properties tool context
pub type ToolPropertiesToolContext =
    PropertiesToolContext<ToolPropertiesService, ToolEntityAccessService>;

/// Build the properties service shared by the properties tools and task adapter.
pub fn build_properties_service(
    pool: sqlx::PgPool,
    entity_access_service: Arc<ToolEntityAccessService>,
) -> Arc<ToolPropertiesService> {
    properties_service_with_events(
        pool,
        entity_access_service,
        MaybeToolEventBroker::NoOp(Default::default()),
    )
}

/// Build canonical property tools with committed changes published to activity.
pub fn build_properties_service_with_broker(
    pool: sqlx::PgPool,
    entity_access_service: Arc<ToolEntityAccessService>,
    broker: ToolEventBroker,
) -> Arc<ToolPropertiesService> {
    properties_service_with_events(
        pool,
        entity_access_service,
        MaybeToolEventBroker::Real(broker),
    )
}

fn properties_service_with_events(
    pool: sqlx::PgPool,
    entity_access_service: Arc<ToolEntityAccessService>,
    broker: MaybeToolEventBroker,
) -> Arc<ToolPropertiesService> {
    Arc::new(
        properties::PropertiesServiceImpl::new(
            properties::PropertiesPgRepo::new(pool.clone()),
            Some(properties::PermissionServiceImpl::new(
                pool.clone(),
                entity_access_service,
            )),
            Some(NoOpNotificationService),
        )
        .with_initiative_assignees(Arc::new(
            initiative::domain::assignees::InitiativeAssignees::new(
                initiative::outbound::PgInitiativeRepo::new(pool),
            ),
        ))
        .with_event_broker(broker),
    )
}

/// Build the real task properties adapter used by document creation tools.
pub fn build_task_properties_adapter(
    pool: sqlx::PgPool,
    properties: Arc<ToolPropertiesService>,
    entity_access_service: Arc<ToolEntityAccessService>,
) -> TaskPropertiesAdapter {
    TaskPropertiesAdapter {
        system_properties: Arc::new(SystemPropertiesServiceImpl::new(
            PgSystemPropertiesRepository::new(pool),
        )),
        properties,
        entity_access_service,
    }
}

/// Build a properties tool context from shared domain and access services.
pub fn build_properties_tool_context(
    properties: Arc<ToolPropertiesService>,
    entity_access_service: Arc<ToolEntityAccessService>,
) -> ToolPropertiesToolContext {
    PropertiesToolContext {
        service: properties,
        entity_access_service,
        actor: bot_id::MACRO_AI_BOT_ID,
    }
}

/// Type alias for the email tool context
pub type ToolEmailToolContext = EmailToolContext<ToolUserEmailService>;

/// Type alias for the call service implementation used by AI tools.
/// Wired with NoOp RTC/connection/notification clients and no recording
/// storage — the AI tools are read-only, so those capabilities are never
/// exercised.
pub type ToolCallService = CallServiceImpl<
    PgCallRepo,
    NoOpCallRtcClient,
    NoOpConnectionService,
    ToolEntityAccessService,
    NoOpNotificationIngress,
    Option<S3RecordingStorage>,
>;

/// Type alias for the read-only call record query service.
pub type ToolCallRecordQueryService = CallRecordQueryServiceImpl<PgCallRepo>;

/// Type alias for the call tool context
pub type ToolCallToolContext = CallToolContext<ToolCallService, ToolEntityAccessService>;

/// Type alias for the notification reader service used by AI tools.
pub type ToolNotificationService = notification::domain::service::NotificationReaderService<
    notification::outbound::repository::DbNotificationRepository<sqlx::PgPool>,
    ToolNotificationQueue,
    NoOpSnsEndpointManager,
>;

/// Type alias for the notification tool context.
pub type ToolNotificationToolContext = NotificationToolContext<ToolNotificationService>;

/// Type alias for the user's per-item notification mute and snooze tool context.
pub type ToolItemNotificationPreferenceToolContext =
    notification::inbound::ai_tool::ItemNotificationPreferenceToolContext<
        notification::outbound::item_preferences::PgItemNotificationPreferenceRepository,
    >;

/// Build the per-item notification preference tool context.
pub fn build_item_notification_preference_tool_context(
    pool: sqlx::PgPool,
) -> ToolItemNotificationPreferenceToolContext {
    notification::inbound::ai_tool::ItemNotificationPreferenceToolContext::new(
        notification::outbound::item_preferences::PgItemNotificationPreferenceRepository(pool),
    )
}

/// Table-changed fan-out for AI tool hosts, the databases crate's publisher.
pub use databases::outbound::gateway_event_publisher::MaybeGatewayTableEventPublisher as ToolTableEventPublisher;

/// Type alias for the databases service implementation used by AI tools:
/// the same port implementations the HTTP surface runs on.
pub type ToolDatabasesService = databases::wiring::PgDatabasesService<
    ToolTableEventPublisher,
    MaybeToolEventBroker,
    ToolEntityAccessService,
>;

/// Type alias for the databases tool context.
pub type ToolDatabasesToolContext =
    DatabasesToolContext<ToolDatabasesService, ToolEntityAccessService>;

/// Build the databases tool context: `events` reaches open clients, `broker`
/// the acting user's activity feed.
pub fn build_databases_tool_context(
    pool: sqlx::PgPool,
    entity_access_service: Arc<ToolEntityAccessService>,
    events: ToolTableEventPublisher,
    broker: MaybeToolEventBroker,
) -> ToolDatabasesToolContext {
    DatabasesToolContext::new(
        databases::wiring::build_service(pool, entity_access_service.clone(), events, broker),
        entity_access_service,
    )
}

/// The contacts the SQL tools read `macro.people` from. Reads only, so
/// nothing is ever invalidated through a notifier.
pub type ToolContactsService =
    ContactsDomainService<DbContactsRepository, Option<ConnectionGatewayNotifier>>;

/// Type alias for the SQL tools' context: SQL over the same databases
/// service the schema tools use, reading rows through Soup.
pub type ToolDatabasesSqlToolContext = DatabasesSqlToolContext<
    ToolDatabasesService,
    ToolEntityAccessService,
    ToolSoupService,
    ToolContactsService,
>;

/// The SQL tools' context with access capped at view, for document answers:
/// the same QueryDatabase, whose writes the access check refuses.
pub type ToolViewOnlyDatabasesSqlToolContext = DatabasesSqlToolContext<
    ToolDatabasesService,
    ViewOnlyAccess<ToolEntityAccessService>,
    ToolSoupService,
    ToolContactsService,
>;

/// Build the SQL tools' context over the schema tools' databases service
/// and entity access, and the host's Soup.
pub fn build_databases_sql_tool_context(
    databases: &ToolDatabasesToolContext,
    soup_service: Arc<ToolSoupService>,
    pool: sqlx::PgPool,
) -> ToolDatabasesSqlToolContext {
    DatabasesSqlToolContext::new(DatabasesSql::new(
        databases.service.clone(),
        databases.entity_access_service.clone(),
        soup_service,
        Arc::new(ContactsDomainService {
            repository: DbContactsRepository::new(pool),
            notifier: None,
        }),
    ))
}

/// Type alias for the chat service implementation used by AI tools.
/// Uses an empty toolset — the read-only tool never invokes tool execution.
pub type ToolChatService =
    ChatServiceImpl<PgChatRepo<PgBotsRepo>, (), ToolEntityAccessManagementService>;

/// Type alias for the project service implementation used by AI tools.
/// Upload, content-hash, and search-cleanup ports are unwired — project
/// tools only create, read, and move projects, never run upload or purge
/// flows.
pub type ToolProjectService = projects::domain::service::ProjectServiceImpl<
    projects::outbound::PgProjectRepo<PgBotsRepo>,
    projects::domain::ports::UnavailableProjectUploadUrlPort,
    projects::domain::ports::UnavailableBulkUploadRequestPort,
    projects::domain::ports::UnavailableShaCounterPort,
    ToolEntityAccessManagementService,
    projects::domain::ports::UnavailableProjectSearchIndexer,
    ToolEventBroker,
>;

/// Type alias for the project tool context. Move dispatch uses the same
/// domain services the other tool contexts run on, so moves fire the same
/// events and side effects as the REST/GraphQL paths.
pub type ToolProjectToolContext = ProjectToolContext<
    ToolProjectService,
    ToolEntityAccessService,
    ToolDocumentService,
    ToolUserEmailService,
    ToolDatabasesService,
>;

/// Build the project tool context from shared domain and access services.
/// The move services must be the same instances the document, email and
/// databases tool contexts run on so mutations share their side-effect wiring.
pub fn build_project_tool_context(
    pool: sqlx::PgPool,
    macro_event_broker: ToolEventBroker,
    entity_access_service: Arc<ToolEntityAccessService>,
    document_service: Arc<ToolDocumentService>,
    email_service: Arc<ToolUserEmailService>,
    databases_service: Arc<ToolDatabasesService>,
) -> ToolProjectToolContext {
    let project_service = projects::domain::service::ProjectServiceImpl::new(
        projects::outbound::PgProjectRepo::new(
            pool.clone(),
            OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(pool.clone()))),
        ),
        projects::domain::ports::UnavailableProjectUploadUrlPort,
        projects::domain::ports::UnavailableBulkUploadRequestPort,
        projects::domain::ports::UnavailableShaCounterPort,
        entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
            entity_access_management::outbound::PgRepository::new(pool),
        ),
        projects::domain::ports::UnavailableProjectSearchIndexer,
        None,
        macro_event_broker,
    );
    ProjectToolContext::new(
        Arc::new(project_service),
        entity_access_service,
        document_service,
        email_service,
        databases_service,
    )
}

/// Type alias for the favorites service used by AI tools and soup's
/// favorites-only filter.
pub type ToolFavoritesService = favorites::domain::service::FavoritesServiceImpl<
    favorites::outbound::pg_favorites_repo::PgFavoritesRepo,
>;

/// Type alias for the favorites tool context.
pub type ToolFavoritesToolContext = favorites::inbound::toolset::FavoritesToolContext<
    favorites::domain::mutation_service::FavoritesMutationServiceImpl<
        ToolFavoritesService,
        ToolEntityAccessService,
    >,
>;

/// Build the favorites service shared by the favorites tools and soup.
pub fn build_favorites_service(pool: sqlx::PgPool) -> Arc<ToolFavoritesService> {
    Arc::new(favorites::domain::service::FavoritesServiceImpl::new(
        favorites::outbound::pg_favorites_repo::PgFavoritesRepo::new(pool),
    ))
}

/// Build the favorites tool context, authorizing favorites with the same
/// entity access service as the other tools.
pub fn build_favorites_tool_context(
    favorites: Arc<ToolFavoritesService>,
    entity_access_service: Arc<ToolEntityAccessService>,
) -> ToolFavoritesToolContext {
    favorites::inbound::toolset::FavoritesToolContext::new(Arc::new(
        favorites::domain::mutation_service::FavoritesMutationServiceImpl::new(
            favorites,
            entity_access_service,
        ),
    ))
}

/// Type alias for the chat tool context
pub type ToolChatToolContext = ChatToolContext<ToolChatService, ToolEntityAccessService>;

/// What an imported document holds.
pub(crate) enum ImportedContent {
    /// Macro markdown.
    Markdown(String),
    /// A Notion page, converted by lexical-service.
    Notion(documents::domain::notion_markdown::NotionMarkdown),
}

/// Creates the Macro entities the import pipeline's fixed mapping calls for
/// (linear → task, notion → md, slack → channel), reusing the same document
/// creator and channel service the other AI tools run on. Task system
/// properties (status, priority, due date, assignee) and channel teammate
/// invites are applied best-effort — an enrichment that fails never fails
/// the import itself.
#[derive(Clone)]
pub struct ToolEntityCreator {
    /// Backend-owned document creation use case (shared with document tools).
    pub document_creator:
        documents::inbound::toolset::DefaultDocumentToolCreator<ToolDocumentService>,
    /// Team lookup so imported tasks get the user's team task numbering.
    pub entity_access_service: Arc<ToolEntityAccessService>,
    /// Channel creation service.
    pub channel_service: Arc<ToolChannelMessagesService>,
    /// Task system-property writes (status / priority / due date / assignees).
    pub task_properties: TaskPropertiesAdapter,
    /// Notion document property and tag enrichment.
    pub document_properties: ToolDocumentPropertiesApplicator,
    /// Team roster lookups, to resolve source-tool emails to teammates.
    pub team_repository: Arc<ToolTeamService>,
    /// Project lifecycle for reviewed issue tracker imports.
    pub initiative_service: Arc<ToolInitiativeService>,
    /// Folder creation for workspace imports (shared with project tools).
    pub project_service: Arc<ToolProjectService>,
    /// Database creation and writes for workspace imports (shared with
    /// database tools).
    pub databases_service: Arc<ToolDatabasesService>,
    /// Team sharing of documents workspace imports write (shared with
    /// document tools).
    pub document_service: Arc<ToolDocumentService>,
}

impl ToolEntityCreator {
    pub(crate) fn creation_principal(
        user: &MacroUserIdStr<'static>,
    ) -> model_owner::CreationPrincipal {
        model_owner::CreationPrincipal::BotForUser {
            bot: bot_id::MACRO_AI_BOT_ID,
            user: user.clone(),
        }
    }

    /// Require `user` to hold edit access on `folder`, as the project and
    /// document tools do before creating inside one.
    pub(crate) async fn authorize_folder(
        &self,
        user: &MacroUserIdStr<'static>,
        folder: uuid::Uuid,
    ) -> anyhow::Result<()> {
        self.entity_access_service
            .generate_entity_access_receipt::<EditAccessLevel>(
                user,
                None,
                &folder.to_string(),
                model_entity::EntityType::Project,
            )
            .await
            .map_err(|error| anyhow::anyhow!("no edit access to folder {folder}: {error:?}"))?;
        Ok(())
    }

    #[allow(clippy::too_many_arguments)]
    async fn create_doc(
        &self,
        user: &MacroUserIdStr<'static>,
        id: Option<uuid::Uuid>,
        name: &str,
        content: ImportedContent,
        subtype: documents::domain::create::MarkdownSubtype,
        folder: Option<uuid::Uuid>,
        dates: Option<import::domain::ports::SourceDates>,
    ) -> anyhow::Result<String> {
        use std::str::FromStr as _;
        let mut metadata = documents::domain::create::NewDocumentMetadata::builder(name);
        if let Some(id) = id {
            metadata = metadata.id(id);
        }
        if let Some(dates) = dates {
            metadata = metadata
                .created_at(dates.created)
                .updated_at(dates.last_edited);
        }
        if let Some(folder) = folder {
            self.authorize_folder(user, folder).await?;
            metadata = metadata.project_id(folder);
        }
        let ai_for_user = Self::creation_principal(user);
        let created = match content {
            ImportedContent::Markdown(markdown) => {
                let document =
                    documents::domain::create::NewPlainTextDocument::builder(metadata.build())
                        .file_type(
                            model::document::FileType::from_str("md")
                                .expect("md is a valid file type"),
                        )
                        .text(markdown)
                        .markdown_subtype(subtype)
                        .build()?;
                self.document_creator
                    .create_plain_text(&ai_for_user, document)
                    .await?
            }
            ImportedContent::Notion(notion) => {
                self.document_creator
                    .create_notion_markdown(
                        &ai_for_user,
                        documents::domain::create::NewNotionDocument {
                            metadata: metadata.build(),
                            notion,
                            subtype,
                        },
                    )
                    .await?
            }
        };
        Ok(created
            .into_response()
            .document_response
            .document_metadata
            .metadata
            .document_id
            .to_string())
    }

    /// The user's team id (when they have one) and its member ids.
    pub(crate) async fn team_roster(
        &self,
        user: &MacroUserIdStr<'static>,
    ) -> (Option<uuid::Uuid>, Vec<MacroUserIdStr<'static>>) {
        use teams::domain::team_repo::TeamRepository as _;
        let team_id = match self.entity_access_service.get_user_team(user).await {
            Ok(team) => team.map(|team| team.team_id),
            Err(e) => {
                tracing::warn!(%user, error = ?e, "failed to get user's team");
                None
            }
        };
        let Some(team_id) = team_id else {
            return (None, Vec::new());
        };
        match self.team_repository.get_team_members(&team_id).await {
            Ok(members) => (
                Some(team_id),
                members
                    .into_iter()
                    .map(|member| macro_user_id::cowlike::CowLike::into_owned(member.user_id))
                    .collect(),
            ),
            Err(e) => {
                tracing::warn!(%user, %team_id, error = ?e, "failed to list team members");
                (Some(team_id), Vec::new())
            }
        }
    }

    /// Create an imported task (with `id` when given), in `folder` when
    /// given, numbered within the user's team and shared with it when
    /// `share_with_team`, then apply its properties best-effort.
    #[expect(
        clippy::too_many_arguments,
        reason = "a task carries its id, content, properties, folder, dates and sharing"
    )]
    pub(crate) async fn create_imported_task(
        &self,
        user: &MacroUserIdStr<'static>,
        id: Option<uuid::Uuid>,
        name: &str,
        content: ImportedContent,
        properties: &import::domain::ports::ImportedTaskProperties,
        folder: Option<uuid::Uuid>,
        dates: Option<import::domain::ports::SourceDates>,
        share_with_team: bool,
    ) -> anyhow::Result<String> {
        // Same team resolution as the CreateDocument tool, so imported tasks
        // number correctly within the user's team; the roster doubles as the
        // assignee-email lookup. A teamless user gets a private task.
        let (team_id, roster) = self.team_roster(user).await;
        let subtype = documents::domain::create::MarkdownSubtype::Task {
            property_values: None,
            share_with_team: share_with_team && team_id.is_some(),
            team_id,
        };
        let task_id = self
            .create_doc(user, id, name, content, subtype, folder, dates)
            .await?;
        self.apply_task_properties(user, &task_id, properties, &roster)
            .await;
        Ok(task_id)
    }

    /// Create an imported markdown document, in `folder` when given and with
    /// its source's `dates` when known, then apply its properties best-effort.
    #[expect(
        clippy::too_many_arguments,
        reason = "an imported document carries its id, name, content, properties, folder and dates"
    )]
    pub(crate) async fn create_imported_document(
        &self,
        user: &MacroUserIdStr<'static>,
        id: Option<uuid::Uuid>,
        name: &str,
        notion: documents::domain::notion_markdown::NotionMarkdown,
        properties: &import::domain::ports::ImportedDocumentProperties,
        folder: Option<uuid::Uuid>,
        dates: Option<import::domain::ports::SourceDates>,
    ) -> anyhow::Result<String> {
        let document_id = self
            .create_doc(
                user,
                id,
                name,
                ImportedContent::Notion(notion),
                documents::domain::create::MarkdownSubtype::Note,
                folder,
                dates,
            )
            .await?;
        let access = match self
            .entity_access_service
            .generate_entity_access_receipt::<EditAccessLevel>(
                user,
                None,
                &document_id,
                model_entity::EntityType::Document,
            )
            .await
        {
            Ok(access) => access,
            Err(error) => {
                tracing::warn!(
                    document_id,
                    error = ?error,
                    "failed to authorize imported document properties"
                );
                return Ok(document_id);
            }
        };
        self.document_properties
            .apply(user, &access, &document_id, properties)
            .await;
        Ok(document_id)
    }

    /// Apply imported task properties best-effort: each one logs and is
    /// skipped on failure so a bad label or unknown assignee never sinks
    /// the import.
    pub(crate) async fn apply_task_properties(
        &self,
        user: &MacroUserIdStr<'static>,
        task_id: &str,
        properties: &import::domain::ports::ImportedTaskProperties,
        roster: &[MacroUserIdStr<'static>],
    ) {
        use models_properties::api::requests::SetPropertyValue;
        use system_properties::SystemPropertyKey;

        let principal = Self::creation_principal(user);

        if let Some(status) = properties.status.as_deref()
            && let Err(e) = match StatusOption::try_from(status) {
                Ok(option) => self
                    .task_properties
                    .system_properties
                    .update_task_status(task_id, option)
                    .await
                    .map_err(anyhow::Error::from),
                Err(e) => Err(anyhow::anyhow!(e)),
            }
        {
            tracing::warn!(task_id, status, error = ?e, "failed to set imported task status");
        }

        if let Some(priority) = properties.priority.as_deref() {
            let option = match priority {
                "Low" => Some(PriorityOption::Low),
                "Medium" => Some(PriorityOption::Medium),
                "High" => Some(PriorityOption::High),
                "Urgent" => Some(PriorityOption::Urgent),
                _ => None,
            };
            match option {
                Some(option) => {
                    if let Err(e) = self
                        .task_properties
                        .set_entity_property(
                            &principal,
                            task_id,
                            SystemPropertyKey::Priority.uuid(),
                            Some(SetPropertyValue::SelectOption {
                                option_id: option.uuid(),
                            }),
                        )
                        .await
                    {
                        tracing::warn!(task_id, priority, error = ?e, "failed to set imported task priority");
                    }
                }
                None => tracing::warn!(task_id, priority, "unknown imported task priority label"),
            }
        }

        if let Some(due_date) = properties.due_date.as_deref() {
            match chrono::NaiveDate::parse_from_str(due_date, "%Y-%m-%d") {
                Ok(date) => {
                    let value = date.and_time(chrono::NaiveTime::MIN).and_utc();
                    if let Err(e) = self
                        .task_properties
                        .set_entity_property(
                            &principal,
                            task_id,
                            SystemPropertyKey::DueDate.uuid(),
                            Some(SetPropertyValue::Date { value }),
                        )
                        .await
                    {
                        tracing::warn!(task_id, due_date, error = ?e, "failed to set imported task due date");
                    }
                }
                Err(e) => {
                    tracing::warn!(task_id, due_date, error = ?e, "unparseable imported task due date");
                }
            }
        }

        if let Some(email) = properties.assignee_email.as_deref() {
            // Only assign teammates — an email with no roster match (an
            // external collaborator, a bot) is silently skipped.
            let Some(assignee) = roster
                .iter()
                .find(|member| member.email_str().eq_ignore_ascii_case(email))
            else {
                return;
            };
            let reference = models_properties::EntityReference::new(
                assignee.as_ref().to_string(),
                models_properties::EntityType::User,
            );
            if let Err(e) = self
                .task_properties
                .set_entity_property(
                    &principal,
                    task_id,
                    SystemPropertyKey::Assignees.uuid(),
                    Some(SetPropertyValue::MultiEntityReference {
                        references: vec![reference],
                    }),
                )
                .await
            {
                tracing::warn!(task_id, email, error = ?e, "failed to set imported task assignee");
            }
        }
    }
}

impl import::domain::ports::EntityCreator for ToolEntityCreator {
    async fn create_task(
        &self,
        user: &MacroUserIdStr<'static>,
        name: &str,
        markdown: &str,
        properties: &import::domain::ports::ImportedTaskProperties,
    ) -> anyhow::Result<String> {
        self.create_imported_task(
            user,
            None,
            name,
            ImportedContent::Markdown(markdown.to_string()),
            properties,
            None,
            None,
            // Single tracked tasks (Linear) are shared with the team, as
            // tasks the user makes are.
            true,
        )
        .await
    }

    async fn create_notion_document(
        &self,
        user: &MacroUserIdStr<'static>,
        name: &str,
        notion_markdown: &str,
        links: &import::domain::ports::NotionLinks,
        properties: &import::domain::ports::ImportedDocumentProperties,
    ) -> anyhow::Result<String> {
        self.create_imported_document(
            user,
            None,
            name,
            crate::import_workspace::notion_markdown(notion_markdown, links),
            properties,
            None,
            None,
        )
        .await
    }

    async fn create_channel(
        &self,
        user: &MacroUserIdStr<'static>,
        name: &str,
        target: &import::domain::models::ImportTargetReservation,
        participant_emails: &[String],
    ) -> anyhow::Result<uuid::Uuid> {
        let (_, roster) = self.team_roster(user).await;
        crate::import_channels::create_channel(
            self.channel_service.as_ref(),
            user,
            name,
            target,
            participant_emails,
            &roster,
        )
        .await
    }
}

/// The connector backends (Pipedream, plus Macro Connect when configured):
/// `None` on deployments where Pipedream isn't configured (its toolsets then
/// come up empty).
pub type ToolPipedreamConnection =
    Option<std::sync::Arc<pipedream_mcp::outbound::dispatch::ConnectorBackends>>;

/// The MCP stack selector wired to the concrete DCS stores: the native
/// server store and the Pipedream connection store. Picks which stack
/// serves a user's tools (Pipedream connectors win; see `mcp_select`).
pub type ToolMcpSelector = mcp_select::McpToolSelector<
    mcp_client::outbound::NativeServerStore,
    pipedream_mcp::outbound::pg_connection_repo::PgConnectionRepo,
    ToolPipedreamConnection,
>;

/// Type alias for the import service implementation used by AI tools.
pub type ToolImportService = import::domain::service::ImportServiceImpl<
    import::outbound::pg_import_repo::PgImportRepo,
    ToolMcpSelector,
    ToolEntityCreator,
    import::outbound::mcp_slack_source::McpSlackSource<ToolMcpSelector>,
    import_notion::outbound::pipedream::PipedreamNotionConnections<
        pipedream_mcp::outbound::pg_connection_repo::PgConnectionRepo,
        pipedream_mcp::outbound::dispatch::ConnectorBackends,
    >,
>;

/// The custom MCP server tools, wired by hosts holding the MCP credentials
/// key.
pub type ToolMcpServerToolContext =
    mcp_client::inbound::toolset::McpServerToolContext<mcp_client::outbound::NativeServerStore>;

/// Type alias for the import tool context, wired by hosts with connector access.
pub type ToolImportToolContext = import::inbound::toolset::ImportToolContext<ToolImportService>;

pub type ToolActivityToolContext = activity::inbound::toolset::ActivityToolContext<
    initiative::domain::personal_activity::ProjectVisibleActivityReads<
        activity::outbound::pg_activity_repo::PgActivityRepo,
        ToolEntityAccessService,
    >,
>;

pub fn build_activity_tool_context(
    pool: sqlx::PgPool,
    properties: Arc<ToolPropertiesService>,
    entity_access_service: Arc<ToolEntityAccessService>,
) -> ToolActivityToolContext {
    activity::inbound::toolset::ActivityToolContext::new(
        initiative::domain::personal_activity::ProjectVisibleActivityReads::new(
            activity::outbound::pg_activity_repo::PgActivityRepo::new(pool),
            entity_access_service.clone(),
        ),
    )
    .with_metadata_resolver(ToolActivityMetadataResolver::new(
        properties,
        entity_access_service,
    ))
}

pub use routines::inbound::RoutineToolContext;

/// Build the routine client from standard service URL and auth configuration.
pub fn build_routine_tool_context() -> anyhow::Result<RoutineToolContext> {
    Ok(RoutineToolContext {
        service: Some(routines::outbound::RoutineClient::new(
            macro_service_urls::ScheduledActionServiceUrl::new()?.as_ref(),
            &macro_auth::InternalApiKey::new()?,
        )?),
    })
}

#[cfg(any(test, feature = "test-support"))]
pub fn no_op_schedule_context() -> RoutineToolContext {
    RoutineToolContext::default()
}

/// The full service context containing all API clients.
/// Individual tools should extract only the clients they need via `FromRef`.
#[derive(Clone, FromRef)]
pub struct ToolServiceContext {
    /// Private explicit memory edits and current-team activity reads.
    pub memory_tool_context: crate::memory::ToolMemoryContext,
    /// Read-only discovery of connectors the caller has not yet authorized.
    pub connector_tool_context: ToolConnectorToolContext,
    pub search_service_client: Arc<search_service_client::SearchServiceClient>,
    pub email_service_client: Arc<email_service_client::EmailServiceClientExternal>,
    pub soup_service: Arc<ToolSoupService>,
    pub email_service: Arc<ToolEmailService>,
    pub activity_tool_context: ToolActivityToolContext,
    #[from_ref(skip)]
    pub document_tool_context: ToolDocumentToolContext,
    pub image_generation_tool_context: ToolImageGenerationToolContext,
    /// Shared cognition-backed generation and decisions, attributed per request.
    pub cognition_tool_context: ToolCognitionToolContext,
    pub properties_tool_context: ToolPropertiesToolContext,
    pub email_tool_context: ToolEmailToolContext,
    pub call_tool_context: ToolCallToolContext,
    pub calendar_tool_context: ToolCalendarToolContext,
    pub team_calendar_tool_context: ToolTeamCalendarToolContext,
    pub booking_link_tool_context: ToolBookingLinkToolContext,
    /// Calendar-service-backed booking administration.
    pub booking_management_tool_context: ToolBookingManagementToolContext,
    pub notification_tool_context: ToolNotificationToolContext,
    /// The user's own per-item notification mutes and snoozes.
    pub item_notification_preference_tool_context: ToolItemNotificationPreferenceToolContext,
    pub databases_tool_context: ToolDatabasesToolContext,
    pub forms_tool_context: ToolFormsToolContext,
    pub databases_sql_tool_context: ToolDatabasesSqlToolContext,
    /// Import staging/tracking tools. `unwired` in hosts that can't build
    /// the import service — calls there fail with a clear error.
    pub import_tool_context: ToolImportToolContext,
    /// Custom MCP server tools. `unwired` in hosts without the MCP
    /// credentials key — calls there fail with a clear error.
    pub mcp_server_tool_context: ToolMcpServerToolContext,
    /// Built per-request via a manual `FromRef` below so it can carry the
    /// running chat's id — the derive's field-clone would freeze it at
    /// startup with no chat id set.
    #[from_ref(skip)]
    pub chat_tool_context: ToolChatToolContext,
    pub channel_tool_context: ToolChannelToolContext,
    /// Direct uploads of channel images and videos; exposed to MCP clients only.
    pub channel_media_upload_tool_context: ToolChannelMediaUploadToolContext,
    pub bot_tool_context: ToolBotToolContext,
    pub coding_agent_tool_context: ToolCodingAgentToolContext,
    /// Authorized agent-session conversation reads.
    pub read_agent_session_context: ToolReadAgentSessionContext,
    pub project_tool_context: ToolProjectToolContext,
    /// Favorite toggles; the same favorites back `soup_service`'s favorites filter.
    pub favorites_tool_context: ToolFavoritesToolContext,
    /// The Discussion of any item: the same message service the document
    /// tools comment through.
    pub message_tool_context: ToolMessageToolContext,
    /// Native task project lifecycle, properties, sharing and history.
    pub initiative_tool_context: ToolInitiativeToolContext,
    pub team_tool_context: ToolTeamToolContext,
    pub crm_tool_context: ToolCrmToolContext,
    /// CRM pipelines: deals by record, fields by name.
    pub pipeline_tool_context: ToolPipelineToolContext,
    /// CRM CSV imports and exports.
    pub crm_transfer_tool_context: ToolCrmTransferToolContext,
    pub skill_tool_context: ToolSkillToolContext,
    pub schedule_tool_context: RoutineToolContext,
    #[from_ref(skip)]
    pub anthropic_tool_context: AnthropicToolContext,
    /// The web search vendor behind `WebSearch` and `WebFetch`.
    #[from_ref(skip)]
    pub web_search_provider: Arc<dyn web_search::domain::ports::SearchProvider>,
    /// Shared admission for independently initiated AI work. Hosts must inject
    /// their configured service; request identity always comes from RequestContext.
    pub admission: Arc<dyn ai_billing::domain::admission::AiAdmissionService>,
    /// Records token usage / cost for AI calls made with this context.
    pub recorder: std::sync::Arc<dyn ai_usage::UsageRecorder>,
    /// The usage context (feature/user/entity) of the request currently using
    /// this context. Set per-session by the caller so AI calls made by tools
    /// (e.g. subagents) are attributed to the feature that spawned them.
    pub usage_context: ai_usage::UsageContext,
}

/// Pipedream discovery dependencies shared by chat tools.
pub type ToolConnectorToolContext = pipedream_mcp::inbound::toolset::ConnectorToolContext<
    pipedream_mcp::outbound::dispatch::ConnectorBackends,
    pipedream_mcp::outbound::pg_connection_repo::PgConnectionRepo,
    mcp_select::NativeOverlayConnections<mcp_client::outbound::NativeServerStore>,
>;

/// Wire connector discovery at the composition boundary.
///
/// `native_servers` answers for overlaid apps, which connect through the
/// native MCP stack; `None` where that stack has no encryption key.
pub fn build_connector_tool_context(
    pool: sqlx::PgPool,
    client: Option<Arc<pipedream_mcp::outbound::dispatch::ConnectorBackends>>,
    native_servers: Option<Arc<mcp_client::outbound::NativeServerStore>>,
) -> ToolConnectorToolContext {
    pipedream_mcp::inbound::toolset::ConnectorToolContext {
        service: Arc::new(
            pipedream_mcp::domain::service::discovery::ConnectorDiscovery::new(
                client,
                Arc::new(pipedream_mcp::outbound::pg_connection_repo::PgConnectionRepo::new(pool)),
                Arc::new(mcp_select::NativeOverlayConnections::new(native_servers)),
            ),
        ),
    }
}

impl FromRef<ToolServiceContext> for AnthropicToolContext {
    fn from_ref(context: &ToolServiceContext) -> Self {
        let mut tools = context.anthropic_tool_context.clone();
        tools.admission = context.admission.clone();
        tools.recorder = context.recorder.clone();
        tools.usage_context = context.usage_context.clone();
        tools
    }
}

impl FromRef<ToolServiceContext> for web_search::inbound::toolset::WebToolContext {
    fn from_ref(context: &ToolServiceContext) -> Self {
        Self {
            service: Arc::new(web_search::domain::service::WebSearchService::new(
                context.web_search_provider.clone(),
                context.admission.clone(),
                context.recorder.clone(),
            )),
            entity: context.usage_context.entity,
        }
    }
}

impl FromRef<ToolServiceContext> for ToolDocumentToolContext {
    fn from_ref(context: &ToolServiceContext) -> Self {
        context
            .document_tool_context
            .clone()
            .with_admission(context.admission.clone())
            .with_recorder(context.recorder.clone())
    }
}

impl ToolServiceContext {
    /// Run the mutating tools as `actor`, delegated for the requesting user,
    /// instead of the default Macro AI bot. Hosts running a specific agent
    /// call this once when they build the context for that agent's session.
    pub fn with_actor(mut self, actor: bot_id::BotId) -> Self {
        self.document_tool_context = self.document_tool_context.with_actor(actor);
        self.message_tool_context = self.message_tool_context.with_actor(actor);
        self.image_generation_tool_context = self.image_generation_tool_context.with_actor(actor);
        self.properties_tool_context = self.properties_tool_context.with_actor(actor);
        self.project_tool_context = self.project_tool_context.with_actor(actor);
        self.initiative_tool_context = self.initiative_tool_context.with_actor(actor);
        self.channel_tool_context = self.channel_tool_context.with_actor(actor);
        self.databases_tool_context = self.databases_tool_context.with_actor(actor);
        self.forms_tool_context.actor = actor;
        self.pipeline_tool_context.actor = actor;
        self.crm_transfer_tool_context.actor = actor;
        self.databases_sql_tool_context = self.databases_sql_tool_context.with_actor(actor);
        self
    }

    /// Run the tools for `caller`, as the public MCP authenticated it: an
    /// agent writes as itself, under its own name; an MCP client writes as the
    /// Macro bot with its name on the post, shown as the author ("Claude Code ·
    /// Agent"); a pasted API key writes as the Macro bot.
    pub async fn for_caller(self, caller: &ai_toolset::ToolCaller) -> Self {
        match caller {
            ai_toolset::ToolCaller::Agent(agent) => {
                let name =
                    agent_name::agent_name(self.bot_tool_context.service.as_ref(), *agent).await;
                let context = self.with_actor(*agent);
                match name {
                    Some(name) => context.with_actor_name(&name),
                    None => context,
                }
            }
            ai_toolset::ToolCaller::McpClient { .. } | ai_toolset::ToolCaller::ApiKey => {
                match caller.via() {
                    Some(client) => self.with_via(client),
                    None => self,
                }
            }
        }
    }

    /// Label the posts the tools make with the client the user works
    /// through.
    fn with_via(mut self, client: &str) -> Self {
        self.message_tool_context = self.message_tool_context.with_via(client.to_owned());
        self.channel_tool_context = self.channel_tool_context.with_via(client.to_owned());
        self.document_tool_context = self.document_tool_context.with_via(client.to_owned());
        self
    }

    /// Name the actor set with [`Self::with_actor`], so what the tools write
    /// is presented under the agent's own name where a reader sees it live -
    /// the cursor the editing worker draws while it types. First-party bots
    /// present under their constant names without this; a user- or
    /// team-owned bot has no name the tools can find on their own.
    pub fn with_actor_name(mut self, name: &str) -> Self {
        self.document_tool_context = self.document_tool_context.with_actor_name(name);
        self
    }
}

impl FromRef<ToolServiceContext> for ToolViewOnlyDatabasesSqlToolContext {
    fn from_ref(context: &ToolServiceContext) -> Self {
        context.databases_sql_tool_context.view_only()
    }
}

impl FromRef<ToolServiceContext> for ai_toolset::NoContext {
    fn from_ref(_ctx: &ToolServiceContext) -> Self {
        ai_toolset::NoContext()
    }
}

impl FromRef<ToolServiceContext> for SoupToolContext<ToolSoupService, ToolEmailService> {
    fn from_ref(ctx: &ToolServiceContext) -> Self {
        SoupToolContext {
            service: ctx.soup_service.clone(),
            email_service: ctx.email_service.clone(),
            self_chat_id: self_chat_id(ctx),
        }
    }
}

impl FromRef<ToolServiceContext> for ToolChatToolContext {
    fn from_ref(ctx: &ToolServiceContext) -> Self {
        ChatToolContext {
            service: ctx.chat_tool_context.service.clone(),
            entity_access_service: ctx.chat_tool_context.entity_access_service.clone(),
            self_chat_id: self_chat_id(ctx),
        }
    }
}

/// Entity id of the chat this request belongs to, when the request is an
/// interactive chat session. `None` for every other feature, in which case
/// nothing about the running chat should be excluded/blocked.
fn self_chat_id(ctx: &ToolServiceContext) -> Option<uuid::Uuid> {
    matches!(ctx.usage_context.feature, ai_usage::AiFeature::Chat)
        .then_some(ctx.usage_context.entity)
        .flatten()
}