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.

59.6 KB
Raw Blame
use std::pin::Pin;

use super::coding_preferences::CodingPreferences;
use super::error::{AgentSessionError, Result};
use super::model::*;
use super::session::StopReason;
use crate::domain::events::AgentSessionLifecycleEvent;
use agent_client_protocol::schema::v1::{McpServer, SessionId};
use agent_fold::domain::model::TurnSignal;
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId, PromptAttachment};
use agent_runtime_protocol::domain::ports::Transport;
use agent_runtime_protocol::domain::schema::v0::{ToRuntimeMessage, ToServerMessage};
use bots::domain::models::BotId;
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
use model_owner::{Owner, OwnerType};
use shared_entity_registry::OwnedPurgeOutcome;
use std::num::NonZeroUsize;

/// A bidirectional connection to an agent runtime.
pub trait AgentConnector:
    Transport<ToRuntimeMessage, ToServerMessage> + Send + Sync + 'static
{
}

impl<T> AgentConnector for T where
    T: Transport<ToRuntimeMessage, ToServerMessage> + Send + Sync + 'static
{
}

/// The facts about a bot that gate opening sessions for it.
#[derive(Debug, Clone)]
pub struct BotFacts {
    /// Whether mentioning the bot runs a coding agent.
    pub has_agent: bool,
    /// Whether this deployment provisions the bot's runtime itself. Managed
    /// bots' sessions are opened by the trigger pipeline, never over HTTP,
    /// and nothing may dial in for them.
    pub is_managed: bool,
    /// Whether this is a first-party system bot rather than a user- or
    /// team-owned persona. System bots belong to everyone.
    pub is_system: bool,
    /// The user who owns the bot, when it is user-owned.
    pub owner_user_id: Option<MacroUserIdStr<'static>>,
    /// Team that owns the bot, when it is team-owned.
    pub owner_team_id: Option<Uuid>,
    /// The registered harness this bot's agent is bound to, when it is one.
    pub harness_id: Option<harness_id::HarnessId>,
    /// Runtime profile for a persisted agent. Fixed system bots have no
    /// persisted profile and use deployment defaults instead.
    pub managed_profile: Option<ManagedAgentProfile>,
    /// Whether the persona is limited to selected channels. Channel co-members
    /// may start a session as it, matching `@` mentions in those channels.
    pub selected_channels: bool,
}

/// Runtime settings snapshotted when a persisted agent opens a session.
#[derive(Debug, Clone)]
pub struct ManagedAgentProfile {
    /// Model configured as this persona's default.
    pub model: String,
    /// Harness serving this persona.
    pub harness: String,
    /// Instructions configured for this persona.
    pub instructions: String,
    /// MCP servers this persona may use.
    pub mcp_servers: AgentMcpServers,
}

/// A managed persona selected for one managed session.
#[derive(Debug, Clone)]
pub struct SelectedManagedPersona {
    /// Bot identity used by the session.
    pub bot_id: BotId,
    /// Runtime settings resolved from a persisted persona. `None` for a fixed
    /// system bot, whose sessions run on the deployment's defaults for it.
    pub profile: Option<ManagedAgentProfile>,
}

/// Read-only lookup of the bots sessions may be opened for.
pub trait BotDirectory: Send + Sync + 'static {
    /// Fetch a bot's facts; `None` when no such bot exists.
    fn bot_facts(&self, bot: BotId) -> impl Future<Output = Result<Option<BotFacts>>> + Send;

    /// Whether a user belongs to a team that owns a persona.
    fn user_has_team(
        &self,
        user: MacroUserIdStr<'static>,
        team_id: Uuid,
    ) -> impl Future<Output = Result<bool>> + Send;

    /// Whether the user and bot share at least one active channel.
    fn user_shares_channel_with_bot(
        &self,
        user: MacroUserIdStr<'static>,
        bot_id: BotId,
    ) -> impl Future<Output = Result<bool>> + Send;
}

/// A persona selected for a session started from Macro, by whoever runs it.
#[derive(Debug, Clone)]
pub enum SelectedPersona {
    /// This deployment provisions the runtime.
    Managed(SelectedManagedPersona),
    /// The persona's operator runs the runtime, which opens its own sessions.
    External {
        /// Bot identity used by the session.
        bot_id: BotId,
    },
}

/// A session asked for from the composer, for a bot whose runtime is its
/// operator's. The runtime creates it, the way it does for a mention.
///
/// No prompt: the caller delivers its own through the control endpoint once
/// the session exists, exactly as it does for a managed one, so a prompt the
/// user typed never rides the trigger topic.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RequestedExternalSession {
    /// The id the runtime is told to create the session under.
    pub session_id: AgentSessionId,
    /// The bot the session runs for.
    pub bot_id: BotId,
    /// Who asked; owns the session that the runtime creates.
    pub owner: MacroUserIdStr<'static>,
    /// The model they chose over the persona's default, when they did. It
    /// reaches the runtime the way the persona's own does: recorded on the
    /// session, then selected when the session binds on its first prompt.
    pub model: Option<String>,
    /// Remote repository selected for this external coding session.
    pub repo_url: Option<String>,
    /// Who is starting the session.
    pub source: SessionSource,
    /// Whether a routine run is listed; a person's session always is.
    pub visibility: SessionVisibility,
    /// What opened the session, told to the runtime on the event.
    pub origin: trigger_context::TriggerOrigin,
}

/// Validate the base branch supported by external repository provisioning.
/// External runtimes currently create every new worktree from origin/main.
pub fn external_repository(
    repo_url: Option<String>,
    branch: Option<&str>,
) -> super::error::Result<Option<String>> {
    if branch.is_some_and(|branch| !matches!(branch, "main" | "origin/main")) {
        return Err(super::error::AgentSessionError::InvalidRepositorySelection(
            "external coding sessions start from origin/main",
        ));
    }
    Ok(repo_url.filter(|url| !url.trim().is_empty()))
}

/// Hands a composer request to the bot's own runtime and waits for the
/// session it creates.
pub trait ExternalSessionRequester: Send + Sync + 'static {
    /// Ask the runtime and return the session once it exists. Fails with
    /// [`AgentSessionError::RuntimeUnavailable`] when no runtime answers.
    fn request(
        &self,
        request: RequestedExternalSession,
    ) -> impl Future<Output = Result<AgentSession>> + Send;
}

/// Why a user cannot select a bot as a managed session persona.
#[derive(Debug)]
pub enum ManagedPersonaError {
    /// No active bot has this id.
    Unknown,
    /// The bot has no agent runtime.
    NotAgent,
    /// A first-party system bot this deployment does not run. It has no
    /// operator to ask and no owner to authorize against, so it is nobody's
    /// to start - a misconfiguration rather than a policy answer.
    UnmanagedSystemBot,
    /// The owner does not own or belong to the persona's owner.
    Forbidden,
    /// The owner is not a user, so no persona rule applies.
    OwnerNotUser(OwnerType),
    /// Looking up the persona or its owner failed.
    Lookup(AgentSessionError),
}

