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.

11.5 KB
Raw Blame
//! The parts a message is made of, and why a turn stopped.

use std::str::FromStr;

use serde::{Deserialize, Serialize};
use specta::Type;

use super::ToolUseId;
use super::elicitation::{
    AnsweredField, ElicitationOutcome, ElicitationRequest, ElicitationRequestId,
};
use super::permission::{PermissionOption, PermissionOutcome};
use super::plan::PlanEntry;
use super::tool::{ToolDetail, ToolName, ToolStatus};
use super::user_tool::UserToolOutcome;
use agent_runtime_protocol::domain::tool_approval::ToolApprovalStatus;
use agent_runtime_protocol::domain::turn::FailureNotice;

/// A unit of renderable content.
#[derive(Debug, Clone, PartialEq, Serialize, Type)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum MessagePart {
    /// Prose from the user or the agent.
    Text {
        /// The prose.
        text: String,
    },
    /// A file the user attached to their prompt, by where it can be fetched.
    ///
    /// Read off the prompt's `resource_link` blocks - the only shape this
    /// side sends files in, since bytes never ride the log. Rendering decides
    /// from `mime_type` whether that is a thumbnail or a chip.
    Attachment {
        /// Where the file can be fetched - a static file service URL.
        uri: String,
        /// Display name, typically the original file name.
        name: String,
        /// The file's media type, when the sender knew it.
        #[serde(rename = "mimeType")]
        mime_type: Option<String>,
        /// Size in bytes, when the sender knew it. A double on the wire:
        /// specta refuses 64-bit integers, and no file this renders is
        /// anywhere near the precision limit.
        #[specta(type = Option<f64>)]
        size: Option<i64>,
    },
    /// The agent's reasoning, which a reader may want to hide by default.
    Thought {
        /// The reasoning.
        text: String,
    },
    /// A tool the agent invoked.
    ToolUse {
        /// The ACP `toolCallId`.
        id: ToolUseId,
        /// What the harness called the tool.
        name: ToolName,
        /// Where the call got to.
        status: ToolStatus,
        /// What the tool did, as far as the log reveals.
        detail: ToolDetail,
    },
    /// The agent asking to proceed.
    Permission {
        /// The agent request id an approval must echo.
        #[serde(rename = "requestId")]
        request_id: super::AgentRequestId,
        /// The tool call permission was requested for.
        #[serde(rename = "toolCall")]
        tool_call: ToolUseId,
        /// The choices offered, in the order ACP listed them.
        options: Vec<PermissionOption>,
        /// How the request has resolved so far.
        outcome: PermissionOutcome,
    },
    /// An MCP tool call the egress proxy is holding, or held, until the
    /// session's owner approved it: made in a turn somebody else prompted.
    ToolApproval {
        /// The approval an answer names.
        #[serde(rename = "approvalId")]
        approval_id: String,
        /// `macro`, or the connected app's slug.
        #[serde(rename = "serverSlug")]
        server_slug: String,
        /// What a person calls the server the tool is on.
        #[serde(rename = "serverName")]
        server_name: String,
        /// The tool called.
        #[serde(rename = "toolName")]
        tool_name: String,
        /// What it was called with.
        #[specta(type = specta_typescript::Unknown)]
        arguments: serde_json::Value,
        /// Who prompted the turn; absent for a bot on nobody's behalf.
        #[serde(rename = "requestedBy")]
        requested_by: Option<String>,
        /// Where it stands.
        status: ToolApprovalStatus,
        /// Who resolved it, when a person did.
        #[serde(rename = "resolvedBy")]
        resolved_by: Option<String>,
        /// Approved for good: the person who asked may make the calls it
        /// covers without the owner being asked again.
        remembered: bool,
    },
    /// A user-issued control operation on the session.
    Control {
        /// The requested operation.
        control: Control,
        /// How the runtime disposed of it so far.
        outcome: ControlOutcome,
    },
    /// The agent's working todo list for the turn.
    Plan {
        /// The tasks, in the order the agent listed them.
        entries: Vec<PlanEntry>,
    },
    /// A background task the harness reported on: a command, subagent or
    /// monitor it started earlier finished or emitted an event. The harness
    /// hands the agent this report as a user turn; it is shown as a system
    /// fact, never as something a person said.
    TaskNotification {
        /// Where the task ended up; absent for a monitor's mid-stream event.
        status: Option<TaskStatus>,
        /// The harness's one-line account, such as `Background command
        /// "Run tests" completed (exit code 0)`.
        summary: String,
        /// The line a monitor streamed, for a monitor event.
        event: Option<String>,
    },
    /// The agent asking the user a question.
    ///
    /// When the question was asked on behalf of a tool call this fold had
    /// already opened (Claude Code's `AskUserQuestion`), this part *replaces*
    /// that tool's part in place: the question is the call, and rendering
    /// both would show one thing twice.
    Elicitation {
        /// The agent's `elicitation/create` request id - what an answer must
        /// echo.
        #[serde(rename = "requestId")]
        request_id: ElicitationRequestId,
        /// The tool call the question belongs to, when the agent said.
        #[serde(rename = "toolCall")]
        tool_call: Option<ToolUseId>,
        /// What the agent is asking, in prose.
        message: String,
        /// The form or URL.
        request: ElicitationRequest,
        /// How it has resolved so far.
        outcome: ElicitationOutcome,
        /// The harness's own reading of the answer, when it reported one
        /// after the response went back (Claude Code echoes the chosen
        /// option through its tool result). Absent otherwise.
        ///
        /// Shaped like [`ElicitationOutcome::Accepted`]'s answers so a reader
        /// renders one vocabulary either way, though a harness keys these by
        /// question prose rather than by property, so each `name` is that
        /// prose rather than a schema property.
        reported: Option<Vec<AnsweredField>>,
        /// For a user tool's review ([`ElicitationRequest::UserTool`]): how
        /// the tool itself ended once the user answered - run with the
        /// reviewed draft, rejected, or failed - read from the absorbed
        /// call's later updates. Absent until the tool reports, and for
        /// every other kind of question.
        #[serde(rename = "toolOutcome")]
        tool_outcome: Option<UserToolOutcome>,
    },
}

