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.

47.1 KB
Raw Blame
//! The machine itself: one input in, ordered effects out.

use std::collections::{HashMap, VecDeque};

use agent_client_protocol::schema::v1::{
    ClientCapabilities, CreateElicitationRequest, CreateElicitationResponse, ElicitationAction,
    ElicitationCapabilities, ElicitationFormCapabilities, ElicitationMode, ElicitationScope,
    ElicitationUrlCapabilities, InitializeRequest, InitializeResponse, LoadSessionRequest,
    LoadSessionResponse, McpServer, NewSessionRequest, NewSessionResponse, PermissionOptionId,
    PermissionOptionKind, RequestId, RequestPermissionOutcome, RequestPermissionRequest, Response,
    ResumeSessionRequest, ResumeSessionResponse, SelectedPermissionOutcome, SessionConfigKind,
    SessionId, SetSessionConfigOptionResponse,
};
use agent_client_protocol::{JsonRpcMessage, RawJsonRpcMessage};
use agent_runtime_protocol::domain::action::{
    AgentAction, AgentActionId, AgentPermissionAction, MODEL_CONFIG_ID, PermissionAnswer,
    permission_response,
};
use agent_runtime_protocol::domain::schema::v0::{
    AcpMessage, SystemEvent, ToRuntimeMessage, ToServerMessage,
};
use agent_runtime_protocol::domain::turn::RuntimeSessionClosedNotification;
use macro_user_id::user_id::MacroUserIdStr;

use crate::PROTOCOL_VERSION;
use crate::domain::error::AgentSessionError;
use crate::domain::model::{
    AgentSessionId, MACRO_AGENT_SESSION_META_KEY, MACRO_PERMISSION_POLICY_META_KEY,
};

use super::types::{
    CloseReason, Effect, Input, OutstandingPermission, PendingAction, PendingElicitation,
    PermissionPolicy, RuntimeStatus, SessionOpening, SessionPhase, SessionRestoreSupport,
    StopReason,
};

const INITIAL_REQUEST_NUM: u64 = 0;

/// Protocol state for one connection of a session to an agent runtime.
///
/// See the [module docs](super) for scope and the sans-IO contract.
pub struct SessionMachine<Token> {
    id: AgentSessionId,
    initialization: Option<crate::domain::model::HistoryBoundary>,
    phase: SessionPhase,
    next_request: u64,
    connection_context: Option<macro_uuid::Uuid>,
    /// Held outside the phase so a partial flush strands nothing.
    pending: VecDeque<PendingAction<Token>>,
    /// The newest turn-occupying request the runtime has not answered yet.
    /// The harness dispatches its queue one turn at a time, so there is at
    /// most one in the ordinary course; a direct `send_action` caller racing
    /// the previous turn's answer displaces the old entry (see
    /// [`Self::flush`]). Its response - result or error alike - is what emits
    /// [`Effect::TurnEnded`].
    in_flight_turn: Option<(RequestId, AgentActionId)>,
    resume_session_id: Option<SessionId>,
    reload_required: bool,
    /// Directory the agent works in, snapshotted on the session row at
    /// creation; `session/new`, `session/resume`, and `session/load` all
    /// carry it, so a reconnect re-enters the directory the session
    /// actually ran in.
    workspace: String,
    /// MCP servers the agent is told to connect to. Carried by `session/new`,
    /// `session/resume`, and `session/load` alike, because the agent process
    /// behind a reconnect is fresh and holds no server from before.
    mcp_servers: Vec<McpServer>,
    /// `mcp_servers` changed after the request that opened this session went
    /// out, so the agent still has the old list. Settled by re-resuming the
    /// live session between turns; see [`Self::begin_mcp_refresh`].
    mcp_refresh_required: bool,
    /// What the connection's `initialize` said about restoring sessions;
    /// `None` until this machine opens. A refresh needs `session/resume`.
    restore: Option<SessionRestoreSupport>,
    permission_policy: PermissionPolicy,
    /// Only for a newly created ACP session; restored sessions retain their model.
    initial_model: Option<String>,
    /// Permission requests the agent is waiting on, keyed by the agent's own
    /// request id - the id an answer has to echo. Only ever populated under
    /// [`PermissionPolicy::Prompt`]; auto-accept answers on arrival.
    outstanding_permissions: HashMap<RequestId, OutstandingPermission>,
}

impl<Token> SessionMachine<Token> {
    /// A fresh connection for `id`: booting, nothing queued.
    pub fn new(
        id: AgentSessionId,
        workspace: String,
        mcp_servers: Vec<McpServer>,
        permission_policy: PermissionPolicy,
    ) -> Self {
        Self {
            id,
            initialization: None,
            phase: SessionPhase::Booting,
            next_request: INITIAL_REQUEST_NUM,
            connection_context: None,
            pending: VecDeque::new(),
            in_flight_turn: None,
            resume_session_id: None,
            reload_required: false,
            workspace,
            mcp_servers,
            mcp_refresh_required: false,
            restore: None,
            permission_policy,
            initial_model: None,
            outstanding_permissions: HashMap::new(),
        }
    }