/// Resolve and authorize a persona for the session's owner, whoever runs its
/// runtime.
///
/// Ownership policy lives in the domain: private personas belong to their
/// owner, team personas are available to team members, selected-channel
/// personas are available to anyone who can `@` them in a shared channel,
/// and managed system bots (the deployment's own coders) are available to
/// everyone, exactly as they are when mentioned in a channel. Every rule is
/// about a person, so an owner that is not a user selects nothing.
///
/// A persona whose runtime its operator runs is authorized by those same
/// rules and only then told apart, so the caller can hand the request to
/// that runtime instead of opening the session here.
pub async fn persona_for_owner<Bots: BotDirectory>(
    bots: &Bots,
    bot_id: BotId,
    owner: &Owner,
) -> std::result::Result<SelectedPersona, ManagedPersonaError> {
    let user = session_owner_user(owner).map_err(|error| match error {
        AgentSessionError::OwnerNotUser(owner_type) => {
            ManagedPersonaError::OwnerNotUser(owner_type)
        }
        other => ManagedPersonaError::Lookup(other),
    })?;
    let facts = bots
        .bot_facts(bot_id)
        .await
        .map_err(ManagedPersonaError::Lookup)?
        .ok_or(ManagedPersonaError::Unknown)?;
    if !facts.has_agent {
        return Err(ManagedPersonaError::NotAgent);
    }
    if facts.is_system {
        if !facts.is_managed {
            return Err(ManagedPersonaError::UnmanagedSystemBot);
        }
        return Ok(SelectedPersona::Managed(SelectedManagedPersona {
            bot_id,
            profile: None,
        }));
    }
    let authorized = if let Some(owner) = &facts.owner_user_id {
        owner.as_ref() == user.as_ref()
            || (facts.selected_channels
                && bots
                    .user_shares_channel_with_bot(user.clone(), bot_id)
                    .await
                    .map_err(ManagedPersonaError::Lookup)?)
    } else if let Some(team_id) = facts.owner_team_id {
        bots.user_has_team(user.clone(), team_id)
            .await
            .map_err(ManagedPersonaError::Lookup)?
            || (facts.selected_channels
                && bots
                    .user_shares_channel_with_bot(user.clone(), bot_id)
                    .await
                    .map_err(ManagedPersonaError::Lookup)?)
    } else {
        false
    };
    if !authorized {
        return Err(ManagedPersonaError::Forbidden);
    }
    if !facts.is_managed {
        return Ok(SelectedPersona::External { bot_id });
    }
    let profile = facts.managed_profile.ok_or(ManagedPersonaError::NotAgent)?;
    Ok(SelectedPersona::Managed(SelectedManagedPersona {
        bot_id,
        profile: Some(profile),
    }))
}

/// The mention that triggered a session, when one did.
///
/// Routes follow-up mentions in the thread to this session and feeds the
/// announcement - the magic-chip message the session's bot posts back into
/// the thread. The mention's text is quoted there for display only; the
/// runtime still delivers it as the first prompt through the session
/// control endpoint. Because all of this is claimed by the caller rather
/// than observed by the trigger pipeline, it never grants the thread's
/// channel any access to the session, and the announcement stands only
/// where the bot can already post.
#[derive(Debug, Clone)]
pub struct SessionThread {
    /// Update a reserved bot response for a task assignment.
    pub reuse_origin_message: bool,
    /// Channel or document the mentioning message was posted in.
    pub parent: messages::domain::models::MessageParent,
    /// Thread the session belongs to.
    pub thread_id: Uuid,
    /// The mentioning message itself.
    pub message_id: Uuid,
    /// The mention's text, quoted in the announcement.
    pub content: String,
}

/// Everything needed to open a session served by an external runtime.
#[derive(Debug, Clone)]
pub struct OpenExternalAgentSession {
    /// The id to create the session under, when the caller was told one: a
    /// runtime answering a composer request creates the session the
    /// requester is already waiting on. Minted here otherwise.
    pub id: Option<AgentSessionId>,
    /// The bot the session runs for.
    pub bot_id: BotId,
    /// Persisted agent settings resolved by the authenticated entry point.
    pub profile: Option<ManagedAgentProfile>,
    /// Absolute directory the bot's harness runs in on its runtime.
    pub workspace: String,
    /// Repository nominally checked out at `workspace`, when stated.
    pub repo_url: Option<String>,
    /// Who owns the session.
    pub owner: Owner,
    /// The thread whose mention triggered the session, when one did.
    pub thread: Option<SessionThread>,
    /// Instructions the session's runtime works under, when any were stated.
    pub instructions: Option<String>,
    /// What opened the session, as the runtime was told on the trigger event.
    /// A description only: it never decides visibility or notifications.
    pub origin: trigger_context::TriggerOrigin,
}

/// Everything needed to open a session the server hosts itself.
///
/// The deployment provisions the selected persona's runtime. Cursor sessions
/// may select an owner-accessible repository and starting branch; workspace
/// paths remain runtime-owned. There is no originating mention to announce.
#[derive(Debug, Clone)]
pub struct OpenManagedSession {
    /// The id the session is created under, when the caller minted one so it
    /// could open a surface on the final id before this answers. `None`
    /// mints one here.
    pub id: Option<AgentSessionId>,
    /// Repository explicitly selected by the caller for a supported runtime.
    pub repo_url: Option<String>,
    /// Starting branch for the selected repository.
    pub repo_branch: Option<super::repository_branch::RepositoryBranch>,
    /// Who owns the session and is credited for its messages.
    pub owner: Owner,
    /// First prompt to deliver once the sandbox is attached. `None` opens an
    /// idle session its owner prompts from the session's own surface.
    pub prompt: Option<FirstPrompt>,
    /// A selected persona's authoritative runtime profile. `None` uses the
    /// deployment's default managed coding persona, or Cursor when a
    /// repository is selected — the only managed persona that honors one.
    pub profile: Option<SelectedManagedPersona>,
    /// Instructions the session's runtime works under. Outranks a persisted
    /// persona's when both are set.
    pub instructions: Option<String>,
    /// Model to run on instead of the persona's own. The session's model from
    /// creation, so its runtime starts on it and nothing is sent to change it.
    pub model: Option<String>,
    /// Who is starting the session.
    pub source: SessionSource,
    /// Whether a routine run is listed; a person's session always is.
    pub visibility: SessionVisibility,
    /// What opened the session.
    pub origin: trigger_context::TriggerOrigin,
}

/// The prompt a managed session opens with, delivered as soon as it can run.
#[derive(Debug, Clone)]
pub struct FirstPrompt {
    /// The id the caller already shows the prompt under, so the logged row
    /// confirms it in place. `None` mints one.
    pub action_id: Option<AgentActionId>,
    /// What to tell the agent.
    pub prompt: String,
    /// Files the prompt refers to, in the order the user attached them.
    pub attachments: Vec<PromptAttachment>,
}

impl FirstPrompt {
    /// A plain text prompt under a minted id.
    pub fn text(prompt: impl Into<String>) -> Self {
        Self {
            action_id: None,
            prompt: prompt.into(),
            attachments: Vec::new(),
        }
    }

