Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
//! A load is a transaction over the visible projection, not new activity.
use agent_client_protocol::schema::v1::{
AGENT_METHOD_NAMES, InitializeRequest, LoadSessionRequest, LoadSessionResponse,
NewSessionRequest, NewSessionResponse, PromptRequest, RequestId, Response,
ResumeSessionRequest, ResumeSessionResponse, SessionId,
};
use agent_client_protocol::{JsonRpcMessage, JsonRpcResponse, RawJsonRpcMessage, RawJsonRpcParams};
use agent_runtime_protocol::domain::schema::v0::{SystemEvent, ToRuntimeMessage, ToServerMessage};
use super::convert::param;
use super::state::{FoldState, StepChange};
use crate::domain::log::{AgentSessionId, AgentSessionLog, Message};
#[derive(Debug, Clone, Default)]
pub(super) struct Replay {
session: Option<AgentSessionId>,
initialization: FoldState,
transaction: Option<Transaction>,
disconnected: bool,
// A failed/abandoned load may still have queued notifications. Handshake
// markers invalidate correlations, but do not prove those frames are live.
quarantined: bool,
replay_session: Option<SessionId>,
pending_open: Option<(RequestId, Opening)>,
/// Original trusted inputs survive load epochs; replay echoes have no metadata.
notification_prompts: Vec<AgentSessionLog>,
completed_noops: std::collections::HashSet<String>,
}
#[derive(Debug, Clone)]
enum Opening {
New,
/// A resume names the session in its request; the response only confirms.
Resume {
session: Option<SessionId>,
},
}
impl Opening {
/// The ACP session id the response opened, or `None` for a response that
/// does not decode as this opening's success. A resume whose request
/// named no session reads as `Some(None)`: accepted, id unknown.
fn accepts(&self, response: &Response<serde_json::Value>) -> Option<Option<SessionId>> {
let Response::Result { result, .. } = response else {
return None;
};
match self {
Self::New => {
NewSessionResponse::from_value(AGENT_METHOD_NAMES.session_new, result.clone())
.ok()
.map(|response| Some(response.session_id.clone()))
}
Self::Resume { session } => {
ResumeSessionResponse::from_value(AGENT_METHOD_NAMES.session_resume, result.clone())
.ok()
.map(|_| session.clone())
}
}
}
}
#[derive(Debug, Clone)]
struct Transaction {
request: RequestId,
session: SessionId,
metadata: crate::domain::model::SessionMetadata,
pending_initialize: Option<RequestId>,
entries: Vec<AgentSessionLog>,
}
pub(super) enum Outcome {
Changes(Vec<StepChange>),
Staged,
Replaced,
}
impl Replay {
fn loading(&self) -> bool {
self.transaction.is_some()
}
fn commit(&mut self, committed: &mut FoldState, completion: AgentSessionLog) -> Outcome {
let mut transaction = self.transaction.take().expect("matched transaction");
transaction.entries.push(completion);
let mut state = FoldState {
metadata: transaction.metadata,
pending_initialize: transaction.pending_initialize,
replaying: true,
acp_session: Some(transaction.session),
..FoldState::default()
};
let mut user_chunks = Vec::new();
let mut provenance = 0;
for entry in transaction.entries {
if is_replay_user(&entry) {
user_chunks.push(entry);
continue;
}
self.replay_users(&mut state, &mut user_chunks, &mut provenance);
state.step(entry);
}
self.replay_users(&mut state, &mut user_chunks, &mut provenance);
if state.turn.as_ref().is_some_and(|turn| {
turn.can_noop
&& turn.noop_buffer == "<noop/>"
&& turn
.prompt_id
.as_ref()
.is_some_and(|id| self.completed_noops.contains(&id.to_string()))
}) {
state.close_turn(Some(crate::domain::model::StopReason::EndTurn));
state.refresh_turn_state();
}
state.replaying = false;
*committed = state;
Outcome::Replaced
}
fn replay_users(
&self,
state: &mut FoldState,
chunks: &mut Vec<AgentSessionLog>,
provenance: &mut usize,
) {
if chunks.is_empty() {
return;
}
let echoed = content_signature(chunks.iter().filter_map(replay_user_content));
let matched = self
.notification_prompts
.iter()
.enumerate()
.skip(*provenance)
.find(|(_, original)| {
let (Message::ToRuntime(ToRuntimeMessage::Acp(acp))
| Message::Notification(ToRuntimeMessage::Acp(acp))) = &original.content
else {
return false;
};
let RawJsonRpcMessage::Request(request) = &acp.0 else {
return false;
};
let Some(blocks) =
param(request.params.as_ref(), "prompt").and_then(|prompt| prompt.as_array())
else {
return false;
};
// Compare the complete input, including attachments, rather than
// recognizing an envelope copied into an unrelated user prompt.
content_signature(blocks.iter()) == echoed
});
// User chunks separated by agent activity start another replayed turn,
// including when the prior system turn buffered a silent response.
if state
.turn
.as_ref()
.is_some_and(|turn| turn.notification || turn.agent.is_some())
{
state.close_turn(Some(crate::domain::model::StopReason::EndTurn));
}
if let Some((index, original)) = matched {
*provenance = index + 1;
state.step(original.clone());
chunks.clear();
} else {
for entry in chunks.drain(..) {
state.step(entry);
}
}
}
pub(super) fn step(&mut self, committed: &mut FoldState, entry: AgentSessionLog) -> Outcome {
// One machine per Macro session. A multiplexed transport must route
// frames before folding; a foreign response must never commit a load.
if self
.session
.is_some_and(|session| session != entry.agent_session_id)
{
return Outcome::Staged;
}
self.session = Some(entry.agent_session_id);
if let Some(noop_turn) = committed.metadata.noop_turn {
self.completed_noops.extend(
committed
.metadata
.notifications
.iter()
.filter(|event| event.turn == noop_turn && event.system_turn)
.map(|event| event.action_id.clone()),
);
}
if !self.loading()
&& let Message::ToRuntime(message) | Message::Notification(message) = &entry.content
&& agent_runtime_protocol::domain::notification::input_from_runtime(message).is_some()
&& !self
.notification_prompts
.iter()
.any(|known| notification_request_id(known) == notification_request_id(&entry))
{
self.notification_prompts.push(entry.clone());
}
if let Message::ToServer(ToServerMessage::Event { event }) = &entry.content {
if matches!(event, SystemEvent::AcpReady | SystemEvent::Disconnected) {
self.quarantined |=
self.transaction.is_some() || matches!(event, SystemEvent::Disconnected);
self.transaction = None;
self.pending_open = None;
self.initialization = FoldState::default();
self.disconnected = matches!(event, SystemEvent::Disconnected);
committed.clear_pending();
}
self.initialization.step(entry.clone());
if let Some(candidate) = &mut self.transaction {
candidate.entries.push(entry.clone());
}
return Outcome::Changes(committed.step(entry));
}
if let Message::ToRuntime(ToRuntimeMessage::Acp(acp))
| Message::Notification(ToRuntimeMessage::Acp(acp)) = &entry.content
&& let RawJsonRpcMessage::Request(request) = &acp.0
{
if InitializeRequest::matches_method(&request.method) {
// Initialization starts a correlation epoch, but does not
// erase committed messages or imply a successful restore.
self.quarantined |= self.loading();
self.transaction = None;
self.pending_open = None;
self.disconnected = false;
self.initialization = FoldState::default();
self.initialization.metadata.status = Some("acp_ready".to_owned());
committed.clear_pending();
self.initialization.step(entry.clone());
} else if !self.disconnected && LoadSessionRequest::matches_method(&request.method) {
let Some(session) =
param(request.params.as_ref(), "sessionId").and_then(|v| v.as_str())
else {
return Outcome::Staged;
};
self.pending_open = None;
let session = SessionId::new(session);
self.replay_session = Some(session.clone());
self.transaction = Some(Transaction {
request: request.id.clone(),
session,
metadata: self.initialization.metadata.clone(),
pending_initialize: self.initialization.pending_initialize.clone(),
entries: vec![entry],
});
return Outcome::Staged;
} else if !self.disconnected
&& self.quarantined
&& !self.loading()
&& let Some(RawJsonRpcParams::Object(params)) = request.params.as_ref()
{
match request.method.as_ref() {
method
if PromptRequest::matches_method(method)
&& PromptRequest::parse_message(method, params).is_ok()
&& self.matches_replay_session(request.params.as_ref()) =>
{
// Only dispatched prompts enter the log; SessionMachine
// dispatches them after the handshake reaches Live.
self.quarantined = false;
self.pending_open = None;
committed.clear_pending();
}
method
if NewSessionRequest::matches_method(method)
&& NewSessionRequest::parse_message(method, params).is_ok() =>
{
self.pending_open = Some((request.id.clone(), Opening::New));
return Outcome::Changes(committed.step(entry));
}
method
if ResumeSessionRequest::matches_method(method)
&& ResumeSessionRequest::parse_message(method, params).is_ok()
&& self.matches_replay_session(request.params.as_ref()) =>
{
let session = param(request.params.as_ref(), "sessionId")
.and_then(|value| value.as_str())
.map(SessionId::new);
self.pending_open = Some((request.id.clone(), Opening::Resume { session }));
return Outcome::Changes(committed.step(entry));
}
_ => {}
}
}
}
if self.disconnected {
return Outcome::Staged;
}
if let Message::ToServer(ToServerMessage::Acp(acp)) = &entry.content
&& let RawJsonRpcMessage::Response(response) = &acp.0
{
let id = match response {
Response::Result { id, .. } | Response::Error { id, .. } => id,
};
if self.initialization.pending_initialize.as_ref() == Some(id) {
self.initialization.step(entry.clone());
if self.transaction.is_none() {
return Outcome::Changes(committed.step(entry));
}
}
if self
.transaction
.as_ref()
.is_some_and(|candidate| &candidate.request == id)
{
// Match SessionMachine::on_session_opened exactly: JSON-RPC
// success alone is insufficient; the ACP result must decode.
if !matches!(response, Response::Result { result, .. }
if LoadSessionResponse::from_value(AGENT_METHOD_NAMES.session_load, result.clone()).is_ok())
{
self.transaction = None;
self.quarantined = true;
return Outcome::Staged;
}
self.quarantined = false;
// Load completion is not turn completion. Keep the last replayed
// turn open so live chunks after the high-water mark append to it.
return self.commit(committed, entry);
}
if self
.pending_open
.as_ref()
.is_some_and(|(pending, _)| pending == id)
{
let (_, opening) = self.pending_open.take().expect("matched opening request");
if let Some(session) = opening.accepts(response) {
self.quarantined = false;
if let Some(session) = session {
committed.acp_session = Some(session);
}
} else {
committed.pending_config_requests.remove(id);
return Outcome::Staged;
}
}
}
if let Some(candidate) = &mut self.transaction {
let params = match &entry.content {
Message::ToServer(ToServerMessage::Acp(acp))
| Message::ToRuntime(ToRuntimeMessage::Acp(acp)) => match &acp.0 {
RawJsonRpcMessage::Request(request) => request.params.as_ref(),
RawJsonRpcMessage::Notification(notification) => notification.params.as_ref(),
_ => None,
},
_ => None,
};
if param(params, "sessionId")
.and_then(|v| v.as_str())
.is_some_and(|session| session != candidate.session.0.as_ref())
{
return Outcome::Staged;
}
candidate.entries.push(entry);
return Outcome::Staged;
}
if self.quarantined {
return Outcome::Staged;
}
Outcome::Changes(committed.step(entry))
}
fn matches_replay_session(
&self,
params: Option<&agent_client_protocol::RawJsonRpcParams>,
) -> bool {
param(params, "sessionId")
.and_then(|value| value.as_str())
.is_some_and(|session| {
self.replay_session
.as_ref()
.is_none_or(|expected| session == expected.0.as_ref())
})
}
}
/// Contents echoed by a runtime while loading history. Only complete matches
/// with trusted original inputs acquire notification semantics.
fn replay_user_content(entry: &AgentSessionLog) -> Option<&serde_json::Value> {
let Message::ToServer(ToServerMessage::Acp(acp)) = &entry.content else {
return None;
};
let RawJsonRpcMessage::Notification(notification) = &acp.0 else {
return None;
};
if notification.method.as_ref() != "session/update" {
return None;
}
let update = param(notification.params.as_ref(), "update")?;
if update.get("sessionUpdate")?.as_str()? != "user_message_chunk" {
return None;
}
update.get("content")
}
fn content_signature<'a>(
blocks: impl Iterator<Item = &'a serde_json::Value>,
) -> (String, Vec<serde_json::Value>) {
let mut text = String::new();
let mut attachments = Vec::new();
for block in blocks {
if block.get("type").and_then(|kind| kind.as_str()) == Some("text") {
text.push_str(
block
.get("text")
.and_then(|text| text.as_str())
.unwrap_or_default(),
);
} else {
attachments.push(block.clone());
}
}
(text, attachments)
}
fn notification_request_id(entry: &AgentSessionLog) -> Option<&RequestId> {
let (Message::ToRuntime(ToRuntimeMessage::Acp(acp))
| Message::Notification(ToRuntimeMessage::Acp(acp))) = &entry.content
else {
return None;
};
let RawJsonRpcMessage::Request(request) = &acp.0 else {
return None;
};
Some(&request.id)
}
fn is_replay_user(entry: &AgentSessionLog) -> bool {
replay_user_content(entry).is_some()
}