    /// A fresh connection that must restore an existing ACP session.
    pub fn resume(
        id: AgentSessionId,
        session_id: SessionId,
        workspace: String,
        mcp_servers: Vec<McpServer>,
        permission_policy: PermissionPolicy,
    ) -> Self {
        Self {
            id,
            initialization: None,
            phase: SessionPhase::Booting,
            next_request: INITIAL_REQUEST_NUM,
            connection_context: None,
            pending: VecDeque::new(),
            in_flight_turn: None,
            resume_session_id: Some(session_id),
            reload_required: false,
            workspace,
            mcp_servers,
            mcp_refresh_required: false,
            restore: None,
            permission_policy,
            initial_model: None,
            outstanding_permissions: HashMap::new(),
        }
    }

    /// Select this model before releasing prompts on a newly created ACP session.
    #[must_use]
    pub fn with_initial_model(mut self, model: Option<String>) -> Self {
        self.initial_model = model;
        self
    }

    /// The session this connection belongs to.
    pub fn id(&self) -> AgentSessionId {
        self.id
    }

    /// Namespace request IDs for a fresh actor on a potentially shared transport.
    pub(crate) fn with_connection_context(mut self, context: macro_uuid::Uuid) -> Self {
        self.connection_context = Some(context);
        self
    }

    /// Retain the durable initialization identity for this actor's connection.
    pub fn initialization_persisted(&mut self, id: macro_uuid::Uuid) {
        self.initialization = Some(crate::domain::model::HistoryBoundary {
            initialization_log_id: id,
        });
    }

    /// Current phase.
    pub fn status(&self) -> RuntimeStatus {
        match &self.phase {
            SessionPhase::Booting => RuntimeStatus::Booting,
            SessionPhase::Initializing { .. }
            | SessionPhase::Opening { .. }
            | SessionPhase::ConfiguringModel { .. } => RuntimeStatus::Handshaking,
            SessionPhase::Live { session_id, .. } => RuntimeStatus::Live {
                session_id: session_id.clone(),
            },
            SessionPhase::Dead => RuntimeStatus::Dead,
        }
    }

    /// Number of accepted actions that have not reached the transport.
    pub fn pending_count(&self) -> usize {
        self.pending.len()
    }

    /// The id of the elicitation this connection is holding for the user, if
    /// any.
    pub fn pending_elicitation(&self) -> Option<&RequestId> {
        match &self.phase {
            SessionPhase::Live {
                elicitation: Some(pending),
                ..
            } => Some(&pending.request_id),
            _ => None,
        }
    }

    /// Advance the machine by one input, returning the effects it implies.
    pub fn handle(&mut self, input: Input<Token>) -> Vec<Effect<Token>> {
        match input {
            Input::Command {
                from,
                action,
                action_id,
                token,
            } => self.on_command(from, action, action_id, token),
            Input::Inbound(message) => self.on_inbound(message),
            Input::Ready { restore } => self.on_connection_ready(restore),
            Input::SharedReady { restore, context } => {
                if !matches!(self.phase, SessionPhase::Booting) {
                    return vec![];
                }
                let mut effects = vec![Effect::EstablishInitialization { context }];
                self.begin_opening(restore, &mut effects);
                effects
            }
            Input::ReplaceMcpServers(servers) => self.on_mcp_servers_replaced(servers),
            Input::SetPermissionPolicy(policy) => {
                self.permission_policy = policy;
                vec![]
            }
            Input::Closed(reason) => self.on_closed(reason),
        }
    }

    fn on_mcp_servers_replaced(&mut self, servers: Vec<McpServer>) -> Vec<Effect<Token>> {
        let mut effects = Vec::new();
        if servers == self.mcp_servers {
            return effects;
        }
        self.mcp_servers = servers;
        match self.phase {
            // The opening request has not gone out yet, and will carry them.
            SessionPhase::Booting | SessionPhase::Initializing { .. } | SessionPhase::Dead => {}
            SessionPhase::Opening { .. } | SessionPhase::ConfiguringModel { .. } => {
                self.mcp_refresh_required = true;
            }
            SessionPhase::Live { .. } => {
                self.mcp_refresh_required = true;
                self.begin_mcp_refresh(&mut effects);
            }
        }
        effects
    }

    /// Re-resume the live session so the agent picks up `mcp_servers`.
    ///
    /// Only between turns and with no question open: a resume mid-turn would
    /// race the prompt it interrupts, so a turn in flight leaves the refresh
    /// for its end, and a held elicitation for its answer. Actions
    /// arriving meanwhile queue behind the resume, so the next prompt runs
    /// with the new servers. An agent that cannot resume, or refuses, is not
    /// asked again until the list changes. Returns whether a resume went out.
    fn begin_mcp_refresh(&mut self, effects: &mut Vec<Effect<Token>>) -> bool {
        if !self.mcp_refresh_required || self.in_flight_turn.is_some() {
            return false;
        }
        let SessionPhase::Live {
            session_id,
            elicitation: None,
        } = &self.phase
        else {
            return false;
        };
        let session_id = session_id.clone();
        self.mcp_refresh_required = false;
        if !self.restore.is_some_and(|restore| restore.resume) {
            tracing::warn!(
                id = %self.id,
                "the agent cannot resume a session; its new MCP servers wait for the next attach"
            );
            return false;
        }
        match self.build_session_request(
            self.resume_request(session_id.clone()),
            SessionOpening::Refresh(session_id),
        ) {
            Ok((resume, request_id, kind)) => {
                effects.push(Effect::Send {
                    from: None,
                    message: ToRuntimeMessage::Acp(AcpMessage(resume)),
                });
                self.phase = SessionPhase::Opening { request_id, kind };
                true
            }
            Err(error) => {
                tracing::error!(
                    error = ?error,
                    id = %self.id,
                    "could not build the session/resume that hands over new MCP servers"
                );
                false
            }
        }
    }