    /// The action this prompt delivers, under its id.
    pub fn into_action(self) -> (AgentActionId, AgentAction) {
        (
            self.action_id.unwrap_or_else(AgentActionId::mint),
            AgentAction::prompt_with_attachments(self.prompt, self.attachments),
        )
    }
}

/// Opens sessions, however they are served. Implemented by the harness, which
/// owns the session-opening semantics.
///
/// Two openings, because the two runtimes differ in who owns the machine: an
/// external session's runtime is hosted by the bot's operator and dials in on
/// its own schedule, while a managed session's sandbox is provisioned here.
/// That difference is why only one of them takes a workspace.
pub trait SessionOpener: Send + Sync + 'static {
    /// Prepare an unprompted hidden in-memory session for an authenticated user.
    fn warm_session(
        &self,
        owner: Owner,
        id: AgentSessionId,
    ) -> impl Future<Output = Result<Option<AgentSession>>> + Send;

    /// Open a session and return the persisted row.
    fn open_external_session(
        &self,
        request: OpenExternalAgentSession,
    ) -> impl Future<Output = Result<AgentSession>> + Send;

    /// Provision a sandbox, open a session on it and return the persisted
    /// row, delivering `prompt` once it is attached.
    fn open_managed_session(
        &self,
        request: OpenManagedSession,
    ) -> impl Future<Output = Result<AgentSession>> + Send;

    /// The session a thread's mentions already route to, if one exists.
    /// What a caller whose open conflicted needs to recover: redeliveries
    /// resume serving the existing session instead of being dropped.
    fn find_thread_session(
        &self,
        thread_id: Uuid,
        bot_id: BotId,
    ) -> impl Future<Output = Result<Option<AgentSessionId>>> + Send;
}

/// The turn currently allowed to initiate work, from shared durable state.
/// Stopping, ended, archived, and deleted sessions have no active turn.
pub trait ActiveSessionTurn: Send + Sync + 'static {
    /// Resolve the starting, running, or blocked turn independently of replica ownership.
    fn active_turn(
        &self,
        id: AgentSessionId,
    ) -> impl Future<Output = Result<Option<agent_runtime_protocol::domain::action::AgentActionId>>> + Send;
}

/// `Send + Sync + 'static` with `Send` futures because callers drive sessions
/// from spawned tasks - a Kafka consumer hands each message to its own task,
/// and a repo whose futures are not `Send` cannot be used there.
#[cfg_attr(feature = "test-utils", mockall::automock)]
pub trait AgentSessionRepo: Send + Sync + 'static {
    /// Persist a new agent session, together with its access grants.
    ///
    /// Part of the contract, not an implementation detail: the owner is
    /// granted owner access, and - when the session was opened by a mention -
    /// the channel that mention was posted in is granted editor access,
    /// resolved from `originating_message_id` rather than trusted from the
    /// caller. The session and its grants land atomically, so a session
    /// cannot exist that nobody, not even its owner, could open.
    fn create(
        &self,
        params: CreateAgentSessionParams,
    ) -> impl Future<Output = Result<AgentSession>> + Send;

    /// Get an agent session by id.
    fn get(&self, id: AgentSessionId) -> impl Future<Output = Result<AgentSession>> + Send;

    /// The agent session with this id, or `None` when there is none.
    fn find(&self, id: AgentSessionId)
    -> impl Future<Output = Result<Option<AgentSession>>> + Send;

    /// The sessions among `ids` that exist, each with what a chip shows and
    /// whether a materialized grant lets `viewer` see it: their own grant,
    /// one through a channel they are still in, or one through their teams -
    /// the same three the read routes' access extractor resolves. Inherited
    /// access that no row materializes (a document collaborator's) is the
    /// service's to resolve from the returned thread parent. Ids with no
    /// session are simply absent.
    fn preview(
        &self,
        viewer: &MacroUserIdStr<'static>,
        ids: &[AgentSessionId],
    ) -> impl Future<Output = Result<Vec<SessionPreviewCandidate>>> + Send;

    /// Replace the session credential when attaching an external runtime.
    fn set_egress_token_hash(
        &self,
        id: AgentSessionId,
        hash: &str,
    ) -> impl Future<Output = Result<()>> + Send;

    /// Record who prompted the turn `id` is about to run.
    fn set_turn_prompter(
        &self,
        id: AgentSessionId,
        prompter: &TurnPrompter,
    ) -> impl Future<Output = Result<()>> + Send;

    /// Record that `user` prompted the session `id` directly, from the
    /// session itself, so a hidden session lists for them. Idempotent; grants
    /// nothing.
    fn add_follower(
        &self,
        id: AgentSessionId,
        user: &MacroUserIdStr<'static>,
    ) -> impl Future<Output = Result<()>> + Send;

    /// Who prompted the turn `id` is running or last ran; `None` before its
    /// first dispatch.
    fn turn_prompter(
        &self,
        id: AgentSessionId,
    ) -> impl Future<Output = Result<Option<TurnPrompter>>> + Send;

    /// The session a sandbox's egress token stands for, if any still does.
    ///
    /// `egress_token_hash` is the SHA-256 hex of the token as presented, never
    /// the token: implementations match on the stored hash, so the comparison
    /// happens in an index rather than over secret-derived bytes in memory.
    ///
    /// `None` rather than an error when nothing matches - a token we never
    /// minted and a token whose session has since been deleted are the same
    /// fact, and the caller refuses both the same way. The whole session comes
    /// back because everything the token entitles its holder to is on the row:
    /// the owner whose credentials it spends, the repository its git traffic is
    /// pinned to, and whether the session is still open.
    fn find_by_egress_token_hash(
        &self,
        egress_token_hash: &str,
    ) -> impl Future<Output = Result<Option<AgentSession>>> + Send;

    /// Find the session associated with an incoming channel context.
    ///
    /// Matches only when `thread_id` and `bot_id` are both given and a session
    /// was created from that thread by that bot -> `CreatedFromThread`;
    /// otherwise `None`. There is nothing else to match: a session does not
    /// own a channel, and messages sent directly to a session arrive through
    /// their own topic rather than as channel events.
    fn find_for_thread(
        &self,
        thread_id: Option<Uuid>,
        bot_id: Option<BotId>,
    ) -> impl Future<Output = Result<ThreadSession>> + Send;

    /// Every session rooted at this thread, newest first, regardless of bot.
    ///
    /// [`find_for_thread`](Self::find_for_thread) answers for one known bot;
    /// this answers when no bot was named - a message in the thread may still
    /// be meant for whichever agent lives there.
    fn find_all_for_thread(
        &self,
        thread_id: Uuid,
    ) -> impl Future<Output = Result<Vec<AgentSession>>> + Send;

    /// The owner's newest sessions, newest first, at most `limit`.
    fn recent_for_owner<'owner>(
        &self,
        owner: &MacroUserIdStr<'owner>,
        limit: NonZeroUsize,
    ) -> impl Future<Output = Result<Vec<AgentSession>>> + Send;

    /// The agent behind a session, for rendering the messages it sent.
    ///
    /// A bot that has been deleted still has messages in the channel, so this
    /// answers for one rather than failing - a session's history should not
    /// stop rendering because its agent was removed.
    fn session_bot(&self, id: BotId) -> impl Future<Output = Result<SessionBot>> + Send;

    /// Persist the agent-assigned ACP session id without replacing other
    /// session fields or reordering the session list.
    fn set_acp_session_id(
        &self,
        id: AgentSessionId,
        acp_session_id: SessionId,
    ) -> impl Future<Output = Result<()>> + Send;

    /// Persist the repository the session works on, or clear it. Idempotent.
    ///
    /// Written after the session is open, because for some runtimes the
    /// repository is not known at creation: a Cursor session's repository
    /// follows from what its first prompt asks for. The row is authoritative
    /// once written - the egress proxy pins the sandbox's git traffic to it -
    /// so `None` is a real answer meaning "this session works on no
    /// repository", not "leave whatever is there".
    fn set_repo_url(
        &self,
        id: AgentSessionId,
        repo_url: Option<String>,
    ) -> impl Future<Output = Result<()>> + Send;

    /// Persist the model the session is running on. Idempotent.
    fn set_model(&self, id: AgentSessionId, model: &str)
    -> impl Future<Output = Result<()>> + Send;

    /// Record who started the session and where it is shown, for a session
    /// whose runtime created the row without knowing either. Idempotent.
    fn set_origin(
        &self,
        id: AgentSessionId,
        source: SessionSource,
        visibility: SessionVisibility,
    ) -> impl Future<Output = Result<()>> + Send;

    /// Persist a name a person chose. Idempotent. The name stops being
    /// generated, so retitling never replaces it.
    fn set_name(&self, id: AgentSessionId, name: &str) -> impl Future<Output = Result<()>> + Send;

    /// Archive or unarchive a session. Idempotent.
    fn set_archived(
        &self,
        id: AgentSessionId,
        archived: bool,
    ) -> impl Future<Output = Result<()>> + Send;

    /// Whether the session is an agent conversation's current one: the
    /// session its channel's messages go to now. A session the conversation
    /// left behind by starting fresh is not.
    fn is_current_conversation_session(
        &self,
        id: AgentSessionId,
    ) -> impl Future<Output = Result<bool>> + Send;

    /// Persist an automatically generated name only while the default remains
    /// and the session is not archived.
    fn set_name_if_default(
        &self,
        id: AgentSessionId,
        name: &str,
    ) -> impl Future<Output = Result<bool>> + Send;

    /// The session's name while it is a generated one that retitling may
    /// replace: `None` once a person named the session, while it still has
    /// the default, or when it is archived.
    fn generated_name(
        &self,
        id: AgentSessionId,
    ) -> impl Future<Output = Result<Option<String>>> + Send;

    /// Replace a generated name only while the session is still called
    /// `current`, that name is still generated, and the session is not
    /// archived. Whether the name changed.
    fn replace_generated_name(
        &self,
        id: AgentSessionId,
        current: &str,
        name: &str,
    ) -> impl Future<Output = Result<bool>> + Send;

    /// Persist the sandbox size this session was spawned with, or resized to.
    fn set_sandbox_size(
        &self,
        id: AgentSessionId,
        size: SandboxSize,
    ) -> impl Future<Output = Result<()>> + Send;

    /// The user's default sandbox size for new `@coder` sessions.
    ///
    /// A missing row is [`SandboxSize::Default`], not an error.
    fn user_sandbox_size(
        &self,
        user_id: &MacroUserIdStr<'static>,
    ) -> impl Future<Output = Result<SandboxSize>> + Send;

    /// Upsert the user's default sandbox size for the next `@coder` mention.
    fn set_user_sandbox_size(
        &self,
        user_id: &MacroUserIdStr<'static>,
        size: SandboxSize,
    ) -> impl Future<Output = Result<()>> + Send;

    /// The user's coding preferences.
    ///
    /// A missing row is every preference off, not an error.
    fn user_coding_preferences(
        &self,
        user_id: &MacroUserIdStr<'static>,
    ) -> impl Future<Output = Result<CodingPreferences>> + Send;

    /// Upsert the user's coding preferences, replacing every field.
    fn set_user_coding_preferences(
        &self,
        user_id: &MacroUserIdStr<'static>,
        preferences: CodingPreferences,
    ) -> impl Future<Output = Result<()>> + Send;

    /// Delete an agent session by id.
    fn delete(&self, id: AgentSessionId) -> impl Future<Output = Result<()>> + Send;

    /// The session's waiting actions, oldest first. Missing row is empty.
    fn list_queued_actions(
        &self,
        id: AgentSessionId,
    ) -> impl Future<Output = Result<Vec<StoredQueuedAction>>> + Send;

    /// Replace the session's waiting actions. An empty slice deletes the row.
    fn replace_queued_actions(
        &self,
        id: AgentSessionId,
        entries: &[StoredQueuedAction],
    ) -> impl Future<Output = Result<()>> + Send;
}

