use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use agent_client_protocol::schema::v1::{
ContentBlock, ContentChunk, Diff, ImageContent, Plan, PlanEntry, PlanEntryPriority,
PlanEntryStatus, SessionId as AcpSessionId, SessionNotification, SessionUpdate, ToolCall,
ToolCallContent, ToolCallId, ToolCallLocation, ToolCallStatus, ToolCallUpdate,
ToolCallUpdateFields, ToolKind,
};
use agent_client_protocol::{Client, ConnectionTo};
use arabica_model::{RuntimeItem, RuntimeRole};
use arabica_protocol::{Event, EventEnvelope};
use arabica_provider::{ModelProgress, ModelProgressSink};
use arabica_session::{EventVisibility, SessionEventObserver};
use serde_json::Value;
pub struct AcpObserver {
connection: ConnectionTo<Client>,
session_id: AcpSessionId,
workspace_root: PathBuf,
streamed: Mutex<StreamedContent>,
open_calls: Mutex<OpenToolCalls>,
}
#[derive(Default)]
struct StreamedContent {
message: String,
reasoning: String,
}
impl AcpObserver {
pub fn new(
connection: ConnectionTo<Client>,
session_id: AcpSessionId,
workspace_root: PathBuf,
) -> Self {
Self {
connection,
session_id,
workspace_root,
streamed: Mutex::new(StreamedContent::default()),
open_calls: Mutex::new(OpenToolCalls::default()),
}
}
pub fn progress_sink(self: &Arc<Self>) -> ModelProgressSink {
let observer = Arc::clone(self);
ModelProgressSink::new(move |progress| {
let update = match progress {
ModelProgress::Start => {
*observer
.streamed
.lock()
.expect("stream state lock poisoned") = StreamedContent::default();
return;
}
ModelProgress::Message(text) => {
observer
.streamed
.lock()
.expect("stream state lock poisoned")
.message
.push_str(&text);
SessionUpdate::AgentMessageChunk(ContentChunk::new(ContentBlock::from(text)))
}
ModelProgress::Reasoning(text) => {
observer
.streamed
.lock()
.expect("stream state lock poisoned")
.reasoning
.push_str(&text);
SessionUpdate::AgentThoughtChunk(ContentChunk::new(ContentBlock::from(text)))
}
};
observer.send(update);
})
}
fn send(&self, update: SessionUpdate) {
if let Err(error) = self
.connection
.send_notification(SessionNotification::new(self.session_id.clone(), update))
{
eprintln!("structure acp: dropped a session/update: {error}");
}
}
}
impl SessionEventObserver for AcpObserver {
fn observe(&self, envelope: &EventEnvelope, _visibility: EventVisibility) {
let mut updates = updates_for(&envelope.event, &envelope.run_id, &self.workspace_root);
updates.extend(
self.open_calls
.lock()
.expect("open tool calls lock poisoned")
.track(&envelope.event, &envelope.run_id),
);
if let Event::ModelResponseItem { item, .. } = &envelope.event {
let streamed = self.streamed.lock().expect("stream state lock poisoned");
let already_sent = match item {
RuntimeItem::Message(message) if message.role == RuntimeRole::Assistant => {
Some(streamed.message.as_str())
}
RuntimeItem::Reasoning(_) => Some(streamed.reasoning.as_str()),
_ => None,
};
if let Some(already_sent) = already_sent
&& !already_sent.is_empty()
&& updates.len() == 1
{
match &mut updates[0] {
SessionUpdate::AgentMessageChunk(chunk)
| SessionUpdate::AgentThoughtChunk(chunk) => {
if let ContentBlock::Text(text) = &mut chunk.content
&& let Some(rest) = text.text.strip_prefix(already_sent)
{
text.text = rest.to_owned();
if text.text.is_empty() {
updates.clear();
}
}
}
_ => {}
}
}
}
for update in updates {
self.send(update);
}
}
}
pub(super) fn acp_tool_call_id(
run_id: &Option<arabica_protocol::RunId>,
call_id: &str,
) -> ToolCallId {
match run_id {
Some(run_id) => ToolCallId::new(format!("{run_id}:{call_id}")),
None => ToolCallId::new(call_id.to_owned()),
}
}
pub fn tool_kind(name: &str) -> ToolKind {
match name {
"read_file" | "list_dir" => ToolKind::Read,
"grep" | "find_files" => ToolKind::Search,
"write_file" | "edit_files" => ToolKind::Edit,
"delete_file" => ToolKind::Delete,
"shell" => ToolKind::Execute,
_ => ToolKind::Other,
}
}
pub fn tool_call_title(name: &str, arguments: &Value) -> String {
let path = arguments.get("path").and_then(Value::as_str);
match name {
"read_file" => path.map_or_else(|| "Read file".to_owned(), |path| format!("Read {path}")),
"list_dir" => path.map_or_else(
|| "List directory".to_owned(),
|path| format!("List {path}"),
),
"write_file" => {
path.map_or_else(|| "Write file".to_owned(), |path| format!("Write {path}"))
}
"delete_file" => {
path.map_or_else(|| "Delete file".to_owned(), |path| format!("Delete {path}"))
}
"edit_files" => {
let count = arguments
.get("edits")
.and_then(Value::as_array)
.map_or(0, Vec::len);
match count {
1 => "Edit 1 file".to_owned(),
count => format!("Edit {count} files"),
}
}
"grep" => arguments
.get("pattern")
.and_then(Value::as_str)
.map_or_else(
|| "Search".to_owned(),
|pattern| format!("Search for {pattern:?}"),
),
"find_files" => arguments.get("glob").and_then(Value::as_str).map_or_else(
|| "Find files".to_owned(),
|glob| format!("Find files matching {glob:?}"),
),
"shell" => arguments
.get("command")
.and_then(Value::as_str)
.map_or_else(
|| "Run command".to_owned(),
|command| format!("Run `{command}`"),
),
other => other.to_owned(),
}
}
fn resolve_path(workspace_root: &Path, arguments: &Value) -> Option<PathBuf> {
arguments
.get("path")
.and_then(Value::as_str)
.map(|path| workspace_root.join(path))
}
fn tool_call_locations(workspace_root: &Path, arguments: &Value) -> Vec<ToolCallLocation> {
resolve_path(workspace_root, arguments)
.map(|path| vec![ToolCallLocation::new(path)])
.unwrap_or_default()
}
pub(super) fn diff_content(
workspace_root: &Path,
name: &str,
arguments: &Value,
) -> Vec<ToolCallContent> {
match name {
"write_file" => {
let Some(path) = resolve_path(workspace_root, arguments) else {
return Vec::new();
};
let Some(content) = arguments.get("content").and_then(Value::as_str) else {
return Vec::new();
};
vec![ToolCallContent::Diff(Diff::new(path, content))]
}
"edit_files" => arguments
.get("edits")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|edit| {
let path = workspace_root.join(edit.get("path")?.as_str()?);
let old_string = edit.get("old_string")?.as_str()?;
let new_string = edit.get("new_string")?.as_str()?;
Some(ToolCallContent::Diff(
Diff::new(path, new_string).old_text(old_string),
))
})
.collect(),
_ => Vec::new(),
}
}
fn message_chunks(content: &[arabica_model::ContentBlock]) -> Vec<ContentBlock> {
content
.iter()
.filter_map(|block| match block {
arabica_model::ContentBlock::Text { text } if !text.is_empty() => {
Some(ContentBlock::from(text.as_str()))
}
_ => None,
})
.collect()
}
pub(super) fn replay_updates_for(
event: &Event,
run_id: &Option<arabica_protocol::RunId>,
workspace_root: &Path,
) -> Vec<SessionUpdate> {
if let Event::MessageAccepted { content, images } = event {
let text = (!content.is_empty() || images.is_empty())
.then(|| ContentBlock::from(content.as_str()));
return text
.into_iter()
.chain(images.iter().map(|image| {
ContentBlock::Image(ImageContent::new(
image.data_base64.clone(),
image.media_type.clone(),
))
}))
.map(|block| SessionUpdate::UserMessageChunk(ContentChunk::new(block)))
.collect();
}
updates_for(event, run_id, workspace_root)
}
pub(super) fn updates_for(
event: &Event,
run_id: &Option<arabica_protocol::RunId>,
workspace_root: &Path,
) -> Vec<SessionUpdate> {
match event {
Event::ModelResponseItem { item, .. } => match item {
RuntimeItem::Message(message) if message.role == RuntimeRole::Assistant => {
message_chunks(&message.content)
.into_iter()
.map(|block| {
let mut chunk = ContentChunk::new(block);
if let Some(id) = &message.id {
chunk = chunk.message_id(id.as_str());
}
SessionUpdate::AgentMessageChunk(chunk)
})
.collect()
}
RuntimeItem::Reasoning(reasoning) if !reasoning.summary.is_empty() => {
let mut chunk = ContentChunk::new(ContentBlock::from(reasoning.summary.join("\n\n")));
if let Some(id) = &reasoning.id {
chunk = chunk.message_id(id.as_str());
}
vec![SessionUpdate::AgentThoughtChunk(chunk)]
}
RuntimeItem::Message(_) | RuntimeItem::Reasoning(_) | RuntimeItem::ToolCall(_)
| RuntimeItem::ToolResult(_) => Vec::new(),
},
Event::ToolCallRequested {
call_id,
name,
arguments,
..
} => {
let mut call = ToolCall::new(acp_tool_call_id(run_id, call_id), tool_call_title(name, arguments))
.name(name.clone())
.kind(tool_kind(name))
.status(ToolCallStatus::Pending)
.raw_input(arguments.clone())
.locations(tool_call_locations(workspace_root, arguments));
let diff = diff_content(workspace_root, name, arguments);
if !diff.is_empty() {
call = call.content(diff);
}
vec![SessionUpdate::ToolCall(call)]
}
Event::ToolCallClassified { call_id, .. } => vec![in_progress(run_id, call_id)],
Event::ToolCallPermissionResolved {
call_id,
outcome: arabica_protocol::ToolPermissionOutcome::Allowed,
..
} => vec![in_progress(run_id, call_id)],
Event::ToolCallCompleted {
call_id,
result,
is_error,
..
} => {
let status = if *is_error {
ToolCallStatus::Failed
} else {
ToolCallStatus::Completed
};
vec![SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
acp_tool_call_id(run_id, call_id),
ToolCallUpdateFields::new()
.status(status)
.content(vec![ToolCallContent::from(result.as_str())]),
))]
}
Event::PlanUpdated { entries, .. } => vec![SessionUpdate::Plan(Plan::new(
entries
.iter()
.map(|entry| {
let status = match entry.status {
arabica_protocol::PlanEntryStatus::Pending => PlanEntryStatus::Pending,
arabica_protocol::PlanEntryStatus::InProgress => PlanEntryStatus::InProgress,
arabica_protocol::PlanEntryStatus::Completed => PlanEntryStatus::Completed,
};
PlanEntry::new(entry.content.clone(), PlanEntryPriority::Medium, status)
})
.collect(),
))],
Event::ToolCallPermissionResolved { .. }
| Event::ToolCallPermissionRequested { .. }
| Event::SessionCreated { .. }
| Event::SessionForked { .. }
| Event::SessionResumed
| Event::SessionSuspended
| Event::SessionClosed
| Event::RunScheduled
| Event::RunStarted
| Event::MessageAccepted { .. }
| Event::ContextRunResolved { .. }
| Event::ContextRequestExposed { .. }
| Event::ContextItemUnfolded { .. }
| Event::ContextCallStarted { .. }
| Event::ContextCallRejected { .. }
| Event::ModelRequestPrepared { .. }
| Event::ModelRouteSelected { .. }
| Event::ModelRouteExplained { .. }
| Event::ToolExecutionObserved { .. }
| Event::ModelCallObserved { .. }
| Event::ModelResponseCompleted { .. }
| Event::ModelResponseRejected { .. }
| Event::ModelResponseNormalized { .. }
| Event::ToolCallReused { .. }
| Event::ToolCallLoopBlocked { .. }
| Event::AgentProgressAdvisory { .. }
| Event::PlanDelegationObserved { .. }
| Event::AgentLoopTerminated { .. }
| Event::TerminalControlTransition { .. }
| Event::CommandOutput { .. }
| Event::RunCompleted { .. }
| Event::RunFailed { .. }
| Event::RunCancelled
| Event::ContextRead { .. }
| Event::ContextSearchResult { .. }
| Event::ContextUpdated { .. }
| Event::ContextDeleted { .. }
| Event::ContextDisclosureSet { .. }
| Event::Error { .. } => Vec::new(),
}
}
#[derive(Default)]
pub(super) struct OpenToolCalls(Vec<(Option<arabica_protocol::RunId>, String)>);
impl OpenToolCalls {
pub(super) fn track(
&mut self,
event: &Event,
run_id: &Option<arabica_protocol::RunId>,
) -> Vec<SessionUpdate> {
let reason = match event {
Event::ToolCallRequested { call_id, .. } => {
self.0.push((run_id.clone(), call_id.clone()));
return Vec::new();
}
Event::ToolCallCompleted { call_id, .. } => {
self.0
.retain(|(open_run, open_call)| open_run != run_id || open_call != call_id);
return Vec::new();
}
Event::RunFailed { .. } | Event::RunCompleted { .. } => {
"The run ended before this tool call reported a result; its outcome is unknown."
}
Event::RunCancelled => {
"The run was cancelled before this tool call reported a result; it may still have taken effect."
}
_ => return Vec::new(),
};
let (ended, open): (Vec<_>, Vec<_>) = std::mem::take(&mut self.0)
.into_iter()
.partition(|(open_run, _)| open_run == run_id);
self.0 = open;
ended
.into_iter()
.map(|(_, call_id)| {
SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
acp_tool_call_id(run_id, &call_id),
ToolCallUpdateFields::new()
.status(ToolCallStatus::Failed)
.content(vec![ToolCallContent::from(reason)]),
))
})
.collect()
}
}
fn in_progress(run_id: &Option<arabica_protocol::RunId>, call_id: &str) -> SessionUpdate {
SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
acp_tool_call_id(run_id, call_id),
ToolCallUpdateFields::new().status(ToolCallStatus::InProgress),
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepted_images_are_replayed_after_their_text() {
let image = arabica_model::ImageInput {
media_type: "image/png".to_owned(),
data_base64: "aGVsbG8=".to_owned(),
};
let event = Event::MessageAccepted {
content: "describe".to_owned(),
images: vec![image.clone()],
};
let updates = replay_updates_for(&event, &None, Path::new("/workspace"));
let blocks: Vec<_> = updates
.iter()
.map(|update| match update {
SessionUpdate::UserMessageChunk(chunk) => &chunk.content,
other => panic!("expected user chunks, got {other:?}"),
})
.collect();
assert!(matches!(blocks[0], ContentBlock::Text(text) if text.text == "describe"));
assert!(matches!(
blocks[1],
ContentBlock::Image(img) if img.data == image.data_base64 && img.mime_type == image.media_type
));
let image_only = Event::MessageAccepted {
content: String::new(),
images: vec![image],
};
let updates = replay_updates_for(&image_only, &None, Path::new("/workspace"));
assert_eq!(updates.len(), 1);
}
#[test]
fn accepted_messages_are_replayed_without_echoing_live_prompts() {
let content = "First line\n\nSecond line: cafรฉ โ";
let event = Event::MessageAccepted {
content: content.to_owned(),
images: Vec::new(),
};
let updates = replay_updates_for(&event, &None, Path::new("/workspace"));
assert_eq!(updates.len(), 1);
let SessionUpdate::UserMessageChunk(chunk) = &updates[0] else {
panic!("expected a user message chunk");
};
let ContentBlock::Text(text) = &chunk.content else {
panic!("expected text content");
};
assert_eq!(text.text, content);
assert!(updates_for(&event, &None, Path::new("/workspace")).is_empty());
}
#[test]
fn calls_left_open_when_a_run_ends_are_reported_failed() {
let run = Some(arabica_protocol::RunId::new("run-1"));
let other = Some(arabica_protocol::RunId::new("run-2"));
let requested = |call_id: &str| Event::ToolCallRequested {
call_id: call_id.to_owned(),
name: "mcp__agentnexus__echo".to_owned(),
arguments: serde_json::json!({}),
provider_state: None,
};
let mut open = OpenToolCalls::default();
assert!(open.track(&requested("done"), &run).is_empty());
assert!(open.track(&requested("dangling"), &run).is_empty());
assert!(open.track(&requested("elsewhere"), &other).is_empty());
let completed = Event::ToolCallCompleted {
call_id: "done".to_owned(),
name: "mcp__agentnexus__echo".to_owned(),
result: "ok".to_owned(),
is_error: false,
};
assert!(open.track(&completed, &run).is_empty());
let settled = open.track(
&Event::RunFailed {
message: "outcome unknown".to_owned(),
},
&run,
);
assert_eq!(settled.len(), 1);
let SessionUpdate::ToolCallUpdate(update) = &settled[0] else {
panic!("expected a tool call update, got {settled:?}");
};
assert_eq!(update.tool_call_id, acp_tool_call_id(&run, "dangling"));
assert_eq!(update.fields.status, Some(ToolCallStatus::Failed));
let cancelled = open.track(&Event::RunCancelled, &other);
assert_eq!(cancelled.len(), 1);
assert!(open.track(&Event::RunCancelled, &run).is_empty());
}
#[test]
fn tool_kind_matches_the_plans_categories() {
assert_eq!(tool_kind("read_file"), ToolKind::Read);
assert_eq!(tool_kind("list_dir"), ToolKind::Read);
assert_eq!(tool_kind("grep"), ToolKind::Search);
assert_eq!(tool_kind("find_files"), ToolKind::Search);
assert_eq!(tool_kind("write_file"), ToolKind::Edit);
assert_eq!(tool_kind("edit_files"), ToolKind::Edit);
assert_eq!(tool_kind("delete_file"), ToolKind::Delete);
assert_eq!(tool_kind("shell"), ToolKind::Execute);
assert_eq!(tool_kind("unknown_future_tool"), ToolKind::Other);
}
#[test]
fn a_tool_call_requested_event_becomes_a_pending_tool_call() {
let run_id = Some(arabica_protocol::RunId::new("run-1"));
let updates = updates_for(
&Event::ToolCallRequested {
call_id: "call-1".to_owned(),
name: "read_file".to_owned(),
arguments: serde_json::json!({"path": "src/main.rs"}),
provider_state: None,
},
&run_id,
Path::new("/workspace"),
);
assert_eq!(updates.len(), 1);
let SessionUpdate::ToolCall(call) = &updates[0] else {
panic!("expected a ToolCall update");
};
assert_eq!(call.tool_call_id, ToolCallId::new("run-1:call-1"));
assert_eq!(call.title, "Read src/main.rs");
assert_eq!(call.kind, ToolKind::Read);
assert_eq!(call.status, ToolCallStatus::Pending);
assert_eq!(
call.locations,
vec![ToolCallLocation::new("/workspace/src/main.rs")]
);
}
#[test]
fn a_write_file_request_carries_a_diff_with_no_old_text() {
let updates = updates_for(
&Event::ToolCallRequested {
call_id: "call-1".to_owned(),
name: "write_file".to_owned(),
arguments: serde_json::json!({"path": "a.txt", "content": "hello"}),
provider_state: None,
},
&Some(arabica_protocol::RunId::new("run-1")),
Path::new("/ws"),
);
let SessionUpdate::ToolCall(call) = &updates[0] else {
panic!("expected a ToolCall update");
};
assert_eq!(call.content.len(), 1);
let ToolCallContent::Diff(diff) = &call.content[0] else {
panic!("expected a Diff content block");
};
assert_eq!(diff.path, PathBuf::from("/ws/a.txt"));
assert_eq!(diff.old_text, None);
assert_eq!(diff.new_text, "hello");
}
#[test]
fn an_edit_files_request_carries_one_diff_per_edit() {
let updates = updates_for(
&Event::ToolCallRequested {
call_id: "call-1".to_owned(),
name: "edit_files".to_owned(),
arguments: serde_json::json!({"edits": [
{"path": "a.txt", "old_string": "old", "new_string": "new"},
{"path": "b.txt", "old_string": "x", "new_string": "y"},
]}),
provider_state: None,
},
&Some(arabica_protocol::RunId::new("run-1")),
Path::new("/ws"),
);
let SessionUpdate::ToolCall(call) = &updates[0] else {
panic!("expected a ToolCall update");
};
assert_eq!(call.content.len(), 2);
}
#[test]
fn classified_and_allowed_both_report_in_progress() {
let run_id = Some(arabica_protocol::RunId::new("run-1"));
for event in [
Event::ToolCallClassified {
call_id: "call-1".to_owned(),
kind: arabica_protocol::ToolInteractionKind::Inspection,
},
Event::ToolCallPermissionResolved {
call_id: "call-1".to_owned(),
outcome: arabica_protocol::ToolPermissionOutcome::Allowed,
scope: arabica_protocol::ToolPermissionScope::Once,
source: arabica_protocol::ToolPermissionSource::Policy,
},
] {
let updates = updates_for(&event, &run_id, Path::new("/ws"));
assert_eq!(updates.len(), 1);
let SessionUpdate::ToolCallUpdate(update) = &updates[0] else {
panic!("expected a ToolCallUpdate");
};
assert_eq!(update.tool_call_id, ToolCallId::new("run-1:call-1"));
assert_eq!(update.fields.status, Some(ToolCallStatus::InProgress));
}
}
#[test]
fn a_denied_permission_resolution_alone_produces_no_update() {
let updates = updates_for(
&Event::ToolCallPermissionResolved {
call_id: "call-1".to_owned(),
outcome: arabica_protocol::ToolPermissionOutcome::Denied,
scope: arabica_protocol::ToolPermissionScope::Once,
source: arabica_protocol::ToolPermissionSource::Policy,
},
&Some(arabica_protocol::RunId::new("run-1")),
Path::new("/ws"),
);
assert!(updates.is_empty());
}
#[test]
fn a_completed_call_reports_success_and_an_errored_one_reports_failure() {
let run_id = Some(arabica_protocol::RunId::new("run-1"));
let ok = updates_for(
&Event::ToolCallCompleted {
call_id: "call-1".to_owned(),
name: "read_file".to_owned(),
result: "file contents".to_owned(),
is_error: false,
},
&run_id,
Path::new("/ws"),
);
let SessionUpdate::ToolCallUpdate(update) = &ok[0] else {
panic!("expected a ToolCallUpdate");
};
assert_eq!(update.fields.status, Some(ToolCallStatus::Completed));
let failed = updates_for(
&Event::ToolCallCompleted {
call_id: "call-2".to_owned(),
name: "shell".to_owned(),
result: "permission denied".to_owned(),
is_error: true,
},
&run_id,
Path::new("/ws"),
);
let SessionUpdate::ToolCallUpdate(update) = &failed[0] else {
panic!("expected a ToolCallUpdate");
};
assert_eq!(update.fields.status, Some(ToolCallStatus::Failed));
}
#[test]
fn assistant_text_becomes_an_agent_message_chunk_but_a_tool_result_item_is_ignored() {
let assistant_message = updates_for(
&Event::ModelResponseItem {
model_step: 1,
item_index: 0,
item: RuntimeItem::Message(arabica_model::MessageItem {
id: Some("msg-1".to_owned()),
role: RuntimeRole::Assistant,
content: vec![arabica_model::ContentBlock::Text {
text: "hello".to_owned(),
}],
provider_state: None,
}),
},
&Some(arabica_protocol::RunId::new("run-1")),
Path::new("/ws"),
);
assert_eq!(assistant_message.len(), 1);
assert!(matches!(
assistant_message[0],
SessionUpdate::AgentMessageChunk(_)
));
let tool_result_item = updates_for(
&Event::ModelResponseItem {
model_step: 1,
item_index: 1,
item: RuntimeItem::ToolResult(arabica_model::ToolResultItem {
id: None,
call_id: "call-1".to_owned(),
name: Some("read_file".to_owned()),
content: vec![arabica_model::ContentBlock::Text {
text: "dup".to_owned(),
}],
is_error: false,
}),
},
&Some(arabica_protocol::RunId::new("run-1")),
Path::new("/ws"),
);
assert!(tool_result_item.is_empty());
}
}