    /// Open on a connection somebody else initialized.
    ///
    /// Ignored unless still booting: the machine that ran the handshake is
    /// told its own result this way too, and a session already opening or
    /// live has nothing to learn from it.
    fn on_connection_ready(&mut self, restore: SessionRestoreSupport) -> Vec<Effect<Token>> {
        let mut effects = Vec::new();
        if matches!(self.phase, SessionPhase::Booting) {
            self.begin_opening(restore, &mut effects);
        }
        effects
    }

    fn on_command(
        &mut self,
        from: Option<MacroUserIdStr<'static>>,
        action: AgentAction,
        action_id: AgentActionId,
        token: Token,
    ) -> Vec<Effect<Token>> {
        let mut effects = Vec::new();

        // An answer is not a request of ours to queue and mint an id for: it
        // resolves one the agent made, and it is only ever valid while that
        // request is open, which cannot be before the session is live.
        if let AgentAction::RespondToPermission(answer) = &action {
            self.on_permission_answer(from, answer, token, &mut effects);
            return effects;
        }
        // A stop cancels the question the agent is waiting on, and does so
        // before the cancel notification goes out, so the agent hears the
        // answer to its request before it hears that the turn is over.
        if matches!(action, AgentAction::Stop) {
            self.cancel_pending_elicitation(from.clone(), &mut effects);
        }

        let session_id = match &self.phase {
            SessionPhase::Booting
            | SessionPhase::Initializing { .. }
            | SessionPhase::Opening { .. }
            | SessionPhase::ConfiguringModel { .. } => {
                // An answer cannot be queued: it names a request id that only
                // a live connection could have received, and any connection
                // that opens from here is a fresh one.
                if let AgentAction::RespondElicitation(_) = &action {
                    effects.push(Effect::Complete {
                        token,
                        result: Err(AgentSessionError::ElicitationNotPending(self.id)),
                    });
                    return effects;
                }
                self.pending.push_back(PendingAction {
                    from,
                    action,
                    action_id,
                    token,
                });
                return effects;
            }
            SessionPhase::Live { session_id, .. } => session_id.clone(),
            SessionPhase::Dead => {
                effects.push(Effect::Complete {
                    token,
                    result: Err(AgentSessionError::Disconnected(self.id)),
                });
                return effects;
            }
        };

        // An answer must match the one elicitation being held, and answering
        // it releases the slot before the response goes out.
        if let AgentAction::RespondElicitation(answer) = &action {
            let matches = matches!(
                &self.phase,
                SessionPhase::Live { elicitation: Some(pending), .. }
                    if pending.request_id == answer.request_id.to_request_id()
            );
            if !matches {
                effects.push(Effect::Complete {
                    token,
                    result: Err(AgentSessionError::ElicitationNotPending(self.id)),
                });
                return effects;
            }
            if let SessionPhase::Live { elicitation, .. } = &mut self.phase {
                *elicitation = None;
            }
        }

        let answers_elicitation = matches!(action, AgentAction::RespondElicitation(_));
        // Through the queue even when live, so an action can never overtake
        // one accepted earlier. (A completed flush leaves the queue empty, so
        // the flush below sends exactly this action.)
        self.pending.push_back(PendingAction {
            from,
            action,
            action_id,
            token,
        });
        self.flush(&session_id, &mut effects);
        // A refresh held back by the question can go now that it is answered.
        if answers_elicitation {
            self.begin_mcp_refresh(&mut effects);
        }
        effects
    }

    fn on_inbound(&mut self, message: ToServerMessage) -> Vec<Effect<Token>> {
        // Host-local recovery is a command to this machine, not a user-facing
        // runtime status or a history replacement frame.
        if matches!(
            message,
            ToServerMessage::Event {
                event: SystemEvent::ReloadRequired
            }
        ) {
            let mut effects = Vec::new();
            if !matches!(self.phase, SessionPhase::Dead) {
                self.reload_required = true;
                if self.in_flight_turn.is_none() {
                    self.begin_reload(&mut effects);
                }
            }
            return effects;
        }
        // Every inbound message is logged, before anything reacts to it: the
        // log stream is the session's history, not a digest of it.
        let mut effects = vec![Effect::Log {
            boundary: None,
            message: message.clone(),
        }];

        match message {
            ToServerMessage::Event {
                event: SystemEvent::AcpReady,
            } => self.begin_handshake(&mut effects),
            ToServerMessage::Acp(AcpMessage(frame)) => self.on_frame(frame, &mut effects),
            _ => {}
        }

        effects
    }