/// The durable record of which provider-side agent an externally-served
/// session runs on.
///
/// Written by the provider's container manager when the agent is minted, read
/// back to resume after a restart, and joined into session reads so a client
/// can link out to the provider. Providers have no queryable label space
/// (Cursor's API cannot answer "which agent belongs to this session"), so
/// this repo is the mapping's single source of truth.
#[cfg_attr(feature = "test-utils", mockall::automock)]
pub trait ExternalSessionRepo: Send + Sync + 'static {
    /// Record (or refresh) a session's provider-side identity.
    ///
    /// Upsert on the session: a session has at most one external backing, and
    /// re-learning the same agent's name or url must not fail the write.
    fn upsert(
        &self,
        id: AgentSessionId,
        external: ExternalSession,
    ) -> impl Future<Output = Result<()>> + Send;

    /// The session's provider-side identity, if it has one.
    fn get(
        &self,
        id: AgentSessionId,
    ) -> impl Future<Output = Result<Option<ExternalSession>>> + Send;

    /// Forget a session's provider-side identity. A session that never had
    /// one is already in the asked-for state, so this succeeds.
    fn delete(&self, id: AgentSessionId) -> impl Future<Output = Result<()>> + Send;
}

/// How often a replica refreshes its heartbeat row.
pub const REPLICA_HEARTBEAT_INTERVAL: std::time::Duration = std::time::Duration::from_secs(10);

/// How stale a replica's heartbeat may be before its claims are up for
/// grabs. Three missed heartbeats: long enough that one slow write does not
/// get a live replica's sessions stolen, short enough that a crashed
/// replica's sessions resume on the next prompt rather than minutes later.
pub const REPLICA_STALE_AFTER: std::time::Duration = std::time::Duration::from_secs(30);

