blob: 5d0a21e36ce04116d9bc18eab452e423bf7528cf [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::*;
use base64::{Engine, engine::general_purpose::STANDARD};
use maka_agent_facts::attachment::{
MAX_INLINE_EXTERNAL_TEXT_BYTES, native_image_extension, sanitize_attachment_filename,
};
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
use std::{
io::Write,
path::{Path, PathBuf},
};
pub(super) struct PreparedPrompt<T> {
pub(super) blocks: Vec<T>,
pub(super) staging_dir: Option<PathBuf>,
}
struct CancelOnDrop(tokio_util::sync::CancellationToken);
impl Drop for CancelOnDrop {
fn drop(&mut self) {
self.0.cancel();
}
}
impl Driver<'_> {
pub(super) fn prompt_content<'a, T: DeserializeOwned + 'a>(
&'a self,
connection: &Connection,
) -> impl std::future::Future<Output = Result<PreparedPrompt<T>, Error>> + Send + 'a {
let capabilities = match connection.peer.as_ref() {
Some(Peer::V1(_, peer)) => Ok((
peer.agent_capabilities.prompt_capabilities.image,
peer.agent_capabilities.prompt_capabilities.embedded_context,
)),
Some(Peer::V2(_, peer)) => Ok(peer
.capabilities
.session
.as_ref()
.and_then(|session| session.prompt.as_ref())
.map_or((false, false), |caps| {
(caps.image.is_some(), caps.embedded_context.is_some())
})),
None => Err(Error::Invalid("ACP peer has not initialized")),
};
async move {
let prepared: Result<PreparedPrompt<T>, Error> = async {
if self.context.cancellation.is_cancelled() {
return Err(Error::Cancelled);
}
let (image, embedded) = capabilities?;
let (attachments, inputs_directory) = if let Some(scope) = &self.context.call {
let attachments = self
.host
.callbacks
.prompt_attachments(scope)
.map_err(|error| Error::Output(executor::Error::Provider(error)))?;
let inputs_directory = if attachments.is_empty() {
None
} else {
Some(PathBuf::from(
self.host
.callbacks
.private_paths(scope)
.map_err(|error| {
Error::Output(executor::Error::IsolationUnavailable(error))
})?
.inputs_directory,
))
};
(attachments, inputs_directory)
} else {
(vec![], None)
};
let text = prompt(
&self.request.content,
self.request.instructions.as_deref(),
self.request.language,
)?;
let (content, staging_dir) = if attachments.is_empty() {
(
text.into_iter()
.map(|text| json!({"type":"text","text":text}))
.collect(),
None,
)
} else {
let mut ticket = self
.context
.call
.as_ref()
.map(|scope| {
scope.resources.reserve().map_err(|error| {
Error::Output(executor::Error::Provider(format!(
"ACP attachment preparation worker rejected: {error}"
)))
})
})
.transpose()?;
if let Some(ticket) = ticket.as_mut() {
ticket.start();
}
let language = self.request.language;
let prep_cancel = self.context.cancellation.child_token();
let _cancel_on_drop = CancelOnDrop(prep_cancel.clone());
let worker_cancel = prep_cancel.clone();
tokio::task::spawn_blocking(move || {
let result = blocks(
text,
attachments,
inputs_directory.as_deref(),
image,
embedded,
language,
&worker_cancel,
);
let result = match result {
Ok((_, dir)) if worker_cancel.is_cancelled() => {
if let Some(dir) = dir
&& let Err(error) = remove_materialized_dir(&dir)
{
eprintln!(
"acp engine: stage=attachment_cleanup_failed path={} error={error}",
dir.display()
);
}
Err(Error::Cancelled)
}
other => other,
};
if let Some(ticket) = ticket {
ticket.complete(Ok(()));
}
result
})
.await
.map_err(|error| {
Error::Output(executor::Error::Provider(format!(
"ACP attachment preparation worker failed: {error}"
)))
})??
};
let decoded = content
.into_iter()
.map(|block| serde_json::from_value(block).map_err(Error::from))
.collect::<Result<Vec<T>, Error>>();
match decoded {
Ok(blocks) => Ok(PreparedPrompt {
blocks,
staging_dir,
}),
Err(error) => {
if let Some(dir) = staging_dir
&& let Err(cleanup_error) = remove_materialized_dir(&dir)
{
eprintln!(
"acp engine: stage=attachment_cleanup_failed path={} error={cleanup_error}",
dir.display()
);
}
Err(error)
}
}
}
.await;
prepared.map_err(|error| match error {
error @ (Error::Invalid(_)
| Error::Decode(_)
| Error::AttachmentIo(_)
| Error::AttachmentRead(_)) => Error::RejectedBeforePrompt(Box::new(error)),
error => error,
})
}
}
}
struct MaterializedFile {
name: String,
mime_type: String,
bytes: usize,
path: String,
}
fn blocks(
text: Vec<String>,
attachments: Vec<crate::ports::PromptAttachment>,
inputs_directory: Option<&Path>,
image: bool,
embedded: bool,
language: maka_agent_facts::language::Language,
cancellation: &tokio_util::sync::CancellationToken,
) -> Result<(Vec<Value>, Option<PathBuf>), Error> {
let mut staging_dir: Option<PathBuf> = None;
let result = (|| {
let mut blocks: Vec<_> = text
.into_iter()
.map(|text| json!({"type":"text","text":text}))
.collect();
let mut materialized_files = Vec::new();
for (index, attachment) in attachments.into_iter().enumerate() {
if attachment.name.is_empty()
|| attachment.name.chars().any(char::is_control)
|| attachment.mime_type.is_empty()
|| attachment.mime_type.chars().any(char::is_control)
{
return Err(Error::Invalid("ACP attachment metadata is invalid"));
}
let resource = attachment.resource;
let total_bytes = resource.bytes();
let is_native_image = native_image_extension(&attachment.mime_type).is_some();
let is_small_text = (attachment.mime_type.starts_with("text/")
|| attachment.mime_type == "application/json")
&& total_bytes <= MAX_INLINE_EXTERNAL_TEXT_BYTES;
if is_native_image && image {
let bytes = read_all(resource.as_ref(), cancellation)?;
let uri = format!("maka-attachment:{index}");
let label = maka_agent_facts::i18n::history::acp_attachment_prefix(language);
blocks.push(json!({"type":"text","text":format!("{label}{}", attachment.name)}));
blocks.push(json!({
"type":"image",
"data":STANDARD.encode(&bytes),
"mimeType":attachment.mime_type,
"uri":uri
}));
} else if is_small_text {
let bytes = read_all(resource.as_ref(), cancellation)?;
if let Some(text) = std::str::from_utf8(&bytes)
.ok()
.filter(|text| !text.contains('\0'))
{
let uri = format!("maka-attachment:{index}");
let label = maka_agent_facts::i18n::history::acp_attachment_prefix(language);
blocks
.push(json!({"type":"text","text":format!("{label}{}", attachment.name)}));
let block = if embedded {
json!({"type":"resource","resource":{"uri":uri,"mimeType":attachment.mime_type,"text":text}})
} else {
json!({"type":"text","text":text})
};
blocks.push(block);
} else {
let path = materialize_bytes(
&mut staging_dir,
inputs_directory,
index,
&attachment.name,
&bytes,
)?;
materialized_files.push(MaterializedFile {
name: attachment.name,
mime_type: attachment.mime_type,
bytes: total_bytes,
path,
});
}
} else {
let path = materialize_stream(
&mut staging_dir,
inputs_directory,
index,
&attachment.name,
resource.as_ref(),
cancellation,
)?;
materialized_files.push(MaterializedFile {
name: attachment.name,
mime_type: attachment.mime_type,
bytes: total_bytes,
path,
});
}
}
if !materialized_files.is_empty() {
let mut summary =
String::from("--- Attached files (read-only local copies for this turn) ---");
for file in materialized_files {
summary.push_str(&format!(
"\n- name: {}, mimeType: {}, bytes: {}, path: {}",
serde_json::to_string(&file.name).expect("attachment name"),
serde_json::to_string(&file.mime_type).expect("attachment mime type"),
file.bytes,
serde_json::to_string(&file.path).expect("attachment path"),
));
}
summary.push_str("\n--- End attached files ---");
blocks.push(json!({"type":"text","text":summary}));
}
if cancellation.is_cancelled() {
return Err(Error::Cancelled);
}
Ok(blocks)
})();
match result {
Ok(blocks) => Ok((blocks, staging_dir)),
Err(error) => {
if let Some(dir) = staging_dir
&& let Err(cleanup_error) = remove_materialized_dir(&dir)
{
eprintln!(
"acp engine: stage=attachment_cleanup_failed path={} error={cleanup_error}",
dir.display()
);
}
Err(error)
}
}
}
fn read_all(
resource: &dyn maka_capabilities::call::ReadResource,
cancellation: &tokio_util::sync::CancellationToken,
) -> Result<Vec<u8>, Error> {
let mut bytes = Vec::with_capacity(resource.bytes());
for start in (0..resource.bytes()).step_by(64 * 1024) {
if cancellation.is_cancelled() {
return Err(Error::Cancelled);
}
let end = (start + 64 * 1024).min(resource.bytes());
let chunk = match resource.read(start..end) {
Ok(chunk) => chunk,
Err(_) if cancellation.is_cancelled() => return Err(Error::Cancelled),
Err(error) => return Err(Error::AttachmentRead(error)),
};
if chunk.len() != end - start {
return Err(Error::Invalid("ACP attachment read is incomplete"));
}
bytes.extend_from_slice(&chunk);
}
Ok(bytes)
}
fn create_local_file(
staging_dir: &mut Option<PathBuf>,
inputs_directory: Option<&Path>,
index: usize,
original_name: &str,
) -> Result<(std::fs::File, PathBuf, String), Error> {
let inputs = inputs_directory.ok_or(Error::Invalid("ACP private inputs directory missing"))?;
let root = match staging_dir.as_ref() {
Some(dir) => dir.clone(),
None => {
let base = dunce::canonicalize(inputs).map_err(io_error)?;
let dir = base.join(format!("maka-acp-{}", uuid::Uuid::new_v4()));
std::fs::create_dir(&dir).map_err(io_error)?;
*staging_dir = Some(dir.clone());
dir
}
};
let slot_dir = root.join(index.to_string());
std::fs::create_dir(&slot_dir).map_err(io_error)?;
let path = slot_dir.join(sanitize_attachment_filename(original_name));
let file = std::fs::File::create_new(&path).map_err(io_error)?;
let utf8 = path
.clone()
.into_os_string()
.into_string()
.map_err(|_| Error::Invalid("ACP attachment path is not UTF-8"))?;
Ok((file, path, utf8))
}
fn materialize_bytes(
staging_dir: &mut Option<PathBuf>,
inputs_directory: Option<&Path>,
index: usize,
original_name: &str,
bytes: &[u8],
) -> Result<String, Error> {
let (mut file, path, utf8) =
create_local_file(staging_dir, inputs_directory, index, original_name)?;
file.write_all(bytes).map_err(io_error)?;
file.flush().map_err(io_error)?;
drop(file);
mark_read_only(&path)?;
Ok(utf8)
}
fn materialize_stream(
staging_dir: &mut Option<PathBuf>,
inputs_directory: Option<&Path>,
index: usize,
original_name: &str,
resource: &dyn maka_capabilities::call::ReadResource,
cancellation: &tokio_util::sync::CancellationToken,
) -> Result<String, Error> {
let (mut file, path, utf8) =
create_local_file(staging_dir, inputs_directory, index, original_name)?;
for start in (0..resource.bytes()).step_by(64 * 1024) {
if cancellation.is_cancelled() {
return Err(Error::Cancelled);
}
let end = (start + 64 * 1024).min(resource.bytes());
let chunk = match resource.read(start..end) {
Ok(chunk) => chunk,
Err(_) if cancellation.is_cancelled() => return Err(Error::Cancelled),
Err(error) => return Err(Error::AttachmentRead(error)),
};
if chunk.len() != end - start {
return Err(Error::Invalid("ACP attachment read is incomplete"));
}
file.write_all(&chunk).map_err(io_error)?;
}
file.flush().map_err(io_error)?;
drop(file);
mark_read_only(&path)?;
Ok(utf8)
}
fn mark_read_only(path: &Path) -> Result<(), Error> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o400)).map_err(io_error)?;
}
#[cfg(not(unix))]
{
let mut permissions = std::fs::metadata(path).map_err(io_error)?.permissions();
permissions.set_readonly(true);
std::fs::set_permissions(path, permissions).map_err(io_error)?;
}
Ok(())
}
pub fn remove_materialized_dir(dir: &Path) -> Result<(), std::io::Error> {
#[cfg(not(unix))]
clear_readonly_tree(dir);
match std::fs::remove_dir_all(dir) {
Ok(()) => Ok(()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error),
}
}
#[cfg(not(unix))]
fn clear_readonly_tree(path: &Path) {
let Ok(entries) = std::fs::read_dir(path) else {
return;
};
for entry in entries.flatten() {
let child = entry.path();
let Ok(file_type) = entry.file_type() else {
continue;
};
if file_type.is_dir() {
clear_readonly_tree(&child);
} else if let Ok(metadata) = std::fs::metadata(&child) {
let mut permissions = metadata.permissions();
if permissions.readonly() {
permissions.set_readonly(false);
let _ = std::fs::set_permissions(&child, permissions);
}
}
}
}
fn io_error(error: std::io::Error) -> Error {
Error::AttachmentIo(error)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ports::PromptAttachment;
use maka_agent_facts::language::Language;
use maka_capabilities::call::ReadResource;
use std::{ops::Range, sync::Arc};
struct BytesResource(Vec<u8>);
impl ReadResource for BytesResource {
fn resource_type(&self) -> maka_plugin_core::contract::ResourceType {
maka_plugin_core::contract::binary_resource_type()
}
fn bytes(&self) -> usize {
self.0.len()
}
fn metadata(&self) -> Value {
Value::Null
}
fn read(&self, range: Range<usize>) -> Result<Vec<u8>, String> {
self.0
.get(range)
.map(<[u8]>::to_vec)
.ok_or_else(|| "invalid range".into())
}
}
fn attachment(name: &str, mime_type: &str, bytes: Vec<u8>) -> PromptAttachment {
PromptAttachment {
name: name.into(),
mime_type: mime_type.into(),
resource: Arc::new(BytesResource(bytes)),
}
}
fn extract_materialized_paths(blocks: &[Value]) -> Vec<PathBuf> {
blocks
.iter()
.filter_map(|block| block.get("text").and_then(Value::as_str))
.flat_map(|text| text.lines())
.filter_map(|line| {
let (_, raw) = line.split_once(", path: ")?;
let path: String = serde_json::from_str(raw).ok()?;
Some(PathBuf::from(path))
})
.collect()
}
#[test]
fn binary_large_text_and_unsupported_images_materialize_to_local_files_instead_of_json_blobs() {
let inputs = tempfile::tempdir().unwrap();
let mp4 = b"\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00mp42isom".to_vec();
let png = b"\x89PNG\r\n\x1a\nfake-png".to_vec();
let large_text = vec![b'x'; MAX_INLINE_EXTERNAL_TEXT_BYTES + 1];
let small_text = b"short note".to_vec();
let (result, staging_dir) = blocks(
vec!["inspect these".into()],
vec![
attachment(
"workgroup-weird.mp4",
"application/octet-stream",
mp4.clone(),
),
attachment("shot.png", "image/png", png.clone()),
attachment("small.txt", "text/plain", small_text.clone()),
attachment("huge.txt", "text/plain", large_text.clone()),
],
Some(inputs.path()),
false,
true,
Language::EN,
&tokio_util::sync::CancellationToken::new(),
)
.unwrap();
let rendered = serde_json::to_string(&result).unwrap();
assert!(
!rendered.contains(r#""blob""#),
"must never embed base64 blob: {rendered}"
);
assert!(rendered.contains("short note"));
let paths = extract_materialized_paths(&result);
assert_eq!(paths.len(), 3, "rendered: {rendered}");
assert_eq!(std::fs::read(&paths[0]).unwrap(), mp4);
assert_eq!(std::fs::read(&paths[1]).unwrap(), png);
assert_eq!(std::fs::read(&paths[2]).unwrap(), large_text);
for path in &paths {
let permissions = std::fs::metadata(path).unwrap().permissions();
assert!(permissions.readonly());
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(permissions.mode() & 0o777, 0o400);
}
}
let staging_dir = staging_dir.expect("staging directory");
assert!(staging_dir.exists());
remove_materialized_dir(&staging_dir).unwrap();
assert!(!staging_dir.exists());
}
#[test]
fn supported_native_images_still_use_acp_image_blocks() {
let inputs = tempfile::tempdir().unwrap();
let png = b"\x89PNG\r\n\x1a\nfake-png".to_vec();
let (result, staging_dir) = blocks(
vec!["see image".into()],
vec![attachment("shot.png", "image/png", png.clone())],
Some(inputs.path()),
true,
false,
Language::EN,
&tokio_util::sync::CancellationToken::new(),
)
.unwrap();
assert!(staging_dir.is_none());
assert_eq!(result.len(), 3);
assert_eq!(result[2]["type"], "image");
assert_eq!(result[2]["mimeType"], "image/png");
assert_eq!(result[2]["data"], STANDARD.encode(&png));
assert!(std::fs::read_dir(inputs.path()).unwrap().next().is_none());
}
#[test]
fn io_failure_and_cancellation_clean_up_staging_and_classify_pre_prompt_io() {
let inputs = tempfile::tempdir().unwrap();
let missing_dir = inputs.path().join("does-not-exist");
let io_err = blocks(
vec!["inspect".into()],
vec![attachment(
"clip.mp4",
"application/octet-stream",
vec![1, 2, 3],
)],
Some(&missing_dir),
false,
false,
Language::EN,
&tokio_util::sync::CancellationToken::new(),
)
.unwrap_err();
assert!(matches!(io_err, Error::AttachmentIo(_)), "got {io_err:?}");
struct CancellingResource {
bytes: Vec<u8>,
cancel: tokio_util::sync::CancellationToken,
}
impl ReadResource for CancellingResource {
fn resource_type(&self) -> maka_plugin_core::contract::ResourceType {
maka_plugin_core::contract::binary_resource_type()
}
fn metadata(&self) -> Value {
json!({})
}
fn bytes(&self) -> usize {
self.bytes.len()
}
fn read(&self, range: std::ops::Range<usize>) -> Result<Vec<u8>, String> {
if range.start > 0 {
self.cancel.cancel();
}
Ok(self.bytes[range].to_vec())
}
}
let cancel = tokio_util::sync::CancellationToken::new();
let cancelled = blocks(
vec!["inspect".into()],
vec![PromptAttachment {
name: "big.mp4".into(),
mime_type: "application/octet-stream".into(),
resource: Arc::new(CancellingResource {
bytes: vec![7u8; 256 * 1024],
cancel: cancel.clone(),
}),
}],
Some(inputs.path()),
false,
false,
Language::EN,
&cancel,
)
.unwrap_err();
assert!(matches!(cancelled, Error::Cancelled), "got {cancelled:?}");
assert!(std::fs::read_dir(inputs.path()).unwrap().next().is_none());
}
}