    fn on_closed(&mut self, reason: CloseReason) -> Vec<Effect<Token>> {
        if matches!(self.phase, SessionPhase::Dead) {
            return Vec::new();
        }
        let mut effects = Vec::new();
        self.die(StopReason::Closed(reason), &mut effects);
        effects
    }

    fn begin_reload(&mut self, effects: &mut Vec<Effect<Token>>) {
        let SessionPhase::Live { session_id, .. } = &self.phase else {
            return;
        };
        self.resume_session_id = Some(session_id.clone());
        self.initialization = None;
        self.phase = SessionPhase::Booting;
        self.begin_handshake(effects);
    }

    /// Ready starts initialization; actions remain queued until `session/new` completes.
    fn begin_handshake(&mut self, effects: &mut Vec<Effect<Token>>) {
        if !matches!(self.phase, SessionPhase::Booting) {
            return;
        }
        // Request ids restart with the connection, so nothing recorded before
        // it could be answered now. Empty in practice; cleared on principle.
        self.outstanding_permissions.clear();

        match self.build_initialize_request() {
            Ok((initialize, request_id)) => {
                effects.push(Effect::Send {
                    from: None,
                    message: ToRuntimeMessage::Acp(AcpMessage(initialize)),
                });
                self.phase = SessionPhase::Initializing { request_id };
            }
            Err(error) => self.die(
                StopReason::HandshakeNotBuildable(error.to_string()),
                effects,
            ),
        }
    }

    fn on_frame(&mut self, frame: RawJsonRpcMessage, effects: &mut Vec<Effect<Token>>) {
        if matches!(self.phase, SessionPhase::Live { .. }) {
            // The in-flight turn's answer ends the turn whichever shape it
            // takes: a result carries the stop reason, an error is the agent
            // refusing the prompt. The fold reads the frame from the log and
            // signals the end; the machine only lets go of the turn.
            if let Some((request_id, _)) = &self.in_flight_turn
                && frame.response_id() == Some(request_id)
            {
                self.in_flight_turn = None;
                self.cancel_outstanding_permissions(effects);
                if self.reload_required {
                    self.begin_reload(effects);
                } else {
                    self.begin_mcp_refresh(effects);
                }
                return;
            }
            if self.reports_runtime_closed(&frame) {
                effects.push(Effect::RuntimeClosed);
                return;
            }
            self.on_permission_request(&frame, effects);
            self.hold_or_refuse_elicitation(&frame, effects);
            return;
        }

        match &self.phase {
            SessionPhase::Initializing { request_id }
                if frame.response_id() == Some(request_id) =>
            {
                self.on_initialized(&frame, effects);
            }
            SessionPhase::Opening { request_id, .. } if frame.response_id() == Some(request_id) => {
                self.on_session_opened(&frame, effects);
            }
            SessionPhase::ConfiguringModel { request_id, .. }
                if frame.response_id() == Some(request_id) =>
            {
                self.on_model_selected(&frame, effects);
            }
            _ => {}
        }
    }

    fn on_initialized(&mut self, frame: &RawJsonRpcMessage, effects: &mut Vec<Effect<Token>>) {
        let RawJsonRpcMessage::Response(Response::Result { result, .. }) = &frame else {
            self.die(StopReason::InitializationRefused, effects);
            return;
        };
        let response = match serde_json::from_value::<InitializeResponse>(result.clone()) {
            Ok(response) => response,
            Err(error) => {
                self.die(
                    StopReason::InitializationUnintelligible(error.to_string()),
                    effects,
                );
                return;
            }
        };

        let restore = SessionRestoreSupport::of(&response);
        // Announced before this session opens: every other session on this
        // connection needs the same answer, and only this machine was told it.
        effects.push(Effect::Initialized { restore });
        self.begin_opening(restore, effects);
        // The load about to start covers every recovery observed so far. A
        // later signal while its reply is queued requires another load.
        self.reload_required = false;
    }

    /// Ask the agent for this session, however it has to be established.
    fn begin_opening(&mut self, restore: SessionRestoreSupport, effects: &mut Vec<Effect<Token>>) {
        self.restore = Some(restore);
        // Whichever request opens the session carries the current list.
        self.mcp_refresh_required = false;
        let opening = match self.resume_session_id.clone() {
            Some(session_id) if restore.resume && !self.reload_required => {
                self.build_resume_session_request(session_id)
            }
            Some(session_id) if restore.load => self.build_load_session_request(session_id),
            Some(_) => {
                self.resume_unsupported(effects);
                return;
            }
            None => self.build_new_session_request(),
        };

        match opening {
            Ok((open, request_id, kind)) => {
                effects.push(Effect::Send {
                    from: None,
                    message: ToRuntimeMessage::Acp(AcpMessage(open)),
                });
                self.phase = SessionPhase::Opening { request_id, kind };
            }
            Err(error) => {
                self.die(
                    StopReason::HandshakeNotBuildable(error.to_string()),
                    effects,
                );
            }
        }
    }