/// The session-management lease: which replica holds a session's live actor.
///
/// Implemented by the same store that persists the session log, never
/// separately - the fence a claim carries is checked by that store's fenced
/// appends, and minting fences in one place while checking them in another
/// is the mis-wiring this coupling forbids.
///
/// Claiming is a single conditional update (compare-and-swap): it succeeds
/// when the session is unmanaged, already ours, or held by a replica whose
/// heartbeat has gone stale, and every success increments the session's
/// fence. Lease changes must not bump list recency: a reclaim, release, or
/// stale takeover is not the conversation being used. There are deliberately
/// no explicit locks anywhere in the contract - see
/// [`ManagerFence`](super::model::ManagerFence) for why a fence, not a lock,
/// is what neutralizes a stale holder.
pub trait SessionOwnership: Send + Sync + 'static {
    /// Claim live management of a session for `replica`, registering the
    /// replica's heartbeat as a side effect so a claim can never dangle on a
    /// replica the store has not seen.
    fn claim(
        &self,
        session: AgentSessionId,
        replica: ReplicaId,
    ) -> impl Future<Output = Result<ClaimOutcome>> + Send;

    /// Release a claim this replica holds. Conditional on the claim's fence
    /// still being current: releasing after having been superseded is a
    /// no-op, never a theft of the successor's claim. A session already
    /// released (or deleted) is in the asked-for state, so this succeeds.
    fn release(&self, claim: &SessionClaim) -> impl Future<Output = Result<()>> + Send;

    /// Refresh this replica's heartbeat, upserting its row and publishing
    /// `address` - the base URL peers forward this replica's sessions'
    /// commands to - when one is known.
    fn heartbeat(
        &self,
        replica: ReplicaId,
        address: Option<&ReplicaAddress>,
    ) -> impl Future<Output = Result<()>> + Send;

    /// What the lease says about a session, from `replica`'s viewpoint: who
    /// holds it (when a replica with a fresh heartbeat does - an absent
    /// holder covers both an unclaimed session and one whose holder has gone
    /// stale, either way claimable) and whether `replica` is itself draining.
    fn lease_view(
        &self,
        session: AgentSessionId,
        replica: ReplicaId,
    ) -> impl Future<Output = Result<LeaseView>> + Send;

    /// Publish that `replica` is shutting down, so nothing new is routed to
    /// it while it drains.
    ///
    /// A deploy's old task keeps heartbeating for its whole drain window, so
    /// liveness alone cannot tell a replica that is serving from one that is
    /// leaving; this is the replica saying which it is. Idempotent: the first
    /// drain wins, and a replica never un-drains.
    fn begin_draining(&self, replica: ReplicaId) -> impl Future<Output = Result<()>> + Send;
}

#[cfg_attr(feature = "test-utils", mockall::automock)]
pub trait AgentSessionLogRepo: Send + Sync + 'static {
    /// Append a frame and its authoritative fold projection atomically. A
    /// supplied claim fences both writes; history boundaries require a claim.
    /// `turn_state` is supplied only when the fold's state changes, avoiding
    /// a session-row write for every streamed token.
    fn create_projected<'a>(
        &'a self,
        log: AgentSessionLog,
        claim: Option<&'a SessionClaim>,
        boundary: Option<HistoryBoundary>,
        turn_state: Option<agent_fold::domain::model::TurnState>,
    ) -> impl Future<Output = Result<StoredAgentSessionLog>> + Send;

    /// Append a log entry and project any system event onto the session status.
    fn create(
        &self,
        log: AgentSessionLog,
    ) -> impl Future<Output = Result<StoredAgentSessionLog>> + Send;

    /// [`create`](Self::create), conditioned on `claim` still holding the
    /// session's current fence.
    ///
    /// This is the write half of the fencing contract: the check and the
    /// append are one atomic operation, so a replica that stalled past its
    /// heartbeat and was superseded cannot interleave frames no matter when
    /// it wakes - its append matches nothing and fails with
    /// [`FencedOut`](super::error::AgentSessionError::FencedOut), which the
    /// actor treats as its cue to tear down.
    fn create_fenced(
        &self,
        log: AgentSessionLog,
        claim: &SessionClaim,
    ) -> impl Future<Output = Result<StoredAgentSessionLog>> + Send;

    /// Append a successful load response and select its initialization atomically,
    /// under the current ownership fence. The boundary must belong to this session.
    fn create_fenced_with_boundary(
        &self,
        log: AgentSessionLog,
        claim: &SessionClaim,
        boundary: Option<HistoryBoundary>,
    ) -> impl Future<Output = Result<StoredAgentSessionLog>> + Send;

    /// Append a run of plain frames in one write, under the current
    /// ownership fence, and return them stamped as the log stored them.
    ///
    /// Plain means: nothing the store projects - no system event, no load
    /// boundary, no Cursor checkpoint. Those keep going through
    /// [`create_fenced_with_boundary`](Self::create_fenced_with_boundary)
    /// one at a time; this is the fast path for the streamed output that is
    /// the bulk of every session. Entries carry their ids already - the
    /// writer hands them out at append time so a caller has a durable
    /// identity before the flush lands - and arrive in append order, which
    /// the store must preserve in `(created_at, id)` order for readers.
    ///
    /// Every entry must belong to `claim`'s session. An empty batch is a
    /// no-op.
    fn create_batch_fenced(
        &self,
        entries: Vec<StoredAgentSessionLog>,
        claim: &SessionClaim,
    ) -> impl Future<Output = Result<Vec<StoredAgentSessionLog>>> + Send;

    /// List effective ACP history in deterministic `(created_at, id)` order.
    /// Starts at the latest successfully loaded initialization, or the beginning.
    /// Raw failed/partial replay frames remain; consumers must stage load attempts.
    /// The first returned row is the inclusive transport reconciliation cursor;
    /// buffered rows ordered before it are obsolete. An empty result has none.
    ///
    /// Entries come back stamped with when the log recorded them: the frame
    /// itself carries no time, and a reader ordering or merging a session's
    /// messages has nothing else to order them by.
    fn list_by_session(
        &self,
        agent_session_id: AgentSessionId,
    ) -> impl Future<Output = Result<Vec<StoredAgentSessionLog>>> + Send;

    /// A single snapshot of durable history when the action was prompted,
    /// or an empty snapshot when absent. Includes frames
    /// before a successful load. Internal action recovery needs their original
    /// request IDs, which replayed display history does not preserve.
    fn list_action_history(
        &self,
        agent_session_id: AgentSessionId,
        action: agent_runtime_protocol::domain::action::AgentActionId,
    ) -> impl Future<Output = Result<Vec<StoredAgentSessionLog>>> + Send;

    /// Every user the log has attributed a frame to: whoever prompted,
    /// answered, or otherwise drove the session. Distinct, unordered; the
    /// owner appears only if they acted. Spans the whole log, resumes
    /// included - someone who prompted before a resume still cares how it
    /// ends.
    fn participants(
        &self,
        agent_session_id: AgentSessionId,
    ) -> impl Future<Output = Result<Vec<MacroUserIdStr<'static>>>> + Send;
}

/// One tool a session's agent may call, as the MCP server offering it
/// describes it - the same name, description and parameter schema the agent
/// itself is shown.
#[derive(Debug, Clone, PartialEq)]
pub struct SessionToolDefinition {
    /// The name the agent calls the tool by, exactly as the server registers
    /// it for this session (an MCP tool arrives as `mcp__<server>__<tool>`).
    pub name: String,
    /// The description the agent chooses the tool on.
    pub description: String,
    /// The JSON schema of the tool's arguments.
    pub parameters: serde_json::Value,
}