impl MessagePart {
    /// The parts nested inside this one: a subagent's own parts. `None` for
    /// every other kind.
    #[must_use]
    pub fn children_mut(&mut self) -> Option<&mut Vec<MessagePart>> {
        match self {
            Self::ToolUse {
                detail: ToolDetail::Subagent { children, .. },
                ..
            } => Some(children),
            _ => None,
        }
    }

    /// The parts nested inside this one, read-only. See [`Self::children_mut`].
    #[must_use]
    pub fn children(&self) -> &[MessagePart] {
        match self {
            Self::ToolUse {
                detail: ToolDetail::Subagent { children, .. },
                ..
            } => children,
            _ => &[],
        }
    }
}

/// How a background task ended, per [`MessagePart::TaskNotification`].
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Serialize, Type, strum::EnumString, strum::IntoStaticStr,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum TaskStatus {
    /// It ran to the end.
    Completed,
    /// It ended with an error or a nonzero exit.
    Failed,
    /// It was stopped, or did not survive the previous session.
    Stopped,
}

/// A session control operation shown in the conversation timeline.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Control {
    /// The runtime was asked to switch models.
    SetModel {
        /// The model slug requested by the caller.
        model: String,
    },
    /// The runtime was asked to change an advertised session setting.
    SetConfigOption {
        /// Opaque config id supplied by the runtime.
        config_id: String,
        /// Opaque select value requested by the caller.
        value: String,
    },
    /// The runtime was asked to compact its context.
    Compact,
    /// The runtime was asked to stop its current work.
    Stop,
}

/// How the runtime disposed of a [`Control`], like [`PermissionOutcome`] for
/// permission requests. Pending is a legitimate final state: a control the
/// session died before answering stays pending.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ControlOutcome {
    /// No response yet.
    Pending,
    /// Acknowledged - immediately so for a stop, which nothing can answer.
    Accepted,
    /// Answered with a JSON-RPC error.
    Rejected {
        /// The error's message, verbatim.
        message: String,
    },
}

/// Why a turn stopped.
///
/// All but one variant is parsed straight off ACP's `stopReason` wire string
/// by [`FromStr`]: the `snake_case` variant names are the wire names, and
/// anything unmodelled falls through to [`Self::Other`], so parsing never
/// fails. [`Self::Failed`] is the exception - no wire string produces it,
/// because it is what a turn that got no `stopReason` at all stopped for.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum StopReason {
    /// The agent finished its turn.
    EndTurn,
    /// The model hit its token limit.
    MaxTokens,
    /// The agent hit its turn-request limit.
    MaxTurnRequests,
    /// The agent declined.
    Refusal,
    /// The turn was cancelled.
    Cancelled,
    /// A stop reason this fold does not model, as its wire string.
    Other {
        /// The unrecognized wire value.
        reason: String,
    },
    /// The runtime answered the prompt with a JSON-RPC error, so the turn
    /// produced no reply and never will.
    ///
    /// Constructed by the fold, never parsed: an error response carries no
    /// `stopReason` to read. Modelled as a stop reason rather than as
    /// something alongside one because that is what it is - a turn that
    /// ended - and because every reader already asks `stop` whether a turn
    /// is still running. A turn left with no stop reason reads as forever in
    /// flight, which is how a failed prompt used to wedge a session.
    Failed {
        /// The runtime's error message, verbatim.
        message: String,
        /// The failure in the person's terms, when the runtime classified it
        /// as one they can act on. Absent for an opaque failure, which a
        /// reader shows as `message` alone.
        #[serde(default)]
        notice: Option<FailureNotice>,
    },
}

impl FromStr for StopReason {
    type Err = std::convert::Infallible;

    fn from_str(reason: &str) -> Result<Self, Self::Err> {
        Ok(match reason {
            "end_turn" => Self::EndTurn,
            "max_tokens" => Self::MaxTokens,
            "max_turn_requests" => Self::MaxTurnRequests,
            "refusal" => Self::Refusal,
            "cancelled" => Self::Cancelled,
            reason => Self::Other {
                reason: reason.to_owned(),
            },
        })
    }
}