    fn on_session_opened(&mut self, frame: &RawJsonRpcMessage, effects: &mut Vec<Effect<Token>>) {
        if let SessionPhase::Opening {
            kind: SessionOpening::Refresh(session_id),
            ..
        } = &self.phase
        {
            // The session was live before this resume and the agent still
            // holds it either way; a refusal only means the old servers stay.
            let session_id = session_id.clone();
            if !matches!(frame, RawJsonRpcMessage::Response(Response::Result { .. })) {
                tracing::warn!(
                    id = %self.id,
                    "the agent refused new MCP servers; the session keeps the ones it had"
                );
            }
            self.finish_opening(session_id, effects);
            return;
        }
        let RawJsonRpcMessage::Response(Response::Result { result, .. }) = frame else {
            self.die(StopReason::SessionRefused, effects);
            return;
        };
        let kind = match &self.phase {
            SessionPhase::Opening { kind, .. } => kind.clone(),
            _ => return,
        };
        let (session_id, persist) = match kind {
            SessionOpening::New => {
                match serde_json::from_value::<NewSessionResponse>(result.clone()) {
                    Ok(response) => (response.session_id, true),
                    Err(error) => {
                        self.die(
                            StopReason::SessionUnintelligible(error.to_string()),
                            effects,
                        );
                        return;
                    }
                }
            }
            SessionOpening::Resume(session_id) => {
                if let Err(error) = serde_json::from_value::<ResumeSessionResponse>(result.clone())
                {
                    self.die(
                        StopReason::SessionUnintelligible(error.to_string()),
                        effects,
                    );
                    return;
                }
                (session_id, false)
            }
            SessionOpening::Refresh(_) => unreachable!("answered before the shared opening path"),
            SessionOpening::Load(session_id) => {
                if let Err(error) = serde_json::from_value::<LoadSessionResponse>(result.clone()) {
                    self.die(
                        StopReason::SessionUnintelligible(error.to_string()),
                        effects,
                    );
                    return;
                }
                let Some(initialization) = self.initialization else {
                    self.die(StopReason::InitializationNotPersisted, effects);
                    return;
                };
                // Only a matching, well-formed successful load selects history.
                // The actor executes this log effect before any readiness side effect.
                if let Some(Effect::Log { boundary, .. }) = effects.first_mut() {
                    *boundary = Some(initialization);
                }
                (session_id, false)
            }
        };

        if persist {
            if let Some(model) = self.initial_model.take() {
                let request_id = self.next_id();
                match AgentAction::set_model(&model).to_runtime(&session_id, request_id.clone()) {
                    Ok(message) => {
                        self.phase = SessionPhase::ConfiguringModel {
                            request_id,
                            session_id,
                            model,
                        };
                        effects.push(Effect::Send {
                            from: None,
                            message,
                        });
                    }
                    Err(error) => self.die(
                        StopReason::HandshakeNotBuildable(error.to_string()),
                        effects,
                    ),
                }
                return;
            }
            effects.push(Effect::PersistAcpSession {
                session_id: session_id.clone(),
            });
        }
        self.finish_opening(session_id, effects);
    }

    fn on_model_selected(&mut self, frame: &RawJsonRpcMessage, effects: &mut Vec<Effect<Token>>) {
        let SessionPhase::ConfiguringModel {
            session_id, model, ..
        } = &self.phase
        else {
            return;
        };
        let selected = match frame {
            RawJsonRpcMessage::Response(Response::Result { result, .. }) => {
                serde_json::from_value::<SetSessionConfigOptionResponse>(result.clone())
                    .ok()
                    .is_some_and(|response| {
                        response.config_options.iter().any(|option| {
                            option.id.to_string() == MODEL_CONFIG_ID
                                && matches!(&option.kind, SessionConfigKind::Select(select)
                                if select.current_value.to_string() == *model)
                        })
                    })
            }
            _ => false,
        };
        if !selected {
            self.die(StopReason::ModelNotSelected(model.clone()), effects);
            return;
        }
        let session_id = session_id.clone();
        effects.push(Effect::PersistAcpSession {
            session_id: session_id.clone(),
        });
        self.finish_opening(session_id, effects);
    }

    fn finish_opening(&mut self, session_id: SessionId, effects: &mut Vec<Effect<Token>>) {
        self.phase = SessionPhase::Live {
            session_id: session_id.clone(),
            elicitation: None,
        };
        if self.reload_required {
            self.begin_reload(effects);
            return;
        }
        if self.begin_mcp_refresh(effects) {
            return;
        }
        self.flush(&session_id, effects);
    }

    fn build_session_request<Request: JsonRpcMessage + serde::Serialize>(
        &mut self,
        request: Request,
        kind: SessionOpening,
    ) -> std::result::Result<
        (RawJsonRpcMessage, RequestId, SessionOpening),
        agent_client_protocol::Error,
    > {
        let (method, params) = request.to_untyped_message()?.into_parts();
        let request_id = self.next_id();
        let request = RawJsonRpcMessage::request(method, params, request_id.clone())?;
        Ok((request, request_id, kind))
    }