/// Lists the tools a session's MCP servers advertise, so the session's
/// telemetry can say what the agent had to choose from
/// (`gen_ai.tool.definitions`).
///
/// Best-effort by contract: a listing that fails, or takes too long, costs
/// a span its tool definitions and nothing else. The one production
/// implementation dials the same egress-proxy URLs the agent is handed, in
/// process, so what it lists is what the agent sees - Macro's own tools and
/// the owner's connected apps alike. A harness's built-in tools (its shell,
/// its file editor) are not on any server and are not listed; the
/// convention does not require them.
///
/// Object-safe on purpose: the session service stores it erased so wiring it
/// is not another type parameter.
pub trait SessionToolCatalog: Send + Sync + 'static {
    /// Every tool the given servers offer. Empty when none do, or when the
    /// listing failed.
    fn tool_definitions(
        &self,
        servers: Vec<McpServer>,
    ) -> std::pin::Pin<Box<dyn Future<Output = Vec<SessionToolDefinition>> + Send + '_>>;
}

/// A [`SessionToolCatalog`] that lists nothing: tests, offline tooling, and
/// deployments with no in-process MCP client.
#[derive(Debug, Clone, Copy, Default)]
pub struct NoOpToolCatalog;

impl SessionToolCatalog for NoOpToolCatalog {
    fn tool_definitions(
        &self,
        _servers: Vec<McpServer>,
    ) -> std::pin::Pin<Box<dyn Future<Output = Vec<SessionToolDefinition>> + Send + '_>> {
        Box::pin(async { Vec::new() })
    }
}

/// One frame appended: its durable identity, and what the fold made of it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Appended {
    /// The log row the frame became.
    pub log_id: Uuid,
    /// What the frame meant for the turn, per the connection's live fold.
    /// Empty for most frames; never filled while catching up on history.
    pub signals: Vec<TurnSignal>,
}

/// Sequential live log writer owned by one session actor.
///
/// A writer may hold streamed frames back and both write and publish them in
/// runs: `append` returning `Ok` means the frame is durable *or buffered*,
/// and [`flush_deadline`](Self::flush_deadline) tells the owning actor when
/// the buffer must next be forced out with [`flush`](Self::flush).
pub trait AgentSessionLogWriter: Send + 'static {
    /// Persist the missing frames of a stable presentation and flush before acknowledging.
    fn present_tool(
        &mut self,
        id: AgentSessionId,
        acp_id: agent_client_protocol::schema::v1::SessionId,
        presentation: super::model::SessionToolPresentation,
    ) -> impl Future<Output = Result<()>> + Send {
        async move {
            let _ = (acp_id, presentation);
            Err(AgentSessionError::Disconnected(id))
        }
    }

    /// Persist and fold one frame into this connection's live projection.
    fn append(&mut self, log: AgentSessionLog) -> impl Future<Output = Result<Appended>> + Send {
        self.append_with_boundary(log, None)
    }

    /// Persist a frame and optional successful-load boundary in one transaction.
    /// Returns its durable row identity, and the turn signals the frame
    /// implied, before the actor continues.
    fn append_with_boundary(
        &mut self,
        log: AgentSessionLog,
        boundary: Option<HistoryBoundary>,
    ) -> impl Future<Output = Result<Appended>> + Send;

    /// Durably write any frames still held back, then push everything
    /// stored but unpublished to the session's viewers. A writer that holds
    /// nothing back has nothing to do.
    fn flush(&mut self) -> impl Future<Output = Result<()>> + Send {
        async { Ok(()) }
    }

    /// When held frames must be flushed by - `None` while nothing is held,
    /// so an idle writer never wakes its owner.
    fn flush_deadline(&self) -> Option<tokio::time::Instant> {
        None
    }
}

/// A session's queue changed; this is the whole queue as it stands now.
///
/// A snapshot rather than a delta so that any one event is self-sufficient:
/// a viewer applies the newest one it has seen and needs nothing else.
#[derive(Debug, Clone)]
pub struct AgentSessionQueueChanged {
    /// The session whose queue this is.
    pub agent_session_id: AgentSessionId,
    /// Everything waiting, oldest (next to dispatch) first.
    pub entries: Vec<QueuedControl>,
}

/// Pushing a live session's frames to whoever is watching it.
///
/// Separate from the durable log: that is what a reader arriving late fetches
/// and folds, while this tells a client already looking at the session what
/// just happened, so it can fold the frame and redraw without refetching.
///
/// Best-effort by contract. A dropped frame costs a viewer some liveness until
/// they reload, and the log it was derived from is already durable - so an
/// implementation may drop, and callers must not fail an append over it.
pub trait AgentSessionRealtime {
    /// Publish a run of appended frames to the session's viewers.
    fn publish(
        &self,
        event: LogAppended,
    ) -> impl Future<Output = Result<(), rootcause::Report>> + Send;

    /// Tell viewers to refetch changed session metadata and the durable log.
    fn publish_updated(
        &self,
        _session: AgentSessionId,
    ) -> impl Future<Output = Result<(), rootcause::Report>> + Send {
        async { Ok(()) }
    }

    /// Publish a user-facing name change to the session's viewers.
    fn publish_renamed(
        &self,
        _event: AgentSessionRenamed,
    ) -> impl Future<Output = Result<(), rootcause::Report>> + Send {
        async { Ok(()) }
    }

    /// Publish a session's changed queue - the whole queue, every time - to
    /// its viewers.
    fn publish_queue_changed(
        &self,
        _event: AgentSessionQueueChanged,
    ) -> impl Future<Output = Result<(), rootcause::Report>> + Send {
        async { Ok(()) }
    }

    /// Tell viewers the session's captured changes moved: a capture started,
    /// finished, or failed. Viewers refetch the changes summary.
    fn publish_changes_updated(
        &self,
        _session: AgentSessionId,
    ) -> impl Future<Output = Result<(), rootcause::Report>> + Send {
        async { Ok(()) }
    }
}

/// Publishing a session's lifecycle facts for anyone downstream: webhooks,
/// notifications, observability.
///
/// Best effort by contract: an implementation logs a failed publish and never
/// returns it, because nothing about the session itself went wrong. Object-
/// safe so the harness and this service can hold it erased rather than as one
/// more type parameter; the broker's `send_event` is generic and cannot be.
pub trait AgentSessionLifecyclePublisher: Send + Sync + 'static {
    /// Publish one fact. Resolves once the publish has been attempted.
    fn publish(
        &self,
        event: AgentSessionLifecycleEvent,
    ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>;
}

impl<Publisher: AgentSessionLifecyclePublisher + ?Sized> AgentSessionLifecyclePublisher
    for std::sync::Arc<Publisher>
{
    fn publish(
        &self,
        event: AgentSessionLifecycleEvent,
    ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
        (**self).publish(event)
    }
}

/// An [`AgentSessionLifecyclePublisher`] that publishes nothing: tests,
/// offline tooling, and replay.
#[derive(Debug, Clone, Copy, Default)]
pub struct NoopLifecyclePublisher;

impl AgentSessionLifecyclePublisher for NoopLifecyclePublisher {
    fn publish(
        &self,
        _event: AgentSessionLifecycleEvent,
    ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
        Box::pin(async {})
    }
}

