blob: 8d606a10884dcd39c341dd7e888aac920de24d5b [file]
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
use super::{
attachments::sniff_mime,
creation,
send::{PreparedAgentSend, PreparedSend},
*,
};
use base64::{Engine as _, engine::general_purpose::STANDARD};
use futures_util::{StreamExt, future::BoxFuture, stream::FuturesUnordered};
use maka_agent_api::contract::cross_root::{
Action, CompletionDestination, CompletionStatus, CrossRootAttachment, DELIVER, DeliveryRequest,
ENDPOINT, LIST, MAX_HOPS, Operation, ReadOutput,
};
use maka_agent_facts::{
artifact::{
Artifact, ArtifactKind, ArtifactSource, content_digest, normalize_name, upload_artifact_id,
},
attachment::{AttachmentKind, AttachmentRef, StorageRef},
durable::{RunOwner, Terminal},
interaction::entity_id,
message::MessageOrigin,
read::{ReadInput, ResourceAddress},
room::RoomAuthor,
};
use maka_agent_state::{
artifacts::{PreparedUpload, SessionScope, Upload},
cross_root::{
Dispatch, Inbox, NextOutgoingPerRoot, OriginalDirectDispatch, Outgoing, PendingOutboxEntry,
PendingWatches, PublishCompletion, RecordDirectDispatch, SetDispatch,
SettleRoomRemoteCompletion, WakeRootOutbox, Watch,
},
queue::MessageResolution,
};
use maka_capabilities::call::{Attachments, Scope, immutable_bytes};
use maka_event_log::{
StoreError,
root_store::DataWriter,
writeback::{Notification, Prepared, Statement},
};
use maka_host_runtime::application::RootCallError;
use maka_plugin_core::operation::RecoveryRef;
use serde::de::DeserializeOwned;
use std::{
collections::{BTreeMap, BTreeSet, HashSet},
io::Read as _,
time::Duration,
};
use uuid::Uuid;
/// Matches the transport RESOURCE_WINDOW (64 MiB) so cross-Root attachment transfers
/// stay within the native streaming window without inventing an arbitrary smaller cap.
const CROSS_ROOT_ATTACHMENT_BUDGET: u64 = 64 * 1024 * 1024;
const CROSS_ROOT_ATTACHMENT_SLOT: &str = "attachments";
pub(super) fn validate_id(id: &str) -> Result<(), String> {
entity_id(id).map_err(|_| format!("Invalid Root or Session ID '{id}'"))
}
pub(super) fn session_target(
root: Option<String>,
session: &str,
) -> Result<(Option<String>, String), String> {
if let Some(root) = &root {
validate_id(root)?;
}
if !session.starts_with("maka://root/") {
return Ok((root, session.to_owned()));
}
let Some(ResourceAddress::RootSession(address)) = ResourceAddress::parse(session)? else {
return Err("Root-qualified Session URI required".into());
};
let (qualified_root, address) = address.into_parts();
if root.is_some_and(|root| root != qualified_root) {
return Err("rootId does not match the Session URI".into());
}
match address {
ResourceAddress::Session {
session_id,
through: None,
before: None,
} => Ok((Some(qualified_root), session_id)),
_ => Err("Root-qualified Session URI must identify a Session".into()),
}
}
fn digest(operation: &Operation) -> Result<String, String> {
serde_json::to_vec(operation)
.map(|bytes| content_digest(&bytes))
.map_err(|e| e.to_string())
}
fn payload(operation: Operation) -> Result<Value, String> {
let request_digest = digest(&operation)?;
serde_json::to_value(DeliveryRequest {
operation,
request_digest,
})
.map_err(|e| e.to_string())
}
pub(super) fn outgoing(operation: Operation) -> Result<Outgoing, String> {
Ok(Outgoing {
op_id: operation.op_id,
request: payload(operation)?,
})
}
pub(super) fn related_id(operation: Uuid, context: &[&str]) -> Uuid {
use sha2::{Digest, Sha256};
let mut digest = Sha256::new();
digest.update(operation.as_bytes());
for field in context {
digest.update((field.len() as u64).to_be_bytes());
digest.update(field.as_bytes());
}
let bytes: [u8; 32] = digest.finalize().into();
uuid::Builder::from_custom_bytes(bytes[..16].try_into().expect("16 digest bytes")).into_uuid()
}
fn clock() -> Result<i64, String> {
now().try_into().map_err(|_| "invalid clock".into())
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct CompletionRoute {
source_root: String,
original_op_id: Uuid,
hop_count: u8,
destination: CompletionDestination,
}
pub(super) struct RoomRelay {
pub inbox: Inbox,
pub author: RoomAuthor,
pub hop: u8,
pub uploads: Vec<PreparedUpload>,
pub attachment_refs: Vec<AttachmentRef>,
}
#[derive(Default)]
struct PreparedCrossRootAttachments {
uploads: Vec<PreparedUpload>,
refs: Vec<AttachmentRef>,
ingested_items: BTreeSet<(String, String)>,
}
impl Owner {
fn root_writer(&self) -> Result<DataWriter, String> {
self.store.data_writer().map_err(|e| e.to_string())
}
pub(super) async fn create_remote(
&self,
input: SessionCreateInput,
target: String,
request: &RecoveryRef,
scope: &Scope,
) -> Result<NativeMutation<SessionCreateOutput>, String> {
validate_remote_create(&input)?;
self.call_root(Operation {
op_id: request.operation,
source_root: self.data_source.state_domain.clone(),
target_root: target,
hop_count: self.outgoing_hop(scope).await?,
action: Action::Create {
input: Box::new(input),
},
})
.await
.map(NativeMutation::Returned)
}
pub(super) fn peer_root_name(&self, root_id: &str) -> Option<String> {
self.root_router.as_ref().and_then(|router| {
router
.peers()
.into_iter()
.find(|peer| peer.root_id == root_id && !peer.name.trim().is_empty())
.map(|peer| peer.name)
})
}
pub(super) async fn list_remote_sessions(
&self,
mut input: SessionListInput,
target: String,
) -> Result<SessionListOutput, String> {
validate_id(&target)?;
input.root_id = None;
let router = self
.root_router
.as_ref()
.ok_or_else(|| format!("No cross-Root route configured for '{target}'"))?;
let payload = serde_json::to_value(&input).map_err(|e| e.to_string())?;
let value = router
.call(&target, ENDPOINT, LIST, payload, Attachments::new(), None)
.await
.map_err(|e| e.to_string())?;
serde_json::from_value(value).map_err(|e| e.to_string())
}
pub(crate) async fn list_root_sessions(
self: &Arc<Self>,
input: SessionListInput,
scope: &Scope,
source_root: Option<&str>,
) -> Result<SessionListOutput, String> {
self.require_root_ingress(scope, source_root)?;
if input.root_id.is_some() {
return Err("Cross-Root session listing must target this Root directly".into());
}
if matches!(input.scope, SessionToolScope::Children) {
let parent = input
.parent_session_id
.as_deref()
.ok_or("Cross-Root children listing requires parentSessionId")?;
validate_id(parent)?;
if self
.scoped_session(scope, parent)
.await?
.configuration
.incognito
{
return Err("Private Sessions cannot be listed across Roots".into());
}
}
self.session_list_local(input, scope, true, false).await
}
pub(super) async fn send_remote(
&self,
mut input: SessionSendInput,
target: String,
request: &RecoveryRef,
scope: &Scope,
) -> Result<NativeMutation<SendResult>, String> {
validate_id(&input.session_id)?;
if self.settings.bot {
self.bot.load().await.map_err(|e| e.to_string())?;
}
if scope
.identity
.agent()
.is_some_and(|caller| self.bot.is(&caller.session_id))
{
return Ok(NativeMutation::Returned(SendResult::NotYourWorker {
session_id: input.session_id,
}));
}
let mut manifests = Vec::new();
let mut stream_attachments = Attachments::new();
if !input.attachments.is_empty() {
let caller = scope
.identity
.agent()
.ok_or("Cross-Root SessionSend attachments require an Agent caller session")?;
let ids = std::mem::take(&mut input.attachments);
manifests = self
.prepare_caller_attachment_manifests(&caller.session_id, &ids)
.await?;
stream_attachments = self
.load_cross_root_attachments(&caller.session_id, &manifests, true)
.await?;
}
let watches_completion = scope.identity.agent().is_some()
&& !matches!(input.on_complete, Some(SessionNotifyMode::None));
let operation = Operation {
op_id: request.operation,
source_root: self.data_source.state_domain.clone(),
target_root: target,
hop_count: self.outgoing_hop(scope).await?,
action: Action::Send {
input: Box::new(input),
caller: scope.identity.agent().cloned(),
attachments: manifests,
},
};
let router = self.root_router.as_ref().ok_or_else(|| {
format!(
"No cross-Root route configured for '{}'",
operation.target_root
)
})?;
let root = operation.target_root.clone();
let outgoing = outgoing(operation)?;
let op_id = outgoing.op_id;
let request = outgoing.request;
if watches_completion {
self.message_writer(scope)?
.write(RecordDirectDispatch {
owner: self.run_owner(),
outgoing: Outgoing {
op_id,
request: request.clone(),
},
})
.await
.map_err(|e| e.to_string())?;
}
let value = router
.call(
&root,
ENDPOINT,
DELIVER,
request,
stream_attachments,
Some(op_id),
)
.await
.map_err(|e| e.to_string())?;
let receipt = serde_json::from_value(value).map_err(|e| e.to_string())?;
Ok(NativeMutation::Returned(receipt))
}
async fn prepare_caller_attachment_manifests(
&self,
caller_session_id: &str,
ids: &[String],
) -> Result<Vec<CrossRootAttachment>, String> {
let mut seen = BTreeSet::new();
let mut total_bytes = 0u64;
let mut manifests = Vec::with_capacity(ids.len());
for (index, id) in ids.iter().enumerate() {
if entity_id(id).is_err() || !seen.insert(id.clone()) {
return Err("agent_attachments_invalid".into());
}
let published = self
.durable
.artifacts()
.get(
SessionScope {
owner: self.run_owner(),
session: caller_session_id.to_owned(),
},
id.clone(),
)
.await
.map_err(|e| e.to_string())?
.filter(|record| {
record.artifact.source == ArtifactSource::UserUpload
&& record.artifact.session_id == caller_session_id
})
.ok_or("agent_attachment_unavailable")?;
let mime_type = published
.artifact
.mime_type
.clone()
.ok_or("agent_attachment_unavailable")?;
let key = format!("att_{index}");
let framed = published
.artifact
.size_bytes
.saturating_add(4)
.saturating_add(key.len() as u64)
.saturating_add(8);
total_bytes = total_bytes.saturating_add(framed);
if total_bytes > CROSS_ROOT_ATTACHMENT_BUDGET {
return Err("Cross-Root attachments exceed the 64 MiB transfer window".into());
}
manifests.push(CrossRootAttachment {
key,
source_artifact_id: published.artifact.id,
name: published.artifact.name,
mime_type,
bytes: published.artifact.size_bytes,
digest: published.payload.digest,
});
}
Ok(manifests)
}
async fn load_cross_root_attachments(
&self,
source_session_id: &str,
manifests: &[CrossRootAttachment],
strict: bool,
) -> Result<Attachments, String> {
let mut bundle = Vec::new();
let mut remaining = CROSS_ROOT_ATTACHMENT_BUDGET;
for manifest in manifests {
let entry_overhead = 4u64
.saturating_add(manifest.key.len() as u64)
.saturating_add(8);
let entry_total = manifest.bytes.saturating_add(entry_overhead);
if entry_total > remaining {
if strict {
return Err("Cross-Root attachments exceed the 64 MiB transfer window".into());
}
tracing::debug!(
session = %source_session_id,
artifact = %manifest.source_artifact_id,
bytes = manifest.bytes,
"Skipping cross-Root wake attachment stream above 64 MiB transfer window"
);
continue;
}
let expected_bytes = usize::try_from(manifest.bytes)
.map_err(|_| "Cross-Root attachment size overflow".to_owned())?;
let expected_digest = manifest.digest.clone();
let loaded = self
.durable
.artifacts()
.with_content(
SessionScope {
owner: self.run_owner(),
session: source_session_id.to_owned(),
},
manifest.source_artifact_id.clone(),
move |record, reader| -> Result<Vec<u8>, String> {
if strict && record.source != ArtifactSource::UserUpload {
return Err("agent_attachment_unavailable".into());
}
let mut buf = Vec::with_capacity(expected_bytes);
reader
.take(expected_bytes as u64 + 1)
.read_to_end(&mut buf)
.map_err(|e| e.to_string())?;
if buf.len() != expected_bytes || content_digest(&buf) != expected_digest {
return Err("agent_attachment_digest_mismatch".into());
}
Ok(buf)
},
)
.await
.map_err(|e| e.to_string())?;
match loaded {
Some(Ok(bytes)) => {
let key_bytes = manifest.key.as_bytes();
let key_len = u32::try_from(key_bytes.len())
.map_err(|_| "Cross-Root attachment key too long".to_owned())?;
remaining -= entry_total;
bundle.extend_from_slice(&key_len.to_le_bytes());
bundle.extend_from_slice(key_bytes);
bundle.extend_from_slice(&(bytes.len() as u64).to_le_bytes());
bundle.extend_from_slice(&bytes);
}
Some(Err(err)) if strict => return Err(err),
None if strict => return Err("agent_attachment_unavailable".into()),
Some(Err(err)) => {
tracing::debug!(
session = %source_session_id,
artifact = %manifest.source_artifact_id,
%err,
"Skipping invalid cross-Root wake attachment stream; falling back to evidence URI"
);
}
None => {
tracing::debug!(
session = %source_session_id,
artifact = %manifest.source_artifact_id,
"Cross-Root wake attachment artifact missing; falling back to evidence URI"
);
}
}
}
let mut attachments = BTreeMap::new();
if !bundle.is_empty() {
attachments.insert(
CROSS_ROOT_ATTACHMENT_SLOT.into(),
immutable_bytes(CROSS_ROOT_ATTACHMENT_SLOT.into(), bundle),
);
}
Ok(attachments)
}
async fn prepare_cross_root_attachments(
&self,
target_session_id: &str,
manifests: &[CrossRootAttachment],
incoming: &Attachments,
strict: bool,
scope: &Scope,
) -> Result<PreparedCrossRootAttachments, String> {
if manifests.is_empty() {
return Ok(PreparedCrossRootAttachments::default());
}
let mut seen_keys = BTreeSet::new();
let mut total_bytes = 0u64;
for manifest in manifests {
if manifest.key.is_empty()
|| manifest.name.is_empty()
|| manifest.name.chars().any(char::is_control)
|| !seen_keys.insert(manifest.key.as_str())
{
return Err("agent_attachments_invalid".into());
}
if strict {
let framed = manifest
.bytes
.saturating_add(4)
.saturating_add(manifest.key.len() as u64)
.saturating_add(8);
total_bytes = total_bytes.saturating_add(framed);
if total_bytes > CROSS_ROOT_ATTACHMENT_BUDGET {
return Err("Cross-Root attachments exceed the 64 MiB transfer window".into());
}
}
}
let Some(bundle_resource) = incoming.get(CROSS_ROOT_ATTACHMENT_SLOT).cloned() else {
if strict {
return Err("agent_attachment_unavailable".into());
}
return Ok(PreparedCrossRootAttachments::default());
};
let cancellation = scope.cancellation.clone();
let stop = self.stop.clone();
let manifests_owned = manifests.to_vec();
let target_session = target_session_id.to_owned();
let run_owner = self.run_owner();
tokio::task::spawn_blocking(move || {
let mut unpacked = unpack_attachment_bundle(&*bundle_resource, &cancellation, &stop)?;
let mut uploads = Vec::with_capacity(manifests_owned.len());
let mut refs = Vec::with_capacity(manifests_owned.len());
let mut ingested_items = BTreeSet::new();
let mut seen_artifact_ids = BTreeSet::new();
for manifest in manifests_owned {
let Some(bytes) = unpacked.remove(&manifest.key) else {
if strict {
return Err("agent_attachment_unavailable".into());
}
continue;
};
if bytes.len() as u64 != manifest.bytes || content_digest(&bytes) != manifest.digest
{
return Err("agent_attachment_digest_mismatch".into());
}
let normalized = normalize_name(&manifest.name);
let detected_mime = sniff_mime(&normalized, &bytes);
let dedup_key = serde_json::to_vec(&(&manifest.digest, &normalized))
.map_err(|e| e.to_string())?;
let logical_id = format!("cross_root_{}", &content_digest(&dedup_key)[7..39]);
let id = upload_artifact_id(&target_session, &logical_id);
ingested_items.insert((manifest.digest.clone(), normalized.clone()));
if !seen_artifact_ids.insert(id.clone()) {
continue;
}
let record = Artifact {
id: id.clone(),
session_id: target_session.clone(),
turn_id: format!("upload_{logical_id}"),
created_at: now(),
name: normalized.clone(),
kind: if detected_mime.starts_with("image/") {
ArtifactKind::Image
} else if detected_mime == "application/pdf" {
ArtifactKind::Pdf
} else {
ArtifactKind::File
},
size_bytes: bytes.len() as u64,
mime_type: Some(detected_mime.into()),
summary: Some(manifest.digest),
source: ArtifactSource::UserUpload,
};
let attachment_ref = AttachmentRef {
kind: AttachmentKind::from_metadata(detected_mime, &normalized),
name: normalized,
mime_type: detected_mime.into(),
bytes: bytes.len() as u64,
storage_ref: StorageRef::SessionFile {
session_id: target_session.clone(),
relative_path: id,
},
};
record
.validate_attachment(&attachment_ref)
.map_err(|_| "agent_attachment_invalid")?;
let prepared = Upload::new(
SessionScope {
owner: run_owner.clone(),
session: target_session.clone(),
},
logical_id.clone(),
logical_id,
record,
bytes,
)
.prepare_statement()
.map_err(|e| e.to_string())?;
uploads.push(prepared);
refs.push(attachment_ref);
}
Ok::<_, String>(PreparedCrossRootAttachments {
uploads,
refs,
ingested_items,
})
})
.await
.map_err(|e| e.to_string())?
}
async fn outgoing_hop(&self, scope: &Scope) -> Result<u8, String> {
let hop = match scope.identity.agent() {
None => 0,
Some(execution) => self
.caller_room_hop(execution, None)
.await?
.unwrap_or(0)
.saturating_add(1),
};
if hop > MAX_HOPS {
return Err("agent_room_hop_limit_reached".into());
}
Ok(hop)
}
async fn call_root<T: DeserializeOwned>(&self, operation: Operation) -> Result<T, String> {
let router = self.root_router.as_ref().ok_or_else(|| {
format!(
"No cross-Root route configured for '{}'",
operation.target_root
)
})?;
let op_id = operation.op_id;
let root = operation.target_root.clone();
let value = router
.call(
&root,
ENDPOINT,
DELIVER,
payload(operation)?,
Attachments::new(),
Some(op_id),
)
.await
.map_err(|e| e.to_string())?;
serde_json::from_value(value).map_err(|e| e.to_string())
}
pub(crate) async fn read_root_resource(
self: &Arc<Self>,
input: ReadInput,
scope: &Scope,
source_root: Option<&str>,
) -> Result<ReadOutput, String> {
self.require_root_ingress(scope, source_root)?;
let mut request = input.resolve().map_err(|e| e.to_string())?;
let Some(ResourceAddress::RootSession(address)) = ResourceAddress::parse(request.path())?
else {
return Err("Read requires a Root-qualified Session resource".into());
};
if address.root_id() != self.data_source.state_domain {
return Err("Read address belongs to another Root".into());
}
let resource = address.into_parts().1;
let session_id = match &resource {
ResourceAddress::Session { session_id, .. }
| ResourceAddress::SessionToolResult { session_id, .. }
| ResourceAddress::SessionAttachment { session_id, .. } => session_id,
_ => unreachable!("Root qualifier only permits supported Session resources"),
};
if self
.scoped_session(scope, session_id)
.await?
.configuration
.incognito
{
return Err("Private Sessions cannot be read across Roots".into());
}
use maka_files_native::{Output, resource};
let output = match resource {
ResourceAddress::Session {
session_id,
through,
before,
} => {
let (markdown, through) = self
.render_session_markdown(
&session_id,
through,
before.as_deref(),
Some(&self.data_source.state_domain),
scope,
)
.await?;
if !request.is_continuation() {
request
.bind_resource(&ResourceAddress::Session {
session_id,
through,
before,
})
.map_err(|e| e.to_string())?;
}
let page = request
.page_with_budget(&markdown, resource::page_budget())
.map_err(|e| e.to_string())?;
Output::Json(serde_json::to_value(page).map_err(|e| e.to_string())?)
}
ResourceAddress::SessionToolResult {
session_id,
event_id,
} => resource::read_tool_result(
self.root_writer()?,
self.run_owner(),
session_id,
event_id,
request,
&scope.cancellation,
)
.await
.map_err(|e| e.to_string())?,
ResourceAddress::SessionAttachment {
session_id,
attachment_id,
} => resource::read_attachment(
self.root_writer()?,
self.run_owner(),
session_id,
attachment_id,
request,
&scope.cancellation,
)
.await
.map_err(|e| e.to_string())?,
_ => unreachable!("Root qualifier only permits supported Session resources"),
};
Ok(match output {
Output::Json(value) => ReadOutput::Page { value },
Output::Image { mime_type, bytes } => ReadOutput::Image {
mime_type,
data: STANDARD.encode(bytes),
},
})
}
fn require_root_ingress(&self, scope: &Scope, source_root: Option<&str>) -> Result<(), String> {
if !matches!(
scope.identity,
maka_capabilities::call::Identity::Remote { .. }
) || self.store.checkpoint_execution().is_some()
{
return Err("Cross-Root operations require an admitted Host peer".into());
}
#[cfg(test)]
if source_root.is_none() && self.root_router.is_some() {
return Ok(());
}
source_root
.map(|_| ())
.ok_or_else(|| "cross_root_source_unbound".into())
}
pub(crate) async fn deliver_root_operation(
self: &Arc<Self>,
request: DeliveryRequest,
transport_operation: &RecoveryRef,
scope: &Scope,
source_root: Option<&str>,
incoming_attachments: &Attachments,
) -> Result<NativeMutation<Value>, String> {
self.require_root_ingress(scope, source_root)?;
let operation = request.operation;
validate_id(&operation.source_root)?;
if source_root.is_some_and(|root| root != operation.source_root) {
return Err("cross_root_source_peer_mismatch".into());
}
if operation.target_root != self.data_source.state_domain
|| operation.source_root == operation.target_root
{
return Err("cross_root_wrong_destination".into());
}
if operation.op_id.is_nil() {
return Err("cross_root_invalid_operation_id".into());
}
if operation.hop_count > MAX_HOPS {
return Err("agent_room_hop_limit_reached".into());
}
if request.request_digest != digest(&operation)? {
return Err("cross_root_invalid_request_digest".into());
}
let inbox = Inbox {
source_root: operation.source_root,
op_id: operation.op_id,
digest: request.request_digest,
};
let writer = self.root_writer()?;
if let Some(receipt) = inbox.receipt(&writer).await.map_err(|e| e.to_string())? {
return Ok(NativeMutation::Returned(receipt));
}
let hop = operation.hop_count;
match operation.action {
Action::Create { input } => {
validate_remote_create(&input)?;
let material = serde_json::json!({
"sourceRevision": input.source_revision,
"patchDigest": input.patch_digest,
});
let result = self
.create_session_tool_local(
*input,
transport_operation,
scope,
Some(creation::Relay {
inbox: inbox.clone(),
material: material.clone(),
}),
)
.await?;
match result {
NativeMutation::Returned(value) => {
settle(&writer, inbox, &value, Some(material), None)
}
NativeMutation::Computed { change } => Ok(NativeMutation::Computed { change }),
NativeMutation::Commit { .. } => {
unreachable!("new Session creation computes its receipt")
}
}
}
Action::Wake {
source_room_id,
source_message_id,
target_session_id,
author,
mut message,
evidence,
context_envelope,
delivery,
attachments,
} => {
validate_id(&source_room_id)?;
validate_id(&source_message_id)?;
validate_id(&target_session_id)?;
if self
.rooms()?
.exists(&target_session_id)
.await
.map_err(|e| e.to_string())?
{
return Err("A Room wake must target an Agent Session".into());
}
let target_session = self.scoped_session(scope, &target_session_id).await?;
let prepared_attachments = if target_session.archived {
PreparedCrossRootAttachments::default()
} else {
self.prepare_cross_root_attachments(
&target_session_id,
&attachments,
incoming_attachments,
false,
scope,
)
.await?
};
for item in evidence {
let key = (item.digest.clone(), normalize_name(&item.name));
if !prepared_attachments.ingested_items.contains(&key) {
message.push_str(&format!(
"\n\nPublished evidence: {} ({}, {} bytes) {}",
item.name, item.digest, item.bytes, item.uri
));
}
}
if let Some(envelope) = context_envelope
&& !envelope.trim().is_empty()
{
message = format!("{envelope}\n\n{message}");
}
let destination = CompletionDestination::Room {
session_id: source_room_id.clone(),
message_id: source_message_id.clone(),
};
let origin = MessageOrigin::Room {
root_id: Some(inbox.source_root.clone()),
session_id: source_room_id,
message_id: source_message_id,
author,
reply_to: None,
mentions: Vec::new(),
hop_count: Some(hop),
};
let mut send = new_send(target_session_id, message);
send.delivery = Some(delivery.unwrap_or(SendDelivery::Steer));
self.admit_root_send(
send,
Some(origin),
Some(SendCompletion::Watch {
destination,
hop_count: hop,
}),
prepared_attachments,
true,
inbox,
transport_operation,
scope,
)
.await
}
Action::Send {
input,
caller,
attachments,
} => {
validate_id(&input.session_id)?;
if input.root_id.is_some() {
return Err("A delivered SessionSend must name a Session on this Root".into());
}
let prepared_attachments = if !attachments.is_empty() {
if !input.attachments.is_empty() {
return Err("agent_attachments_invalid".into());
}
let target_session = self.scoped_session(scope, &input.session_id).await?;
if target_session.archived {
return Err("agent_session_archived".into());
}
self.prepare_cross_root_attachments(
&input.session_id,
&attachments,
incoming_attachments,
true,
scope,
)
.await?
} else {
PreparedCrossRootAttachments::default()
};
let is_room = self
.rooms()?
.exists(&input.session_id)
.await
.map_err(|e| e.to_string())?;
if is_room {
let author = match caller {
Some(caller) => RoomAuthor::Remote {
root_id: inbox.source_root.clone(),
session_id: caller.session_id,
},
None => RoomAuthor::Human,
};
return self
.send_room_relay(
to_send(*input),
transport_operation,
scope,
Some(RoomRelay {
inbox,
author,
hop,
uploads: prepared_attachments.uploads,
attachment_refs: prepared_attachments.refs,
}),
)
.await
.map(|result| match result {
NativeMutation::Computed { change } => {
NativeMutation::Computed { change }
}
_ => unreachable!("Room post computes its receipt"),
});
}
let destination = caller.as_ref().and_then(|caller| {
(!matches!(input.on_complete, Some(SessionNotifyMode::None))).then(|| {
CompletionDestination::Session {
session_id: caller.session_id.clone(),
}
})
});
let origin = MessageOrigin::CrossRoot {
root_id: inbox.source_root.clone(),
session_id: caller.map(|caller| caller.session_id),
hop_count: hop,
};
self.admit_root_send(
to_send(*input),
Some(origin),
destination.map(|destination| SendCompletion::Watch {
destination,
hop_count: hop,
}),
prepared_attachments,
false,
inbox,
transport_operation,
scope,
)
.await
}
Action::Complete {
original_op_id,
destination,
worker_session_id,
message_id,
status,
error,
} => {
if inbox.op_id
!= related_id(
original_op_id,
&[
"complete",
&self.data_source.state_domain,
&inbox.source_root,
],
)
{
return Err("cross_root_invalid_completion_id".into());
}
validate_id(&message_id)?;
match destination {
CompletionDestination::Room {
session_id,
message_id,
} => {
validate_id(&session_id)?;
validate_id(&message_id)?;
self.scoped_session(scope, &session_id).await?;
let remote_status = match status {
CompletionStatus::Completed => "completed",
CompletionStatus::Failed => "failed",
CompletionStatus::Cancelled => "cancelled",
};
let change = writer
.prepare_result(|_| {
Ok(SettleRoomRemoteCompletion {
inbox,
owner: self.run_owner(),
original_op_id,
session_id,
source_message_id: message_id,
worker_session_id: worker_session_id.clone(),
status: remote_status,
error,
})
})
.map_err(|e| e.to_string())?;
Ok(NativeMutation::Computed { change })
}
CompletionDestination::Session { session_id } => {
validate_id(&session_id)?;
let worker = ResourceAddress::Session {
session_id: worker_session_id.clone(),
through: None,
before: None,
}
.format_qualified(&inbox.source_root)?;
let label = match status {
CompletionStatus::Completed => "completed",
CompletionStatus::Failed => "failed",
CompletionStatus::Cancelled => "was cancelled",
};
let text = match error {
Some(detail) if !detail.trim().is_empty() => format!(
"Remote Agent {worker} {label} message {message_id}: {detail}"
),
_ => format!("Remote Agent {worker} {label} message {message_id}."),
};
let original = OriginalDirectDispatch {
owner: self.run_owner(),
op_id: original_op_id,
target_root: inbox.source_root.clone(),
worker_session: worker_session_id.clone(),
caller_session: session_id.clone(),
};
let send = new_send(session_id, text);
let origin = MessageOrigin::CrossRoot {
root_id: inbox.source_root.clone(),
session_id: Some(worker_session_id),
hop_count: hop,
};
self.admit_root_send(
send,
Some(origin),
Some(SendCompletion::Verify(original)),
PreparedCrossRootAttachments::default(),
false,
inbox,
transport_operation,
scope,
)
.await
}
}
}
}
}
#[allow(clippy::too_many_arguments)]
async fn admit_root_send(
self: &Arc<Self>,
input: Send,
origin: Option<MessageOrigin>,
completion: Option<SendCompletion>,
prepared_attachments: PreparedCrossRootAttachments,
room_wake: bool,
inbox: Inbox,
request: &RecoveryRef,
scope: &Scope,
) -> Result<NativeMutation<Value>, String> {
if !input.mentions.is_empty() || input.reply_to.is_some() {
return Err("agent_room_message_required".into());
}
let key = self.send_key(request, &input.session_id);
let mut message: MessageInput = input.message.clone().into();
message.attachments = if !prepared_attachments.refs.is_empty() {
Some(prepared_attachments.refs)
} else {
self.attachment_refs(&input.session_id, input.attachments.clone(), scope)
.await?
};
let uploads = prepared_attachments.uploads;
let writer = self.root_writer()?;
let is_room_steer = room_wake && matches!(input.delivery, Some(SendDelivery::Steer));
let retry_send = is_room_steer.then(|| Send {
session_id: input.session_id.clone(),
message: input.message.clone(),
delivery: Some(SendDelivery::Queue),
on_complete: input.on_complete,
backend: input.backend.clone(),
expected_run_id: input.expected_run_id,
attachments: input.attachments.clone(),
mentions: input.mentions.clone(),
reply_to: input.reply_to.clone(),
quotes: input.quotes.clone(),
});
let target_session_id = input.session_id.clone();
let mut prepared = self
.prepare_agent_send(input, message.clone(), origin.clone(), &key, request, scope)
.await?;
if let Some(queued) = retry_send
&& matches!(
&prepared,
PreparedSend::Returned(SendResult::Rejected {
reason: SendRejection::TurnStopped,
..
})
)
&& self
.latest_session_run(&target_session_id)
.await
.ok()
.flatten()
.is_none_or(|view| view.terminal.is_some())
{
prepared = self
.prepare_agent_send(queued, message, origin, &key, request, scope)
.await?;
}
match prepared {
PreparedSend::Returned(value) => {
let original = match completion {
Some(SendCompletion::Verify(original)) => Some(original),
_ => None,
};
settle(&writer, inbox, &value, None, original)
}
PreparedSend::Ready {
mut value,
statement,
} => {
let (watch, original) = match completion {
Some(SendCompletion::Watch {
destination,
hop_count,
}) => {
value.completion = Some(CompletionRegistration::Registered);
let watch = Watch {
session: value.session_id.clone(),
message: value.message_id.clone(),
route: serde_json::to_value(CompletionRoute {
source_root: inbox.source_root.clone(),
original_op_id: inbox.op_id,
hop_count,
destination,
})
.map_err(|e| e.to_string())?,
};
(Some(watch), None)
}
Some(SendCompletion::Verify(original)) => (None, Some(original)),
None => (None, None),
};
let change = writer
.prepare_result(|_| {
Ok(RootSend {
owner: self.run_owner(),
inbox,
value,
statement,
uploads,
room_wake,
watch,
original,
})
})
.map_err(|e| e.to_string())?;
Ok(NativeMutation::Computed { change })
}
}
}
pub(super) fn start_root_delivery(self: &Arc<Self>) {
let Some(router) = self.root_router.clone() else {
return;
};
let owner = self.clone();
self.background(move |stop| async move {
const MAX_INFLIGHT_ROOTS: usize = 16;
let mut changes = owner.store.subscribe_changes();
let mut online_rx = router.subscribe_online();
let mut inflight: FuturesUnordered<BoxFuture<'static, Result<(String, bool), String>>> =
FuturesUnordered::new();
let mut inflight_roots: HashSet<String> = HashSet::new();
let mut pending_online_wakes: HashSet<String> = HashSet::new();
loop {
let mut next_wake_delay: Option<Duration> = None;
if inflight.len() < MAX_INFLIGHT_ROOTS {
let writer = match owner.root_writer() {
Ok(writer) => writer,
Err(error) => {
tracing::error!(%error, "Cross-Root outbox stopped");
return;
}
};
let now = match clock() {
Ok(now) => now,
Err(error) => {
tracing::error!(%error, "Cross-Root outbox stopped");
return;
}
};
let batch = match writer
.query(NextOutgoingPerRoot {
owner: owner.run_owner(),
now,
exclude_roots: inflight_roots.iter().cloned().collect(),
limit: MAX_INFLIGHT_ROOTS - inflight.len(),
})
.await
{
Ok(batch) => batch,
Err(error) => {
tracing::error!(%error, "Cross-Root outbox stopped");
return;
}
};
for entry in batch.ready {
if inflight_roots.insert(entry.target_root.clone()) {
let owner = owner.clone();
let router = router.clone();
let writer = writer.clone();
let stop = stop.clone();
inflight.push(Box::pin(async move {
owner
.dispatch_outbox_entry(&*router, writer, entry, &stop)
.await
}));
}
}
next_wake_delay = batch
.next_wake_at
.map(|at| Duration::from_millis(at.saturating_sub(now) as u64));
}
let sleep = async {
match next_wake_delay {
Some(duration) => tokio::time::sleep(duration).await,
None => std::future::pending::<()>().await,
}
};
let online_event = async {
match online_rx.as_mut() {
Some(rx) => Some(rx.recv().await),
None => std::future::pending().await,
}
};
tokio::select! {
() = stop.cancelled() => return,
Some(completed) = inflight.next(), if !inflight.is_empty() => {
match completed {
Ok((target_root, true)) => {
inflight_roots.remove(&target_root);
if pending_online_wakes.remove(&target_root)
&& let Ok(writer) = owner.root_writer()
&& let Ok(now) = clock()
&& owner.producer().await.is_some()
{
let _ = writer
.write(WakeRootOutbox {
owner: owner.run_owner(),
target_root,
now,
})
.await;
}
}
Ok((_, false)) => return,
Err(error) => {
tracing::error!(%error, "Cross-Root outbox stopped");
return;
}
}
}
() = sleep => {},
result = changes.changed() => if result.is_err() { return; },
event = online_event => match event {
Some(Ok(root_id)) => {
if inflight_roots.contains(&root_id) {
pending_online_wakes.insert(root_id);
} else if let Ok(writer) = owner.root_writer()
&& let Ok(now) = clock()
&& owner.producer().await.is_some()
{
let _ = writer
.write(WakeRootOutbox {
owner: owner.run_owner(),
target_root: root_id,
now,
})
.await;
}
}
Some(Err(tokio::sync::broadcast::error::RecvError::Lagged(_))) => {}
Some(Err(tokio::sync::broadcast::error::RecvError::Closed)) => {
online_rx = None;
}
None => {}
}
}
}
});
let owner = self.clone();
self.background(move |stop| async move {
let mut changes = owner.store.subscribe_changes();
loop {
if let Err(error) = owner.publish_root_completions(&stop).await {
tracing::error!(%error, "Cross-Root completion publication failed");
}
tokio::select! {
() = stop.cancelled() => return,
result = changes.changed() => if result.is_err() { return; },
}
}
});
}
async fn dispatch_outbox_entry(
&self,
router: &dyn maka_host_runtime::application::RootRouter,
writer: DataWriter,
entry: PendingOutboxEntry,
stop: &CancellationToken,
) -> Result<(String, bool), String> {
let target_root = entry.target_root;
let attachments = self.wake_outbox_attachments(&entry.request).await;
let call = tokio::select! {
biased;
() = stop.cancelled() => return Ok((target_root, false)),
result = router.call(
&target_root,
ENDPOINT,
DELIVER,
entry.request,
attachments,
Some(Uuid::new_v4()),
) => result,
};
let dispatch = match call {
Ok(value) => Dispatch::Settled(value),
Err(RootCallError::Rejected(error)) => {
Dispatch::Settled(serde_json::json!({ "error": error }))
}
Err(RootCallError::Unavailable(error)) => {
let shift = entry.attempts.min(5);
let backoff_ms = (2_000_i64 << shift).min(60_000);
tracing::debug!(
target = %target_root,
op_id = %entry.op_id,
attempts = entry.attempts,
backoff_ms,
%error,
"Cross-Root delivery deferred"
);
Dispatch::RetryAt {
next_attempt: clock()?.saturating_add(backoff_ms),
error,
}
}
};
let Some(_producer) = self.producer().await else {
return Ok((target_root, false));
};
writer
.write(SetDispatch {
owner: self.run_owner(),
op_id: entry.op_id,
result: dispatch,
})
.await
.map_err(|e| e.to_string())?;
Ok((target_root, true))
}
async fn wake_outbox_attachments(&self, request: &Value) -> Attachments {
let Ok(delivery) = serde_json::from_value::<DeliveryRequest>(request.clone()) else {
return Attachments::new();
};
let Action::Wake {
source_room_id,
attachments,
..
} = delivery.operation.action
else {
return Attachments::new();
};
if attachments.is_empty() {
return Attachments::new();
}
self.load_cross_root_attachments(&source_room_id, &attachments, false)
.await
.unwrap_or_default()
}
async fn publish_root_completions(&self, stop: &CancellationToken) -> Result<(), String> {
let writer = self.root_writer()?;
let mut after = None;
while !stop.is_cancelled() {
let watches = writer
.query(PendingWatches {
owner: self.run_owner(),
after,
})
.await
.map_err(|e| e.to_string())?;
let Some(last) = watches.last() else {
return Ok(());
};
after = Some((last.session.clone(), last.message.clone()));
let mut runs = BTreeSet::new();
let mut resolutions = Vec::with_capacity(watches.len());
for watch in watches {
let resolution = self
.durable
.queue()
.resolve_message(watch.session.clone(), watch.message.clone())
.await
.map_err(|e| e.to_string())?;
if let MessageResolution::Delivered { run, .. } = resolution {
runs.insert(run);
}
resolutions.push((watch, resolution));
}
let states = self
.durable
.notification_states(self.run_owner(), runs)
.await
.map_err(|e| e.to_string())?;
for (watch, resolution) in resolutions {
let terminal = match resolution {
MessageResolution::Delivered { run, .. } => {
states.get(&run).and_then(|state| state.terminal.clone())
}
MessageResolution::Cancelled | MessageResolution::Missing => {
Some(Terminal::Cancelled)
}
MessageResolution::Pending => None,
};
let status = match terminal {
Some(Terminal::Completed) => CompletionStatus::Completed,
Some(Terminal::Failed) => CompletionStatus::Failed,
Some(Terminal::Cancelled) => CompletionStatus::Cancelled,
None => continue,
};
let route: CompletionRoute =
serde_json::from_value(watch.route.clone()).map_err(|e| e.to_string())?;
let outgoing = outgoing(Operation {
op_id: related_id(
route.original_op_id,
&[
"complete",
&route.source_root,
&self.data_source.state_domain,
],
),
source_root: self.data_source.state_domain.clone(),
target_root: route.source_root,
hop_count: route.hop_count,
action: Action::Complete {
original_op_id: route.original_op_id,
destination: route.destination,
worker_session_id: watch.session.clone(),
message_id: watch.message.clone(),
status,
error: None,
},
})?;
let Some(_producer) = self.producer().await else {
return Ok(());
};
writer
.write(PublishCompletion {
owner: self.run_owner(),
watch,
outgoing,
})
.await
.map_err(|e| e.to_string())?;
}
}
Ok(())
}
}
fn unpack_attachment_bundle(
resource: &dyn maka_capabilities::call::ReadResource,
cancellation: &CancellationToken,
stop: &CancellationToken,
) -> Result<BTreeMap<String, Vec<u8>>, String> {
if resource.resource_type() != maka_plugin_core::contract::binary_resource_type()
|| resource.encoding() != maka_capabilities::call::ResourceEncoding::Bytes
{
return Err("agent_attachment_invalid".into());
}
let total = resource.bytes();
if total as u64 > CROSS_ROOT_ATTACHMENT_BUDGET {
return Err("Cross-Root attachments exceed the 64 MiB transfer window".into());
}
let mut raw = Vec::with_capacity(total);
for offset in (0..total).step_by(64 * 1024) {
if cancellation.is_cancelled() || stop.is_cancelled() {
return Err("agent_attachment_cancelled".into());
}
let end = (offset + 64 * 1024).min(total);
let chunk = resource.read(offset..end)?;
if chunk.len() != end - offset {
return Err("agent_attachment_invalid".into());
}
raw.extend_from_slice(&chunk);
}
let mut cursor = 0usize;
let mut out = BTreeMap::new();
while cursor < raw.len() {
let key_len_end = cursor.checked_add(4).ok_or("agent_attachment_invalid")?;
if key_len_end > raw.len() {
return Err("agent_attachment_invalid".into());
}
let key_len = u32::from_le_bytes(raw[cursor..key_len_end].try_into().unwrap()) as usize;
cursor = key_len_end;
let key_end = cursor
.checked_add(key_len)
.ok_or("agent_attachment_invalid")?;
if key_end > raw.len() {
return Err("agent_attachment_invalid".into());
}
let key = std::str::from_utf8(&raw[cursor..key_end])
.map_err(|_| "agent_attachment_invalid")?
.to_owned();
cursor = key_end;
let val_len_end = cursor.checked_add(8).ok_or("agent_attachment_invalid")?;
if val_len_end > raw.len() {
return Err("agent_attachment_invalid".into());
}
let val_len = usize::try_from(u64::from_le_bytes(
raw[cursor..val_len_end].try_into().unwrap(),
))
.map_err(|_| "agent_attachment_invalid")?;
cursor = val_len_end;
let val_end = cursor
.checked_add(val_len)
.ok_or("agent_attachment_invalid")?;
if val_end > raw.len() {
return Err("agent_attachment_invalid".into());
}
if out.insert(key, raw[cursor..val_end].to_vec()).is_some() {
return Err("agent_attachments_invalid".into());
}
cursor = val_end;
}
Ok(out)
}
fn validate_remote_create(input: &SessionCreateInput) -> Result<(), String> {
if input.target_root.is_some() || input.fork_from.is_some() {
return Err("Cross-Root creation requires a new Session on the target Root".into());
}
match &input.workspace {
None
| Some(SessionWorkspaceTarget::Same | SessionWorkspaceTarget::Worktree { path: None }) => {
Err("Cross-Root creation requires an explicit workspace on the target Root".into())
}
_ => Ok(()),
}
}
fn new_send(session_id: String, message: String) -> Send {
Send {
session_id,
message,
delivery: Some(SendDelivery::Queue),
on_complete: None,
backend: None,
expected_run_id: None,
attachments: Vec::new(),
mentions: Vec::new(),
reply_to: None,
quotes: Vec::new(),
}
}
fn to_send(input: SessionSendInput) -> Send {
Send {
session_id: input.session_id,
message: input.message,
delivery: input.delivery,
on_complete: None,
backend: input.backend,
expected_run_id: input.expected_run_id,
attachments: input.attachments,
mentions: input.mentions,
reply_to: input.reply_to,
quotes: Vec::new(),
}
}
enum SendCompletion {
Watch {
destination: CompletionDestination,
hop_count: u8,
},
Verify(OriginalDirectDispatch),
}
fn settle(
writer: &DataWriter,
inbox: Inbox,
receipt: &impl Serialize,
material: Option<Value>,
original: Option<OriginalDirectDispatch>,
) -> Result<NativeMutation<Value>, String> {
let receipt = serde_json::to_value(receipt).map_err(|e| e.to_string())?;
let change = writer
.prepare_result(|_| {
Ok(RecordReceipt {
inbox,
receipt,
material,
original,
})
})
.map_err(|e| e.to_string())?;
Ok(NativeMutation::Computed { change })
}
fn unchanged(value: Value) -> Prepared<Value> {
Prepared {
value,
changed: false,
notification: Notification::NONE,
}
}
struct RecordReceipt {
inbox: Inbox,
receipt: Value,
material: Option<Value>,
original: Option<OriginalDirectDispatch>,
}
impl Statement for RecordReceipt {
type Value = Value;
type Output = Value;
fn execute(&self, db: &rusqlite::Connection) -> Result<Prepared<Value>, StoreError> {
if let Some(original) = self.inbox.read(db)? {
return Ok(unchanged(original));
}
if let Some(original) = &self.original {
original.verify(db)?;
}
self.inbox
.record(db, &self.receipt, self.material.as_ref())?;
Ok(Prepared {
value: self.receipt.clone(),
changed: true,
notification: Notification::NONE,
})
}
fn committed(value: Value) -> Value {
value
}
fn isolated_rejection(error: &StoreError) -> bool {
matches!(
error.underlying(),
StoreError::InvalidTransition(_) | StoreError::SessionNotFound
)
}
}
struct RootSend {
owner: RunOwner,
inbox: Inbox,
value: super::send::QueuedSend,
statement: Box<PreparedAgentSend>,
uploads: Vec<PreparedUpload>,
room_wake: bool,
watch: Option<Watch>,
original: Option<OriginalDirectDispatch>,
}
impl Statement for RootSend {
type Value = Value;
type Output = Value;
fn retain(&self) -> Vec<Arc<dyn std::marker::Send + Sync>> {
let mut retained = self.statement.retain();
for upload in &self.uploads {
retained.extend(upload.retain());
}
retained
}
fn execute(&self, db: &rusqlite::Connection) -> Result<Prepared<Value>, StoreError> {
if let Some(original) = self.inbox.read(db)? {
return Ok(unchanged(original));
}
if let Some(original) = &self.original {
original.verify(db)?;
}
let mut notification = Notification::NONE;
for upload in &self.uploads {
let uploaded = upload.execute(db)?;
notification = notification.combine(uploaded.notification);
}
let queued = if self.room_wake {
self.statement.execute_for_room(db)?
} else {
self.statement.execute(db)?
};
if let Some(watch) = &self.watch {
watch.insert(db, &self.owner)?;
}
let receipt = serde_json::to_value(self.value.clone().receipt(queued.value.revision))?;
self.inbox.record(db, &receipt, None)?;
Ok(Prepared {
value: receipt,
changed: true,
notification: notification.combine(queued.notification),
})
}
fn committed(value: Value) -> Value {
value
}
fn isolated_rejection(error: &StoreError) -> bool {
Inbox::is_conflict(error)
|| OriginalDirectDispatch::is_missing(error)
|| PreparedAgentSend::isolated_rejection(error)
}
}