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.

16.2 KB
Raw Blame
//! Opening, closing, and failing turns.

use crate::domain::error::FoldError;
use crate::domain::model::{Author, FailureNotice, FoldedMessage, MessagePart, StopReason, TurnId};
use agent_client_protocol::RawJsonRpcParams;
use agent_client_protocol::schema::v1::{Error, PromptRequest, RequestId};
use agent_runtime_protocol::domain::action::AgentActionId;
use chrono::{DateTime, Utc};
use macro_user_id::user_id::MacroUserIdStr;
use non_empty::NonEmpty;

use super::convert::{deserialize_params, same_attachment, user_content_part};
use super::state::{Changed, FoldState, Turn};

impl FoldState {
    /// Adjacent user chunks form one replayed prompt; agent activity separates turns.
    ///
    /// Text chunks extend the prompt's text part; an attachment chunk becomes
    /// its own part after it, the same shape [`Self::begin_turn`] derives
    /// from an original prompt, so a replayed session renders like a live one.
    pub(super) fn replay_user_part(&mut self, part: MessagePart) -> Option<Changed> {
        if matches!(&part, MessagePart::Text { text } if text.is_empty()) {
            return None;
        }
        if self.turn.as_ref().is_some_and(|turn| turn.agent.is_none())
            && let Some(message) = self.messages.last_mut()
            && matches!(message.author, Author::User { .. })
        {
            if message
                .parts
                .iter()
                .any(|existing| same_attachment(existing, &part))
            {
                return None;
            }
            match part {
                MessagePart::Text { text } => match message.parts.get_mut(0) {
                    Some(MessagePart::Text { text: held }) => held.push_str(&text),
                    // The prompt so far was attachments only; its text leads.
                    _ => message.parts.insert(0, MessagePart::Text { text }),
                },
                part => message.parts.push(part),
            }
            return Some(Changed::updated(self.messages.len() - 1));
        }
        self.close_turn(Some(StopReason::EndTurn));
        self.begin_turn_without_prompt();
        let id = self.open_turn().id;
        let message = self.messages.len();
        self.messages.push(FoldedMessage {
            id,
            author: Author::User { user_id: None },
            request_id: None,
            parts: NonEmpty::one(part),
            stop: None,
            pending: self.speculative,
            posted_at: None,
        });
        Some(Changed::new(message))
    }

    /// Add an image fetched after the prompt was sent onto that prompt.
    ///
    /// The same URI already on the message is left alone: a resource link and
    /// the image frame fetched from it are one picture.
    pub(super) fn append_prompt_attachment(&mut self, part: MessagePart) -> Option<Changed> {
        let turn_id = self.turn.as_ref()?.id;
        let message = self.messages.iter().position(|message| {
            message.id == turn_id && matches!(message.author, Author::User { .. })
        })?;
        if self.messages[message]
            .parts
            .iter()
            .any(|existing| same_attachment(existing, &part))
        {
            return None;
        }
        self.messages[message].parts.push(part);
        Some(Changed::updated(message))
    }