/// Told what the session's log meant for its turn, and when its live actor
/// stops.
///
/// What the harness gates its prompt queue on: a turn ending means the agent
/// can take the next queued prompt, an actor stopping means no turn is in
/// flight anymore however the last one looked. Every method fires from the
/// actor's own task, so implementations must only hand the fact off -
/// enqueue, notify - never do the resulting work inline.
///
/// Turn signals come from the connection's live fold - the same fold the
/// chip renders from - so "the turn ended" has one definition. That includes
/// turns nobody here prompted: a resumed session's runtime reports those
/// with `_session/turn_complete`, and the fold closes them too.
///
/// Object-safe and synchronous on purpose: the service stores it erased so
/// wiring it is not another type parameter, and the one production
/// implementation admits work to a queue synchronously.
pub trait SessionTurnObserver: Send + Sync + 'static {
    /// A fold-derived fact about the session's turn.
    fn signal(&self, id: AgentSessionId, signal: TurnSignal);

    /// The session's live actor is gone - disconnect, teardown, or crash. Any
    /// in-flight turn went with it, without a [`TurnSignal::TurnEnded`].
    fn session_stopped(&self, id: AgentSessionId, reason: StopReason);

    /// The runtime reported, with `_session/closed`, that the person or agent
    /// deliberately ended the runtime session backing this session. Never
    /// told for a disconnect or crash; may be told again after a reconnect.
    fn runtime_closed(&self, id: AgentSessionId);
}

impl<T: SessionTurnObserver + ?Sized> SessionTurnObserver for std::sync::Arc<T> {
    fn signal(&self, id: AgentSessionId, signal: TurnSignal) {
        (**self).signal(id, signal);
    }

    fn session_stopped(&self, id: AgentSessionId, reason: StopReason) {
        (**self).session_stopped(id, reason);
    }

    fn runtime_closed(&self, id: AgentSessionId) {
        (**self).runtime_closed(id);
    }
}

/// Two observers told the same facts, in order. How the composition root
/// fans one session service's signals out to the harness (which drains its
/// queue on them) and to anything else that wants to know a turn ended.
impl<A: SessionTurnObserver, B: SessionTurnObserver> SessionTurnObserver for (A, B) {
    fn signal(&self, id: AgentSessionId, signal: TurnSignal) {
        self.0.signal(id, signal.clone());
        self.1.signal(id, signal);
    }

    fn session_stopped(&self, id: AgentSessionId, reason: StopReason) {
        self.0.session_stopped(id, reason.clone());
        self.1.session_stopped(id, reason);
    }

    fn runtime_closed(&self, id: AgentSessionId) {
        self.0.runtime_closed(id);
        self.1.runtime_closed(id);
    }
}

/// A [`SessionTurnObserver`] for services with no queue above them: tests,
/// offline tooling, and replay.
#[derive(Debug, Clone, Copy, Default)]
pub struct NoOpTurnObserver;

impl SessionTurnObserver for NoOpTurnObserver {
    fn signal(&self, _id: AgentSessionId, _signal: TurnSignal) {}

    fn session_stopped(&self, _id: AgentSessionId, _reason: StopReason) {}

    fn runtime_closed(&self, _id: AgentSessionId) {}
}

/// A [`SessionTurnObserver`] bound after construction, for the composition
/// root's chicken-and-egg: the session service wants its observer at build
/// time, and the observer (the harness) is built *from* the session service.
///
/// Events before `bind` are dropped. That window is the instants between the
/// two constructions, before anything serves traffic - nothing turns then.
#[derive(Default)]
pub struct LateBoundTurnObserver {
    observer: std::sync::OnceLock<Box<dyn SessionTurnObserver>>,
}

impl LateBoundTurnObserver {
    /// An observer awaiting its target.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Attach the real observer. A second bind is a wiring bug; the first
    /// stays authoritative and the duplicate is dropped.
    pub fn bind(&self, observer: impl SessionTurnObserver) {
        let _ = self.observer.set(Box::new(observer));
    }
}

impl SessionTurnObserver for LateBoundTurnObserver {
    fn signal(&self, id: AgentSessionId, signal: TurnSignal) {
        if let Some(observer) = self.observer.get() {
            observer.signal(id, signal);
        }
    }

    fn session_stopped(&self, id: AgentSessionId, reason: StopReason) {
        if let Some(observer) = self.observer.get() {
            observer.session_stopped(id, reason);
        }
    }

    fn runtime_closed(&self, id: AgentSessionId) {
        if let Some(observer) = self.observer.get() {
            observer.runtime_closed(id);
        }
    }
}

/// Generates a concise display name from a session's first prompt, and
/// replaces it once the conversation has outgrown it.
pub trait AgentSessionNameGenerator: Send + Sync + 'static {
    /// Generate a name, or `None` when naming is disabled for this service.
    fn generate_name(
        &self,
        session: &AgentSession,
        initial_prompt: &str,
    ) -> impl Future<Output = Result<Option<String>, rootcause::Report>> + Send;

    /// A name that describes the conversation better than `current`, or
    /// `None` to keep it. Asked after every finished turn of a session whose
    /// name was generated, so a name should change only when it has clearly
    /// stopped fitting. Keeps every name by default.
    fn retitle(
        &self,
        _session: &AgentSession,
        _current: &str,
        _conversation: &super::retitle::ConversationDigest,
    ) -> impl Future<Output = Result<Option<String>, rootcause::Report>> + Send {
        async { Ok(None) }
    }
}

/// Disables automatic agent-session naming.
#[derive(Debug, Clone, Copy, Default)]
pub struct NoOpAgentSessionNameGenerator;

impl AgentSessionNameGenerator for NoOpAgentSessionNameGenerator {
    async fn generate_name(
        &self,
        _session: &AgentSession,
        _initial_prompt: &str,
    ) -> Result<Option<String>, rootcause::Report> {
        Ok(None)
    }
}

/// An [`AgentSessionRealtime`] that streams nowhere.
///
/// Dropping every frame is a legal implementation of the port - it is
/// best-effort by contract - so this is what a writer with no viewers to serve
/// gets: `seed_jsonl` replaying a recording into the database, and tests that
/// are asserting on the durable side of an append.
#[derive(Debug, Clone, Copy, Default)]
pub struct NoOpRealtime;

impl AgentSessionRealtime for NoOpRealtime {
    async fn publish(&self, _event: LogAppended) -> Result<(), rootcause::Report> {
        Ok(())
    }
}

/// One control operation, and who is responsible for it.
#[derive(Debug, Clone)]
pub struct ControlEvent {
    /// What the agent was asked to do.
    pub action: AgentAction,
    /// The id the caller already speculated this action under, when it minted
    /// one. Adopted as the accepted id so the caller's optimistic entry is
    /// promoted in place rather than retracted and reissued; `None` leaves
    /// the recipient to mint one.
    pub action_id: Option<AgentActionId>,
    /// The user responsible, absent when a bot acted on nobody's behalf.
    ///
    /// `None` means "no user is responsible", not "unknown" - a bot's own
    /// actions are attributed to the bot, which this field does not carry.
    pub actor: Option<MacroUserIdStr<'static>>,
    /// Why the agent is being asked, when a runtime forwards a triggered
    /// prompt. Users driving a session directly supply none.
    pub context: Option<trigger_context::TriggerContext>,
}