    fn build_resume_session_request(
        &mut self,
        session_id: SessionId,
    ) -> std::result::Result<
        (RawJsonRpcMessage, RequestId, SessionOpening),
        agent_client_protocol::Error,
    > {
        self.build_session_request(
            self.resume_request(session_id.clone()),
            SessionOpening::Resume(session_id),
        )
    }

    fn resume_request(&self, session_id: SessionId) -> ResumeSessionRequest {
        ResumeSessionRequest::new(session_id, self.workspace.clone())
            .mcp_servers(self.mcp_servers.clone())
            .meta(self.session_meta())
    }

    fn build_load_session_request(
        &mut self,
        session_id: SessionId,
    ) -> std::result::Result<
        (RawJsonRpcMessage, RequestId, SessionOpening),
        agent_client_protocol::Error,
    > {
        self.build_session_request(
            LoadSessionRequest::new(session_id.clone(), self.workspace.clone())
                .mcp_servers(self.mcp_servers.clone())
                .meta(self.session_meta()),
            SessionOpening::Load(session_id),
        )
    }

    /// Names the Macro session an ACP session belongs to, so a runtime that
    /// multiplexes sessions over one connection (macrod) can tell them apart.
    fn session_meta(&self) -> agent_client_protocol::schema::v1::Meta {
        let mut meta = agent_client_protocol::schema::v1::Meta::new();
        meta.insert(
            MACRO_AGENT_SESSION_META_KEY.to_owned(),
            serde_json::Value::String(self.id.to_string()),
        );
        let permission_policy: &'static str = self.permission_policy.into();
        meta.insert(
            MACRO_PERMISSION_POLICY_META_KEY.to_owned(),
            serde_json::Value::String(permission_policy.to_owned()),
        );
        meta
    }

    fn build_initialize_request(
        &mut self,
    ) -> std::result::Result<(RawJsonRpcMessage, RequestId), agent_client_protocol::Error> {
        let request_id = self.next_id();
        Ok((initialize_request(request_id.clone())?, request_id))
    }

    fn build_new_session_request(
        &mut self,
    ) -> std::result::Result<
        (RawJsonRpcMessage, RequestId, SessionOpening),
        agent_client_protocol::Error,
    > {
        self.build_session_request(
            NewSessionRequest::new(self.workspace.clone())
                .mcp_servers(self.mcp_servers.clone())
                .meta(self.session_meta()),
            SessionOpening::New,
        )
    }

    /// Whether `frame` is the runtime's `_session/closed` for the live ACP
    /// session. One naming another session, or unreadable, says nothing.
    fn reports_runtime_closed(&self, frame: &RawJsonRpcMessage) -> bool {
        let (RawJsonRpcMessage::Notification(notification), SessionPhase::Live { session_id, .. }) =
            (frame, &self.phase)
        else {
            return false;
        };
        RuntimeSessionClosedNotification::matches_method(&notification.method)
            && notification
                .params
                .clone()
                .and_then(|params| {
                    serde_json::from_value::<RuntimeSessionClosedNotification>(params.into_value())
                        .ok()
                })
                .is_some_and(|closed| &closed.session_id == session_id)
    }

    /// A `session/request_permission` from the agent. The agent blocks until
    /// it is answered, so every path out of here either answers now or records
    /// the request so a user's answer can find it.
    fn on_permission_request(
        &mut self,
        frame: &RawJsonRpcMessage,
        effects: &mut Vec<Effect<Token>>,
    ) {
        let RawJsonRpcMessage::Request(request) = frame else {
            return;
        };
        if !RequestPermissionRequest::matches_method(&request.method) {
            return;
        }

        let parsed = request.params.clone().and_then(|params| {
            serde_json::from_value::<RequestPermissionRequest>(params.into_value()).ok()
        });
        let Some(parsed) = parsed else {
            // Nothing to show a user and nothing to choose from, under either
            // policy; cancelling is the only answer that does not invent one.
            self.send_permission_response(
                None,
                request.id.clone(),
                RequestPermissionOutcome::Cancelled,
                effects,
            );
            return;
        };

        match self.permission_policy {
            PermissionPolicy::AutoAccept => {
                let outcome = parsed
                    .options
                    .iter()
                    .find(|option| matches!(option.kind, PermissionOptionKind::AllowAlways))
                    .or_else(|| {
                        parsed
                            .options
                            .iter()
                            .find(|option| matches!(option.kind, PermissionOptionKind::AllowOnce))
                    })
                    .map(|option| {
                        RequestPermissionOutcome::Selected(SelectedPermissionOutcome::new(
                            option.option_id.clone(),
                        ))
                    })
                    .unwrap_or(RequestPermissionOutcome::Cancelled);
                self.send_permission_response(None, request.id.clone(), outcome, effects);
            }
            // Nothing goes out: the logged request is what the fold renders
            // as a pending prompt, and the answer arrives as a command.
            PermissionPolicy::Prompt => {
                let options = parsed
                    .options
                    .into_iter()
                    .map(|option| option.option_id)
                    .collect();
                self.outstanding_permissions
                    .insert(request.id.clone(), OutstandingPermission { options });
            }
        }
    }