    /// Handle a `session/prompt`: emit the user's message, open a turn.
    pub(super) fn begin_turn(
        &mut self,
        prompt_id: &RequestId,
        params: Option<&RawJsonRpcParams>,
        user_id: Option<MacroUserIdStr<'static>>,
        logged_at: Option<DateTime<Utc>>,
    ) -> Vec<Changed> {
        // A speculative prompt behind a stop is the queue head, dispatching
        // once the cancel lands. The turn it follows can only end one way,
        // so that end is predicted here rather than leaving the turn open
        // under the prompt that replaces it. A confirmed prompt never does
        // this: the runtime's own response closes its turn, in log order.
        let closed =
            if self.speculative && self.turn.as_ref().is_some_and(|turn| turn.stop_requested) {
                self.close_turn(Some(StopReason::Cancelled))
            } else {
                // A second prompt without an intervening response means the
                // previous turn never got one. Its agent message is already in
                // `messages` and already reads `stop: None`, so there is nothing
                // left to report.
                let closed = self.close_turn(None);
                debug_assert!(
                    closed.is_none(),
                    "closing a turn without a stop reason changes nothing"
                );
                None
            };

        let id = TurnId(self.turns_opened);
        self.turns_opened += 1;

        // A params shape this fold does not recognize derives no text, same
        // as an empty prompt - see the module docs on why a mismatch here
        // degrades rather than warns: `PromptRequest`'s own fields (a session
        // id, an optional `_meta`) carry nothing this fold renders, so there
        // is nothing to warn *about* beyond "no text," which showing no user
        // message already says.
        //
        // Text blocks join into one part, since a harness may split prose
        // across blocks; each attached file is its own part, in prompt order
        // after the text, which is the order this side sends them in.
        let input = params.cloned().and_then(|params| {
            let value = params.into_value();
            value
                .get("_meta")?
                .get(agent_runtime_protocol::domain::notification::NOTIFICATIONS_META)
                .and_then(|value| {
                    serde_json::from_value::<
                        agent_runtime_protocol::domain::notification::NotificationInput,
                    >(value.clone())
                    .ok()
                })
        });
        let mut text = String::new();
        let mut attachments = Vec::new();
        if let Some(request) = deserialize_params::<PromptRequest>(params) {
            // A confirmed prompt names the session the runtime answers
            // to; a speculative one only echoes what this fold already
            // knew, so it must not become the source of that fact.
            if !self.speculative {
                self.acp_session = Some(request.session_id.clone());
            }
            for (index, block) in request.prompt.into_iter().enumerate() {
                if index == 0 && input.is_some() {
                    continue;
                }
                match user_content_part(block) {
                    Some(MessagePart::Text { text: chunk }) => text.push_str(&chunk),
                    Some(part)
                        if !attachments
                            .iter()
                            .any(|existing| same_attachment(existing, &part)) =>
                    {
                        attachments.push(part)
                    }
                    Some(_) => {}
                    None => {}
                }
            }
        }
        let system_turn = input.as_ref().is_some_and(|input| input.system_turn);
        if let Some(input) = input {
            for notification in input.notifications {
                if let Some(existing) = self
                    .metadata
                    .notifications
                    .iter_mut()
                    .find(|existing| existing.id == notification.id.to_string())
                {
                    // A recovered interrupted action keeps the event identity,
                    // but its response belongs to the retry's turn.
                    existing.turn = id.0;
                    existing.action_id = prompt_id.to_string();
                    existing.system_turn = system_turn;
                    continue;
                }
                self.metadata
                    .notifications
                    .push(crate::domain::model::SessionNotification {
                        id: notification.id.to_string(),
                        subject_id: notification.subject_id,
                        created_at: notification.created_at,
                        event: notification.event,
                        turn: id.0,
                        action_id: prompt_id.to_string(),
                        system_turn,
                    });
            }
        }
        let mut parts = attachments;
        if !system_turn && !text.is_empty() {
            parts.insert(0, MessagePart::Text { text });
        }

        // A prompt carrying nothing renderable derives no user message, but
        // still opens the turn the agent will answer into.
        let changed = NonEmpty::new(parts).ok().map(|parts| {
            let message = self.messages.len();
            self.messages.push(FoldedMessage {
                id,
                author: Author::User { user_id },
                request_id: AgentActionId::from_request_id(prompt_id),
                parts,
                stop: None,
                pending: self.speculative,
                posted_at: logged_at,
            });
            Changed::new(message)
        });

        self.turn = Some(Turn {
            id,
            notification: system_turn,
            noop_buffer: String::new(),
            pending_thought: String::new(),
            can_noop: system_turn,
            prompt_pending: self.speculative,
            stop_requested: false,
            prompt_id: Some(prompt_id.clone()),
            agent: None,
            plan_position: None,
        });

        closed.into_iter().chain(changed).collect()
    }

    /// Handle the response to `session/prompt`: close the turn.
    pub(super) fn end_turn(
        &mut self,
        response_id: &RequestId,
        value: Option<&serde_json::Value>,
    ) -> Option<Changed> {
        let stop = value
            .and_then(|value| value.get("stopReason"))
            .and_then(|reason| reason.as_str())
            // Infallible: `StopReason`'s unmodelled variant is strum's default.
            .and_then(|reason| reason.parse().ok());

        let closes_the_open_turn = match self.turn.as_ref() {
            Some(turn) => match &turn.prompt_id {
                // The ordinary case: the response to the prompt that opened it.
                Some(prompt_id) => prompt_id == response_id,
                // A turn nothing prompted has no id to match against, so the
                // first response reporting a stop reason is taken as its
                // answer - the prompt it belongs to is in an earlier log.
                None => stop.is_some(),
            },
            None => false,
        };

        if !closes_the_open_turn {
            // Responses to `initialize`, `session/new` and `session/load`
            // land here. Only flag one that looks like a turn ending.
            if stop.is_some() {
                self.warn(FoldError::UncorrelatedResponse);
            }
            return None;
        }

        let new_message = self.turn.as_ref().is_some_and(|turn| turn.agent.is_none());
        if let Some(turn) = self.turn.as_mut()
            && turn.can_noop
            && turn.noop_buffer != "<noop/>"
        {
            turn.can_noop = false;
            let remaining = std::mem::take(&mut turn.noop_buffer);
            let thought = std::mem::take(&mut turn.pending_thought);
            if !thought.is_empty() {
                self.append_thought(thought);
            }
            self.append_text(remaining);
        }
        self.close_turn(stop).map(|changed| {
            if new_message {
                Changed::new(changed.message)
            } else {
                changed
            }
        })
    }