/// What accepting a control operation did with it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ControlDisposition {
    /// The action reached the agent's runtime.
    Sent,
    /// A turn was running, so the action waits in the session's queue and
    /// dispatches when that turn ends. Until then it can be listed, edited,
    /// and removed under its action id.
    Queued,
}

/// A control operation the recipient accepted: the id a caller correlates
/// with, and what became of it.
#[derive(Debug, Clone)]
pub struct AcceptedControl {
    /// Matches `requestId` on the folded message the action derives once it
    /// dispatches, and names the queue entry until then.
    pub action_id: AgentActionId,
    /// Whether it went out or waits.
    pub disposition: ControlDisposition,
}

/// One action waiting in a session's queue, as a reader sees it.
#[derive(Debug, Clone)]
pub struct QueuedControl {
    /// The id the action was accepted under.
    pub action_id: AgentActionId,
    /// What will be delivered - a prompt's text is the raw user text, which
    /// is what editing replaces.
    pub action: AgentAction,
    /// The user who queued it, absent when a bot acted on nobody's behalf.
    pub actor: Option<MacroUserIdStr<'static>>,
    /// When it was accepted.
    pub created_at: chrono::DateTime<chrono::Utc>,
}

/// Whoever holds a session's live resources, told when the durable session
/// changes in a way those resources have to follow.
///
/// In-process today: a session's actor and its container live in one address
/// space, so only the process that opened the session can act on this. The
/// port exists so that coupling is named rather than assumed, and so the
/// control routes can be mounted against it without knowing what a harness is.
#[cfg_attr(feature = "test-utils", mockall::automock)]
pub trait AgentSessionNotificationRecipient: Send + Sync + 'static {
    /// Persist a nonblocking tool presentation through the owning session actor.
    fn present_tool(
        &self,
        id: AgentSessionId,
        actor: MacroUserIdStr<'static>,
        presentation: super::model::SessionToolPresentation,
    ) -> impl Future<Output = Result<()>> + Send {
        async move {
            let _ = (actor, presentation);
            Err(AgentSessionError::Disconnected(id))
        }
    }

    /// Release and delete every session owned by a user before account deletion.
    /// Internal account lifecycle only; shared sessions owned by others are untouched.
    fn delete_user_sessions(
        &self,
        owner: MacroUserIdStr<'static>,
    ) -> impl Future<Output = Result<()>> + Send;

    /// The session is going away: release its live resources and delete it.
    fn session_deleted(&self, id: AgentSessionId) -> impl Future<Output = Result<()>> + Send;

    /// Release and delete one session while `expected_owner` still owns it.
    /// Internal owner removal only. A missing session is already purged; one
    /// under another owner is untouched.
    fn purge_owned_session(
        &self,
        id: AgentSessionId,
        expected_owner: &Owner,
    ) -> impl Future<Output = Result<OwnedPurgeOutcome>> + Send;

    /// A control operation the live connection has to be told about. Returns
    /// the action id the caller correlates against the fold stream, and
    /// whether the action went out or waits in the session's queue.
    ///
    /// A caller-supplied [`ControlEvent::action_id`] is adopted as that id.
    /// Re-sending an action under an id the session still has queued or in
    /// flight reports what became of the first one instead of accepting a
    /// second, so a retried request cannot double-prompt.
    fn control_event(
        &self,
        id: AgentSessionId,
        event: ControlEvent,
    ) -> impl Future<Output = Result<AcceptedControl>> + Send;

    /// The actions waiting in this session's queue, oldest first.
    fn queued_controls(
        &self,
        id: AgentSessionId,
    ) -> impl Future<Output = Result<Vec<QueuedControl>>> + Send;

    /// Replace a queued prompt's text. [`AgentSessionError::QueuedControlNotFound`]
    /// once it has dispatched; [`AgentSessionError::QueuedControlNotEditable`]
    /// for a queued action that carries no text.
    ///
    /// `actor` is the user responsible, judged by the same gates as sending:
    /// whoever may not prompt a session may not rewrite what it is about to
    /// be prompted with.
    fn edit_queued_control(
        &self,
        id: AgentSessionId,
        action_id: AgentActionId,
        prompt: String,
        actor: Option<MacroUserIdStr<'static>>,
    ) -> impl Future<Output = Result<()>> + Send;

    /// Remove a queued action before it dispatches.
    /// [`AgentSessionError::QueuedControlNotFound`] once it has. `actor` as
    /// on [`Self::edit_queued_control`].
    fn remove_queued_control(
        &self,
        id: AgentSessionId,
        action_id: AgentActionId,
        actor: Option<MacroUserIdStr<'static>>,
    ) -> impl Future<Output = Result<()>> + Send;

    /// Run a queued action next. Moves it to the front of the queue and, when
    /// a turn is in flight, cancels that turn so this entry dispatches ahead
    /// of anything queued before it. [`AgentSessionError::QueuedControlNotFound`]
    /// once it has dispatched. `actor` as on [`Self::edit_queued_control`].
    fn steer_queued_control(
        &self,
        id: AgentSessionId,
        action_id: AgentActionId,
        actor: Option<MacroUserIdStr<'static>>,
    ) -> impl Future<Output = Result<()>> + Send;

    /// Resize this session's sandbox and remember `size` as the owner's default.
    fn set_sandbox_size(
        &self,
        id: AgentSessionId,
        size: SandboxSize,
    ) -> impl Future<Output = Result<()>> + Send;

    /// The harness currently bound to serve this session, resolved through its
    /// bot's binding. `None` for a managed session or an unbound bot.
    ///
    /// The control routes use it to confine a harness caller to the sessions
    /// its own daemon serves: ownership alone would let a harness that merely
    /// acts for a user drive or delete sessions another harness serves for the
    /// same user.
    fn session_harness(
        &self,
        id: AgentSessionId,
    ) -> impl Future<Output = Result<Option<harness_id::HarnessId>>> + Send;
}

#[cfg(test)]
mod test;

/// Current view access to a session, resolved the way a read route resolves
/// it - including share links and access inherited from the document a session
/// was opened from, which no access row materializes.
///
/// Object-safe so the service holds it erased, like its turn observer.
pub trait SessionViewAccess: Send + Sync + 'static {
    /// Whether `viewer` may currently view `session`.
    fn can_view<'a>(
        &'a self,
        viewer: &'a MacroUserIdStr<'static>,
        session: AgentSessionId,
    ) -> Pin<Box<dyn Future<Output = Result<bool>> + Send + 'a>>;
}

/// Only materialized grants count: a process with no entity-access service,
/// or a test, never discovers link or inherited access.
#[derive(Debug, Clone, Copy, Default)]
pub struct NoInheritedSessionAccess;

impl SessionViewAccess for NoInheritedSessionAccess {
    fn can_view<'a>(
        &'a self,
        _viewer: &'a MacroUserIdStr<'static>,
        _session: AgentSessionId,
    ) -> Pin<Box<dyn Future<Output = Result<bool>> + Send + 'a>> {
        Box::pin(async { Ok(false) })
    }
}