Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions crates/agent/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ process = [
"dep:sha2",
"dep:smol",
"dep:ureq",
"dep:url",
"dep:uuid",
"dep:windows",
"dep:libc",
Expand All @@ -38,6 +39,7 @@ toml = { version = "1.1", optional = true }
# The version the store in `tcode-services` pins: one Turso in the build.
turso = { version = "=0.8.4", default-features = false, optional = true }
ureq = { version = "3", default-features = false, features = ["rustls", "gzip"], optional = true }
url = { version = "2", optional = true }
uuid = { version = "1", features = ["v4"], optional = true }

[target.'cfg(unix)'.dependencies]
Expand Down
23 changes: 20 additions & 3 deletions crates/agent/src/acp_session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,16 @@ pub(crate) trait Dialect: Send + Sync + 'static {
notification: acp::SessionNotification,
) -> Vec<AgentEvent>;

/// Async enrichment on the canonical events produced for a notification,
/// run after the session state lock is released and before emission.
fn enrich_events(
&self,
_cwd: &Path,
_events: &mut [AgentEvent],
) -> impl Future<Output = ()> + Send {
async {}
}

/// Dialect-specific tool name when the generic ACP mapping finds none
/// (for example Antigravity's `Run mcp_<server>_<tool>` titles).
fn tool_name(
Expand Down Expand Up @@ -1094,13 +1104,15 @@ async fn run_actor<D: Dialect>(
let update = (method == "session/update")
.then(|| acp::SessionNotification::deserialize(&params).ok())
.flatten();
let events = {
let (mut events, cwd) = {
let mut state = client.state.lock_recover();
match update {
let events = match update {
Some(update) => dialect.session_update(&mut state, update),
None => dialect.notification(&mut state, &method, params),
}
};
(events, state.cwd().to_path_buf())
};
dialect.enrich_events(&cwd, &mut events).await;
client.emit_all(events).await;
Ok(())
}
Expand Down Expand Up @@ -2662,6 +2674,11 @@ impl State {
}
}

/// The session's working directory.
pub(crate) fn cwd(&self) -> &Path {
&self.cwd
}

/// Whether `session/load` is still answering.
pub(crate) fn loading(&self) -> bool {
self.loading
Expand Down
196 changes: 196 additions & 0 deletions crates/agent/src/antigravity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -553,6 +553,60 @@ fn chunk_is_empty(block: &acp::ContentBlock) -> bool {
}
}

/// When Antigravity's `read_file` reads an image over ACP (`agy` 1.5.x), it
/// sends only the text placeholder `"Showing binary file of type image/..."`
/// with no `ContentBlock::Image`. Extract the file path and declared MIME type
/// so Tcode can capture the image bytes from disk.
fn binary_image_read_target(event: &AgentEvent, cwd: &Path) -> Option<(PathBuf, String)> {
let AgentEvent::ItemCompleted(ThreadItem {
content:
ItemContent::ToolCall {
image_reads,
output,
status: ItemStatus::Completed,
family,
..
},
..
}) = event
else {
return None;
};
if !image_reads.is_empty() {
return None;
}
let Some(crate::ToolFamily::Read { path, .. }) = family.as_deref() else {
return None;
};
if path.is_empty() {
return None;
}
let mime = output
.as_deref()?
.trim()
.strip_prefix("Showing binary file of type ")?
.trim();
mime.starts_with("image/")
.then(|| (cwd.join(path), mime.to_owned()))
}

pub(super) fn read_image_file(path: &Path, declared_mime: Option<&str>) -> Option<Attachment> {
use base64::Engine as _;
match std::fs::read(path) {
Ok(bytes) => {
let encoded = base64::engine::general_purpose::STANDARD.encode(bytes);
crate::tool_output::image(declared_mime, &encoded)
}
Err(error) => {
log::warn!(
"antigravity: could not preserve image read {}: {error}",
path.display()
);
None
}
}
}

fn tool_error_summary(
content: Option<&[acp::ToolCallContent]>,
raw_output: Option<&Value>,
Expand Down Expand Up @@ -994,6 +1048,23 @@ impl Dialect for Antigravity {
events
}

async fn enrich_events(&self, cwd: &Path, events: &mut [AgentEvent]) {
for event in events {
let Some((path, mime)) = binary_image_read_target(event, cwd) else {
continue;
};
if let Some(image) =
crate::process::unblock(move || read_image_file(&path, Some(&mime))).await
&& let AgentEvent::ItemCompleted(ThreadItem {
content: ItemContent::ToolCall { image_reads, .. },
..
}) = event
{
image_reads.push(image);
}
}
}

fn tool_name(
&self,
title: &str,
Expand Down Expand Up @@ -1701,4 +1772,129 @@ mod tests {
assert_eq!(normalize_mcp_tool_name("Run schedule", &servers), None);
assert_eq!(normalize_mcp_tool_name("read_file", &servers), None);
}

/// `read_file` on an image over `agy acp` 1.5.23 sends only the text
/// placeholder `"Showing binary file of type image/..."` with no inline
/// image block; `enrich_events` captures the file from disk, skips
/// non-image binaries, and does not duplicate inline images.
#[test]
fn read_file_image_captures_bytes_from_disk_and_skips_non_images() {
use base64::Engine as _;

const PNG_B64: &str = "iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAAEElEQVR4nGNgYPiPAw0pCQCpcD/BFMrqcwAAAABJRU5ErkJggg==";
let dir = std::env::temp_dir().join(format!("tcode-agy-img-test-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
let png_path = dir.join("shot.png");
let pdf_path = dir.join("doc.pdf");
std::fs::write(
&png_path,
base64::engine::general_purpose::STANDARD
.decode(PNG_B64)
.unwrap(),
)
.unwrap();
std::fs::write(&pdf_path, b"%PDF-1.4\n").unwrap();

let dialect = Antigravity::default();
let mut state = State::new(ProviderKind::Antigravity, dir.clone());
let _ = state.begin_agent_turn("turn-1");

let _ = dialect.session_update(
&mut state,
notification(json!({
"sessionUpdate": "tool_call",
"toolCallId": "call_img",
"title": "File shot.png",
"kind": "read",
"status": "in_progress",
"locations": [{ "path": png_path }],
"rawInput": { "Path": png_path }
})),
);
let mut completed = dialect.session_update(
&mut state,
notification(json!({
"sessionUpdate": "tool_call_update",
"toolCallId": "call_img",
"status": "completed",
"rawOutput": "Showing binary file of type image/png",
"content": [{
"type": "content",
"content": { "type": "text", "text": "Showing binary file of type image/png" }
}]
})),
);
smol::block_on(dialect.enrich_events(&dir, &mut completed));
assert!(matches!(
completed.as_slice(),
[AgentEvent::ItemCompleted(ThreadItem {
id,
content: ItemContent::ToolCall {
image_reads,
output: Some(output),
family: Some(family),
..
},
..
})] if id == "call_img"
&& output == "Showing binary file of type image/png"
&& matches!(family.as_ref(), crate::ToolFamily::Read { .. })
&& image_reads.len() == 1
&& image_reads[0].media_type == "image/png"
&& image_reads[0].data_base64 == PNG_B64
));

// If ACP already delivered an inline image block, enrichment does not duplicate it.
let mut inline = dialect.session_update(
&mut state,
notification(json!({
"sessionUpdate": "tool_call",
"toolCallId": "call_inline",
"title": "File shot.png",
"kind": "read",
"status": "completed",
"locations": [{ "path": png_path }],
"content": [
{ "type": "content", "content": { "type": "text", "text": "Showing binary file of type image/png" } },
{ "type": "content", "content": { "type": "image", "mimeType": "image/png", "data": PNG_B64 } }
]
})),
);
smol::block_on(dialect.enrich_events(&dir, &mut inline));
assert!(matches!(
inline.as_slice(),
[AgentEvent::ItemCompleted(ThreadItem {
content: ItemContent::ToolCall { image_reads, .. },
..
})] if image_reads.len() == 1
));

// Non-image binary reads (such as PDF) stay text-only.
let mut pdf = dialect.session_update(
&mut state,
notification(json!({
"sessionUpdate": "tool_call",
"toolCallId": "call_pdf",
"title": "File doc.pdf",
"kind": "read",
"status": "completed",
"locations": [{ "path": pdf_path }],
"rawOutput": "Showing binary file of type application/pdf",
"content": [{
"type": "content",
"content": { "type": "text", "text": "Showing binary file of type application/pdf" }
}]
})),
);
smol::block_on(dialect.enrich_events(&dir, &mut pdf));
assert!(matches!(
pdf.as_slice(),
[AgentEvent::ItemCompleted(ThreadItem {
content: ItemContent::ToolCall { image_reads, .. },
..
})] if image_reads.is_empty()
));

let _ = std::fs::remove_dir_all(&dir);
}
}
Loading
Loading