    /// End the open turn because its prompt was answered with an error.
    ///
    /// The turn has to end even when the agent produced nothing at all -
    /// which is the common case, since a runtime that rejects a prompt
    /// rejects it before writing anything. That is why this cannot go
    /// through [`Self::close_turn`], whose job is to stamp a stop reason on
    /// an agent message that exists: here the agent message is created if
    /// need be, so the failure has somewhere to live and the turn is
    /// unambiguously over.
    pub(super) fn fail_turn(&mut self, response_id: &RequestId, error: &Error) -> Option<Changed> {
        let closes_the_open_turn = self
            .turn
            .as_ref()
            .and_then(|turn| turn.prompt_id.as_ref())
            .is_some_and(|prompt_id| prompt_id == response_id);
        if !closes_the_open_turn {
            return None;
        }

        // An error is worth showing under any turn, control's included, so
        // this mints unconditionally where a clean close does not.
        let turn = self.turn.take()?;
        let (agent, changed) = match turn.agent {
            Some(agent) => (agent, Changed::updated(agent)),
            None => self.mint_agent_message(turn.id),
        };
        self.messages[agent].stop = Some(StopReason::Failed {
            message: error.message.clone(),
            notice: FailureNotice::from_error_data(error.data.as_ref()),
        });
        Some(changed)
    }

    /// Close the open turn, recording on its agent message how it stopped.
    ///
    /// Usually the agent message has been in [`State::messages`] since the
    /// agent's first part, and all that is left is the stop reason. When the
    /// agent produced nothing at all, one is minted to carry it: readers ask
    /// whether a turn is running by looking for a stop reason on the
    /// transcript's tail, so recording none anywhere reads as working
    /// forever. That is a stop pressed before the first chunk - a first
    /// prompt spends ~10s creating the Cursor agent - which answers
    /// `session/prompt` with `cancelled` and nothing to stamp it on.
    pub(super) fn close_turn(&mut self, stop: Option<StopReason>) -> Option<Changed> {
        let Some(stop) = stop else {
            // Nothing to record, so nothing to mint a message for.
            self.turn = None;
            return None;
        };
        let turn = self.turn.take()?;
        if turn.notification && turn.can_noop && turn.noop_buffer == "<noop/>" {
            self.metadata.noop_turn = Some(turn.id.0);
            return None;
        }
        let (message, changed) = match turn.agent {
            Some(message) => (message, Changed::updated(message)),
            None => self.mint_agent_message(turn.id),
        };
        self.messages[message].stop = Some(stop);
        Some(changed)
    }

    /// Mint the agent message a turn never opened, so a stop reason has
    /// somewhere to sit. Reported as new: the client has not seen it.
    pub(super) fn mint_agent_message(&mut self, turn: TurnId) -> (usize, Changed) {
        let message = self.messages.len();
        self.messages.push(FoldedMessage {
            id: turn,
            author: Author::Agent,
            request_id: None,
            parts: NonEmpty::one(MessagePart::Text {
                text: String::new(),
            }),
            stop: None,
            pending: self.speculative,
            posted_at: None,
        });
        (message, Changed::new(message))
    }

    /// Open a turn for agent content that arrived without a prompt.
    ///
    /// A session resumed through `session/load` picks up mid-conversation: the
    /// prompt the agent is answering is in the log of the session it resumed,
    /// not this one. Dropping the content for want of a prompt folded such a
    /// session to nothing at all - hundreds of frames of real work rendering
    /// as an empty channel - and showing the reply without the question is
    /// plainly better than showing neither.
    ///
    /// The turn is numbered like any other and produces no user message, since
    /// there is no prompt to attribute one to. It is closed by the first
    /// response carrying a stop reason; see [`State::end_turn`].
    pub(super) fn begin_turn_without_prompt(&mut self) {
        let id = TurnId(self.turns_opened);
        self.turns_opened += 1;

        self.turn = Some(Turn {
            id,
            notification: false,
            noop_buffer: String::new(),
            pending_thought: String::new(),
            can_noop: false,
            prompt_pending: false,
            stop_requested: false,
            prompt_id: None,
            agent: None,
            plan_position: None,
        });
    }
}