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.

7.5 KB
Raw Blame
//! Session-level state derived from the log.

use agent_runtime_protocol::domain::review::ReviewUpdatedNotification;
use serde::{Deserialize, Serialize};
use specta::Type;

use super::PendingInteraction;
use super::elicitation::PendingElicitation;
use crate::domain::session_config::SessionConfigOption;

/// Which ACP agent produced a session's log.
///
/// ACP names none of a harness's conventions - which `_meta` keys it writes,
/// what it calls its tools, how it reports a subagent - so the fold has to
/// know who it is reading in order to read those. The agent announces itself
/// in the `initialize` response's `agentInfo.name`; a log that starts
/// mid-session (a resume) is recognized from the `_meta` namespaces its
/// first tool frames carry instead. Carried on the metadata so a reader can
/// show it and never has to infer it.
///
/// [`Self::Unknown`] is a real state, not a failure: every reader falls back
/// to the harness-neutral conventions, and a harness this fold has not met
/// still folds to the generic vocabulary.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Type)]
#[serde(rename_all = "snake_case")]
pub enum Harness {
    /// `@agentclientprotocol/claude-agent-acp`.
    ClaudeCode,
    /// `OpenCode`, whose ACP server is built in.
    OpenCode,
    /// OpenAI Codex, through `codex-acp`.
    Codex,
    /// Cursor cloud agents, through this repository's `cursor_cloud_agents`.
    Cursor,
    /// Macro's own in-process agent, `agent_inmem`.
    Macro,
    /// Nous Research's Hermes agent.
    Hermes,
    /// OpenClaw.
    OpenClaw,
    /// Not announced, or an agent this fold does not know.
    #[default]
    Unknown,
}

/// Session-level state derived from the log, latest-wins and carried whole.
/// Fields start absent and fill in as the log reveals them.
///
/// `PartialEq` only: a pending form's numeric bounds are `f64`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SessionMetadata {
    /// System events, projected independently of the conversation messages.
    pub notifications: Vec<SessionNotification>,
    /// The newest saved revision of each review the log announced, in the
    /// order they were first announced.
    pub review_revisions: Vec<ReviewUpdatedNotification>,
    /// The last notification turn whose entire answer was suppressed.
    pub noop_turn: Option<u32>,
    /// The agent that produced the log. See [`Harness`].
    pub harness: Harness,
    /// Current model per the runtime's own `configOptions` responses, so a
    /// rejected model change never moves it.
    pub model: Option<String>,
    /// The models the runtime offers, in the order it listed them.
    pub supported_models: Vec<ModelOption>,
    /// Every setting the ACP agent currently advertises. The list is replaced
    /// whole whenever ACP returns a new `configOptions` snapshot.
    pub config_options: Vec<SessionConfigOption>,
    /// Session title, when the harness reports one.
    pub title: Option<String>,
    /// The slash commands the harness most recently advertised, in the order
    /// it listed them. Empty until the first `available_commands_update`,
    /// which arrives right after session setup, before any turn.
    pub available_commands: Vec<AvailableCommand>,
    /// The last system event's wire name (`"acp_ready"`, `"disconnected"`),
    /// `None` until the runtime reports one.
    pub status: Option<String>,
    /// Requests the user can answer on the current turn and connection.
    /// Multiple permissions may coexist with the one allowed elicitation.
    /// History remains in the transcript after these live requests clear.
    pub pending_interactions: Vec<PendingInteraction>,
    /// Where the newest turn stands, as one value. Readers used to derive it
    /// from the transcript's tail, the status, and their own record of what
    /// they had posted; this is that derivation done once, in the fold.
    pub turn: TurnState,
}

impl SessionMetadata {
    /// The one elicitation the session can currently answer, if any.
    #[must_use]
    pub fn pending_elicitation(&self) -> Option<&PendingElicitation> {
        self.pending_interactions
            .iter()
            .find_map(|pending| match pending {
                PendingInteraction::Elicitation(question) => Some(question),
                PendingInteraction::Permission(_) | PendingInteraction::ToolApproval(_) => None,
            })
    }
}

/// Where the newest turn stands.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Type, strum::AsRefStr)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum TurnState {
    /// No turn is open.
    #[default]
    Idle,
    /// No turn is open, and the newest agent reply failed.
    Failed,
    /// A prompt this client issued is on the wire, unconfirmed, and the agent
    /// has produced nothing. Only a speculative fold reports this.
    Starting,
    /// A turn is open and the agent is working.
    Running,
    /// A stop was issued against the open turn and no stop reason has arrived.
    Stopping,
    /// The open turn is waiting on a permission, elicitation, or tool
    /// approval response.
    Blocked,
    /// The runtime reported `disconnected`; whatever was open is not moving.
    Disconnected,
}

/// One slash command the harness advertises.
///
/// Mirrors ACP's `AvailableCommand`, flattened: the only input shape ACP
/// defines today is "unstructured text after the name," so the hint is
/// carried directly rather than through a nested enum.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AvailableCommand {
    /// Bare name as advertised (`"qc"`, `"honeycomb:query-patterns"`) - no
    /// leading slash, which is client syntax rather than part of the name.
    pub name: String,
    /// Human-readable description, verbatim from the harness.
    pub description: String,
    /// Placeholder text for the command's input, when it takes any.
    pub input_hint: Option<String>,
}

/// One model the runtime offers.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ModelOption {
    /// The value to send back to select this model.
    pub id: String,
    /// Human-readable label.
    pub name: String,
    /// Descriptive copy - pricing, context size, and the like.
    pub description: Option<String>,
    /// Image input support, absent when the runtime does not advertise it.
    #[specta(optional)]
    pub supports_images: Option<bool>,
    /// The heading the runtime listed this model under, when it grouped its
    /// options (ACP's `SessionConfigSelectGroup.name`). `None` for a runtime
    /// that offered a flat list; the flattened order still follows the
    /// runtime's, group by group.
    pub group: Option<String>,
}

/// A timeline event or a card state change. Never a conversation message.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SessionNotification {
    /// Outbox identity.
    pub id: String,
    /// Subject identity used to find an existing card.
    pub subject_id: String,
    /// Event creation time, RFC3339.
    pub created_at: String,
    /// Kind-specific facts, kept out of message search and export.
    #[serde(flatten)]
    pub event: agent_runtime_protocol::domain::notification::NotificationEvent,
    /// Turn that received it.
    pub turn: u32,
    /// Stable delivery action identity.
    pub action_id: String,
    /// Whether this turn had no user prompt.
    pub system_turn: bool,
}