    /// A user's answer to a request held open under
    /// [`PermissionPolicy::Prompt`].
    fn on_permission_answer(
        &mut self,
        from: Option<MacroUserIdStr<'static>>,
        answer: &AgentPermissionAction,
        token: Token,
        effects: &mut Vec<Effect<Token>>,
    ) {
        if matches!(self.phase, SessionPhase::Dead) {
            effects.push(Effect::Complete {
                token,
                result: Err(AgentSessionError::Disconnected(self.id)),
            });
            return;
        }
        let Some(outstanding) = self.outstanding_permissions.get(&answer.request_id) else {
            effects.push(Effect::Complete {
                token,
                result: Err(AgentSessionError::PermissionRequestNotFound(self.id)),
            });
            return;
        };
        if let PermissionAnswer::Selected { option_id } = &answer.answer
            && !outstanding
                .options
                .iter()
                .any(|offered| offered == &PermissionOptionId::new(option_id.clone()))
        {
            effects.push(Effect::Complete {
                token,
                result: Err(AgentSessionError::PermissionOptionUnknown(self.id)),
            });
            return;
        }

        self.outstanding_permissions.remove(&answer.request_id);
        self.send_permission_response(
            from,
            answer.request_id.clone(),
            answer.answer.to_acp(),
            effects,
        );
        effects.push(Effect::Complete {
            token,
            result: Ok(()),
        });
    }

    /// An `elicitation/create` is held for the user rather than answered - the
    /// one agent request this machine does not resolve on its own. What
    /// cannot be held is refused on the spot with `-32602`, the code the
    /// protocol names for a mode the client did not advertise: a request
    /// this machine cannot parse, a mode it does not render, a request
    /// scoped outside any session, one for another session on the same
    /// connection, or a second question while the first is still open.
    fn hold_or_refuse_elicitation(
        &mut self,
        frame: &RawJsonRpcMessage,
        effects: &mut Vec<Effect<Token>>,
    ) {
        let RawJsonRpcMessage::Request(request) = frame else {
            return;
        };
        if !CreateElicitationRequest::matches_method(&request.method) {
            return;
        }
        let SessionPhase::Live {
            session_id,
            elicitation,
        } = &mut self.phase
        else {
            return;
        };

        let parsed = request
            .params
            .clone()
            .ok_or("an elicitation needs params")
            .and_then(|params| {
                serde_json::from_value::<CreateElicitationRequest>(params.into_value())
                    .map_err(|_| "the elicitation did not parse")
            });
        let refusal = match parsed {
            Err(reason) => Some(reason),
            Ok(elicitation_request) => {
                let scope = match &elicitation_request.mode {
                    ElicitationMode::Form(form) => Some(&form.scope),
                    ElicitationMode::Url(url) => Some(&url.scope),
                    // `#[non_exhaustive]`: an `Other` mode, or one ACP adds later.
                    _ => None,
                };
                match scope {
                    None => Some("this client renders only form and url elicitations"),
                    Some(ElicitationScope::Request(_)) => {
                        Some("request-scoped elicitation is not supported")
                    }
                    Some(ElicitationScope::Session(scope)) if &scope.session_id != session_id => {
                        Some("the elicitation names another session")
                    }
                    Some(ElicitationScope::Session(_)) if elicitation.is_some() => {
                        Some("one elicitation at a time")
                    }
                    Some(ElicitationScope::Session(_)) => None,
                    // `#[non_exhaustive]` scope.
                    Some(_) => Some("unrecognized elicitation scope"),
                }
            }
        };

        match refusal {
            None => {
                *elicitation = Some(PendingElicitation {
                    request_id: request.id.clone(),
                });
            }
            Some(reason) => {
                let error = agent_client_protocol::Error::invalid_params().data(reason);
                effects.push(Effect::Send {
                    from: None,
                    message: ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::response(
                        request.id.clone(),
                        Err(error),
                    ))),
                });
            }
        }
    }

    /// Answer the held elicitation with `cancel` and release the slot. What a
    /// stop does before its cancel notification, so the agent's request is
    /// resolved rather than left dangling on a turn that is ending anyway.
    fn cancel_pending_elicitation(
        &mut self,
        from: Option<MacroUserIdStr<'static>>,
        effects: &mut Vec<Effect<Token>>,
    ) {
        let SessionPhase::Live { elicitation, .. } = &mut self.phase else {
            return;
        };
        let Some(pending) = elicitation.take() else {
            return;
        };
        let Ok(result) =
            serde_json::to_value(CreateElicitationResponse::new(ElicitationAction::Cancel))
        else {
            return;
        };
        effects.push(Effect::Send {
            from,
            message: ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::response(
                pending.request_id,
                Ok(result),
            ))),
        });
    }

    /// Resolve every request the agent is still waiting on with `Cancelled`.
    /// ACP requires each request to be answered, and once the turn is over -
    /// cancelled, ended, or the connection gone - there is no answer to give.
    fn cancel_outstanding_permissions(&mut self, effects: &mut Vec<Effect<Token>>) {
        let ids: Vec<RequestId> = self
            .outstanding_permissions
            .drain()
            .map(|(id, _)| id)
            .collect();
        for id in ids {
            self.send_permission_response(None, id, RequestPermissionOutcome::Cancelled, effects);
        }
    }

    fn send_permission_response(
        &self,
        from: Option<MacroUserIdStr<'static>>,
        request_id: RequestId,
        outcome: RequestPermissionOutcome,
        effects: &mut Vec<Effect<Token>>,
    ) {
        match permission_response(request_id, outcome) {
            Ok(message) => effects.push(Effect::Send { from, message }),
            Err(error) => {
                tracing::error!(error = ?error, id = %self.id, "could not build a permission response")
            }
        }
    }

    /// Send everything queued, oldest first. Each action's [`Effect::Complete`]
    /// directly follows its [`Effect::Send`], so the shell aborting a batch
    /// mid-way strands no false completions - and an action that cannot be
    /// expressed as ACP fails alone, without taking the connection down.
    fn flush(&mut self, session_id: &SessionId, effects: &mut Vec<Effect<Token>>) {
        while let Some(queued) = self.pending.pop_front() {
            let request_id = queued.action_id.to_request_id();
            match queued.action.to_runtime(session_id, request_id.clone()) {
                Ok(message) => {
                    if queued.action.occupies_turn() {
                        // The harness dispatches one turn at a time, but
                        // `send_action` is public and a direct caller can race
                        // the previous turn's answer. Track the newest: its
                        // answer is what ends the turn, and the displaced
                        // one's answer simply matches nothing.
                        if let Some((_, displaced)) =
                            self.in_flight_turn.replace((request_id, queued.action_id))
                        {
                            tracing::warn!(
                                id = %self.id,
                                %displaced,
                                "a turn-occupying action was sent while a turn was in flight"
                            );
                        }
                    }
                    effects.push(Effect::Send {
                        from: queued.from,
                        message,
                    });
                    // ACP: after `session/cancel`, the client answers every
                    // permission request still open with `Cancelled`.
                    if matches!(queued.action, AgentAction::Stop) {
                        self.cancel_outstanding_permissions(effects);
                    }
                    effects.push(Effect::Complete {
                        token: queued.token,
                        result: Ok(()),
                    });
                }
                Err(error) => effects.push(Effect::Complete {
                    token: queued.token,
                    result: Err(error.into()),
                }),
            }
        }
    }

    /// End the connection: fail everything queued, then stop. The `Stop` is
    /// last so the shell resolves waiting callers before it tears down.
    ///
    /// A turn that was in flight is forgotten without [`Effect::TurnEnded`]:
    /// the turn did not end, the session stopped, and the shell reports that
    /// as its own event.
    fn die(&mut self, reason: StopReason, effects: &mut Vec<Effect<Token>>) {
        self.phase = SessionPhase::Dead;
        self.in_flight_turn = None;
        // Open permission requests are answered `Cancelled` while the agent
        // can still hear it. When the transport itself is what died, the
        // sends could only fail; the agent is gone either way.
        if reason.transport_is_up() {
            self.cancel_outstanding_permissions(effects);
        } else {
            self.outstanding_permissions.clear();
        }
        while let Some(queued) = self.pending.pop_front() {
            effects.push(Effect::Complete {
                token: queued.token,
                result: Err(AgentSessionError::Disconnected(self.id)),
            });
        }
        effects.push(Effect::Stop { reason });
    }

    fn resume_unsupported(&mut self, effects: &mut Vec<Effect<Token>>) {
        self.phase = SessionPhase::Dead;
        while let Some(queued) = self.pending.pop_front() {
            effects.push(Effect::Complete {
                token: queued.token,
                result: Err(AgentSessionError::ResumeUnsupported(self.id)),
            });
        }
        effects.push(Effect::Stop {
            reason: StopReason::ResumeUnsupported,
        });
    }

    /// Namespaced so a caller's request id can never collide with ours - and
    /// carries the session, so sessions sharing one connection cannot collide
    /// with each other either.
    fn next_id(&mut self) -> RequestId {
        let id = RequestId::Str(match self.connection_context {
            Some(context) => format!("agent_session:{}:{context}:{}", self.id, self.next_request),
            None => format!("agent_session:{}:{}", self.id, self.next_request),
        });
        self.next_request += 1;
        id
    }
}

/// The one `initialize` a connection sends, whoever sends it.
pub(crate) fn initialize_request(
    request_id: RequestId,
) -> std::result::Result<RawJsonRpcMessage, agent_client_protocol::Error> {
    // Both elicitation modes are advertised: the session page renders
    // forms and opens URLs after consent. Agents that check (they must)
    // will only ask once this says they may - so this line must never
    // ship ahead of `hold_or_refuse_elicitation`, or every agent that
    // asks hangs on a request nothing answers.
    let capabilities = ClientCapabilities::new().elicitation(
        ElicitationCapabilities::new()
            .form(ElicitationFormCapabilities::new())
            .url(ElicitationUrlCapabilities::new()),
    );
    let (method, params) = InitializeRequest::new(PROTOCOL_VERSION)
        .client_capabilities(capabilities)
        .to_untyped_message()?
        .into_parts();
    RawJsonRpcMessage::request(method, params, request_id)
}